method2testcases stringlengths 118 6.63k |
|---|
### Question:
ResultLattice { public boolean insert(Result node) { if (valid(node)) { int l = node.getEmbeddedFD().lhs.cardinality(); if (! layers.containsKey(l)) { layers.put(l, new LinkedList<Result>()); } if (!layers.get(l).contains(node)) { layers.get(l).add(node); } return true; } return false; } ResultLattice(int rhs); ResultLattice(Result root); boolean insert(Result node); List<Result> getLayer(int i); int size(); boolean contains(BitSet lhs, int rhs); boolean contains(Result node); List<Result> getParents(Result child); List<Result> getChildren(Result node); 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)); ResultLattice lattice = new ResultLattice(node); lattice.insert(child); boolean inserted = lattice.insert(offendingResult); Assert.assertFalse(inserted); } |
### Question:
Pattern implements Comparable<Pattern> { public boolean matches(int[] tuple) { for (int i = 0; i < ids.length; i += 1) { int id = ids[i]; PatternEntry entry = patternEntries[i]; if (! entry.matches(tuple[id])) { return false; } } return true; } Pattern(Map<Integer, PatternEntry> attributes); boolean matches(int[] tuple); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); Int2ReferenceArrayMap<PatternEntry> getAttributes(); void setAttributes(Map<Integer, PatternEntry> attributes); int[] getIds(); PatternEntry[] getPatternEntries(); float getSupport(); void setSupport(float support); float getConfidence(); List<IntArrayList> getCover(); void setCover(List<IntArrayList> cover); int getNumKeepers(); void setNumKeepers(int numKeepers); int getNumCover(); void updateCover(Pattern pattern); void updateKeepers(int[] rhs); double calculateG1(int[] rhs); @Override int compareTo(Pattern other); }### Answer:
@Test public void testVariablePatternEntryMatching() { VariablePatternEntry entry = new VariablePatternEntry(); Assert.assertTrue(entry.matches(1)); Assert.assertTrue(entry.matches(123)); Assert.assertTrue(entry.matches(444)); }
@Test public void testConstantPatternEntryMatching() { ConstantPatternEntry entry = new ConstantPatternEntry(42); Assert.assertFalse(entry.matches(1)); Assert.assertFalse(entry.matches(123)); Assert.assertFalse(entry.matches(444)); Assert.assertTrue(entry.matches(42)); }
@Test public void testPatternMatching() { Map<Integer, PatternEntry> attributes = new HashMap<>(); attributes.put(Integer.valueOf(0), new VariablePatternEntry()); attributes.put(Integer.valueOf(1), new ConstantPatternEntry(2)); attributes.put(Integer.valueOf(2), new ConstantPatternEntry(4)); Pattern pattern = new Pattern(attributes); Assert.assertTrue(pattern.matches(new int[] {1, 2, 4})); Assert.assertTrue(pattern.matches(new int[] {6, 2, 4})); Assert.assertFalse(pattern.matches(new int[] {6, 2, 5})); Assert.assertFalse(pattern.matches(new int[] {6, 3, 4})); } |
### Question:
LhsUtils { public static List<BitSet> generateLhsSubsets(BitSet lhs) { List<BitSet> results = new LinkedList<>(); for (int i = lhs.nextSetBit(0); i >= 0; i = lhs.nextSetBit(i + 1)) { BitSet subset = (BitSet) lhs.clone(); subset.flip(i); if (subset.cardinality() > 0) { results.add(subset); } } return results; } static void addSubsetsTo(FDTreeElement.InternalFunctionalDependency fd, Collection<FDTreeElement.InternalFunctionalDependency> collection); static List<BitSet> generateLhsSubsets(BitSet lhs); static List<BitSet> generateLhsSupersets(BitSet lhs, int numAttributes); }### Answer:
@Test public void testGenerateLhsSubsetsDoesNotReturnAnythingIfThereAreNoSubsets() { List<BitSet> results = LhsUtils.generateLhsSubsets(new BitSet(64)); Assert.assertEquals(0, results.size()); }
@Test public void testGenerateLhsSubsetsDoesGenerateSetsWithOneLessAttribute() { BitSet parent = generateLhs(64, new int[] {1, 2, 3}); List<BitSet> results = LhsUtils.generateLhsSubsets(parent); Assert.assertEquals(3, results.size()); Assert.assertTrue(results.contains(generateLhs(64, new int[] {1, 2}))); Assert.assertTrue(results.contains(generateLhs(64, new int[] {2, 3}))); Assert.assertTrue(results.contains(generateLhs(64, new int[] {1, 3}))); } |
### Question:
ConstantPatternExpansionStrategy extends ExpansionStrategy { @Override public Pattern generateNullPattern(BitSet attributes) { Map<Integer, PatternEntry> allVariables = new HashMap<>(); for (int i = attributes.nextSetBit(0); i >= 0; i = attributes.nextSetBit(i + 1)) { allVariables.put(Integer.valueOf(i), new VariablePatternEntry()); } return new Pattern(allVariables); } ConstantPatternExpansionStrategy(int[][] values); static String getIdentifier(); @Override Pattern generateNullPattern(BitSet attributes); @Override List<Pattern> getChildPatterns(Pattern currentPattern); }### Answer:
@Test public void testNullPatternGenerationSubset() { ConstantPatternExpansionStrategy out = new ConstantPatternExpansionStrategy(new int[][] {}); Pattern nullPattern = out.generateNullPattern(createAttributes(5, new int[] {2, 4})); PatternEntry[] patternEntries = nullPattern.getPatternEntries(); Assert.assertEquals(2, patternEntries.length); Assert.assertTrue(patternEntries[0] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[1] instanceof VariablePatternEntry); }
@Test public void testNullPatternGenerationAllSet() { ConstantPatternExpansionStrategy out = new ConstantPatternExpansionStrategy(new int[][] {}); Pattern nullPattern = out.generateNullPattern(createAttributes(7, new int[] {0, 1, 2, 3, 4, 5, 6})); PatternEntry[] patternEntries = nullPattern.getPatternEntries(); Assert.assertEquals(7, patternEntries.length); Assert.assertTrue(patternEntries[0] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[1] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[2] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[3] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[4] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[5] instanceof VariablePatternEntry); Assert.assertTrue(patternEntries[6] instanceof VariablePatternEntry); }
@Test public void testNullPatternGenerationNoneSet() { ConstantPatternExpansionStrategy out = new ConstantPatternExpansionStrategy(new int[][] {}); Pattern nullPattern = out.generateNullPattern(createAttributes(3, new int[] {})); PatternEntry[] patternEntries = nullPattern.getPatternEntries(); Assert.assertEquals(0, patternEntries.length); } |
### Question:
ConstantPatternExpansionStrategy extends ExpansionStrategy { @Override public List<Pattern> getChildPatterns(Pattern currentPattern) { List<Pattern> result = new LinkedList<>(); for (IntArrayList cluster : currentPattern.getCover()) { result.addAll(getChildPatterns(currentPattern, cluster)); } return result; } ConstantPatternExpansionStrategy(int[][] values); static String getIdentifier(); @Override Pattern generateNullPattern(BitSet attributes); @Override List<Pattern> getChildPatterns(Pattern currentPattern); }### Answer:
@Test public void testGetChildPatternsFromExistingPattern() { int[][] values = new int[][] { new int[] {0, 1, 2}, new int[] {0, 3, 4} }; Pattern pattern = new Pattern(createAttributeMap(new int[] {0, -1, -1})); List<IntArrayList> cover = new ArrayList<>(); cover.add(new IntArrayList(new int[] {0})); cover.add(new IntArrayList(new int[] {1})); pattern.setCover(cover); ConstantPatternExpansionStrategy out = new ConstantPatternExpansionStrategy(values); List<Pattern> children = out.getChildPatterns(pattern); Assert.assertEquals(4, children.size()); Assert.assertTrue(containsPattern(children, new Pattern(createAttributeMap(new int[] {0, 1, -1})))); Assert.assertTrue(containsPattern(children, new Pattern(createAttributeMap(new int[] {0, -1, 2})))); Assert.assertTrue(containsPattern(children, new Pattern(createAttributeMap(new int[] {0, 3, -1})))); Assert.assertTrue(containsPattern(children, new Pattern(createAttributeMap(new int[] {0, -1, 4})))); }
@Test public void testGetChildPatternsFromExistingPatternWithNoVariables() { int[][] values = new int[][] { new int[] {0, 1, 2}, new int[] {0, 1, 2} }; Pattern pattern = new Pattern(createAttributeMap(new int[] {0, 1, 2})); List<IntArrayList> cover = new ArrayList<>(); cover.add(new IntArrayList(new int[] {0})); cover.add(new IntArrayList(new int[] {1})); pattern.setCover(cover); ConstantPatternExpansionStrategy out = new ConstantPatternExpansionStrategy(values); List<Pattern> children = out.getChildPatterns(pattern); Assert.assertEquals(0, children.size()); } |
### Question:
DVSuperLogLog extends DVSuperLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVSuperLogLog.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVSuperLogLog.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVSuperLogLog extends DVSuperLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
DVHyperLogLog extends DVHyperLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVHyperLogLog.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVHyperLogLog.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVHyperLogLog extends DVHyperLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
PruningGraph { public boolean find(ColumnCombinationBitset columnCombination) { return findRecursively(columnCombination, new ColumnCombinationBitset(), 1); } PruningGraph(int numberOfColumns, int overflowTreshold, boolean positiveFeature); void add(ColumnCombinationBitset columnCombination); boolean find(ColumnCombinationBitset columnCombination); }### Answer:
@Test public void testFind() { PruningGraph graph = fixture.getGraphWith1Element(); assertFalse(graph.find(fixture.columnCombinationAC)); assertTrue(graph.find(fixture.columnCombinationABC)); }
@Test public void testFindWithOverflow() { PruningGraph graph = fixture.getGraphWith2ElementAndOverflow(); assertFalse(graph.find(fixture.columnCombinationAC)); assertTrue(graph.find(fixture.columnCombinationABC)); }
@Test public void testFindWithOverflowNonUnique() { PruningGraph graph = fixture.getGraphWith2ElementAndOverflowNonUnique(); assertFalse(graph.find(fixture.columnCombinationAC)); assertTrue(graph.find(fixture.columnCombinationB)); assertTrue(graph.find(fixture.columnCombinationBC)); } |
### 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:
DuccAlgorithm { public void run(List<PositionListIndex> pliList) throws AlgorithmExecutionException { this.found = 0; this.graphTraverser.init(pliList, this.uccReceiver, this.relationName, this.columnNames); this.found = this.graphTraverser.traverseGraph(); } DuccAlgorithm(String relationName, List<String> columnNames,
UniqueColumnCombinationResultReceiver uccReceiver); DuccAlgorithm(String relationName, List<String> columnNames,
UniqueColumnCombinationResultReceiver uccReceiver, Random random); void setRawKeyError(long keyError); void run(List<PositionListIndex> pliList); ImmutableList<ColumnCombinationBitset> getMinimalUniqueColumnCombinations(); Map<ColumnCombinationBitset, PositionListIndex> getCalculatedPlis(); public int found; }### Answer:
@Test public void testExecute() throws AlgorithmExecutionException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { AlgorithmTestFixture fixture = new AlgorithmTestFixture(); RelationalInput relationalInput = fixture.getInputGenerator().generateNewCopy(); Random random = mock(Random.class); when(random.nextInt(anyInt())).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (Integer) args[0] - 1; } }); DuccAlgorithm ducc = new DuccAlgorithm( relationalInput.relationName(), relationalInput.columnNames(), fixture.getUniqueColumnCombinationResultReceiver(), random); ducc.run(new PLIBuilder(relationalInput).getPLIList()); fixture.verifyUniqueColumnCombinationResultReceiver(); }
@Test public void testExecuteWithHoles() throws AlgorithmExecutionException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { DuccTestFixtureWithHoles fixture = new DuccTestFixtureWithHoles(); Random random = mock(Random.class); when(random.nextInt(anyInt())).thenAnswer(new Answer<Integer>() { protected int[] randomVariables = {8, 0, 0, 0, 3, 2, 0, 1, 1, 1, 0, 0, 0, 0, 0, 2, 0}; protected int numberOfInvocations = 0; @Override public Integer answer(InvocationOnMock invocation) throws Throwable { if (numberOfInvocations < randomVariables.length) { return randomVariables[numberOfInvocations++]; } else { return 0; } } }); DuccAlgorithm ducc = new DuccAlgorithm(fixture.relationName, fixture.columnNames, fixture.uniqueColumnCombinationResultReceiver, random); RelationalInput relationalInput = fixture.getInputGenerator().generateNewCopy(); ducc.run(new PLIBuilder(relationalInput).getPLIList()); fixture.verifyUniqueColumnCombinationResultReceiver(); } |
### Question:
UccGraphTraverser extends GraphTraverser { public void init(List<PositionListIndex> basePLIs, UniqueColumnCombinationResultReceiver resultReceiver, String relationName, List<String> columnNames) throws CouldNotReceiveResultException, ColumnNameMismatchException { this.resultReceiver = resultReceiver; this.relationName = relationName; this.columnNames = columnNames; this.filterNonUniqueColumnCombinationBitsets(basePLIs); this.numberOfColumns = this.calculatedPlis.size(); this.negativeGraph = new PruningGraph(this.numberOfColumns, this.OVERFLOW_THRESHOLD, false); this.positiveGraph = new PruningGraph(this.numberOfColumns, this.OVERFLOW_THRESHOLD, true); this.randomWalkTrace = new LinkedList<>(); this.seedCandidates = this.buildInitialSeeds(); this.holeFinder = new HoleFinder(this.numberOfColumns); } UccGraphTraverser(); UccGraphTraverser(Random random); void setDesiredKeyError(long desiredKeyError); void init(List<PositionListIndex> basePLIs,
UniqueColumnCombinationResultReceiver resultReceiver, String relationName,
List<String> columnNames); }### Answer:
@Test public void testTraverseGraph() throws CouldNotReceiveResultException, ColumnNameMismatchException { List<PositionListIndex> pliList = fixture.getPLIList(); LinkedList<String> columnNames = new LinkedList<>(); Integer i; for (i = 0; i < pliList.size(); i++) { columnNames.add(i.toString()); } ImmutableList<String> immutableColumnNames = ImmutableList.copyOf(columnNames); UccGraphTraverser graph = new UccGraphTraverser(); graph.init(fixture.getPLIList(), mock(UniqueColumnCombinationResultReceiver.class), "relation", immutableColumnNames); Collection<ColumnCombinationBitset> expectedUniqueColumnCombinations = fixture.getExpectedBitset(); graph.traverseGraph(); assertThat(graph.getMinimalPositiveColumnCombinations(), IsIterableContainingInAnyOrder .containsInAnyOrder(expectedUniqueColumnCombinations.toArray( new ColumnCombinationBitset[expectedUniqueColumnCombinations.size()]))); } |
### Question:
Ducc implements UniqueColumnCombinationsAlgorithm, RelationalInputParameterAlgorithm,
BooleanParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> spec = new ArrayList<>(); ConfigurationRequirementRelationalInput input = new ConfigurationRequirementRelationalInput(INPUT_HANDLE); spec.add(input); ConfigurationRequirementBoolean nullEqualsNull = new ConfigurationRequirementBoolean(NULL_EQUALS_NULL); Boolean[] defaultNullEqualsNull = new Boolean[1]; defaultNullEqualsNull[0] = true; nullEqualsNull.setDefaultValues(defaultNullEqualsNull); nullEqualsNull.setRequired(true); spec.add(nullEqualsNull); return spec; } Ducc(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(UniqueColumnCombinationResultReceiver receiver); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { ConfigurationRequirementRelationalInput expectedSpecification1 = new ConfigurationRequirementRelationalInput(Ducc.INPUT_HANDLE); ConfigurationRequirementBoolean expectedSpecification2 = new ConfigurationRequirementBoolean(Ducc.NULL_EQUALS_NULL); List<ConfigurationRequirement<?>> spec = ducc.getConfigurationRequirements(); assertEquals(2, spec.size()); assertEquals(expectedSpecification1.getIdentifier(), spec.get(0).getIdentifier()); assertEquals(expectedSpecification2.getIdentifier(), spec.get(1).getIdentifier()); } |
### Question:
Ducc implements UniqueColumnCombinationsAlgorithm, RelationalInputParameterAlgorithm,
BooleanParameterAlgorithm { @Override public void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values) throws AlgorithmConfigurationException { if (identifier.equals(INPUT_HANDLE)) { inputGenerator = values[0]; } else { throw new AlgorithmConfigurationException("Operation should not be called"); } } Ducc(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(UniqueColumnCombinationResultReceiver receiver); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testSetConfigurationValueStringSimpleRelationalInputGenerator() throws AlgorithmConfigurationException { RelationalInputGenerator expectedInputGenerator = mock(RelationalInputGenerator.class); ducc.setRelationalInputConfigurationValue(Ducc.INPUT_HANDLE, expectedInputGenerator); assertEquals(expectedInputGenerator, ducc.inputGenerator); }
@Test public void testSetConfigurationValueStringSimpleRelationalInputGeneratorFail() throws AlgorithmConfigurationException { RelationalInputGenerator expectedInputGenerator = mock(RelationalInputGenerator.class); try { ducc.setRelationalInputConfigurationValue("wrong identifier", expectedInputGenerator); fail("UnsupportedOperationException was expected but was not thrown"); } catch (AlgorithmConfigurationException e) { } assertEquals(null, ducc.inputGenerator); } |
### Question:
Ducc implements UniqueColumnCombinationsAlgorithm, RelationalInputParameterAlgorithm,
BooleanParameterAlgorithm { @Override public void setBooleanConfigurationValue(String identifier, Boolean... values) throws AlgorithmConfigurationException { if (identifier.equals(NULL_EQUALS_NULL)) { this.nullEqualsNull = values[0]; } else { throw new AlgorithmConfigurationException("Operation should not be called"); } } Ducc(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(UniqueColumnCombinationResultReceiver receiver); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testSetConfigurationValueNullEqualsNull() throws AlgorithmConfigurationException { boolean nullEqualsNull = false; ducc.setBooleanConfigurationValue(Ducc.NULL_EQUALS_NULL, nullEqualsNull); assertEquals(nullEqualsNull, ducc.nullEqualsNull); } |
### Question:
Ducc implements UniqueColumnCombinationsAlgorithm, RelationalInputParameterAlgorithm,
BooleanParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { RelationalInput input; input = inputGenerator.generateNewCopy(); PLIBuilder pliBuilder = new PLIBuilder(input, this.nullEqualsNull); List<PositionListIndex> plis = pliBuilder.getPLIList(); DuccAlgorithm duccAlgorithm = new DuccAlgorithm(input.relationName(), input.columnNames(), this.resultReceiver); duccAlgorithm.run(plis); } Ducc(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(UniqueColumnCombinationResultReceiver receiver); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() throws AlgorithmExecutionException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { AlgorithmTestFixture fixture = new AlgorithmTestFixture(); ducc.setRelationalInputConfigurationValue(Ducc.INPUT_HANDLE, fixture.getInputGenerator()); ducc.setResultReceiver(fixture.getUniqueColumnCombinationResultReceiver()); Random random = mock(Random.class); when(random.nextDouble()).thenReturn(1d); ducc.random = random; ducc.execute(); fixture.verifyUniqueColumnCombinationResultReceiver(); } |
### Question:
Ducc implements UniqueColumnCombinationsAlgorithm, RelationalInputParameterAlgorithm,
BooleanParameterAlgorithm { @Override public void setResultReceiver(UniqueColumnCombinationResultReceiver receiver) { this.resultReceiver = receiver; } Ducc(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(UniqueColumnCombinationResultReceiver receiver); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testSetResultReceiverUniqueColumnCombinationResultReceiver() { UniqueColumnCombinationResultReceiver expectedResultReceiver = mock(UniqueColumnCombinationResultReceiver.class); ducc.setResultReceiver(expectedResultReceiver); assertSame(expectedResultReceiver, ducc.resultReceiver); } |
### Question:
DVPCSA extends DVPCSAAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVPCSA.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVPCSA.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVPCSA extends DVPCSAAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
FdMine 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 execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { assertThat(algorithm.getConfigurationRequirements(), hasItem(isA(ConfigurationRequirementRelationalInput.class))); } |
### Question:
FdMine 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 execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testSetConfigurationValueStringRelationalInputGenerator() { RelationalInputGenerator expectedInputGenerator = mock(RelationalInputGenerator.class); algorithm.setRelationalInputConfigurationValue(FdMine.INPUT_FILE_TAG, expectedInputGenerator); assertSame(expectedInputGenerator, algorithm.inputGenerator); } |
### Question:
FdMine implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public void execute() throws InputGenerationException, InputIterationException, CouldNotReceiveResultException, AlgorithmConfigurationException, ColumnNameMismatchException { RelationalInput input = inputGenerator.generateNewCopy(); relationName = input.relationName(); columnNames = input.columnNames(); PLIBuilder pliBuilder = new PLIBuilder(input); int columnIndex = 0; for (PositionListIndex pli : pliBuilder.getPLIList()) { plis.put(new ColumnCombinationBitset(columnIndex), pli); columnIndex++; } r = new ColumnCombinationBitset(); Set<ColumnCombinationBitset> candidateSet = new HashSet<>(); for (columnIndex = 0; columnIndex < input.numberOfColumns(); columnIndex++) { r.addColumn(columnIndex); candidateSet.add(new ColumnCombinationBitset(columnIndex)); } for (ColumnCombinationBitset xi : candidateSet) { closure.put(xi, new ColumnCombinationBitset()); } while (!candidateSet.isEmpty()) { for (ColumnCombinationBitset xi : candidateSet) { computeNonTrivialClosure(xi); obtainFdAndKey(xi); } obtainEqSet(candidateSet); pruneCandidates(candidateSet); generateCandidates(candidateSet); } displayFD(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() throws AlgorithmExecutionException { AlgorithmTestFixture fixture = new AlgorithmTestFixture(); algorithm.setRelationalInputConfigurationValue(FdMine.INPUT_FILE_TAG, fixture.getInputGenerator()); algorithm.setResultReceiver(fixture.getFunctionalDependencyResultReceiver()); algorithm.execute(); fixture.verifyFunctionalDependencyResultReceiverForFDMine(); } |
### Question:
FdMine implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver) { this.resultReceiver = resultReceiver; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testSetResultReceiver() { FunctionalDependencyResultReceiver expectedResultReceiver = mock(FunctionalDependencyResultReceiver.class); algorithm.setResultReceiver(expectedResultReceiver); assertSame(expectedResultReceiver, algorithm.resultReceiver); } |
### Question:
DVLogLog extends DVLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVLogLog.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVLogLog.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVLogLog extends DVLogLogAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
ParserHelper { public static boolean isDouble(String s) { return s != null && doublePattern.test(s); } static boolean isDouble(String s); static boolean isInteger(String s); static boolean isInteger(String s, int radix); }### Answer:
@Test public void testIsDouble() { assertTrue(ParserHelper.isDouble("1.0")); assertFalse(ParserHelper.isDouble("Z2")); } |
### Question:
Column { @Override public String toString() { return tableName + "." + name; } Column(String tableName, String name); Type getType(); String getName(); @Override String toString(); void addLine(String string); Comparable<?> getValue(int line); Long getLong(int line); Double getDouble(int line); String getString(int line); }### Answer:
@Test public void testToString() { Column c = new Column("relation", "test"); Assert.assertEquals("relation.test", c.toString()); } |
### Question:
DVAKMV extends DVAKMVAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVAKMV.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVAKMV.Identifier.RELATIVE_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVAKMV extends DVAKMVAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
DVMinCount extends DVMinCountAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVMinCount.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVMinCount.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVMinCount extends DVMinCountAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
DVFM extends DVFMAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(DVFM.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementString inputstandard_error=new ConfigurationRequirementString(DVFM.Identifier.STANDARD_ERROR.name()); inputstandard_error.setRequired(false); String[] Defaults={"0.01"}; inputstandard_error.setDefaultValues(Defaults); conf.add(inputstandard_error); return conf; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testGetConfigurationRequirements() { } |
### Question:
DVFM extends DVFMAlgorithm implements BasicStatisticsAlgorithm, RelationalInputParameterAlgorithm, StringParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.execute(); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setResultReceiver(BasicStatisticsResultReceiver resultReceiver); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setStringConfigurationValue(String identifier, String... values); @Override String getAuthors(); @Override String getDescription(); }### Answer:
@Test public void testExecute() { } |
### Question:
VirtualColumnStore extends AbstractColumnStore { public ColumnIterator getRows(SimpleColumnCombination activeColumns) { this.initHashCaches(); try { return new VirtualColumnStore.ColumnIterator(this.inputGenerator.generateNewCopy(), activeColumns); } catch (Exception e) { throw new RuntimeException(e); } } VirtualColumnStore(int numColumns, int sampleGoal, RelationalInputGenerator inputGenerator, boolean isCloseConnectionsRigorously); ColumnIterator getRows(SimpleColumnCombination activeColumns); static VirtualColumnStore[] create(RelationalInputGenerator[] fileInputGenerators, int sampleGoal, boolean isCloseConnectionsRigorously); }### Answer:
@Test public void testGetRows() throws Exception { rb.setHeader("col1", "col2", "col3") .addRow("a", "a", "b") .addRow("1", "2", "2"); VirtualColumnStore cs = createColumnStore(rb.build()); 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"); VirtualColumnStore cs = createColumnStore(rb.build()); 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"); VirtualColumnStore cs = createColumnStore(rb.build()); 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)); } VirtualColumnStore cs = createColumnStore(rb.build()); 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 increaseNumApplicationsUniquenessPruning(final int level) { this.increaseMeasure(this.numApplicationsUniquenessPruning, level); } Statistics(final String algorithmName); void increaseNumPartitionCombinationsBySize(final int size); void increaseNumApplicationsEquivalenceLhsPruning(final int level); void increaseNumApplicationsEquivalenceRhsPruning(final int level); void increaseNumApplicationsUniquenessPruning(final int level); @Override String toString(); void increaseNumApplicationsSwapPruning(final int level); void increaseNumApplicationsMinimalityLhsPruning(final int level); void increaseNumApplicationsMinimalityRhsPruning(final int level); void increaseNumApplicationsValidRhsPruning(final int level); void increaseNumApplicationsMergePruning(final int level); int getNumFoundDependencies(); void setNumFoundDependencies(final int numFoundDependencies); int getNumFoundDependenciesInPreCheck(); void setNumFoundDependenciesInPreCheck(final int numFoundDependenciesInPreCheck); long getNumDependencyChecks(); void setNumDependencyChecks(final long numDependencyChecks); String getAlgorithmName(); void setAlgorithmName(final String algorithmName); long getTypeInferralTime(); void setTypeInferralTime(final long typeInferralTime); long getLoadDataTime(); void setLoadDataTime(final long loadDataTime); long getInitPartitionsTime(); void setInitPartitionsTime(final long initPartitionsTime); long getComputeDependenciesTime(); void setComputeDependenciesTime(final long computeDependenciesTime); long getPruneTime(); void setPruneTime(final long pruneTime); long getGenNextTime(); void setGenNextTime(final long genNextTime); }### Answer:
@Test public void testIncreaseNumApplicationsUniquenessPruning() { final Statistics stats = new Statistics("test"); int level = 3; stats.increaseNumApplicationsUniquenessPruning(level); stats.increaseNumApplicationsUniquenessPruning(level); level += 4; stats.increaseNumApplicationsUniquenessPruning(level); stats.increaseNumApplicationsUniquenessPruning(level); stats.increaseNumApplicationsUniquenessPruning(level); stats.increaseNumApplicationsUniquenessPruning(level); level++; stats.increaseNumApplicationsUniquenessPruning(level); stats.increaseNumApplicationsUniquenessPruning(level); level = 2; stats.increaseNumApplicationsUniquenessPruning(level); level++; stats.increaseNumApplicationsUniquenessPruning(level); assertTrue(stats.toString().contains( "numApplicationsUniquenessPruning=[0, 1, 3, 0, 0, 0, 4, 2]")); } |
### Question:
CachedSimilarityMeasure implements SimilarityMeasure<T> { @Override public double calculateSimilarity(T obj1, T obj2) { return calculateSimilarity(UnorderedPair.of(obj1, obj2)); } @Override double calculateSimilarity(T obj1, T obj2); @Override double calculateSimilarity(UnorderedPair<T> pair); @Override void hash(Hasher hasher); }### Answer:
@Test public void test() { doReturn(Double.valueOf(0.5)).when(sim).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(2))); doReturn(Double.valueOf(1.0 / 3)).when(sim).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(3))); SimilarityMeasure<Integer> cachedSim = CachedSimilarityMeasure.<Integer>builder() .similarityMeasure(sim) .build(); assertThat(cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(2))).isEqualTo(0.5); assertThat(cachedSim.calculateSimilarity(Integer.valueOf(2), Integer.valueOf(1))).isEqualTo(0.5); assertThat(cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(3))).isEqualTo(1.0 / 3); }
@Test public void testCache() { SimilarityMeasure<Integer> cachedSim = CachedSimilarityMeasure.<Integer>builder() .similarityMeasure(sim) .maximumSize(1) .build(); cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(2)); verify(sim).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(2))); cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(2)); verify(sim).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(2))); }
@Test public void testNoCache() { SimilarityMeasure<Integer> cachedSim = CachedSimilarityMeasure.<Integer>builder() .similarityMeasure(sim) .maximumSize(0) .build(); cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(2)); verify(sim).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(2))); cachedSim.calculateSimilarity(Integer.valueOf(1), Integer.valueOf(2)); verify(sim, times(2)).calculateSimilarity(UnorderedPair.of(Integer.valueOf(1), Integer.valueOf(2))); } |
### Question:
DefaultSimilarityClassifier implements SimilarityClassifier<T> { @Override public boolean areSimilar(T obj1, T obj2) { return calculateSimilarity(obj1, obj2) >= threshold; } @Override boolean areSimilar(T obj1, T obj2); @Override SimilarityClassifier<T> asClassifier(double newThreshold); @Override String toString(); }### Answer:
@Test public void test() { assertThat(getClassifier(0.6).areSimilar("foo", "bar")).isFalse(); assertThat(getClassifier(0.5).areSimilar("foo", "bar")).isTrue(); assertThat(getClassifier(0.4).areSimilar("foo", "bar")).isTrue(); } |
### Question:
SortedNeighborhoodPairGenerator implements PairGenerator<T> { @Override public Result<T> generate(Collection<T> left, Collection<T> right) { int expectedComputations = left.size() * Math.min(windowSize, right.size()); log.info("Will compute approximately {} similarities", Integer.valueOf(expectedComputations)); Collection<T> sortedLeft = sort(left); Collection<T> sortedRight = sort(right); Stream<Tuple2<T, Collection<T>>> pairs = new Task(sortedLeft, sortedRight).generate(); boolean complete = right.size() <= windowSize; return new Result<>(pairs, complete); } @Override Result<T> generate(Collection<T> left, Collection<T> right); @Override void hash(Hasher hasher); }### Answer:
@Test public void test() { PairGenerator<Integer> generator = createComputer(); Collection<Tuple2<Integer, Collection<Integer>>> similarities = generator .generate(Arrays.asList(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(6)), Arrays.asList(Integer.valueOf(1), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5))) .getPairs() .collect(Collectors.toList()); assertThat(similarities).hasSize(4); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(1), Arrays.asList(Integer.valueOf(1), Integer.valueOf(3)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(2), Arrays.asList(Integer.valueOf(1), Integer.valueOf(3), Integer.valueOf(4)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(3), Arrays.asList(Integer.valueOf(1), Integer.valueOf(3), Integer.valueOf(4)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(6), Collections.singletonList(Integer.valueOf(5)))); }
@Test public void testNull() { PairGenerator<Integer> generator = createComputer(); Collection<Tuple2<Integer, Collection<Integer>>> similarities = generator .generate(Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)), Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3))) .getPairs() .collect(Collectors.toList()); assertThat(similarities).hasSize(4); assertThat(similarities).contains(new Tuple2<>(null, Arrays.asList(null, Integer.valueOf(1)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(1), Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(2)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(2), Arrays.asList(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)))); assertThat(similarities).contains(new Tuple2<>(Integer.valueOf(3), Arrays.asList(Integer.valueOf(2), Integer.valueOf(3)))); } |
### Question:
StringUtils { public static String toLowerCase(String s) { return Optional.ofNullable(s) .map(String::toLowerCase) .orElse(null); } static String toLowerCase(String s); static String join(CharSequence delimiter, Iterable<?> elements); }### Answer:
@Test public void testToLowerCase() { assertThat(StringUtils.toLowerCase("foO")).isEqualTo("foo"); assertThat(StringUtils.toLowerCase(null)).isNull(); } |
### Question:
OptionalDouble { public Optional<Double> boxed() { return map(d -> Double.valueOf(d)); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testBoxed() { assertThat(OptionalDouble.empty().boxed()).isEmpty(); assertThat(OptionalDouble.of(1.0).boxed()).hasValue(1.0); } |
### Question:
OptionalDouble { public static OptionalDouble empty() { return EMPTY; } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testEmpty() { assertThat(OptionalDouble.empty().boxed()).isEmpty(); } |
### Question:
OptionalDouble { public OptionalDouble filter(@NonNull DoublePredicate predicate) { if (!optional.isPresent()) { return this; } return predicate.test(optional.getAsDouble()) ? this : empty(); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testFilter() { assertThat(OptionalDouble.empty().filter(d -> d > 2.0).isPresent()).isFalse(); assertThat(OptionalDouble.of(2.0).filter(d -> d > 2.0).isPresent()).isFalse(); assertThat(OptionalDouble.of(3.0).filter(d -> d > 2.0).isPresent()).isTrue(); } |
### Question:
OptionalDouble { public void ifPresent(DoubleConsumer consumer) { optional.ifPresent(consumer); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testIfPresent() { DoubleCollection collection = new DoubleArrayList(); OptionalDouble.of(2.0).ifPresent(collection::add); assertThat(collection).hasSize(1); assertThat(collection).contains(2.0); } |
### Question:
OptionalDouble { public boolean isPresent() { return optional.isPresent(); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testIsPresent() { assertThat(OptionalDouble.empty().isPresent()).isFalse(); assertThat(OptionalDouble.of(1.0).isPresent()).isTrue(); } |
### Question:
OptionalDouble { public <T> Optional<T> map(@NonNull DoubleFunction<T> mapper) { return optional.isPresent() ? Optional.ofNullable(mapper.apply(optional.getAsDouble())) : Optional.empty(); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testMap() { assertThat(OptionalDouble.empty().map(d -> 1)).isEmpty(); assertThat(OptionalDouble.of(2.0).map(d -> 1)).hasValue(1); } |
### Question:
OptionalDouble { public static OptionalDouble of(double value) { return new OptionalDouble(value); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testOf() { assertThat(OptionalDouble.of(2.0).boxed()).hasValue(2.0); } |
### Question:
OptionalDouble { public static OptionalDouble ofNullable(Double value) { return value == null ? empty() : of(value.doubleValue()); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testOfNullable() { assertThat(OptionalDouble.ofNullable(null).boxed()).isEmpty(); assertThat(OptionalDouble.ofNullable(1.0).boxed()).hasValue(1.0); } |
### Question:
OptionalDouble { public double orElse(double other) { return optional.orElse(other); } private OptionalDouble(); private OptionalDouble(double value); static OptionalDouble empty(); static OptionalDouble of(double value); static OptionalDouble ofNullable(Double value); Optional<Double> boxed(); OptionalDouble filter(@NonNull DoublePredicate predicate); double getAsDouble(); void ifPresent(DoubleConsumer consumer); boolean isPresent(); Optional<T> map(@NonNull DoubleFunction<T> mapper); double orElse(double other); }### Answer:
@Test public void testOrElse() { assertThat(OptionalDouble.empty().orElse(2.0)).isEqualTo(2.0); assertThat(OptionalDouble.of(1.0).orElse(2.0)).isEqualTo(1.0); } |
### Question:
ReflectionUtils { @SuppressWarnings("unchecked") public static <T> Optional<T> get(Field field, Object obj) { try { T value = (T) field.get(obj); return Optional.ofNullable(value); } catch (Exception e) { return Optional.empty(); } } static MakeAccessible<A> accessible(A accessibleObject); @SuppressWarnings("unchecked") static Optional<T> get(Field field, Object obj); static Optional<T> getAnnotationIfPresent(
AnnotatedElement annotatedElement, Class<T> annotationClass); static Optional<T> getDefaultValue(Class<? extends Annotation> annotation,
String property); static boolean isBooleanField(Field field); }### Answer:
@Test public void testGet() throws NoSuchFieldException { HelperClass obj = new HelperClass(); Field field = HelperClass.class.getDeclaredField(ACCESSIBLE); boolean accessible = true; obj.setAccessible(accessible); assertThat(obj.getAccessible()).isEqualTo(accessible); assertThat(ReflectionUtils.get(field, obj)).hasValue(accessible); }
@Test public void testGetInaccessible() throws NoSuchFieldException { HelperClass obj = new HelperClass(); Field field = HelperClass.class.getDeclaredField(INACCESSIBLE); boolean inaccessible = true; obj.setInaccessible(inaccessible); assertThat(obj.getInaccessible()).isEqualTo(inaccessible); assertThat(ReflectionUtils.get(field, obj)).isEmpty(); } |
### Question:
ReflectionUtils { public static <T extends Annotation> Optional<T> getAnnotationIfPresent( AnnotatedElement annotatedElement, Class<T> annotationClass) { if (annotatedElement.isAnnotationPresent(annotationClass)) { T annotation = annotatedElement.getAnnotation(annotationClass); return Optional.of(annotation); } return Optional.empty(); } static MakeAccessible<A> accessible(A accessibleObject); @SuppressWarnings("unchecked") static Optional<T> get(Field field, Object obj); static Optional<T> getAnnotationIfPresent(
AnnotatedElement annotatedElement, Class<T> annotationClass); static Optional<T> getDefaultValue(Class<? extends Annotation> annotation,
String property); static boolean isBooleanField(Field field); }### Answer:
@Test public void testGetAnnotationIfPresent() throws NoSuchFieldException { Field annotated = HelperClass.class.getDeclaredField(ANNOTATED); Field notAnnotated = HelperClass.class.getDeclaredField(NOT_ANNOTATED); assertThat(ReflectionUtils.getAnnotationIfPresent(annotated, Deprecated.class)).isPresent(); assertThat(ReflectionUtils.getAnnotationIfPresent(notAnnotated, Deprecated.class)) .isEmpty(); } |
### Question:
ReflectionUtils { public static <T> Optional<T> getDefaultValue(Class<? extends Annotation> annotation, String property) { try { Object defaultValue = annotation.getDeclaredMethod(property).getDefaultValue(); return Optional.ofNullable(defaultValue) .map(CastUtils::as); } catch (NoSuchMethodException e) { return Optional.empty(); } } static MakeAccessible<A> accessible(A accessibleObject); @SuppressWarnings("unchecked") static Optional<T> get(Field field, Object obj); static Optional<T> getAnnotationIfPresent(
AnnotatedElement annotatedElement, Class<T> annotationClass); static Optional<T> getDefaultValue(Class<? extends Annotation> annotation,
String property); static boolean isBooleanField(Field field); }### Answer:
@Test public void testGetDefaultValue() { assertThat(ReflectionUtils.getDefaultValue(HelperAnnotation.class, "property")) .hasValue("foo"); }
@Test public void testGetDefaultValueMissing() { assertThat(ReflectionUtils.getDefaultValue(HelperAnnotation.class, "missing")).isEmpty(); }
@Test public void testGetDefaultValueNoDefault() { assertThat(ReflectionUtils.getDefaultValue(HelperAnnotation.class, "noDefault")).isEmpty(); } |
### Question:
ReflectionUtils { public static boolean isBooleanField(Field field) { Class<?> type = field.getType(); return boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type); } static MakeAccessible<A> accessible(A accessibleObject); @SuppressWarnings("unchecked") static Optional<T> get(Field field, Object obj); static Optional<T> getAnnotationIfPresent(
AnnotatedElement annotatedElement, Class<T> annotationClass); static Optional<T> getDefaultValue(Class<? extends Annotation> annotation,
String property); static boolean isBooleanField(Field field); }### Answer:
@Test public void testIsBooleanField() throws NoSuchFieldException { assertThat( ReflectionUtils.isBooleanField(HelperClass.class.getDeclaredField(PRIMITIVE_BOOLEAN))) .isTrue(); assertThat( ReflectionUtils.isBooleanField(HelperClass.class.getDeclaredField(OBJECT_BOOLEAN))) .isTrue(); assertThat(ReflectionUtils.isBooleanField(HelperClass.class.getDeclaredField(NOT_BOOLEAN))) .isFalse(); } |
### Question:
Differ { public static <T> DiffResult<T> diff(Collection<T> a, Collection<T> b) { return new Differ<>(a, b).diff(); } static DiffResult<T> diff(Collection<T> a, Collection<T> b); }### Answer:
@Test public void test() { DiffResult<Integer> result = Differ.diff(Arrays.asList(1, 2, 3, 3), Arrays.asList(1, 3, 4)); assertThat(result.getCommon()).hasSize(2); assertThat(result.getCommon()).contains(1, 3); assertThat(result.getOnlyA()).hasSize(1); assertThat(result.getOnlyA()).contains(2); assertThat(result.getOnlyB()).hasSize(1); assertThat(result.getOnlyB()).contains(4); }
@Test public void testIsSame() { assertThat(Differ.diff(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)).isSame()).isTrue(); assertThat(Differ.diff(Arrays.asList(1, 2, 3), Arrays.asList(1, 3)).isSame()).isFalse(); } |
### Question:
StoredObjectService { public void store(Object object) throws IOException { Files.createParentDirs(file); try (ObjectOutput out = new ObjectOutputStream(new FileOutputStream(file))) { out.writeObject(object); log.info("Stored object in {}", file); } catch (IOException e) { file.delete(); throw e; } } boolean exists(); Object read(); void store(Object object); }### Answer:
@Ignore @Test(expected = IOException.class) public void testFailedWrite() throws IOException { File file = folder.newFile(); file.delete(); StoredObjectService service = new StoredObjectService(file); try (RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel channel = raf.getChannel(); FileLock ignored = channel.lock()) { service.store("foo"); fail(); } } |
### Question:
MetricsUtils { public static MetricRegistry getDefaultRegistry() { MetricRegistry registry = SharedMetricRegistries.tryGetDefault(); return Optional.ofNullable(registry) .orElseGet(MetricsUtils::setDefaultRegistry); } static MetricRegistry getDefaultRegistry(); static void registerGauge(String name, T value); static Context timer(Class<?> clazz, String name); }### Answer:
@Test public void testDefaultRegistry() { assertThat(MetricsUtils.getDefaultRegistry()).isNotNull(); } |
### Question:
MetricsUtils { public static Context timer(Class<?> clazz, String name) { Timer timer = getDefaultRegistry() .timer(name(clazz, name)); return timer.time(); } static MetricRegistry getDefaultRegistry(); static void registerGauge(String name, T value); static Context timer(Class<?> clazz, String name); }### Answer:
@SuppressWarnings("EmptyTryBlock") @Test public void testTimer() { try (Context ignored = MetricsUtils.timer(MetricsUtilsTest.class, "foo")) { } Timer timer = MetricsUtils.getDefaultRegistry().timer(name(MetricsUtilsTest.class, "foo")); assertThat(timer.getCount()).isGreaterThanOrEqualTo(1L); } |
### Question:
CastUtils { public static <T> T as(Object obj) { return (T) obj; } static T as(Object obj); }### Answer:
@Test public void test() { Object obj = "foo"; String casted = CastUtils.as(obj); assertThat(casted).isEqualTo("foo"); }
@SuppressWarnings("unused") @Test(expected = ClassCastException.class) public void testFailedCast() { Object obj = "1"; Integer ignored = CastUtils.<Integer>as(obj); fail(); } |
### Question:
UnorderedPair { public static <T> UnorderedPair<T> of(T value1, T value2) { Set<T> set = ImmutableSet.of(value1, value2); return new UnorderedPair<>(set); } static UnorderedPair<T> of(T value1, T value2); T getFirst(); T getSecond(); }### Answer:
@Test public void testEquality() { UnorderedPair<Integer> pair1 = UnorderedPair.of(1, 2); UnorderedPair<Integer> pair2 = UnorderedPair.of(2, 1); assertThat(pair1).isEqualTo(pair2); }
@Test public void testNotEquals() { assertThat(UnorderedPair.of(1, 2)).isNotEqualTo(UnorderedPair.of(1, 3)); } |
### Question:
ObjectUtils { public static boolean bothNull(Object obj1, Object obj2) { return obj1 == null && obj2 == null; } static boolean bothNull(Object obj1, Object obj2); static boolean eitherNull(Object obj1, Object obj2); static boolean notEquals(Object obj1, Object obj2); }### Answer:
@Test public void testBothNull() { assertThat(ObjectUtils.bothNull(null, null)).isTrue(); assertThat(ObjectUtils.bothNull("", null)).isFalse(); assertThat(ObjectUtils.bothNull(null, "")).isFalse(); assertThat(ObjectUtils.bothNull("", "")).isFalse(); } |
### Question:
ObjectUtils { public static boolean eitherNull(Object obj1, Object obj2) { return obj1 == null || obj2 == null; } static boolean bothNull(Object obj1, Object obj2); static boolean eitherNull(Object obj1, Object obj2); static boolean notEquals(Object obj1, Object obj2); }### Answer:
@Test public void testEitherNull() { assertThat(ObjectUtils.eitherNull(null, null)).isTrue(); assertThat(ObjectUtils.eitherNull("", null)).isTrue(); assertThat(ObjectUtils.eitherNull(null, "")).isTrue(); assertThat(ObjectUtils.eitherNull("", "")).isFalse(); } |
### Question:
FileUtils { public static WithFile with(File file) { return new WithFile(file); } static WithFile with(File file); }### Answer:
@Test public void testWriteLines() throws IOException { WithFile withFile = FileUtils.with(folder.newFile()); withFile.writeLines(Arrays.asList("foo", "bar")); Optional<Collection<String>> lines = withFile.readLines(); assertThat(lines, isPresentAnd(hasSize(2))); assertThat(lines, isPresentAnd(hasItem("foo"))); assertThat(lines, isPresentAnd(hasItem("bar"))); } |
### Question:
ObservationDownloader { static List<Observation> retrieveObservation(String loincCode) { List<Observation> results = new ArrayList<>(); Bundle bundle = client.search().forResource(Observation.class) .where(new TokenClientParam("code").exactly().systemAndCode(LOINC_SYSTEM, loincCode)) .prettyPrint() .returnBundle(Bundle.class) .execute(); while (true) { for (Bundle.BundleEntryComponent bundleEntryComponent : bundle.getEntry() ){ Observation observation = (Observation) bundleEntryComponent.getResource(); results.add(observation); } if (bundle.getLink(IBaseBundle.LINK_NEXT) != null){ bundle = client.loadPage().next(bundle).execute(); } else { break; } } return results; } static void iteratorHapiFHIRServer(); }### Answer:
@Test @Disabled("This test tries to fetch observation from hapi-fhir test server, so the returning observations various") public void retrieveObservation() throws Exception { String testLoinc = "1558-6"; List<Observation> observations = ObservationDownloader.retrieveObservation( testLoinc); assertEquals(4, observations.size()); String testLoinc2 = "600-7"; observations = ObservationDownloader.retrieveObservation(testLoinc2); assertEquals(185, observations.size()); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public char randChar() { boolean lowercase = rand.nextBoolean(); if (lowercase) { return randLowerCaseChar(); } else { return randUpperCaseChar(); } } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randChar() throws Exception { int iter = 1000; for (int i = 0; i < iter; i++) { char c = randomGenerator.randChar(); assertTrue(c >= 'A' && c <='Z' || c >= 'a' && c <= 'z'); } } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<Character> randLowerCaseChars(int num) { if (num <= 0) throw new IllegalArgumentException(); Character [] chars = new Character[num]; for (int i = 0; i < num; i++) { chars[i] = randLowerCaseChar(); } return Arrays.asList(chars); } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randLowerCaseChars() throws Exception { int iter = 1000; List<Character> chars = randomGenerator.randLowerCaseChars(iter); chars.forEach(c -> assertTrue(c >= 'a' && c <= 'z')); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<Character> randUpperCaseChars(int num) { if (num <= 0) throw new IllegalArgumentException(); Character [] chars = new Character[num]; for (int i = 0; i < num; i++) { chars[i] = randUpperCaseChar(); } return Arrays.asList(chars); } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randUpperCaseChars() throws Exception { int iter = 1000; List<Character> chars = randomGenerator.randUpperCaseChars(iter); chars.forEach(c -> assertTrue(c >= 'A' && c <= 'Z')); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<Character> randChars(int num) { if (num <= 0) throw new IllegalArgumentException(); Character [] chars = new Character[num]; for (int i = 0; i < num; i++) { chars[i] = randChar(); } return Arrays.asList(chars); } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randChars() throws Exception { int iter = 1000; List<Character> chars = randomGenerator.randChars(iter); assertEquals(iter, chars.size()); chars.forEach(c -> assertTrue(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public int randInt(int lowBound, int upBound) { return rand.nextInt(upBound - lowBound) + lowBound; } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randInt() throws Exception { int iter = 1000; int low = 0; int high = 10; int r; for (int i = 0; i < iter; i++) { r = randomGenerator.randInt(low, high); assertTrue(r >= 0 && r <= 9); } } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<Integer> randIntegers(int lowBount, int upBount, int length) { if (length <= 0) { throw new IllegalArgumentException(); } Integer[] intList = new Integer[length]; for (int i = 0; i < length; i++) { intList[i] = randInt(lowBount, upBount); } return Arrays.asList(intList); } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randIntegers() throws Exception { int iter = 1000; int low = 0; int high = 10; List<Integer> ints = randomGenerator.randIntegers(low, high, iter); ints.forEach(i -> assertTrue(i >= 0 && i <= 9)); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public String randString(int charCount, int intCount, boolean mustSeartWithAlph) { if (charCount <= 0 || intCount <= 0) { throw new IllegalArgumentException(); } String string = randString(charCount, intCount); if (mustSeartWithAlph) { while (!Character.isAlphabetic(string.charAt(0))) { string = randString(charCount, intCount); } return string; } else { return string; } } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randString() { int iter = 1000; int charNum = 5; int intNum = 5; for (int i = 0; i < iter; i++) { String string = randomGenerator.randString(charNum, intNum, false); assertEquals(charNum + intNum, string.length()); } } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph) { List<String> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(randString(alphNum, digitNum, mustStartWithAlph)); } return list; } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randStrings() { int iter = 1000; int charNum = 5; int intNum = 5; List<String> strings = randomGenerator.randStrings(iter, charNum, intNum, true); strings.forEach(s -> { assertEquals(charNum + intNum, s.length()); assertTrue(Character.isAlphabetic(s.charAt(0))); }); } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public double randDouble(double lowBound, double upBound) { return rand.nextDouble() * (upBound - lowBound) + lowBound; } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randDouble() { int iter = 1000; int low = 0; int high = 10; for (int i = 0; i < iter; i++) { double d = randomGenerator.randDouble(low, high); assertTrue(d >= low && d < high); } } |
### Question:
RandomGeneratorImpl implements RandomGenerator { @Override public List<Double> randDoubles(int size, double lowBound, double upBound) { List<Double> list = new ArrayList<>(); DoubleStream stream = rand.doubles(size, lowBound, upBound); stream.forEach(list::add); return list; } @Override char randLowerCaseChar(); @Override char randUpperCaseChar(); @Override char randChar(); @Override List<Character> randLowerCaseChars(int num); @Override List<Character> randUpperCaseChars(int num); @Override List<Character> randChars(int num); @Override int randInt(int lowBound, int upBound); @Override List<Integer> randIntegers(int lowBount, int upBount, int length); @Override String randString(int charCount, int intCount, boolean mustSeartWithAlph); @Override List<String> randStrings(int size, int alphNum, int digitNum, boolean mustStartWithAlph); @Override double randDouble(double lowBound, double upBound); @Override List<Double> randDoubles(int size, double lowBound, double upBound); @Override boolean randBoolean(); }### Answer:
@Test public void randDoubles() { int size = 1000; int low = 0; int high = 10; List<Double> list = randomGenerator.randDoubles(size, low, high); list.forEach(d -> assertTrue(d >= low && d < high)); } |
### Question:
ObservationDownloader { static String longestObservation(List<Observation> observations) { if (observations.isEmpty()) { throw new IllegalArgumentException("Empty list error!"); } String longest = null; int size = 0; for (Observation observation : observations) { String current = jsonParser.setPrettyPrint(true).encodeResourceToString(observation).trim(); if ((observation.hasValueQuantity() || observation.hasValueCodeableConcept()) && current.length() > size) { System.out.printf("Found a larger observation\ncurrent observation size : %d\n already found size: %d\n", current.length(), size); size = current.length(); longest = current; } } return longest; } static void iteratorHapiFHIRServer(); }### Answer:
@Test @Disabled("same as above, can fail when server changes") public void longestObservation() throws Exception { String testLoinc = "600-7"; String longestObservation = ObservationDownloader.longestObservation(ObservationDownloader.retrieveObservation(testLoinc)); if (longestObservation != null) { System.out.println(longestObservation); } } |
### Question:
Loinc2Hpo { public HpoTerm4TestOutcome query(LoincId loincId, Code testResult) throws AnnotationNotFoundException, LoincCodeNotAnnotatedException { if (!this.annotationMap.containsKey(loincId)) { throw new LoincCodeNotAnnotatedException(); } if (!this.annotationMap.get(loincId).getCandidateHpoTerms().containsKey(testResult)){ throw new AnnotationNotFoundException(); } return this.annotationMap.get(loincId).getCandidateHpoTerms().get(testResult); } Loinc2Hpo(Map<LoincId, Loinc2HpoAnnotationModel> annotationMap,
CodeSystemConvertor converter); Loinc2Hpo(String path, CodeSystemConvertor converter); Map<LoincId, Loinc2HpoAnnotationModel> getAnnotationMap(); CodeSystemConvertor getConverter(); Code convertToInternal(Code original); HpoTerm4TestOutcome query(LoincId loincId, Code testResult); HpoTerm4TestOutcome query(LoincId loincId, String system, String id); }### Answer:
@Test public void queryWithInterpretationCode() throws Exception { LoincId loincId = new LoincId("2823-3"); Code low = new Code().setSystem("FHIR").setCode("L"); HpoTerm4TestOutcome hpo_coded_phenotype = loinc2Hpo.query(loincId, low); assertFalse(hpo_coded_phenotype.isNegated()); assertEquals(hpo_coded_phenotype.getId().getValue(), "HP:0002900"); Code normal = new Code().setSystem("FHIR").setCode("N"); hpo_coded_phenotype = loinc2Hpo.query(loincId, normal); assertTrue(hpo_coded_phenotype.isNegated()); assertEquals(hpo_coded_phenotype.getId().getValue(), "HP:0011042"); loincId = new LoincId("2349-9"); Code positive = new Code().setSystem("FHIR").setCode("POS"); hpo_coded_phenotype = loinc2Hpo.query(loincId, positive); assertFalse(hpo_coded_phenotype.isNegated()); assertEquals(hpo_coded_phenotype.getId().getValue(), "HP:0003076"); Code negative = new Code().setSystem("FHIR").setCode("NEG"); hpo_coded_phenotype = loinc2Hpo.query(loincId, negative); assertTrue(hpo_coded_phenotype.isNegated()); assertEquals(hpo_coded_phenotype.getId().getValue(), "HP:0003076"); loincId = new LoincId("5778-6"); Code snomed_code = new Code().setSystem("snomed-ct").setCode("449071000124107"); hpo_coded_phenotype = loinc2Hpo.query(loincId, snomed_code); assertFalse(hpo_coded_phenotype.isNegated()); assertEquals(hpo_coded_phenotype.getId().getValue(), "HP:0032001"); }
@Test public void queryWithStrings() throws Exception { LoincId loincId = new LoincId("2823-3"); String system = "FHIR"; String codeLow = "L"; assertEquals(loinc2Hpo.query(loincId, system, codeLow).getId().getValue(), "HP:0002900"); } |
### Question:
BagOfTermsWithFrequencies implements InferWithHPOHierarchy { public void addTerm(TermId termId, int count) { if (termCounts.containsKey(termId)) { termCounts.put(termId, termCounts.get(termId) + count); } else { termCounts.put(termId, count); } } BagOfTermsWithFrequencies(String patientId, Ontology hpo); BagOfTermsWithFrequencies(String patientId, Map<TermId, Integer> termCounts, Ontology hpo); void addTerm(TermId termId, int count); String getPatientId(); Map<TermId, Integer> getOriginalTermCounts(); Map<TermId, Integer> getInferredTermCounts(); @Override void infer(); @Override String toString(); }### Answer:
@Test public void addTerm() { assertNotNull(hpo); BagOfTermsWithFrequencies bag1 = new BagOfTermsWithFrequencies(patientId, hpo); assertNotNull(bag1); bag1.addTerm(TermId.of(HP_PREFIX, "0003074"), 5); assertEquals(bag1.getOriginalTermCounts().size(), 1); bag1.addTerm(TermId.of(HP_PREFIX, "0011297"), 1); assertEquals(bag1.getOriginalTermCounts().size(), 2); bag1.addTerm(TermId.of(HP_PREFIX, "0040064"), 1); assertEquals(bag1.getOriginalTermCounts().size(), 3); } |
### Question:
BagOfTermsWithFrequencies implements InferWithHPOHierarchy { @Override public void infer() { this.inferred = new LinkedHashMap<>(termCounts); termCounts.entrySet().forEach(entry -> { Set<TermId> ancesstors = OntologyAlgorithm.getAncestorTerms(hpo, entry.getKey(), false); ancesstors.forEach(t -> { inferred.putIfAbsent(t, 0); inferred.put(t, inferred.get(t) + entry.getValue()); }); }); } BagOfTermsWithFrequencies(String patientId, Ontology hpo); BagOfTermsWithFrequencies(String patientId, Map<TermId, Integer> termCounts, Ontology hpo); void addTerm(TermId termId, int count); String getPatientId(); Map<TermId, Integer> getOriginalTermCounts(); Map<TermId, Integer> getInferredTermCounts(); @Override void infer(); @Override String toString(); }### Answer:
@Test public void infer() { assertNotNull(hpo); BagOfTermsWithFrequencies bag1 = new BagOfTermsWithFrequencies(patientId, hpo); assertNotNull(bag1); bag1.addTerm(TermId.of(HP_PREFIX, "0003074"), 5); assertEquals(bag1.getOriginalTermCounts().size(), 1); bag1.addTerm(TermId.of(HP_PREFIX, "0011297"), 3); bag1.addTerm(TermId.of(HP_PREFIX, "0040064"), 1); assertEquals(bag1.getOriginalTermCounts().size(), 3); bag1.infer(); Map<TermId, Integer> inferred = bag1.getInferredTermCounts(); TermId all = TermId.of(HP_PREFIX, "0000001"); assertEquals(inferred.get(all).longValue(), 9); TermId phenotypicAbnormality = TermId.of(HP_PREFIX, "0000118"); assertEquals(inferred.get(phenotypicAbnormality).longValue(), 9); TermId abnormalityOfLimbs = TermId.of(HP_PREFIX, "0040064"); assertEquals(inferred.get(abnormalityOfLimbs).longValue(), 4); TermId abnormalGlucoseHomeostasis = TermId.of(HP_PREFIX, "0011014"); assertEquals(inferred.get(abnormalGlucoseHomeostasis).longValue(), 5); } |
### Question:
BagOfTerms implements InferWithHPOHierarchy { public String getPatient() { return this.patient; } BagOfTerms(String patient, Ontology hp); BagOfTerms(String patient, Set<TermId> hpterms, Ontology hp); String getPatient(); Set<TermId> getOriginalTerms(); Set<TermId> getInferedTerms(); void addTerm(TermId term); @Override void infer(); }### Answer:
@Test public void getPatient() { BagOfTerms patient1 = new BagOfTerms(patientId, hpo); assertEquals(patient1.getPatient(), patientId); } |
### Question:
BagOfTerms implements InferWithHPOHierarchy { public Set<TermId> getOriginalTerms() { return new LinkedHashSet<>(this.terms); } BagOfTerms(String patient, Ontology hp); BagOfTerms(String patient, Set<TermId> hpterms, Ontology hp); String getPatient(); Set<TermId> getOriginalTerms(); Set<TermId> getInferedTerms(); void addTerm(TermId term); @Override void infer(); }### Answer:
@Test public void getOriginalTerms() { BagOfTerms patient1 = new BagOfTerms(patientId, hpo); assertEquals(patient1.getOriginalTerms().size(), 0); patient1.addTerm(TermId.of(HP_PREFIX, "0003074")); assertEquals(patient1.getOriginalTerms().size(), 1); patient1.addTerm(TermId.of(HP_PREFIX, "0011297")); assertEquals(patient1.getOriginalTerms().size(), 2); } |
### Question:
BagOfTerms implements InferWithHPOHierarchy { public Set<TermId> getInferedTerms() { return new LinkedHashSet<>(this.terms_inferred); } BagOfTerms(String patient, Ontology hp); BagOfTerms(String patient, Set<TermId> hpterms, Ontology hp); String getPatient(); Set<TermId> getOriginalTerms(); Set<TermId> getInferedTerms(); void addTerm(TermId term); @Override void infer(); }### Answer:
@Test public void getInferedTerms() { BagOfTerms patient1 = new BagOfTerms(patientId, hpo); patient1.addTerm(TermId.of(HP_PREFIX, "0003074")); patient1.addTerm(TermId.of(HP_PREFIX, "0011297")); assertEquals(patient1.getInferedTerms().size(), 0); } |
### Question:
LoincId implements Serializable { @Override @JsonValue public String toString() { return String.format("%d-%d",num,suffix); } LoincId(String loinccode); LoincId(String loinccode, boolean hasPrefix); @Override boolean equals(Object o); @Override int hashCode(); @Override @JsonValue String toString(); }### Answer:
@Test public void testConstructor() throws MalformedLoincCodeException { String code = "15074-8"; LoincId id = new LoincId(code); assertEquals(code,id.toString()); }
@Test public void testConstructor2() throws MalformedLoincCodeException { String code = "3141-9"; LoincId id = new LoincId(code); assertEquals(code,id.toString()); }
@Test public void testBadCode() { Assertions.assertThrows(MalformedLoincCodeException.class, () -> { String code = "15074-"; LoincId id = new LoincId(code); assertEquals(code,id.toString()); }); }
@Test public void testBadCode2() throws MalformedLoincCodeException { Assertions.assertThrows(MalformedLoincCodeException.class, () -> { String code = "1507423"; LoincId id = new LoincId(code); assertEquals(code, id.toString()); }); } |
### Question:
Settings { public static Settings loadSettings(Settings settings, String settingsPath) throws IOException { BufferedReader br = new BufferedReader(new FileReader(settingsPath)); String line = null; while ((line = br.readLine()) != null) { int idx=line.indexOf(":"); if (idx<0) { logger.error("Malformed settings line (no semicolon): "+line); } if (line.length()<idx+2) { logger.error("Malformed settings line (value too short): "+line); } String key,value; key=line.substring(0,idx).trim(); value=line.substring(idx+1).trim(); if (key.equals("biocuratorid")) settings.setBiocuratorID(value); else if (key.equals("loincTablePath")) settings.setLoincCoreTablePath(value); else if (key.equals("hp-obo")) settings.setHpoOboPath(value); else if (key.equals("hp-owl")) settings.setHpoOwlPath(value); else if (key.equals("autosave to")) settings.setAnnotationFolder(value); else if (key.equals("loinc-list-color")) { String[] entries = value.split("\\|"); settings.setUserCreatedLoincListsColor( Arrays.stream(entries) .map(e -> e.split(",")) .collect(Collectors.toMap(e -> e[0], e -> e[1]))); } } br.close(); return settings; } Settings(); Settings(String hpoOboPath, String hpoOwlPath, String loincCoreTablePath, String annotationFolder, String biocuratorID, Map<String, String> userCreatedLoincListsColor); static Settings loadSettings(Settings settings, String settingsPath); static void writeSettings(Settings settings, String path); static Logger getLogger(); static void setLogger(Logger logger); String getHpoOboPath(); StringProperty hpoOboPathProperty(); void setHpoOboPath(String hpoOboPath); String getHpoOwlPath(); StringProperty hpoOwlPathProperty(); void setHpoOwlPath(String hpoOwlPath); String getLoincCoreTablePath(); StringProperty loincCoreTablePathProperty(); void setLoincCoreTablePath(String loincCoreTablePath); String getAnnotationFolder(); StringProperty annotationFolderProperty(); void setAnnotationFolder(String annotationFolder); String getBiocuratorID(); StringProperty biocuratorIDProperty(); void setBiocuratorID(String biocuratorID); Map<String, String> getUserCreatedLoincListsColor(); void setUserCreatedLoincListsColor(Map<String, String> userCreatedLoincListsColor); BooleanProperty isCompleteProperty(); boolean status(); String toString(); }### Answer:
@Test public void loadSettings() throws Exception { Settings.loadSettings(settings, settingsPath); System.out.println(settings.getAnnotationFolder()); System.out.println(settings.getBiocuratorID()); System.out.println(settings.getHpoOboPath()); System.out.println(settings.getHpoOwlPath()); System.out.println(settings.getLoincCoreTablePath()); System.out.println(settings.getUserCreatedLoincListsColor()); System.out.println(System.getProperty("user.home")); } |
### Question:
LoincId implements Serializable { @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof LoincId)) { return false; } LoincId other = (LoincId) o; return (this.num==other.num && this.suffix==other.suffix); } LoincId(String loinccode); LoincId(String loinccode, boolean hasPrefix); @Override boolean equals(Object o); @Override int hashCode(); @Override @JsonValue String toString(); }### Answer:
@Test public void testEquals()throws MalformedLoincCodeException { String code1="19048-8"; String code2="19048-8"; LoincId id1=new LoincId(code1); LoincId id2=new LoincId(code2); assertEquals(id1,id2); } |
### Question:
CodeSystemConvertor { public Code convertToInternalCode(Code code) throws InternalCodeNotFoundException { if (!this.codeConversionmap.containsKey(code)) { throw new InternalCodeNotFoundException("Could not find an internal code that match to: " + code.getSystem() + " " + code.getCode()); } return this.codeConversionmap.get(code); } CodeSystemConvertor(); void addCodeConversionMap(Map<Code, Code> newMap); Code convertToInternalCode(Code code); Map<Code, Code> getCodeConversionmap(); }### Answer:
@Test public void convertToInternalCode() throws Exception { CodeSystemConvertor codeSystemConvertor = new CodeSystemConvertor(); Code v2 = Code.getNewCode().setSystem("http: Code internal = codeSystemConvertor.convertToInternalCode(v2); assertEquals(InternalCodeSystem.SYSTEMNAME, internal.getSystem()); assertEquals("POS", internal.getCode()); assertEquals("present", internal.getDisplay()); Code v2_1 = Code.getNewCode().setSystem("http: Code internal2 = codeSystemConvertor.convertToInternalCode(v2_1); assertEquals(InternalCodeSystem.SYSTEMNAME, internal2.getSystem()); assertNotEquals("N", internal2.getCode()); assertNotEquals("normal", internal2.getDisplay()); Code v2_2 = Code.getNewCode().setSystem("http: Code internal3 = codeSystemConvertor.convertToInternalCode(v2_2); assertEquals(InternalCodeSystem.SYSTEMNAME, internal2.getSystem()); assertNotEquals("POS", internal2.getCode()); assertNotEquals("present", internal2.getDisplay()); Code v2_3 = Code.getNewCode().setSystem("http: Code internal4 = codeSystemConvertor.convertToInternalCode(v2_3); assertEquals(InternalCodeSystem.SYSTEMNAME, internal2.getSystem()); assertEquals("A", internal2.getCode()); assertEquals("abnormal", internal2.getDisplay()); } |
### Question:
Code implements Serializable { public String getCode() { return code; } Code(); Code(String system, String code, String display); Code(Code otherCode); Code(Coding coding); static Code getNewCode(); String getSystem(); Code setSystem(String system); String getCode(); Code setCode(String code); String getDisplay(); Code setDisplay(String display); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getCode() throws Exception { Code code = new Code(); code.setCode("H"); assertNotNull(code.getCode()); assertEquals("H", code.getCode()); } |
### Question:
Code implements Serializable { public String getDisplay() { return display; } Code(); Code(String system, String code, String display); Code(Code otherCode); Code(Coding coding); static Code getNewCode(); String getSystem(); Code setSystem(String system); String getCode(); Code setCode(String code); String getDisplay(); Code setDisplay(String display); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getDisplay() { Code code = new Code(); code.setDisplay("above normal"); assertNotNull(code.getDisplay()); assertEquals("above normal", code.getDisplay()); } |
### Question:
Code implements Serializable { @Override public boolean equals(Object obj){ if (obj instanceof Code) { Code other = (Code) obj; return other.getSystem().equals(this.system) && other.getCode().equals(this.code); } return false; } Code(); Code(String system, String code, String display); Code(Code otherCode); Code(Coding coding); static Code getNewCode(); String getSystem(); Code setSystem(String system); String getCode(); Code setCode(String code); String getDisplay(); Code setDisplay(String display); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void equals() { Code code1 = Code.getNewCode().setSystem("http: Code code2 = Code.getNewCode().setSystem("http: assertEquals(code1, code2); Code code3 = Code.getNewCode().setSystem("http: assertEquals(code1, code3); Code code4 = Code.getNewCode().setSystem("http: assertNotEquals(code1, code4); Code code5 = Code.getNewCode().setSystem("http: assertNotEquals(code1, code5); Code code6 = Code.getNewCode().setSystem("http: assertEquals(code1, code6); } |
### Question:
Code implements Serializable { @Override public int hashCode(){ return system.hashCode() + code.hashCode()*37; } Code(); Code(String system, String code, String display); Code(Code otherCode); Code(Coding coding); static Code getNewCode(); String getSystem(); Code setSystem(String system); String getCode(); Code setCode(String code); String getDisplay(); Code setDisplay(String display); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testhashCode() { Code code1 = Code.getNewCode().setSystem("http: Code code2 = Code.getNewCode().setSystem("http: assertEquals(code1.hashCode(), code2.hashCode()); Code code3 = Code.getNewCode().setSystem("http: assertEquals(code1.hashCode(), code3.hashCode()); Code code4 = Code.getNewCode().setSystem("http: assertNotEquals(code1.hashCode(), code4.hashCode()); Code code5 = Code.getNewCode().setSystem("http: assertNotEquals(code1.hashCode(), code5.hashCode()); Code code6 = Code.getNewCode().setSystem("http: assertEquals(code1.hashCode(), code6.hashCode()); } |
### Question:
Code implements Serializable { @Override public String toString(){ String toString = String.format("System: %s; Code: %s, Display: %s", system, code, display); return toString; } Code(); Code(String system, String code, String display); Code(Code otherCode); Code(Coding coding); static Code getNewCode(); String getSystem(); Code setSystem(String system); String getCode(); Code setCode(String code); String getDisplay(); Code setDisplay(String display); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testtoString() { Code code1 = Code.getNewCode().setSystem("http: assertEquals("System: http: } |
### Question:
PhenoSetUnionFind { public UnionFind<TermId> getUnionFind() { return this.unionFind; } PhenoSetUnionFind(Set<TermId> hpoTermSet, Map<LoincId, Loinc2HpoAnnotationModel> annotationMap); UnionFind<TermId> getUnionFind(); }### Answer:
@Test public void checkDataStructureSetUpCorrectly() { Term term1 = hpoTermMap.get("Hypocapnia"); Term term2 = hpoTermMap.get("Hypercapnia"); assertTrue(unionFind.getUnionFind().inSameSet(term1.getId(), term2.getId())); Term term3 = hpoTermMap.get("Nitrituria"); assertFalse(unionFind.getUnionFind().inSameSet(term1.getId(), term3.getId())); } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public PhenoSet phenoset() { return this.phenoset; } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void phenoset() { assertEquals(2, glucosetimeLine.phenoset().getSet().size()); } |
### Question:
Settings { public static void writeSettings(Settings settings, String path) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(path)); String biocuratorID = settings.getBiocuratorID(); String pathToLoincCoreTableFile = settings.getLoincCoreTablePath(); String pathToHpoOboFile = settings.getHpoOboPath(); String pathToHpoOwlFile = settings.getHpoOwlPath(); String pathToAutoSavedFolder = settings.getAnnotationFolder(); Map<String, String> userCreatedLoincListsColor = settings.getUserCreatedLoincListsColor(); if (biocuratorID!=null) { bw.write(String.format("biocuratorid:%s\n",biocuratorID)); } if (pathToLoincCoreTableFile!=null) { bw.write(String.format("loincTablePath:%s\n",pathToLoincCoreTableFile)); } if (pathToHpoOboFile!=null) { bw.write(String.format("hp-obo:%s\n",pathToHpoOboFile)); } if (pathToHpoOwlFile!= null) { bw.write(String.format("hp-owl:%s\n", pathToHpoOwlFile)); } if (pathToAutoSavedFolder != null) { bw.write(String.format("autosave to:%s\n", pathToAutoSavedFolder)); } if (!userCreatedLoincListsColor.isEmpty()) { bw.write("loinc-list-color:"); List<String> list_color_pair = userCreatedLoincListsColor.entrySet().stream() .map(e -> e.getKey() + "," + e.getValue()) .collect(Collectors.toList()); bw.write(String.join("|", list_color_pair)); bw.write("\n"); } bw.close(); } catch (IOException e) { e.printStackTrace(); logger.error("Could not write settings at " + path); } } Settings(); Settings(String hpoOboPath, String hpoOwlPath, String loincCoreTablePath, String annotationFolder, String biocuratorID, Map<String, String> userCreatedLoincListsColor); static Settings loadSettings(Settings settings, String settingsPath); static void writeSettings(Settings settings, String path); static Logger getLogger(); static void setLogger(Logger logger); String getHpoOboPath(); StringProperty hpoOboPathProperty(); void setHpoOboPath(String hpoOboPath); String getHpoOwlPath(); StringProperty hpoOwlPathProperty(); void setHpoOwlPath(String hpoOwlPath); String getLoincCoreTablePath(); StringProperty loincCoreTablePathProperty(); void setLoincCoreTablePath(String loincCoreTablePath); String getAnnotationFolder(); StringProperty annotationFolderProperty(); void setAnnotationFolder(String annotationFolder); String getBiocuratorID(); StringProperty biocuratorIDProperty(); void setBiocuratorID(String biocuratorID); Map<String, String> getUserCreatedLoincListsColor(); void setUserCreatedLoincListsColor(Map<String, String> userCreatedLoincListsColor); BooleanProperty isCompleteProperty(); boolean status(); String toString(); }### Answer:
@Test public void writeSettings() throws Exception { } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public List<PhenotypeComponent> getTimeLine() { return new LinkedList<>(this.phenosetTimeLine); } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void getTimeLine() { assertEquals(4, glucosetimeLine.getTimeLine().size()); } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public void insert(PhenotypeComponent newAbnorm) { phenoset.add(newAbnorm.abnormality()); if (this.phenosetTimeLine.isEmpty()) { phenosetTimeLine.add(newAbnorm); return; } for (int i = 0; i < phenosetTimeLine.size(); i++) { PhenotypeComponent current = phenosetTimeLine.get(i); if (current.effectiveStart().after(newAbnorm.effectiveStart())) { newAbnorm.changeEffectiveEnd(current.effectiveStart()); phenosetTimeLine.add(i, newAbnorm); break; } if (current.effectiveEnd().after(newAbnorm.effectiveStart())){ current.changeEffectiveEnd(newAbnorm.effectiveStart()); if (i != phenosetTimeLine.size() - 1) { newAbnorm.changeEffectiveEnd(phenosetTimeLine.get(i + 1).effectiveStart()); } phenosetTimeLine.add(i + 1, newAbnorm); break; } } messageTimeLine(); return; } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void insert() throws Exception { } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public PhenotypeComponent current(Date date) { for (PhenotypeComponent current : this.phenosetTimeLine) { if (current.isEffective(date)) { return current; } } return null; } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void current() throws Exception { assertEquals(hypoglycemia.getId(), glucosetimeLine.current(dateFormat.parse( "2016-12-30 10:33:33")).abnormality()); assertEquals(hypoglycemia.getId(), glucosetimeLine.current(dateFormat.parse( "2017-12-30 10:33:33")).abnormality()); } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public PhenotypeComponent persistDuring(Date start, Date end) { for (PhenotypeComponent component : this.phenosetTimeLine) { if (component.isPersistingDuring(start, end)) { return component; } } return null; } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void persistDuring() throws Exception { Date date1 = dateFormat.parse("2017-06-20 10:33:33"); Date date2 = dateFormat.parse("2017-06-30 10:33:33"); Date date3 = dateFormat.parse("2017-10-30 10:33:33"); assertNotNull(glucosetimeLine.persistDuring(date1, date2)); assertNull(glucosetimeLine.persistDuring(date2, date3)); assertEquals(hypoglycemia.getId(), glucosetimeLine.persistDuring(date1, date2).abnormality()); } |
### Question:
PhenoSetTimeLineImpl implements PhenoSetTimeLine { @Override public List<PhenotypeComponent> occurredDuring(Date start, Date end) { return this.phenosetTimeLine.stream() .filter(p -> p.occurredDuring(start, end)) .collect(Collectors.toList()); } PhenoSetTimeLineImpl(PhenoSet phenoset); @Override PhenoSet phenoset(); @Override List<PhenotypeComponent> getTimeLine(); @Override void insert(PhenotypeComponent newAbnorm); @Override PhenotypeComponent current(Date date); @Override PhenotypeComponent persistDuring(Date start, Date end); @Override List<PhenotypeComponent> occurredDuring(Date start, Date end); }### Answer:
@Test public void occurredDuring() throws Exception { Date date0 = dateFormat.parse("2000-10-30 10:33:33"); Date date1 = dateFormat.parse("2017-06-20 10:33:33"); Date date2 = dateFormat.parse("2017-06-30 10:33:33"); Date date3 = dateFormat.parse("2017-10-30 10:33:33"); Date date4 = dateFormat.parse("2017-10-30 10:33:33"); Date date5 = dateFormat.parse("2019-10-30 10:33:33"); assertNotNull(glucosetimeLine.occurredDuring(date0, date5)); assertEquals(4, glucosetimeLine.occurredDuring(date0, date5).size()); assertEquals(1, glucosetimeLine.occurredDuring(date0, date1).size()); assertEquals(2, glucosetimeLine.occurredDuring(date0, date3).size()); } |
### Question:
PhenoSetImpl implements PhenoSet { @Override public boolean sameSet(TermId term) { if (termSet.isEmpty()) { return false; } else { return this.hpoTermUnionFind.inSameSet(term, termSet.iterator().next()); } } PhenoSetImpl(UnionFind<TermId> hpoTermUnionFind); @Override Set<TermId> getSet(); @Override boolean sameSet(TermId term); @Override boolean hasOccurred(TermId term); @Override void add(TermId hpoTerm); }### Answer:
@Test public void sameSet() { assertFalse(phenoSet.sameSet(hypocapnia.getId())); phenoSet.add(hypercapnia.getId()); assertTrue(phenoSet.sameSet(hypocapnia.getId())); } |
### Question:
PhenoSetImpl implements PhenoSet { @Override public boolean hasOccurred(TermId term) { return !this.termSet.isEmpty() && this.termSet.contains(term); } PhenoSetImpl(UnionFind<TermId> hpoTermUnionFind); @Override Set<TermId> getSet(); @Override boolean sameSet(TermId term); @Override boolean hasOccurred(TermId term); @Override void add(TermId hpoTerm); }### Answer:
@Test public void hasOccurred() { assertFalse(phenoSet.hasOccurred(hypocapnia.getId())); phenoSet.add(hypocapnia.getId()); assertTrue(phenoSet.hasOccurred(hypocapnia.getId())); assertFalse(phenoSet.hasOccurred(hypercapnia.getId())); phenoSet.add(hypercapnia.getId()); assertTrue(phenoSet.hasOccurred(hypercapnia.getId())); } |
### Question:
PatientSummaryImpl implements PatientSummary { @Override public Patient patient() { return this.patient; } PatientSummaryImpl(Patient patient, UnionFind<TermId> hpoTermUnionFind); @Override Patient patient(); @Override void addTest(LabTest test); @Override void addTest(List<LabTest> tests); @Override List<LabTest> tests(); @Override List<PhenoSetTimeLine> timeLines(); @Override List<PhenotypeComponent> phenoAt(Date timepoint); @Override List<PhenotypeComponent> phenoPersistedDuring(Date start, Date end); @Override List<PhenotypeComponent> phenoOccurredDuring(Date start, Date end); @Override List<PhenotypeComponent> phenoSinceBorn(); }### Answer:
@Test public void patient() { assertNotNull(patientSummary.patient()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.