method2testcases
stringlengths
118
3.08k
### 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: 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: 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: 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: 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()); }
### Question: PatientSummaryImpl implements PatientSummary { @Override public List<PhenotypeComponent> phenoAt(Date timepoint) { return phenoSetTimeLines.stream() .map(timeLine -> timeLine.current(timepoint)) .collect(Collectors.toList()); } 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 phenoAt() throws Exception { LabTest test2 = new LabTestImpl.Builder() .effectiveStart(dateFormat.parse("2017-10-20 10:30:00")) .loincId(new LoincId("15074-7")) .outcome(new HpoTerm4TestOutcome(hypoglycemia.getId(), false)) .patient(patient) .resourceId("unknown resource id") .build(); patientSummary.addTest(test2); assertEquals(3, patientSummary.tests().size()); assertEquals(2, patientSummary.timeLines().size()); }
### Question: PatientSummaryImpl implements PatientSummary { @Override public List<PhenotypeComponent> phenoPersistedDuring(Date start, Date end) { return phenoSetTimeLines.stream() .map(timeline -> timeline.persistDuring(start, end)) .collect(Collectors.toList()); } 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 phenoPersistedDuring() throws Exception { LabTest test2 = new LabTestImpl.Builder() .effectiveStart(dateFormat.parse("2017-10-20 10:30:00")) .loincId(new LoincId("15074-7")) .outcome(new HpoTerm4TestOutcome(hypoglycemia.getId(), false)) .patient(patient) .resourceId("unknown resource id") .build(); patientSummary.addTest(test2); assertEquals(2, patientSummary.phenoPersistedDuring(dateFormat.parse("2016-10-22 10:00:00"), dateFormat.parse("2016-12-31 00:00:00")).size()); }
### Question: GitHubPopup { public String retrieveSuggestedTerm() { String newTerm = "UNKNOWN"; try { String[] lineElements = githubIssueText.split("\n")[1].split(":"); if (lineElements.length == 2) { newTerm = lineElements[1].trim(); } } catch (Exception e) { } return newTerm; } GitHubPopup(LoincEntry loincEntry); GitHubPopup(LoincEntry loincEntry, Term term, boolean childterm); void setLabels(List<String> labels); void displayWindow(Stage ownerWindow); void setupGithubUsernamePassword(String ghuname, String ghpword); boolean wasCancelled(); void setGithubIssueText(String githubIssueText); String retrieveGitHubIssue(); String retrieveSuggestedTerm(); String getGitHubUserName(); String getGitHubPassWord(); @Deprecated String getGitHubLabel(); List<String> getGitHubLabels(); void setBiocuratorId(String id); }### Answer: @Test public void retrieveSuggestedTerm() throws Exception { String issue = "Suggest creating a new child term of %s [%s] for Loinc %s [%s]\n" + "New term label:\n" + "New term comment (if any):\n" + "Your biocurator ID for loinc2hpo (if desired): %s"; GitHubPopup popup = new GitHubPopup(null); popup.setGithubIssueText(issue); assertEquals("UNKNOWN", popup.retrieveSuggestedTerm()); }
### Question: PatientSummaryImpl implements PatientSummary { @Override public List<PhenotypeComponent> phenoSinceBorn() { List<PhenotypeComponent> patientPhenotypes = new ArrayList<>(); phenoSetTimeLines.forEach(timeLine -> patientPhenotypes.addAll(timeLine.getTimeLine())); return patientPhenotypes; } 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 phenoSinceBorn() throws Exception { LabTest test2 = new LabTestImpl.Builder() .effectiveStart(dateFormat.parse("2017-10-20 10:30:00")) .loincId(new LoincId("15074-7")) .outcome(new HpoTerm4TestOutcome(hypoglycemia.getId(), false)) .patient(patient) .resourceId("unknown resource id") .build(); patientSummary.addTest(test2); assertEquals(3, patientSummary.phenoSinceBorn().size()); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public Date effectiveStart() { return this.start; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void effectiveStart() throws Exception { assertEquals("2016-09-30 09:30:00", dateFormat.format(testComponent.effectiveStart())); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public Date effectiveEnd() { return this.end; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void effectiveEnd() throws Exception { assertTrue(testComponent.effectiveStart().before(testComponent.effectiveEnd())); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public boolean isEffective(Date timepoint) { if (timepoint.before(start) || timepoint.after(end)) { return false; } return true; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void isEffective() throws Exception { assertFalse(testComponent.isEffective(dateFormat.parse("2016-09-29 10:00:00"))); assertTrue(testComponent.isEffective(dateFormat.parse("2016-09-30 09:30:00"))); assertTrue(testComponent.isEffective(dateFormat.parse("2016-09-30 09:30:01"))); assertTrue(testComponent.isEffective(dateFormat.parse("2016-09-30 10:30:00"))); assertTrue(testComponent.isEffective(dateFormat.parse("2020-09-30 09:30:01"))); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public TermId abnormality() { return this.hpoTerm; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void abnormality() throws Exception { assertEquals(hyperglycemia.getId(), testComponent.abnormality()); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public boolean isNegated() { return this.isNegated; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void isNegated() throws Exception { assertFalse(testComponent.isNegated()); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public void changeEffectiveStart(Date start) { this.start = start; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void changeEffectiveStart() throws Exception { assertTrue(testComponent.isEffective(dateFormat.parse("2016-09-30 09:30:01"))); testComponent.changeEffectiveStart(dateFormat.parse("2016-09-30 10:30:01")); assertFalse(testComponent.isEffective(dateFormat.parse("2016-09-30 09:30:01"))); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public void changeEffectiveEnd(Date end) { this.end = end; } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void changeEffectiveEnd() throws Exception { assertTrue(testComponent.isEffective(dateFormat.parse("2020-09-30 09:30:01"))); testComponent.changeEffectiveEnd(dateFormat.parse("2018-09-30 09:30:01")); assertFalse(testComponent.isEffective(dateFormat.parse("2020-09-30 09:30:01"))); }
### Question: PhenotypeComponentImpl implements PhenotypeComponent { @Override public boolean occurredDuring(Date start, Date end) { return !(start.after(this.end) || end.before(this.start)); } private PhenotypeComponentImpl(); private PhenotypeComponentImpl(@NotNull Date start, @Nullable Date end, @NotNull TermId hpoTerm, boolean isNegated); @Override Date effectiveStart(); @Override Date effectiveEnd(); @Override boolean isEffective(Date timepoint); @Override boolean isPersistingDuring(Date start, Date end); @Override boolean occurredDuring(Date start, Date end); @Override TermId abnormality(); @Override boolean isNegated(); @Override void changeEffectiveStart(Date start); @Override void changeEffectiveEnd(Date end); }### Answer: @Test public void occurredDuring() throws Exception { Date date00 = dateFormat.parse("2014-09-30 10:33:33"); Date date0 = dateFormat.parse("2016-05-30 10:33:33"); Date date1 = dateFormat.parse("2018-09-30 10:33:33"); Date date2 = dateFormat.parse("2018-10-30 10:33:33"); Date date3 = dateFormat.parse("2018-11-30 10:33:33"); Date date4 = dateFormat.parse("2018-12-30 10:33:33"); testComponent.changeEffectiveEnd(date2); assertFalse(testComponent.occurredDuring(date00, date0)); assertTrue(testComponent.occurredDuring(date0, testComponent.effectiveStart())); assertTrue(testComponent.occurredDuring(date0, date1)); assertTrue(testComponent.occurredDuring(date1, date3)); assertTrue(testComponent.occurredDuring(date2, date3)); assertFalse(testComponent.occurredDuring(date3, date4)); }
### Question: ColorUtils { public static String colorValue(int red, int green, int blue) { return String.format(COLORVALUEFORMAT, red, green, blue); } static String colorValue(int red, int green, int blue); static String colorValue(Color color); }### Answer: @Test public void colorValue() throws Exception { } @Test public void colorValue1() throws Exception { Color color = Color.AQUA; System.out.println(ColorUtils.colorValue(color)); }
### Question: GitHubPoster { public void setLabel(String l) { this.githubLabel = l; reformatPayloadWithLabel(githubLabel); } GitHubPoster(String uname, String passw, String title, String messagebody); String getHttpResponse(); void setLabel(String l); void setLabel(List<String> labels); String debugLabelsArray4Json(); String debugReformatpayloadWithLabel(); void postIssue(); }### Answer: @Test public void testPayload() { GitHubPoster poster = new GitHubPoster(null, null, null, null); List<String> labels = new ArrayList<>(); labels.add("loinc"); labels.add("immunology"); poster.setLabel(labels); }
### Question: RandomGeneratorImpl implements RandomGenerator { @Override public char randLowerCaseChar() { return (char) (rand.nextInt(26) + 'a'); } @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 randLowerCaseChar() throws Exception { int iter = 1000; for (int i = 0; i < iter; i++) { char c = randomGenerator.randLowerCaseChar(); assertTrue(c >= 'a' && c <='z'); } }
### Question: RandomGeneratorImpl implements RandomGenerator { @Override public char randUpperCaseChar() { return (char) (rand.nextInt(26) + 'A'); } @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 randUpperCaseChar() throws Exception { int iter = 1000; for (int i = 0; i < iter; i++) { char c = randomGenerator.randUpperCaseChar(); assertTrue(c >= 'A' && c <='Z'); } }
### Question: CachedSampleVariantProvider implements SampleVariantsProvider { @Override public FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant) { if (genotypeRecordCache.containsKey(variant)) { return genotypeRecordCache.get(variant); } FixedSizeIterable<GenotypeRecord> sampleGenotypeRecords = sampleVariantProvider.getSampleGenotypeRecords(variant); genotypeRecordCache.put(variant, sampleGenotypeRecords); return sampleGenotypeRecords; } CachedSampleVariantProvider(SampleVariantsProvider sampleVariantProvider, int cacheSize); @Override List<Alleles> getSampleVariants(GeneticVariant variant); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); }### Answer: @Test public void getSampleGenotypeRecords() { SampleVariantsProvider sampleVariantProvider = mock(SampleVariantsProvider.class); CachedSampleVariantProvider cachedSampleVariantProvider = new CachedSampleVariantProvider(sampleVariantProvider , 1); GeneticVariant variant = mock(GeneticVariant.class); cachedSampleVariantProvider.getSampleGenotypeRecords(variant); cachedSampleVariantProvider.getSampleGenotypeRecords(variant); verify(sampleVariantProvider, times(1)).getSampleGenotypeRecords(variant); }
### Question: MultiPartGenotypeData extends AbstractRandomAccessGenotypeData { @Override public Map<String, Annotation> getVariantAnnotationsMap() { return variantAnnotationsMap; } MultiPartGenotypeData(Collection<RandomAccessGenotypeData> genotypeDataCollection); MultiPartGenotypeData(RandomAccessGenotypeData... genotypeDataCollection); MultiPartGenotypeData(Set<RandomAccessGenotypeData> genotypeDataCollection); static MultiPartGenotypeData createFromVcfFolder(File vcfFolder, int cacheSize, double minimumPosteriorProbabilityToCall); static MultiPartGenotypeData createFromGenFolder(File genFolder, int cacheSize, double minimumPosteriorProbabilityToCall); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); }### Answer: @Test public void testGetVariantAnnotationsMap() { assertEquals(chr1VarAnnotated.getVariantAnnotationsMap(), expectedVariantAnnotationMap); assertEquals(chr2VarAnnotated.getVariantAnnotationsMap(), expectedVariantAnnotationMap); assertEquals(multiPartVarAnnotated.getVariantAnnotationsMap(), expectedVariantAnnotationMap); }
### Question: MultiPartGenotypeData extends AbstractRandomAccessGenotypeData { @Override public Map<String, SampleAnnotation> getSampleAnnotationsMap() { return sampleAnnotationsMap; } MultiPartGenotypeData(Collection<RandomAccessGenotypeData> genotypeDataCollection); MultiPartGenotypeData(RandomAccessGenotypeData... genotypeDataCollection); MultiPartGenotypeData(Set<RandomAccessGenotypeData> genotypeDataCollection); static MultiPartGenotypeData createFromVcfFolder(File vcfFolder, int cacheSize, double minimumPosteriorProbabilityToCall); static MultiPartGenotypeData createFromGenFolder(File genFolder, int cacheSize, double minimumPosteriorProbabilityToCall); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); }### Answer: @Test public void testGetSampleAnnotationsMap() { assertEquals(chr1SampleAnnotated.getSampleAnnotationsMap(), expectedSampleAnnotationMap); assertEquals(chr2SampleAnnotated.getSampleAnnotationsMap(), expectedSampleAnnotationMap); assertEquals(multiPartSampleAnnotated.getSampleAnnotationsMap(), expectedSampleAnnotationMap); }
### Question: PedFileDriver implements PlinkFileParser, Iterable<PedEntry> { public long getNrOfElements() throws IOException { if (nrElements == -1) nrElements = getNumberOfNonEmptyLines(file, FILE_ENCODING); return nrElements; } PedFileDriver(File pedFile); PedFileDriver(File pedFile, char separator); PedFileDriver(File pedFile, String separators); List<PedEntry> getAllEntries(); @Override Iterator<PedEntry> iterator(); List<PedEntry> getEntries(final long from, final long to); long getNrOfElements(); @Override void close(); void reset(); }### Answer: @Test public void PED_construct() throws Exception { assertEquals(9, pedfd.getNrOfElements()); }
### Question: MapFileDriver implements PlinkFileParser { public long getNrOfElements() throws IOException { if (nrElements == -1) nrElements = getNumberOfNonEmptyLines(file, FILE_ENCODING); return nrElements; } MapFileDriver(File mapFile); MapFileDriver(File mapFile, char separator); MapFileDriver(File mapFile, String separators); List<MapEntry> getEntries(final long from, final long to); List<MapEntry> getAllEntries(); static MapEntry parseEntry(String line, String separators); long getNrOfElements(); @Override void close(); void reset(); }### Answer: @Test public void MAP_construct() throws Exception { assertEquals(10, mapfd.getNrOfElements()); }
### Question: PedMapGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public List<String> getSeqNames() { return new ArrayList<String>(seqNames); } PedMapGenotypeData(String basePath); PedMapGenotypeData(File pedFile, File mapFile); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override List<Alleles> getSampleVariants(GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override Iterator<GeneticVariant> iterator(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); }### Answer: @Test public void getSeqNames() { List<String> seqNames = genotypeData.getSeqNames(); assertNotNull(seqNames); assertEquals(seqNames.size(), 2); assertEquals(seqNames.get(0), "22"); assertEquals(seqNames.get(1), "23"); }
### Question: PedMapGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public List<Sequence> getSequences() { List<Sequence> sequences = new ArrayList<Sequence>(seqNames.size()); for (String seqName : seqNames) { sequences.add(new SimpleSequence(seqName, null, this)); } return sequences; } PedMapGenotypeData(String basePath); PedMapGenotypeData(File pedFile, File mapFile); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override List<Alleles> getSampleVariants(GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override Iterator<GeneticVariant> iterator(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); }### Answer: @Test public void testGetSequences() { List<Sequence> sequences = genotypeData.getSequences(); assertNotNull(sequences); assertEquals(sequences.size(), 2); }
### Question: PedMapGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public List<Sample> getSamples() { return samples; } PedMapGenotypeData(String basePath); PedMapGenotypeData(File pedFile, File mapFile); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override List<Alleles> getSampleVariants(GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override Iterator<GeneticVariant> iterator(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); }### Answer: @Test public void testGetSamples() { List<Sample> samples = genotypeData.getSamples(); assertNotNull(samples); assertEquals(samples.size(), 9); assertEquals(samples.get(0).getId(), "1042"); assertEquals(samples.get(0).getFamilyId(), "F1042"); }
### Question: Statistics { public static double calculateSpearmanTwoTailedPvalue(double spearmanCorrelation, int sampleSize){ double z = Math.sqrt((sampleSize-3)/1.06) * atanh(spearmanCorrelation); NormalDistribution normalDistribution = new NormalDistribution(); double p = 2*normalDistribution.cumulativeProbability(-Math.abs(z)); if (Double.isNaN(z)){ p = 0; } if (Double.isNaN(spearmanCorrelation)){ p = 1; } return p; } static double calculateSpearmanTwoTailedPvalue(double spearmanCorrelation, int sampleSize); static double anova(double sumOfSquaresModelA, double sumOfSquaresModelB, int degreesOfFreedomA, int degreesOfFreedomB, Boolean no_intercept); }### Answer: @Test public void calculateSpearmanTwoTailedPvalueTest() throws Exception { double expectedPval = 1.773084e-06; double observedPval = Statistics.calculateSpearmanTwoTailedPvalue(0.1504121, 1000); assertEquals(expectedPval,observedPval, 0.001); expectedPval = 1; observedPval = Statistics.calculateSpearmanTwoTailedPvalue(0, 1000); assertEquals(expectedPval,observedPval, 0.001); } @Test public void calculateSpearmanTwoTailedPvalueNaNTest() throws Exception { double expectedPval = 0; double observedPval = Statistics.calculateSpearmanTwoTailedPvalue(1000000, 1000); assertEquals(expectedPval,observedPval, 0.001); }
### Question: SmoothSort { public static <C extends Comparable<? super C>> void sort(C[] m) { sortInternaly(m,0,m.length-1); } static void sort(C[] m); static void sort(C[] m, int fromIndex, int toIndex); }### Answer: @Test public void testSort() { Integer[] l1 = { 5, 1024, 1, 88, 0, 1024 }; Integer[] l1c = { 5, 1024, 1, 88, 0, 1024 }; SmoothSort.sort(l1); Arrays.sort(l1c); boolean correct=true; for(int i=0;i<l1.length;i++){ if(!l1[i].equals(l1c[i])){ correct = false; break; } } assertEquals(correct, true); Double[] l3 = { 5.0d, 1024.5d, 1.0d, 88.0d, 0.0d, 1024.0d }; Double[] l3c = { 5.0d, 1024.5d, 1.0d, 88.0d, 0.0d, 1024.0d }; SmoothSort.sort(l3,1,5); Arrays.sort(l3c,1,5); correct=true; for(int i=0;i<l3.length;i++){ if(!l3[i].equals(l3c[i])){ correct = false; break; } } assertEquals(correct, true); String[] l2 = { "gamma", "beta", "alpha", "zoolander" }; String[] l2c = { "gamma", "beta", "alpha", "zoolander" }; SmoothSort.sort(l2); Arrays.sort(l2c); correct=true; for(int i=0;i<l2.length;i++){ if(!l2[i].equals(l2c[i])){ correct = false; break; } } assertEquals(correct, true); }
### Question: GenomicBoundaries implements Iterable<GenomicBoundary<V>> { public Iterator<GenomicBoundary<V>> iterator() { return new GenomicBoundariesIterator<V>(genomicsBoundaries); } GenomicBoundaries(String genomicsBoundarysFilePath); GenomicBoundaries(); GenomicBoundaries(String genomicsBoundarysFilePath, int margin); final void addBoundary(String chromosome, Integer beginPoint, int endPoint); final void removeSubBoundaries(); final void mergeOverlappingBoundaries(); boolean isChromosomeInBoundary(String chromosome); Set<String> getChromosomes(); boolean isInBoundary(String chromosome, int position, int listIndex); GenomicBoundary getBoundary(String chromosome, int position, int listIndex); Iterator<GenomicBoundary<V>> iterator(); int getBoundaryCountChromosome(String chromosome); int getBoudaryCount(); void writeBoundariesToBedFile(String bedFilePath, String trackName); TreeMap<Integer, ArrayList<GenomicBoundary<V>>> getGenomicBoundariesMap(String chromosome); Collection<ArrayList<GenomicBoundary<V>>> getGenomicBoundaries(String chromosome); void mergeGenomicBoundaries(GenomicBoundaries otherGenomicBoundariesSet); HashMap<String, TreeMap<Integer, ArrayList<GenomicBoundary<V>>>> getGenomicBoundaries(); final void addBoundary(String chromosome, Integer beginPoint, int endPoint, V annotation); }### Answer: @Test public void testIterator(){ String chromosome = "1"; Integer beginPoint = 1; int endPoint = 3; GenomicBoundaries<Object> instance = new GenomicBoundaries(); instance.addBoundary(chromosome, 1, 8); instance.addBoundary(chromosome, 2, 11); instance.addBoundary(chromosome, 3, 14); int[] expectedResults = new int[3]; expectedResults[0] = 1; expectedResults[1] = 2; expectedResults[2] = 3; int n=0; }
### Question: GenomicBoundary implements Comparable<GenomicBoundary> { public String getChromosome() { return chromosome; } GenomicBoundary(String chromosome, Integer start, int stop); GenomicBoundary(String chromosome, Integer start, int stop, V annotation); String getChromosome(); Integer getStart(); int getStop(); @Override int compareTo(GenomicBoundary other); boolean isInBoundarie(int position); boolean isInBoundarie(int position, int margin); boolean isPartOfBoundary(GenomicBoundary other); boolean isOverlaping(GenomicBoundary other); V getAnnotation(); int getLength(boolean isInclusive); }### Answer: @Test public void testGetChromosome() { GenomicBoundary instance = new GenomicBoundary("1", 1, 2); String expResult = "1"; String result = instance.getChromosome(); assertEquals(result, expResult); }
### Question: GenomicBoundary implements Comparable<GenomicBoundary> { public Integer getStart() { return start; } GenomicBoundary(String chromosome, Integer start, int stop); GenomicBoundary(String chromosome, Integer start, int stop, V annotation); String getChromosome(); Integer getStart(); int getStop(); @Override int compareTo(GenomicBoundary other); boolean isInBoundarie(int position); boolean isInBoundarie(int position, int margin); boolean isPartOfBoundary(GenomicBoundary other); boolean isOverlaping(GenomicBoundary other); V getAnnotation(); int getLength(boolean isInclusive); }### Answer: @Test public void testGetStart() { GenomicBoundary instance = new GenomicBoundary("1", 1, 2); Integer expResult = 1; Integer result = instance.getStart(); assertEquals(result, expResult); }
### Question: GenomicBoundary implements Comparable<GenomicBoundary> { public int getStop() { return stop; } GenomicBoundary(String chromosome, Integer start, int stop); GenomicBoundary(String chromosome, Integer start, int stop, V annotation); String getChromosome(); Integer getStart(); int getStop(); @Override int compareTo(GenomicBoundary other); boolean isInBoundarie(int position); boolean isInBoundarie(int position, int margin); boolean isPartOfBoundary(GenomicBoundary other); boolean isOverlaping(GenomicBoundary other); V getAnnotation(); int getLength(boolean isInclusive); }### Answer: @Test public void testGetStop() { GenomicBoundary instance = new GenomicBoundary("1", 1, 2); int expResult = 2; int result = instance.getStop(); assertEquals(result, expResult); }
### Question: GenomicBoundary implements Comparable<GenomicBoundary> { public boolean isPartOfBoundary(GenomicBoundary other){ if(other == null){ return false; } return other.start <= this.start && other.stop >= this.stop ? true : false; } GenomicBoundary(String chromosome, Integer start, int stop); GenomicBoundary(String chromosome, Integer start, int stop, V annotation); String getChromosome(); Integer getStart(); int getStop(); @Override int compareTo(GenomicBoundary other); boolean isInBoundarie(int position); boolean isInBoundarie(int position, int margin); boolean isPartOfBoundary(GenomicBoundary other); boolean isOverlaping(GenomicBoundary other); V getAnnotation(); int getLength(boolean isInclusive); }### Answer: @Test public void testIsPartOfBoundary() { GenomicBoundary other = new GenomicBoundary("1", 1, 5); GenomicBoundary instance = new GenomicBoundary("1", 1, 5); boolean expResult = true; boolean result = instance.isPartOfBoundary(other); assertEquals(result, expResult); other = new GenomicBoundary("1", 1, 6); expResult = true; result = instance.isPartOfBoundary(other); assertEquals(result, expResult); other = new GenomicBoundary("1", 1, 4); expResult = false; result = instance.isPartOfBoundary(other); assertEquals(result, expResult); other = new GenomicBoundary("1", 2, 6); expResult = false; result = instance.isPartOfBoundary(other); assertEquals(result, expResult); other = new GenomicBoundary("1", 2, 7); expResult = false; result = instance.isPartOfBoundary(other); assertEquals(result, expResult); }
### Question: PileupEntry { public String getChr() { return chr; } PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, int minimumBaseQuality); PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, String basesQualityString, int minimumBaseQuality); String getChr(); int getPos(); Allele getRefAllele(); int getReadDepth(); TObjectIntHashMap<Allele> getAlleleCounts(); int getAlleleCount(Allele allele); TObjectDoubleHashMap<Allele> getAlleleAverageQualities(); double getAlleleAverageQuality(Allele allele); int getMinimumBaseQuality(); }### Answer: @Test public void testGetChr() { assertEquals(entry1.getChr(), "1"); }
### Question: PileupEntry { public int getPos() { return pos; } PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, int minimumBaseQuality); PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, String basesQualityString, int minimumBaseQuality); String getChr(); int getPos(); Allele getRefAllele(); int getReadDepth(); TObjectIntHashMap<Allele> getAlleleCounts(); int getAlleleCount(Allele allele); TObjectDoubleHashMap<Allele> getAlleleAverageQualities(); double getAlleleAverageQuality(Allele allele); int getMinimumBaseQuality(); }### Answer: @Test public void testGetPos() { assertEquals(entry1.getPos(), 1); }
### Question: PileupEntry { public Allele getRefAllele() { return refAllele; } PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, int minimumBaseQuality); PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, String basesQualityString, int minimumBaseQuality); String getChr(); int getPos(); Allele getRefAllele(); int getReadDepth(); TObjectIntHashMap<Allele> getAlleleCounts(); int getAlleleCount(Allele allele); TObjectDoubleHashMap<Allele> getAlleleAverageQualities(); double getAlleleAverageQuality(Allele allele); int getMinimumBaseQuality(); }### Answer: @Test public void testGetRefAllele() { assertEquals(entry1.getRefAllele(), Allele.G); }
### Question: PileupEntry { public int getReadDepth() { return readDepth; } PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, int minimumBaseQuality); PileupEntry(String chr, int pos, Allele refAllele, int readDepth, String basesString, String basesQualityString, int minimumBaseQuality); String getChr(); int getPos(); Allele getRefAllele(); int getReadDepth(); TObjectIntHashMap<Allele> getAlleleCounts(); int getAlleleCount(Allele allele); TObjectDoubleHashMap<Allele> getAlleleAverageQualities(); double getAlleleAverageQuality(Allele allele); int getMinimumBaseQuality(); }### Answer: @Test public void testGetReadDepth() { assertEquals(entry1.getReadDepth(), 10); }
### Question: ZScores { public static double pToZTwoTailed(double p) { p = p / 2; return pToZ(p); } static double zToR(double z, int n); static double getWeightedZ(float[] zScores, int[] sampleSizes); static double getWeightedZ(double[] zScores, int[] sampleSizes); static double getWeightedZ(float[] zScores, int[] sampleSizes, double[] weights); static double getDatasetSizeWeightedZ(float[] zScores, int[] sampleSizes, double[] weights); static double getWeightedZ(double[] zScores, int[] sampleSizes, double[] weights); static double zToP(double z); static double pToZ(double p); static double pToZTwoTailed(double p); static double correlationToZ(double correlation, int nrSamples, StudentT tDist); static double correlationToP(double correlation, int nrSamples, StudentT tDist); static double zScoreToCorrelation(double obsZ, int nrSamples); static double extrapolateZScore(int originalSampleSize, int newSampleSize, double originalZ); static double betaToZ(double b, double se, double n); static double[] zToBeta(double z, double maf, int n); }### Answer: @Test public void pToZTwoTailed() { assertEquals(ZScores.pToZTwoTailed(0), -40, 0.00000001); assertEquals(ZScores.pToZTwoTailed(1), 0, 0.00000001); assertEquals(ZScores.pToZTwoTailed(1.523971e-23), -10, 0.00001); assertEquals(ZScores.pToZTwoTailed(1e-308), -37.55912122001427, 0.00001); assertEquals(ZScores.pToZTwoTailed(0.04550026), -2, 0.00001); }
### Question: IntervalTree { public ArrayList<E> getElementsOverlappingQuery(final int query) { final ArrayList<E> results = new ArrayList<E>(); rootNode.queryNode(results, query); return results; } IntervalTree(final E[] elements, Class<E> classE); IntervalTree(final List<E> elements, Class<E> classE); ArrayList<E> getElementsOverlappingQuery(final int query); int size(); boolean isEmpty(); }### Answer: @Test public void testGetElementsOverlappingQuery() { ArrayList result = testIntervalTree.getElementsOverlappingQuery(0); assertEquals(result.size(), 2); assertTrue(result.contains(elements.get(0))); assertTrue(result.contains(elements.get(4))); result = testIntervalTree.getElementsOverlappingQuery(2); assertEquals(result.size(), 2); assertTrue(result.contains(elements.get(0))); assertTrue(result.contains(elements.get(4))); result = testIntervalTree.getElementsOverlappingQuery(5); assertEquals(result.size(), 4); assertTrue(result.contains(elements.get(0))); assertTrue(result.contains(elements.get(4))); assertTrue(result.contains(elements.get(1))); assertTrue(result.contains(elements.get(5))); result = testIntervalTree.getElementsOverlappingQuery(10); assertEquals(result.size(), 6); assertTrue(result.contains(elements.get(0))); assertTrue(result.contains(elements.get(4))); assertTrue(result.contains(elements.get(1))); assertTrue(result.contains(elements.get(5))); assertTrue(result.contains(elements.get(2))); assertTrue(result.contains(elements.get(3))); result = testIntervalTree.getElementsOverlappingQuery(11); assertEquals(result.size(), 2); assertTrue(result.contains(elements.get(4))); assertTrue(result.contains(elements.get(2))); result = testIntervalTree.getElementsOverlappingQuery(25); assertEquals(result.size(), 0); result = testIntervalTree.getElementsOverlappingQuery(20); assertEquals(result.size(), 1); assertTrue(result.contains(elements.get(4))); }
### Question: AseMle { protected static double lnbico(final int n, final int k) { if (n < 0 || k < 0 || k > n) { throw new IllegalArgumentException("bad args in bico"); } if (n < 171) { return Math.log(Math.floor(0.5 + factrl(n) / (factrl(k) * factrl(n - k)))); } return factln(n) - factln(k) - factln(n - k); } AseMle(IntArrayList a1Counts, IntArrayList a2Counts); double getMaxLikelihood(); double getMaxLikelihoodP(); double getRatioD(); double getRatioP(); }### Answer: @Test public void testLnBico() { assertEquals(AseMle.lnbico(1369, 689), 945.052036055064, 0.000001); assertEquals(AseMle.lnbico(12345, 6789), 8490.2927640914, 0.000001); assertEquals(AseMle.lnbico(123456, 67890), 84950.948114749, 0.000001); assertEquals(AseMle.lnbico(20, 10), 12.126791314602454, 0.000001); assertEquals(AseMle.lnbico(200, 10), 37.6501117434664266, 0.000001); }
### Question: GenotypeDataCompareTool { public static boolean same(GenotypeData gd1, GenotypeData gd2) { if (gd1.getSamples().equals(gd2.getSamples())) { if (gd1.getVariantAnnotations().equals(gd2.getVariantAnnotations())) { Iterator<GeneticVariant> it1 = gd1.iterator(); Iterator<GeneticVariant> it2 = gd2.iterator(); while (it1.hasNext()) { if (!it2.hasNext()) { return false; } GeneticVariant v1 = it1.next(); GeneticVariant v2 = it2.next(); if (!same(v1, v2)) { return false; } } if (it2.hasNext()) { return false; } else { return true; } } } return false; } static boolean same(GenotypeData gd1, GenotypeData gd2); static boolean same(GeneticVariant v1, GeneticVariant v2); }### Answer: @Test public void testPedMap() throws FileNotFoundException, IOException, URISyntaxException { try { GenotypeData genotypeData1 = new PedMapGenotypeData(getTestPed(), getTestMap()); new PedMapGenotypeWriter(genotypeData1).write("pedmapcomparetest"); GenotypeData genotypeData2 = new PedMapGenotypeData("pedmapcomparetest"); assertTrue(GenotypeDataCompareTool.same(genotypeData1, genotypeData2)); } finally { new File("pedmapcomparetest.ped").delete(); new File("pedmapcomparetest.map").delete(); } }
### Question: Utils { public static <T> List<T> iteratorToList(Iterator<T> iterator) { List<T> result = new ArrayList<T>(); while (iterator.hasNext()) { result.add(iterator.next()); } return result; } static List<T> iteratorToList(Iterator<T> iterator); static boolean isSnp(List<String> alleles); static char getComplementNucleotide(char allele); static void createEmptyFile(File file, String fileName); static final Map<Character, Character> COMPLEMENTAL_NUCLEOTIDES; }### Answer: @Test public void iteratorToList() { List<String> list = Arrays.asList("1", "2", null); assertEquals(Utils.iteratorToList(list.iterator()), list); }
### Question: GenGenotypeWriter implements GenotypeWriter { @Override public void write(String basePath) throws IOException { if (!genotypeData.isOnlyContaingSaveProbabilityGenotypes()) { LOGGER.warn("WARNING!!! writing dosage genotype data to .gen posterior probabilities file. Using heuristic method to convert to probabilities, this is not guaranteed to be accurate. See manual for more details."); } write(new File(basePath + ".gen"), new File(basePath + ".sample")); } GenGenotypeWriter(GenotypeData genotypeData); @Override void write(String basePath); void write(File genFile, File sampleFile); static final Charset FILE_ENCODING; static final char LINE_ENDING; }### Answer: @Test public void write() throws IOException, URISyntaxException { writer.write(tmpOutputFolder.getAbsolutePath() + fileSep + "test"); GenotypeData genotypeDataWritten = RandomAccessGenotypeDataReaderFormats.GEN.createGenotypeData(tmpOutputFolder.getAbsolutePath() + fileSep + "test", 0); assertTrue(GenotypeDataCompareTool.same(genotypeData, genotypeDataWritten)); }
### Question: HapsGenotypeWriter implements GenotypeWriter { @Override public void write(String basePath) throws IOException { write(new File(basePath + ".haps"), new File(basePath + ".sample")); } HapsGenotypeWriter(GenotypeData genotypeData); @Override void write(String basePath); void write(File hapsFile, File sampleFile); static final Charset FILE_ENCODING; static final char LINE_ENDING; }### Answer: @Test public void write() throws IOException, URISyntaxException { writer.write(tmpOutputFolder.getAbsolutePath() + fileSep + "test"); GenotypeData genotypeDataWritten = RandomAccessGenotypeDataReaderFormats.SHAPEIT2.createGenotypeData(tmpOutputFolder.getAbsolutePath() + fileSep + "test", 0); assertTrue(GenotypeDataCompareTool.same(genotypeData, genotypeDataWritten)); assertEquals(genotypeData.getSamples().get(0).getMissingRate(), 0.25, 0.000001); assertEquals(genotypeData.getSamples().get(1).getMissingRate(), 0, 0.000001); assertEquals(genotypeData.getSamples().get(2).getMissingRate(), 0, 0.000001); assertEquals(genotypeData.getSamples().get(3).getMissingRate(), 0, 0.000001); assertEquals(genotypeData.getSamples().get(0).getAnnotationValues().get("bin1"), Boolean.TRUE); assertEquals(genotypeData.getSamples().get(1).getAnnotationValues().get("bin1"), Boolean.FALSE); assertEquals(genotypeData.getSamples().get(2).getAnnotationValues().get("bin1"), Boolean.TRUE); assertEquals(genotypeData.getSamples().get(3).getAnnotationValues().get("bin1"), Boolean.TRUE); genotypeData.close(); }
### Question: Allele implements Comparable<Allele> { public Allele getComplement() { if (isSnpAllele()) { return complement; } else { throw new RuntimeException("Complement currently only supported for SNPs"); } } private Allele(String allele); private Allele(char allele); boolean isSnpAllele(); String getAlleleAsString(); char getAlleleAsSnp(); Allele getComplement(); static Allele create(String alleleString); static Allele create(char alleleChar); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override int compareTo(Allele other); final static Allele A; final static Allele C; final static Allele G; final static Allele T; final static Allele ZERO; }### Answer: @Test public void getComplement() { assertEquals(Allele.A.getComplement().getAlleleAsString(), "T"); }
### Question: Allele implements Comparable<Allele> { public char getAlleleAsSnp() { return snpAllele; } private Allele(String allele); private Allele(char allele); boolean isSnpAllele(); String getAlleleAsString(); char getAlleleAsSnp(); Allele getComplement(); static Allele create(String alleleString); static Allele create(char alleleChar); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override int compareTo(Allele other); final static Allele A; final static Allele C; final static Allele G; final static Allele T; final static Allele ZERO; }### Answer: @Test public void getSnpAllele() { assertEquals(Allele.A.getAlleleAsSnp(), 'A'); }
### Question: Allele implements Comparable<Allele> { public String getAlleleAsString() { return allele; } private Allele(String allele); private Allele(char allele); boolean isSnpAllele(); String getAlleleAsString(); char getAlleleAsSnp(); Allele getComplement(); static Allele create(String alleleString); static Allele create(char alleleChar); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override int compareTo(Allele other); final static Allele A; final static Allele C; final static Allele G; final static Allele T; final static Allele ZERO; }### Answer: @Test public void getStringAllele() { assertEquals(Allele.A.getAlleleAsString(), "A"); }
### Question: Allele implements Comparable<Allele> { public boolean isSnpAllele() { return (byte) snpAllele != -1; } private Allele(String allele); private Allele(char allele); boolean isSnpAllele(); String getAlleleAsString(); char getAlleleAsSnp(); Allele getComplement(); static Allele create(String alleleString); static Allele create(char alleleChar); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override int compareTo(Allele other); final static Allele A; final static Allele C; final static Allele G; final static Allele T; final static Allele ZERO; }### Answer: @Test public void isSnpAllele() { assertEquals(Allele.A.isSnpAllele(), true); }
### Question: TabixIndex implements GenotypeDataIndex { @Override public List<String> getSeqNames() { return Collections.unmodifiableList(Arrays.asList(seqNames)); } TabixIndex(File tabixIndexFile, File bzipFile, VariantLineMapper variantLineMapper); @Override List<String> getSeqNames(); TIndex[] getIndex(); @Override VariantQuery createQuery(); @Override RawLineQuery createRawLineQuery(); TabixIterator queryTabixIndex(String sequence, final int beg, final int end, BlockCompressedInputStream bzipInputStream); }### Answer: @Test public void getSeqNames() { List<String> seqNames = index.getSeqNames(); assertNotNull(seqNames); assertEquals(seqNames.size(), 3); assertEquals(seqNames.get(0), "1"); assertEquals(seqNames.get(1), "2"); assertEquals(seqNames.get(2), "3"); }
### Question: VcfGeneticVariantMeta implements GeneticVariantMeta { public VcfGeneticVariantMeta(VcfMeta vcfMeta, Iterable<String> vcfRecordFormat) { if (vcfMeta == null) { throw new IllegalArgumentException("vcfMeta is null"); } if (vcfRecordFormat == null) { throw new IllegalArgumentException("vcfRecord is null"); } this.vcfMeta = vcfMeta; this.vcfRecordFormat = vcfRecordFormat; } VcfGeneticVariantMeta(VcfMeta vcfMeta, Iterable<String> vcfRecordFormat); @Override Iterable<String> getRecordIds(); @Override Type getRecordType(String recordId); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void VcfGeneticVariantMeta() { new VcfGeneticVariantMeta(null, null); }
### Question: VcfGeneticVariantMeta implements GeneticVariantMeta { @Override public Iterable<String> getRecordIds() { return vcfRecordFormat; } VcfGeneticVariantMeta(VcfMeta vcfMeta, Iterable<String> vcfRecordFormat); @Override Iterable<String> getRecordIds(); @Override Type getRecordType(String recordId); }### Answer: @Test public void getRecordIds() { List<String> ids = Lists.newArrayList(vcfGeneticVariantMeta.getRecordIds()); assertEquals(ids, Arrays.asList("GT", "DP", "EC", "CONFS")); }
### Question: VcfGeneticVariantMeta implements GeneticVariantMeta { @Override public Type getRecordType(String recordId) { boolean found = false; for (String record : vcfRecordFormat) { found = record.equals(recordId); if (found) { break; } } if (!found) { return null; } VcfMetaFormat format = vcfMeta.getFormatMeta(recordId); if (format == null) { return null; } String number = format.getNumber(); boolean isListValue = number.equals("A") || number.equals("R") || number.equals("G") || number.equals(".") || Integer.valueOf(number) > 1; switch (format.getType()) { case CHARACTER: return isListValue ? Type.CHAR_LIST : Type.CHAR; case FLOAT: return isListValue ? Type.FLOAT_LIST : Type.FLOAT; case INTEGER: return isListValue ? Type.INTEGER_LIST : Type.INTEGER; case STRING: return isListValue ? Type.STRING_LIST : Type.STRING; default: throw new IllegalArgumentException("invalid vcf format type [" + format.getType() + "]"); } } VcfGeneticVariantMeta(VcfMeta vcfMeta, Iterable<String> vcfRecordFormat); @Override Iterable<String> getRecordIds(); @Override Type getRecordType(String recordId); }### Answer: @Test public void getRecordType() { assertEquals(GeneticVariantMeta.Type.STRING, vcfGeneticVariantMeta.getRecordType("GT")); assertEquals(GeneticVariantMeta.Type.INTEGER, vcfGeneticVariantMeta.getRecordType("DP")); assertEquals(GeneticVariantMeta.Type.INTEGER_LIST, vcfGeneticVariantMeta.getRecordType("EC")); assertEquals(GeneticVariantMeta.Type.FLOAT_LIST, vcfGeneticVariantMeta.getRecordType("CONFS")); assertNull(vcfGeneticVariantMeta.getRecordType("invalid")); }
### Question: VcfGenotypeRecord implements GenotypeRecord { public VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample) { if(vcfMeta == null) throw new IllegalArgumentException("vcfMeta is null"); if(vcfRecord == null) throw new IllegalArgumentException("vcfRecord is null"); if(vcfSample == null) throw new IllegalArgumentException("vcfSample is null"); this.vcfMeta = vcfMeta; this.vcfRecord = vcfRecord.createClone(); this.vcfSample = vcfSample.createClone(); } VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample); @Override Object getGenotypeRecordData(String recordId); @Override Alleles getSampleAlleles(); @Override float[] getSampleProbs(); @Override float getSampleDosage(); @Override boolean containsGenotypeRecord(String recordId); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void VcfGenotypeRecord() { new VcfGenotypeRecord(null, null, null); }
### Question: VcfGenotypeRecord implements GenotypeRecord { @Override public Alleles getSampleAlleles() { List<Allele> alleles = vcfSample.getAlleles(); if(vcfSample.getAlleles() != null){ return Alleles.createAlleles(alleles); } else { return null; } } VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample); @Override Object getGenotypeRecordData(String recordId); @Override Alleles getSampleAlleles(); @Override float[] getSampleProbs(); @Override float getSampleDosage(); @Override boolean containsGenotypeRecord(String recordId); }### Answer: @Test public void getSampleAlleles() { Map<String, String> propertiesGt = new HashMap<String, String>(); propertiesGt.put("ID", "GT"); propertiesGt.put("Number", "1"); propertiesGt.put("Type", "String"); propertiesGt.put("Description", "Genotype"); VcfMetaFormat vcfMetaFormatGt = new VcfMetaFormat(propertiesGt); VcfMeta vcfMeta = new VcfMeta(); vcfMeta.addFormatMeta(vcfMetaFormatGt); String[] recordTokens = new String[]{"x", "x", "x", "G", "A", "x", "x", "x", "GT:DP:EC:CONFS"}; VcfRecord vcfRecord = new VcfRecord(vcfMeta, recordTokens); String[] sampleTokens = new String[]{"1/0", "5", "5", "5.300,5.300,1.000"}; VcfSample vcfSample = new VcfSample(vcfRecord, sampleTokens ); VcfGenotypeRecord vcfGenotypeRecord = new VcfGenotypeRecord(vcfMeta, vcfRecord, vcfSample); List<Allele> alleles = vcfGenotypeRecord.getSampleAlleles().getAlleles(); assertEquals(alleles.get(0).getAlleleAsSnp(), 'A'); assertEquals(alleles.get(1).getAlleleAsSnp(), 'G'); }
### Question: Alleles implements Iterable<Allele>, Comparable<Alleles> { public boolean contains(Allele queryAllele) { return (alleles.contains(queryAllele)); } private Alleles(List<Allele> alleles); static Alleles createAlleles(List<Allele> alleleList); static Alleles createAlleles(Allele... allele); static Alleles createBasedOnString(List<String> stringAlleles); static Alleles createBasedOnString(String allele1, String allele2); static Alleles createBasedOnChars(char allele1, char allele2); static Alleles createBasedOnChars(char[] charAlleles); List<Allele> getAlleles(); List<String> getAllelesAsString(); int getAlleleCount(); boolean isSnp(); char[] getAllelesAsChars(); @Override String toString(); Alleles getComplement(); boolean sameAlleles(Alleles other); boolean isAtOrGcSnp(); @Override Iterator<Allele> iterator(); Allele get(int alleleIndex); boolean contains(Allele queryAllele); boolean containsAll(Alleles queryAlleles); @Override int compareTo(Alleles other); @Override int hashCode(); @Override boolean equals(Object obj); Alleles createCopyWithoutDuplicates(); static final Alleles BI_ALLELIC_MISSING; }### Answer: @Test public void contains() { Alleles alleles = Alleles.createBasedOnString(Arrays.asList("A", "T")); assertEquals(alleles.contains(Allele.A), true); assertEquals(alleles.contains(Allele.T), true); assertEquals(alleles.contains(Allele.C), false); assertEquals(alleles.contains(Allele.create("AA")), false); }
### Question: CertificateManager { public boolean hasNoCertificates() { return (certs == null || certs.length == 0); } CertificateManager(KeyStoreLoader loader); void setPasswordRequestListener(KeyStoreEntryPasswordRequestListener passwordRequestListener); void setKeyStoreRequestListener(KeyStoreRequestListener keyStoreRequestListener); Certificate[] getCerts(); boolean hasNoCertificates(); byte[] sign(Certificate cert, byte[] challenge); Signature extractSignature(Certificate cert); boolean verify(Certificate cert, byte[] original, byte[] signed); void load(); }### Answer: @Test public void testHasNoCertificates() { boolean hasNoCertificates = manager.hasNoCertificates(); assertFalse(hasNoCertificates); }