method2testcases
stringlengths
118
6.63k
### Question: SequentialActionGroup extends ActionGroupBase { @Override public final void execute() { if (mCurrentAction == null) { startNextAction(); } handleCurrentAction(); } SequentialActionGroup(Scheduler scheduler, Clock clock, Collection<Action> actions, Queue<ActionContext> actionQueue); SequentialActionGroup(Clock clock); SequentialActionGroup(); @Override SequentialActionGroup add(Action action); @Override SequentialActionGroup add(Action... actions); @Override SequentialActionGroup add(Collection<Action> actions); @Override SequentialActionGroup andThen(Action... actions); @Override final void initialize(); @Override final void execute(); @Override boolean isFinished(); @Override void end(boolean wasInterrupted); }### Answer: @Test public void execute_noActionCurrentlyRunning_startsNextAction() throws Exception { List<Action> actions = Collections.singletonList( ActionsMock.actionMocker().build() ); ActionContext context = mock(ActionContext.class); Deque<ActionContext> contexts = new ArrayDeque<>(Collections.singleton( context )); SequentialActionGroup actionGroup = new SequentialActionGroup( mock(Scheduler.class), mClock, actions, contexts); actionGroup.execute(); verify(context, times(1)).prepareForRun(); }
### Question: PeriodicAction extends ActionBase { @Override public void execute() { if (!mNextRun.isValid() || mClock.currentTime().largerThanOrEquals(mNextRun)) { mRunnable.run(); mNextRun = mClock.currentTime().add(mPeriod); } } PeriodicAction(Clock clock, Runnable runnable, Time period, Time nextRun); PeriodicAction(Clock clock, Runnable runnable, Time period); PeriodicAction(Runnable runnable, Time period); @Override void initialize(); @Override void execute(); }### Answer: @Test public void execute_notFirstRunTimeHasElapsed_runsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(1); when(mClock.currentTime()).thenReturn(nextRun); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, times(1)).run(); } @Test public void execute_notFirstRunTimeNotElapsed_notRunsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(2); when(mClock.currentTime()).thenReturn(Time.seconds(1)); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, never()).run(); }
### Question: DoubleBuffer { public void write(T value) { int index = mReadIndex.get(); mArray.set(index, value); mReadIndex.updateAndGet(mReadIndexUpdater); } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }### Answer: @Test public void write_ofObject_writesObjectToWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.write(VALUE); assertEquals(VALUE, innerArray.get(0)); } @Test public void write_ofObject_swapsWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); doubleBuffer.write(VALUE); assertEquals(1, readIndex.get()); }
### Question: Time implements Comparable<Time> { public boolean equals(Time other) { return CompareResult.EQUAL_TO.is(compareTo(other)); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }### Answer: @Test public void equals_thisIsNotValidOtherIsNotValid_returnsTrue() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertTrue(THIS.equals(OTHER)); }
### Question: DoubleBuffer { public T read() { T value = mArray.get(mReadIndex.get()); if (value == null) { throw new NoSuchElementException("nothing to read"); } return value; } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }### Answer: @Test public void read_initialValues_throwsNoSuchElementException() throws Exception { assertThrows(NoSuchElementException.class, ()->{ AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.read(); }); } @Test public void read_valueExistsInArray_returnsThatValue() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); Object read = doubleBuffer.read(); assertEquals(VALUE, read); } @Test public void read_withIndexOnItem_swapsReadIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); Object value = doubleBuffer.read(); assertEquals(VALUE, value); }
### Question: SyncPipeJunction implements Pipeline<T> { @Override public void process(T input) throws VisionException { for (Pipeline<? super T> pipeline : mPipelines) { pipeline.process(input); } } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }### Answer: @Test public void process_forInput_passesToAllPipes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Object INPUT = new Object(); SyncPipeJunction<Object> syncPipeJunction = new SyncPipeJunction<>(PIPELINES); syncPipeJunction.process(INPUT); for (Pipeline pipeline : PIPELINES) { verify(pipeline, times(1)).process(eq(INPUT)); } }
### Question: SyncPipeJunction implements Pipeline<T> { @Override public Pipeline<T> divergeTo(Pipeline<? super T> pipeline) { mPipelines.add(pipeline); return this; } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }### Answer: @Test public void divergeTo_forNewPipeline_addsPipelineToJunctionWithPreviousOnes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Pipeline<? super Object> NEW_PIPELINE = mock(Pipeline.class); Collection<Pipeline> pipelines = new ArrayList<>(Arrays.asList(PIPELINES)); SyncPipeJunction syncPipeJunction = new SyncPipeJunction(pipelines); syncPipeJunction.divergeTo(NEW_PIPELINE); assertThat(pipelines, containsInRelativeOrder(PIPELINES)); assertThat(pipelines, hasItem(NEW_PIPELINE)); }
### Question: ProcessorChain implements Processor { @SuppressWarnings("unchecked") @Override public Object process(Object input) throws VisionException { Object out = input; for (Processor processor : mProcessors) { out = processor.process(out); } return out; } ProcessorChain(Collection<Processor> processors); ProcessorChain(Processor... processors); @SuppressWarnings("unchecked") static Processor<T, R2> create(Processor<T, R> in, Processor<? super R, R2> out); @SuppressWarnings("unchecked") @Override Object process(Object input); @Override Processor pipeTo(Processor processor); }### Answer: @Test public void process_withTwoProcessors_processesInAndPipesToOut() throws Exception { final Object INPUT = new Object(); final Object OUTPUT_IN = new Object(); final Processor<Object, Object> PROCESSOR_IN = mockProcessorWithInputOutput(INPUT, OUTPUT_IN); final Processor<Object, Object> PROCESSOR_OUT = mock(Processor.class); ProcessorChain processorChain = new ProcessorChain(PROCESSOR_IN, PROCESSOR_OUT); processorChain.process(INPUT); verify(PROCESSOR_IN, times(1)).process(eq(INPUT)); verify(PROCESSOR_OUT, times(1)).process(eq(OUTPUT_IN)); } @Test public void process_withMultipleProcessors_processesThroughAll() throws Exception { final Object[] DATA = { new Object(), new Object(), new Object(), new Object() }; final Processor[] PROCESSORS = new Processor[DATA.length - 1]; for (int i = 0; i < PROCESSORS.length; i++) { PROCESSORS[i] = mockProcessorWithInputOutput(DATA[i], DATA[i+1]); } ProcessorChain processorChain = new ProcessorChain(PROCESSORS); processorChain.process(DATA[0]); for (int i = 0; i < PROCESSORS.length; i++) { verify(PROCESSORS[i], times(1)).process(eq(DATA[i])); } } @Test public void process_withTypedProcessors_producesCorrectEndResult() throws Exception { final Processor[] PROCESSORS = { (Processor<Object, Integer>) Object::hashCode, (Processor<Integer, String>) String::valueOf, (Processor<String, Character>) input -> input.charAt(0) }; final Object INPUT = new Object(); final Object EXPECTED_RESULT = String.valueOf(INPUT.hashCode()).charAt(0); ProcessorChain processorChain = new ProcessorChain(PROCESSORS); Object output = processorChain.process(INPUT); assertThat(output, equalTo(EXPECTED_RESULT)); }
### Question: ProcessorPair implements Processor<T, R2> { @Override public R2 process(T input) throws VisionException { R out = mIn.process(input); return mOut.process(out); } ProcessorPair(Processor<T, R> in, Processor<? super R, R2> out); @Override R2 process(T input); }### Answer: @Test public void process_forInput_processesInAndPipesToOut() throws Exception { final Object INPUT = new Object(); final Object OUTPUT_IN = new Object(); final Processor<Object, Object> PROCESSOR_IN = mock(Processor.class); when(PROCESSOR_IN.process(eq(INPUT))).thenReturn(OUTPUT_IN); final Processor<Object, Object> PROCESSOR_OUT = mock(Processor.class); ProcessorPair<Object, Object, Object> processorPair = new ProcessorPair<>(PROCESSOR_IN, PROCESSOR_OUT); processorPair.process(INPUT); verify(PROCESSOR_IN, times(1)).process(eq(INPUT)); verify(PROCESSOR_OUT, times(1)).process(eq(OUTPUT_IN)); }
### Question: RequirementsControl { public void updateRequirementsNoCurrentAction(Action action) { for (Requirement requirement : action.getConfiguration().getRequirements()) { mActionsOnRequirement.remove(requirement); } } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }### Answer: @Test public void updateRequirementsNoCurrentAction_actionUsesAllSubsystems_removesAllSubsystems() throws Exception { Collection<Subsystem> subsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(subsystems) .build(); subsystems.forEach((s) -> mActionsOnSubsystems.put(s, action)); mRequirementsControl.updateRequirementsNoCurrentAction(action); MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.anEmptyMap()); } @Test public void updateRequirementsNoCurrentAction_actionUsesSome_removesOnlyMatchingSubsystems() throws Exception { Collection<Subsystem> otherSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Collection<Subsystem> usedSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(usedSubsystems) .build(); otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class))); usedSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, action)); mRequirementsControl.updateRequirementsNoCurrentAction(action); MatcherAssert.assertThat(mActionsOnSubsystems.keySet(), IsIterableWithSize.iterableWithSize(otherSubsystems.size())); MatcherAssert.assertThat(mActionsOnSubsystems.keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder(otherSubsystems.toArray())); }
### Question: InProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { mPipeline.process(input); return mProcessor.process(input); } InProcessorJunction(Processor<T, R> processor, Pipeline<? super T> pipeline); @Override R process(T input); @Override Processor<T, R> divergeIn(Pipeline<? super T> pipeline); }### Answer: @Test public void process_forInput_processesAndPipesInputToPipeline() throws Exception { final Object INPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); final Pipeline<Object> PIPELINE = mock(Pipeline.class); InProcessorJunction<Object, Object> inProcessorJunction = new InProcessorJunction<>(PROCESSOR, PIPELINE); inProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(INPUT)); }
### Question: OutProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { R out = mProcessor.process(input); mPipeline.process(out); return out; } OutProcessorJunction(Processor<T, R> processor, Pipeline<? super R> pipeline); @Override R process(T input); @Override Processor<T, R> divergeOut(Pipeline<? super R> pipeline); }### Answer: @Test public void process_forInput_processesAndPipesOutputToPipeline() throws Exception { final Object INPUT = new Object(); final Object OUTPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); when(PROCESSOR.process(eq(INPUT))).thenReturn(OUTPUT); final Pipeline<Object> PIPELINE = mock(Pipeline.class); OutProcessorJunction<Object, Object> outProcessorJunction = new OutProcessorJunction<>(PROCESSOR, PIPELINE); outProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(OUTPUT)); }
### Question: RequirementsControl { public void updateRequirementsWithNewRunningAction(Action action) { for (Requirement requirement : action.getConfiguration().getRequirements()) { if (mActionsOnRequirement.containsKey(requirement)) { Action currentAction = mActionsOnRequirement.get(requirement); currentAction.cancel(); mLogger.warn("Requirements conflict in Scheduler between {} and new action {} over requirement {}", currentAction.toString(), action.toString(), requirement.toString()); } mActionsOnRequirement.put(requirement, action); } } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }### Answer: @Test public void updateRequirementsWithNewRunningAction_actionWithSomeRequirements_addsRequirementsToMap() throws Exception { Collection<Subsystem> otherSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Collection<Subsystem> usedSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(usedSubsystems) .build(); otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class))); mRequirementsControl.updateRequirementsWithNewRunningAction(action); MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.aMapWithSize(usedSubsystems.size() + otherSubsystems.size())); otherSubsystems.forEach((s)-> MatcherAssert.assertThat(mActionsOnSubsystems, IsMapContaining.hasEntry(equalTo(s), any(Action.class)))); usedSubsystems.forEach((s)-> MatcherAssert.assertThat(mActionsOnSubsystems, IsMapContaining.hasEntry(s, action))); } @Test public void updateRequirementsWithNewRunningAction_requirementHasAction_cancelsAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.updateRequirementsWithNewRunningAction(newAction); verify(action, times(1)).cancel(); } @Test public void updateRequirementsWithNewRunningAction_requirementHasAction_replacesAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.updateRequirementsWithNewRunningAction(newAction); MatcherAssert.assertThat(mActionsOnSubsystems, Matchers.not(IsMapContaining.hasEntry(action, subsystem))); }
### Question: SPARQLBasedTrivialInconsistencyFinder extends AbstractTrivialInconsistencyFinder { @Override public void run(boolean resume) { for(AbstractTrivialInconsistencyFinder checker : incFinders){ if(!(checker instanceof InverseFunctionalityBasedInconsistencyFinder) || isApplyUniqueNameAssumption()){ try { checker.run(resume); fireNumberOfConflictsFound(checker.getExplanations().size()); if(checker.terminationCriteriaSatisfied()){ break; } } catch (Exception e) { e.printStackTrace(); } } } if(!terminationCriteriaSatisfied()){ fireFinished(); completed = true; } } SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks); SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks, InconsistencyType... inconsistencyTypes); void setInconsistencyTypes(InconsistencyType... inconsistencyTypes); @Override void setApplyUniqueNameAssumption(boolean applyUniqueNameAssumption); @Override void setStopIfInconsistencyFound(boolean stopIfInconsistencyFound); @Override void setAxiomsToIgnore(Set<OWLAxiom> axiomsToIgnore); @Override void addProgressMonitor(SPARQLBasedInconsistencyProgressMonitor mon); @Override void run(boolean resume); boolean isCompleted(); static void main(String[] args); }### Answer: @Test public void testRun() { incFinder.run(); } @Test public void testGetExplanations() { incFinder.run(); Set<Explanation<OWLAxiom>> explanations = incFinder.getExplanations(); for (Explanation<OWLAxiom> explanation : explanations) { System.out.println(explanation.getAxioms()); } }
### Question: GenerateTradeData { public List<Trade> createRandomData(int number) throws Exception { return null; } Trade createTradeData(int number, List<Party> partyList, List<Instrument> instrumentList); List<Trade> createRandomData(int number); }### Answer: @Test public void testGenerateRandomInstrument() throws Exception { GenerateRandomInstruments ranIns = new GenerateRandomInstruments(); assert (ranIns.createRandomData(50).size() == 50); } @Test public void testGeneratePartyData() throws Exception { GenerateRandomParty ransPty = new GenerateRandomParty(); assert (ransPty.createRandomData(50).size() == 50); }
### Question: SegmentedLog { public void truncateSuffix(long newEndIndex) { if (newEndIndex >= getLastLogIndex()) { return; } LOG.info("Truncating log from old end index {} to new end index {}", getLastLogIndex(), newEndIndex); while (!startLogIndexSegmentMap.isEmpty()) { Segment segment = startLogIndexSegmentMap.lastEntry().getValue(); try { if (newEndIndex == segment.getEndIndex()) { break; } else if (newEndIndex < segment.getStartIndex()) { totalSize -= segment.getFileSize(); segment.getRandomAccessFile().close(); String fullFileName = logDataDir + File.separator + segment.getFileName(); FileUtils.forceDelete(new File(fullFileName)); startLogIndexSegmentMap.remove(segment.getStartIndex()); } else if (newEndIndex < segment.getEndIndex()) { int i = (int) (newEndIndex + 1 - segment.getStartIndex()); segment.setEndIndex(newEndIndex); long newFileSize = segment.getEntries().get(i).offset; totalSize -= (segment.getFileSize() - newFileSize); segment.setFileSize(newFileSize); segment.getEntries().removeAll( segment.getEntries().subList(i, segment.getEntries().size())); FileChannel fileChannel = segment.getRandomAccessFile().getChannel(); fileChannel.truncate(segment.getFileSize()); fileChannel.close(); segment.getRandomAccessFile().close(); String oldFullFileName = logDataDir + File.separator + segment.getFileName(); String newFileName = String.format("%020d-%020d", segment.getStartIndex(), segment.getEndIndex()); segment.setFileName(newFileName); String newFullFileName = logDataDir + File.separator + segment.getFileName(); new File(oldFullFileName).renameTo(new File(newFullFileName)); segment.setRandomAccessFile(RaftFileUtils.openFile(logDataDir, segment.getFileName(), "rw")); } } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } } } SegmentedLog(String raftDataDir, int maxSegmentFileSize); RaftProto.LogEntry getEntry(long index); long getEntryTerm(long index); long getFirstLogIndex(); long getLastLogIndex(); long append(List<RaftProto.LogEntry> entries); void truncatePrefix(long newFirstIndex); void truncateSuffix(long newEndIndex); void loadSegmentData(Segment segment); void readSegments(); RaftProto.LogMetaData readMetaData(); void updateMetaData(Long currentTerm, Integer votedFor, Long firstLogIndex, Long commitIndex); RaftProto.LogMetaData getMetaData(); long getTotalSize(); }### Answer: @Test public void testTruncateSuffix() throws IOException { String raftDataDir = "./data"; SegmentedLog segmentedLog = new SegmentedLog(raftDataDir, 32); Assert.assertTrue(segmentedLog.getFirstLogIndex() == 1); List<RaftProto.LogEntry> entries = new ArrayList<>(); for (int i = 1; i < 10; i++) { RaftProto.LogEntry entry = RaftProto.LogEntry.newBuilder() .setData(ByteString.copyFrom(("testEntryData" + i).getBytes())) .setType(RaftProto.EntryType.ENTRY_TYPE_DATA) .setIndex(i) .setTerm(i) .build(); entries.add(entry); } long lastLogIndex = segmentedLog.append(entries); Assert.assertTrue(lastLogIndex == 9); segmentedLog.truncatePrefix(5); FileUtils.deleteDirectory(new File(raftDataDir)); }
### Question: Snapshot { public TreeMap<String, SnapshotDataFile> openSnapshotDataFiles() { TreeMap<String, SnapshotDataFile> snapshotDataFileMap = new TreeMap<>(); String snapshotDataDir = snapshotDir + File.separator + "data"; try { Path snapshotDataPath = FileSystems.getDefault().getPath(snapshotDataDir); snapshotDataPath = snapshotDataPath.toRealPath(); snapshotDataDir = snapshotDataPath.toString(); List<String> fileNames = RaftFileUtils.getSortedFilesInDirectory(snapshotDataDir, snapshotDataDir); for (String fileName : fileNames) { RandomAccessFile randomAccessFile = RaftFileUtils.openFile(snapshotDataDir, fileName, "r"); SnapshotDataFile snapshotFile = new SnapshotDataFile(); snapshotFile.fileName = fileName; snapshotFile.randomAccessFile = randomAccessFile; snapshotDataFileMap.put(fileName, snapshotFile); } } catch (IOException ex) { LOG.warn("readSnapshotDataFiles exception:", ex); throw new RuntimeException(ex); } return snapshotDataFileMap; } Snapshot(String raftDataDir); void reload(); TreeMap<String, SnapshotDataFile> openSnapshotDataFiles(); void closeSnapshotDataFiles(TreeMap<String, SnapshotDataFile> snapshotDataFileMap); RaftProto.SnapshotMetaData readMetaData(); void updateMetaData(String dir, Long lastIncludedIndex, Long lastIncludedTerm, RaftProto.Configuration configuration); RaftProto.SnapshotMetaData getMetaData(); String getSnapshotDir(); AtomicBoolean getIsInstallSnapshot(); AtomicBoolean getIsTakeSnapshot(); Lock getLock(); }### Answer: @Test public void testReadSnapshotDataFiles() throws IOException { String raftDataDir = "./data"; File file = new File("./data/message"); file.mkdirs(); File file1 = new File("./data/message/queue1.txt"); file1.createNewFile(); File file2 = new File("./data/message/queue2.txt"); file2.createNewFile(); File snapshotFile = new File("./data/snapshot"); snapshotFile.mkdirs(); Path link = FileSystems.getDefault().getPath("./data/snapshot/data"); Path target = FileSystems.getDefault().getPath("./data/message").toRealPath(); Files.createSymbolicLink(link, target); Snapshot snapshot = new Snapshot(raftDataDir); TreeMap<String, Snapshot.SnapshotDataFile> snapshotFileMap = snapshot.openSnapshotDataFiles(); System.out.println(snapshotFileMap.keySet()); Assert.assertTrue(snapshotFileMap.size() == 2); Assert.assertTrue(snapshotFileMap.firstKey().equals("queue1.txt")); Files.delete(link); FileUtils.deleteDirectory(new File(raftDataDir)); }
### Question: MergedItem { static MergedItem newInjectedRow(int type) { return new MergedItem(type, type, true); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }### Answer: @Test public void testNewInjectedRowBuilder() { MergedItem mergedItem = MergedItem.newInjectedRow(1); assertThat(mergedItem.injected, is(true)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(1L)); }
### Question: MergedItem { static MergedItem newRow(int type, long id) { return new MergedItem(type, id, false); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }### Answer: @Test public void testNewRowBuilder() { MergedItem mergedItem = MergedItem.newRow(1, 2L); assertThat(mergedItem.injected, is(false)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(2L)); } @Test public void testMergedItemEqual() { MergedItem mergedItem1 = MergedItem.newRow(1, 2L); MergedItem mergedItem2 = MergedItem.newRow(1, 2L); MergedItem mergedItem3 = MergedItem.newRow(1, 3L); assertThat(mergedItem1, is(mergedItem2)); assertThat(mergedItem1, is(not(mergedItem3))); }
### Question: VectorCalculator { int[] calculateFromChildItemPositionTranslationVector() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int vectorSize = maxInjectedItemPosition - dataProvider.getInjectedItemCount() + 2; int[] vector = new int[vectorSize]; int accumulator = 0; int vectorIndex = 0; for (int i = 0; vectorIndex < vectorSize; i++) { if (!dataProvider.isItemInjectedOnPosition(i)) { vector[vectorIndex++] = accumulator; } else { accumulator++; } } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }### Answer: @Test public void calculateFromChildItemPositionTranslationVector() throws Exception { testFromChildVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 3, 4 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 2, 4, 5 }); }
### Question: VectorCalculator { int[] calculateNumberOfInjectedItemsUpToPosition() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int[] vector = new int[maxInjectedItemPosition + 1]; int previousValue = 0; for (int i = 0; i < vector.length; i++) { vector[i] = previousValue + (dataProvider.isItemInjectedOnPosition(i) ? 1 : 0); previousValue = vector[i]; } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }### Answer: @Test public void calculateNumberOfInjectedItemsUpToPosition() throws Exception { testNumberOfInjectedItemsVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 1, 2, 3, 3, 4 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 1, 2, 2, 3, 4, 4, 5 }); }
### Question: MergedListDiffer extends DiffUtil.Callback { void updateData(List<MergedItem> oldList, List<MergedItem> newList) { this.oldList = oldList; this.newList = newList; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer: @Test public void returnsCorrectSizeOfOldList() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, Collections.<MergedItem>emptyList()); }
### Question: MergedListDiffer extends DiffUtil.Callback { @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { MergedItem oldRow = oldList.get(oldItemPosition); MergedItem newRow = newList.get(newItemPosition); return oldRow.type == newRow.type && oldRow.id == newRow.id; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer: @Test public void testAreItemsTheSame() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(4)); }}); assertThat(mergedListDiffer.areItemsTheSame(0, 0), is(true)); assertThat(mergedListDiffer.areItemsTheSame(1, 1), is(false)); }
### Question: MergedListDiffer extends DiffUtil.Callback { @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return true; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer: @Test public void areContentsTheSameAlwaysReturnsTrue() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); assertThat(mergedListDiffer.areContentsTheSame(1, 1), is(true)); }
### Question: Parameter implements Cloneable { public Parameter(String name) { setNameAndParent(name,null); } Parameter(String name); Parameter(String name, boolean value); Parameter(String name, int value); Parameter(String name, long value); Parameter(String name, float value); Parameter(String name, double value); Parameter(String name, String value); Parameter(String name, boolean[] values); Parameter(String name, int[] values); Parameter(String name, long[] values); Parameter(String name, float[] values); Parameter(String name, double[] values); Parameter(String name, String[] values); Parameter(String name, boolean value, String units); Parameter(String name, int value, String units); Parameter(String name, long value, String units); Parameter(String name, float value, String units); Parameter(String name, double value, String units); Parameter(String name, String value, String units); Parameter(String name, boolean[] values, String units); Parameter(String name, int[] values, String units); Parameter(String name, long[] values, String units); Parameter(String name, float[] values, String units); Parameter(String name, double[] values, String units); Parameter(String name, String[] values, String units); Parameter(String name, ParameterSet parent); Object clone(); Parameter replaceWith(Parameter par); Parameter copyTo(ParameterSet parent); Parameter copyTo(ParameterSet parent, String name); Parameter moveTo(ParameterSet parent); Parameter moveTo(ParameterSet parent, String name); void remove(); String getName(); void setName(String name); String getUnits(); void setUnits(String units); int getType(); void setType(int type); ParameterSet getParent(); boolean getBoolean(); int getInt(); long getLong(); float getFloat(); double getDouble(); String getString(); boolean[] getBooleans(); int[] getInts(); long[] getLongs(); float[] getFloats(); double[] getDoubles(); String[] getStrings(); void setBoolean(boolean value); void setInt(int value); void setLong(long value); void setFloat(float value); void setDouble(double value); void setString(String value); void setBooleans(boolean[] values); void setInts(int[] values); void setLongs(long[] values); void setFloats(float[] values); void setDoubles(double[] values); void setStrings(String[] values); boolean isNull(); boolean isBoolean(); boolean isInt(); boolean isLong(); boolean isFloat(); boolean isDouble(); boolean isString(); String toString(); boolean equals(Object o); int hashCode(); final static int NULL; final static int BOOLEAN; final static int INT; final static int LONG; final static int FLOAT; final static int DOUBLE; final static int STRING; }### Answer: @Test public void testParameter() { Parameter par = new Parameter("fo<o","Hello"); assertEquals("Hello",par.getString()); par.setString("true"); assertTrue(par.getBoolean()); par.setString("3141"); assertEquals(3141,par.getInt()); par.setString("3141.0"); assertEquals(3141.0f,par.getFloat()); par.setString("3.141"); assertEquals(3.141,par.getDouble()); double[] empty = new double[0]; par.setDoubles(empty); assertEquals(Parameter.DOUBLE,par.getType()); par.setFloats(null); assertEquals(Parameter.FLOAT,par.getType()); float[] fvalues = {1.2f,3.4f}; par.setFloats(fvalues); fvalues = par.getFloats(); assertEquals(1.2f,fvalues[0]); assertEquals(3.4f,fvalues[1]); par.setUnits("km/s"); assertEquals("km/s",par.getUnits()); boolean[] bvalues = {true,false}; par.setBooleans(bvalues); bvalues = par.getBooleans(); assertTrue(bvalues[0]); assertFalse(bvalues[1]); par.setUnits(null); assertNull(par.getUnits()); }
### Question: DMatrixSvd { public int rank() { double eps = ulp(1.0); double tol = max(_m,_n)*_s[0]*eps; int r = 0; for (int i=0; i<_mn; ++i) { if (_s[i]>tol) ++r; } return r; } DMatrixSvd(DMatrix a); DMatrix getU(); DMatrix getS(); double[] getSingularValues(); DMatrix getV(); DMatrix getVTranspose(); double norm2(); double cond(); int rank(); }### Answer: @Test public void testRank() { DMatrix a = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, }); DMatrixSvd svda = new DMatrixSvd(a); assertEqualExact(svda.rank(),2); DMatrix b = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, {0.0, 0.0}, }); DMatrixSvd svdb = new DMatrixSvd(b); assertEqualExact(svdb.rank(),2); DMatrix c = new DMatrix(new double[][]{ {1.0, 3.0, 0.0}, {7.0, 9.0, 0.0}, }); DMatrixSvd svdc = new DMatrixSvd(c); assertEqualExact(svdc.rank(),2); }
### Question: TridiagonalFMatrix { public void solve(float[] r, float[] u) { if (_w==null) _w = new float[_n]; float t = _b[0]; u[0] = r[0]/t; for (int j=1; j<_n; ++j) { _w[j] = _c[j-1]/t; t = _b[j]-_a[j]*_w[j]; u[j] = (r[j]-_a[j]*u[j-1])/t; } for (int j=_n-1; j>0; --j) u[j-1] -= _w[j]*u[j]; } TridiagonalFMatrix(int n); TridiagonalFMatrix(int n, float[] a, float[] b, float[] c); int n(); float[] a(); float[] b(); float[] c(); void solve(float[] r, float[] u); float[] times(float[] x); void times(float[] x, float[] y); }### Answer: @Test public void testSolve() { int n = 100; float[] a = randfloat(n); float[] b = randfloat(n); float[] c = randfloat(n); for (int i=0; i<n; ++i) b[i] += a[i]+c[i]; TridiagonalFMatrix t = new TridiagonalFMatrix(n,a,b,c); float[] r = randfloat(n); float[] u = zerofloat(n); t.solve(r,u); float[] s = t.times(u); assertEqualFuzzy(r,s); }
### Question: DMatrixQrd { public boolean isFullRank() { for (int j=0; j<_n; ++j) { if (_rdiag[j]==0.0) return false; } return true; } DMatrixQrd(DMatrix a); boolean isFullRank(); DMatrix getQ(); DMatrix getR(); DMatrix solve(DMatrix b); }### Answer: @Test public void testRankDeficient() { DMatrix a = new DMatrix(new double[][]{ {0.0, 0.0}, {3.0, 4.0}, }); DMatrixQrd qrd = new DMatrixQrd(a); assertFalse(qrd.isFullRank()); }
### Question: Units implements Cloneable { public static synchronized boolean define(String name, boolean plural, String definition) throws UnitsFormatException { return addDefinition(name,plural,definition); } Units(); Units(String definition); Object clone(); boolean equals(Object object); boolean equals(Units units); float toSI(float value); double toSI(double value); float fromSI(float value); double fromSI(double value); float floatShiftFrom(Units units); double doubleShiftFrom(Units units); float floatScaleFrom(Units units); double doubleScaleFrom(Units units); boolean haveDimensions(); boolean haveDimensionsOf(Units units); String standardDefinition(); static Units add(Units units, double s); static Units sub(Units units, double s); static Units mul(Units units, double s); static Units div(Units units, double s); static Units mul(Units units1, Units units2); static Units div(Units units1, Units units2); static Units inv(Units units); static Units pow(Units units, int p); static synchronized boolean define(String name, boolean plural, String definition); static synchronized boolean isValidDefinition(String definition); static synchronized boolean isDefined(String name); }### Answer: @Test public void testDefine() { boolean isValid, defined; try { isValid = Units.isValidDefinition("degrees F"); assertTrue(isValid); Units.define("degrees F",false,"degF"); defined = Units.isDefined("degrees F"); assertTrue(defined); isValid = Units.isValidDefinition("degrees C"); assertTrue(isValid); Units.define("degrees C",false,"degC"); defined = Units.isDefined("degrees C"); assertTrue(defined); Units.define("cubic_inches",false,"in^3"); defined = Units.isDefined("m"); assertTrue(defined); defined = Units.define("m",false,"meters"); assertTrue(!defined); } catch (UnitsFormatException e) { assertTrue(false); } defined = true; try { Units.define("foo_inches",false,"foo inches"); } catch (UnitsFormatException e) { defined = false; } assertTrue(!defined); }
### Question: SincInterpolator { public static SincInterpolator fromErrorAndFrequency( double emax, double fmax) { return new SincInterpolator(emax,fmax,0); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }### Answer: @Test public void testErrorAndFrequency() { for (double emax:_emaxs) { for (double fmax:_fmaxs) { SincInterpolator si = SincInterpolator.fromErrorAndFrequency(emax,fmax); testInterpolator(si); } } }
### Question: SincInterpolator { public static SincInterpolator fromErrorAndLength( double emax, int lmax) { return new SincInterpolator(emax,0.0,lmax); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }### Answer: @Test public void testErrorAndLength() { for (double emax:_emaxs) { for (int lmax:_lmaxs) { SincInterpolator si = SincInterpolator.fromErrorAndLength(emax,lmax); testInterpolator(si); } } }
### Question: SincInterpolator { public static SincInterpolator fromFrequencyAndLength( double fmax, int lmax) { return new SincInterpolator(0.0,fmax,lmax); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }### Answer: @Test public void testFrequencyAndLength() { for (double fmax:_fmaxs) { for (int lmax:_lmaxs) { if ((1.0-2.0*fmax)*lmax>1.0) { SincInterpolator si = SincInterpolator.fromFrequencyAndLength(fmax,lmax); testInterpolator(si); } } } }
### Question: RecursiveExponentialFilter { public void apply(float[] x, float[] y) { apply1(x,y); } RecursiveExponentialFilter(double sigma); RecursiveExponentialFilter(double sigma1, double sigma23); RecursiveExponentialFilter( double sigma1, double sigma2, double sigma3); void setEdges(Edges edges); void apply(float[] x, float[] y); void apply(float[][] x, float[][] y); void apply(float[][][] x, float[][][] y); void apply1(float[] x, float[] y); void apply1(float[][] x, float[][] y); void apply2(float[][] x, float[][] y); void apply1(float[][][] x, float[][][] y); void apply2(float[][][] x, float[][][] y); void apply3(float[][][] x, float[][][] y); }### Answer: @Test public void testFrequencyResponse() { int n = 501; double sigma = 4.0; float[] x = new float[n]; x[n/2] = 1.0f; float[] ye = new float[n]; float[] yg = new float[n]; RecursiveExponentialFilter ref = new RecursiveExponentialFilter(sigma); RecursiveGaussianFilter rgf = new RecursiveGaussianFilter(sigma); ref.apply(x,ye); rgf.apply0(x,yg); Fft fft = new Fft(n); fft.setCenter(true); Sampling sf = fft.getFrequencySampling1(); int i0 = sf.indexOfNearest(0.0); float[] ae = cabs(fft.applyForward(ye)); float[] ag = cabs(fft.applyForward(yg)); float e0 = ae[i0]; float e1 = (ae[i0+1]-ae[i0-1])/2.0f; float e2 = ae[i0+1]-2.0f*ae[i0]+ae[i0-1]; float g0 = ag[i0]; float g1 = (ag[i0+1]-ag[i0-1])/2.0f; float g2 = ag[i0+1]-2.0f*ag[i0]+ag[i0-1]; assertEquals(e0,g0,0.0001); assertEquals(e1,g1,0.0001); assertEquals(e2,g2,0.01*abs(g2)); }
### Question: HilbertTransformFilter { public void apply(int n, float[] x, float[] y) { Conv.conv(_filter.length,-(_filter.length-1)/2,_filter,n,0,x,n,0,y); } HilbertTransformFilter(); HilbertTransformFilter(int nmax, float emax, float fmin, float fmax); void apply(int n, float[] x, float[] y); int length(); }### Answer: @Test public void testApply() { int[] nmax_test = {NMAX_DEFAULT,100000,100000,100000,100000}; float[] emax_test = {EMAX_DEFAULT,0.010f,0.010f,0.001f,0.001f}; float[] fmin_test = {FMIN_DEFAULT,0.050f,0.025f,0.100f,0.010f}; float[] fmax_test = {FMAX_DEFAULT,0.475f,0.450f,0.400f,0.490f}; int ntest = emax_test.length; for (int itest=0; itest<ntest; ++itest) { int nmax = nmax_test[itest]; float emax = emax_test[itest]; float fmin = fmin_test[itest]; float fmax = fmax_test[itest]; HilbertTransformFilter htf = new HilbertTransformFilter(nmax,emax,fmin,fmax); int lhtf = htf.length(); int nxy = lhtf; float[] x = new float[nxy]; x[(lhtf-1)/2] = 1.0f; float[] y = new float[nxy]; htf.apply(nxy,x,y); int nfft = FftReal.nfftSmall(16*nxy); FftReal fft = new FftReal(nfft); int mfft = nfft/2+1; float[] hfft = new float[2*mfft]; for (int i=0; i<nxy; ++i) hfft[i] = y[i]; fft.realToComplex(1,hfft,hfft); int jfmin = 1+(int)(fmin*nfft); int jfmax = (int)(fmax*nfft); float[] afft = abs(sub(cabs(hfft),1.0f)); float error = max(copy(1+jfmax-jfmin,jfmin,afft)); assertTrue(error<=emax,"actual error less than maximum expected error"); } }
### Question: Parallel { public static void loop(int end, LoopInt body) { loop(0,end,1,1,body); } static void loop(int end, LoopInt body); static void loop(int begin, int end, LoopInt body); static void loop(int begin, int end, int step, LoopInt body); static void loop( int begin, int end, int step, int chunk, LoopInt body); static V reduce(int end, ReduceInt<V> body); static V reduce(int begin, int end, ReduceInt<V> body); static V reduce( int begin, int end, int step, ReduceInt<V> body); static V reduce( int begin, int end, int step, int chunk, ReduceInt<V> body); static void setParallel(boolean parallel); }### Answer: @Test public void testUnsafe() { final Unsafe<Worker> nts = new Unsafe<Worker>(); loop(20,new LoopInt() { public void compute(int i) { Worker w = nts.get(); if (w==null) nts.set(w=new Worker()); w.work(); } }); }
### Question: Eigen { public static void solveSymmetric22(float[][] a, float[][] v, float[] d) { float a00 = a[0][0]; float a01 = a[0][1], a11 = a[1][1]; float v00 = 1.0f, v01 = 0.0f; float v10 = 0.0f, v11 = 1.0f; if (a01!=0.0f) { float tiny = 0.1f*sqrt(FLT_EPSILON); float c,r,s,t,u,vpr,vqr; u = a11-a00; if (abs(a01)<tiny*abs(u)) { t = a01/u; } else { r = 0.5f*u/a01; t = (r>=0.0f)?1.0f/(r+sqrt(1.0f+r*r)):1.0f/(r-sqrt(1.0f+r*r)); } c = 1.0f/sqrt(1.0f+t*t); s = t*c; u = s/(1.0f+c); r = t*a01; a00 -= r; a11 += r; vpr = v00; vqr = v10; v00 = vpr-s*(vqr+vpr*u); v10 = vqr+s*(vpr-vqr*u); vpr = v01; vqr = v11; v01 = vpr-s*(vqr+vpr*u); v11 = vqr+s*(vpr-vqr*u); } d[0] = a00; d[1] = a11; v[0][0] = v00; v[0][1] = v01; v[1][0] = v10; v[1][1] = v11; if (d[0]<d[1]) { float dt = d[1]; d[1] = d[0]; d[0] = dt; float[] vt = v[1]; v[1] = v[0]; v[0] = vt; } } static void solveSymmetric22(float[][] a, float[][] v, float[] d); static void solveSymmetric22(double[][] a, double[][] v, double[] d); static void solveSymmetric33(double[][] a, double[][] v, double[] d); static void solveSymmetric33Fast( double[][] a, double[][] v, double[] d); }### Answer: @Test public void testSymmetric22() { int nrand = 10000; double[][] v = new double[2][2]; double[] d = new double[2]; for (int irand=0; irand<nrand; ++irand) { double[][] a = randdouble(2,2); a = add(a, transpose(a)); Eigen.solveSymmetric22(a,v,d); check(a,v,d); } }
### Question: Eigen { public static void solveSymmetric33(double[][] a, double[][] v, double[] d) { solveSymmetric33Jacobi(a,v,d); } static void solveSymmetric22(float[][] a, float[][] v, float[] d); static void solveSymmetric22(double[][] a, double[][] v, double[] d); static void solveSymmetric33(double[][] a, double[][] v, double[] d); static void solveSymmetric33Fast( double[][] a, double[][] v, double[] d); }### Answer: @Test public void testSymmetric33() { double[][] v = new double[3][3]; double[] d = new double[3]; int nrand = 10000; for (int irand=0; irand<nrand; ++irand) { double[][] a = makeRandomSymmetric33(); Eigen.solveSymmetric33(a,v,d); check(a,v,d); } } @Test public void testSymmetric33Special() { double[][] v = new double[3][3]; double[] d = new double[3]; double[][][] as = {ASMALL,A100,A110,A111,ATEST1}; for (double[][] a:as) { Eigen.solveSymmetric33(a,v,d); check(a,v,d); } }
### Question: Real1 { public Real1 plus(Real1 ra) { return add(this,ra); } Real1(Sampling s); Real1(float[] v); Real1(Sampling s, float[] v); Real1(int n, double d, double f); Real1(int n, double d, double f, float[] v); Real1(Real1 r); Sampling getSampling(); float[] getValues(); Real1 resample(Sampling s); Real1 plus(Real1 ra); Real1 plus(float ar); Real1 convolve(Real1 ra); Sampling getFourierSampling(int nmin); static Real1 zero(int n); static Real1 zero(Sampling s); static Real1 fill(double ar, int n); static Real1 fill(double ar, Sampling s); static Real1 ramp(double fv, double dv, int nv); static Real1 ramp(double fv, double dv, Sampling s); static Real1 add(Real1 ra, Real1 rb); static Real1 add(float ar, Real1 rb); static Real1 add(Real1 ra, float br); static Real1 sub(Real1 ra, Real1 rb); static Real1 sub(float ar, Real1 rb); static Real1 sub(Real1 ra, float br); static Real1 mul(Real1 ra, Real1 rb); static Real1 mul(float ar, Real1 rb); static Real1 mul(Real1 ra, float br); static Real1 div(Real1 ra, Real1 rb); static Real1 div(float ar, Real1 rb); static Real1 div(Real1 ra, float br); }### Answer: @Test public void testMath() { Real1 ra = RAMP1; Real1 rb = RAMP1; Real1 rc = ra.plus(rb); Real1 re = RAMP2; assertRealEquals(re,rc); }
### Question: Real1 { public Real1 resample(Sampling s) { Sampling t = _s; int[] overlap = t.overlapWith(s); if (overlap!=null) { int ni = overlap[0]; int it = overlap[1]; int is = overlap[2]; Real1 rt = this; Real1 rs = new Real1(s); float[] xt = rt.getValues(); float[] xs = rs.getValues(); while (--ni>=0) xs[is++] = xt[it++]; return rs; } throw new UnsupportedOperationException("no interpolation, yet"); } Real1(Sampling s); Real1(float[] v); Real1(Sampling s, float[] v); Real1(int n, double d, double f); Real1(int n, double d, double f, float[] v); Real1(Real1 r); Sampling getSampling(); float[] getValues(); Real1 resample(Sampling s); Real1 plus(Real1 ra); Real1 plus(float ar); Real1 convolve(Real1 ra); Sampling getFourierSampling(int nmin); static Real1 zero(int n); static Real1 zero(Sampling s); static Real1 fill(double ar, int n); static Real1 fill(double ar, Sampling s); static Real1 ramp(double fv, double dv, int nv); static Real1 ramp(double fv, double dv, Sampling s); static Real1 add(Real1 ra, Real1 rb); static Real1 add(float ar, Real1 rb); static Real1 add(Real1 ra, float br); static Real1 sub(Real1 ra, Real1 rb); static Real1 sub(float ar, Real1 rb); static Real1 sub(Real1 ra, float br); static Real1 mul(Real1 ra, Real1 rb); static Real1 mul(float ar, Real1 rb); static Real1 mul(Real1 ra, float br); static Real1 div(Real1 ra, Real1 rb); static Real1 div(float ar, Real1 rb); static Real1 div(Real1 ra, float br); }### Answer: @Test public void testResample() { Real1 ra = FILL1; Sampling sa = ra.getSampling(); int n1 = sa.getCount(); double d1 = sa.getDelta(); int m1 = n1/3; Sampling sb = sa.shift(-m1*d1); Real1 rb = ra.resample(sb); float[] vb = rb.getValues(); for (int i1=0; i1<m1; ++i1) assertEquals(0.0,vb[i1],0.0); for (int i1=m1; i1<n1; ++i1) assertEquals(1.0,vb[i1],0.0); Sampling sc = sa.shift(m1*d1); Real1 rc = ra.resample(sc); float[] vc = rc.getValues(); for (int i1=0; i1<n1-m1; ++i1) assertEquals(1.0,vc[i1],0.0); for (int i1=n1-m1; i1<n1; ++i1) assertEquals(0.0,vc[i1],0.0); }
### Question: RecursiveGaussianFilter { public void apply0(float[] x, float[] y) { _filter.applyN(0,x,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }### Answer: @Test public void test1() { float sigma = 10.0f; int n = 1+2*(int)(sigma*4.0f); int k = (n-1)/2; float[] x = zerofloat(n); float[] y = zerofloat(n); x[k] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply0(x,y); for (int i=0; i<n; ++i) { float gi = gaussian(sigma,i-k); assertEquals(gi,y[i],tolerance); } }
### Question: MedianFinder { public float findMedian(float[] x) { Check.argument(_n==x.length,"length of x is valid"); copy(x,_x); int k = (_n-1)/2; quickPartialSort(k,_x); float xmed = _x[k]; if (_n%2==0) { float xmin = _x[_n-1]; for (int i=_n-2; i>k; --i) if (_x[i]<xmin) xmin = _x[i]; xmed = 0.5f*(xmed+xmin); } return xmed; } MedianFinder(int n); float findMedian(float[] x); float findMedian(float[] w, float[] x); }### Answer: @Test public void testUnweighted() { Random r = new Random(); int ntest = 100; for (int itest=0; itest<ntest; ++itest) { int n = 1+(r.nextBoolean()?r.nextInt(100):r.nextInt(10)); float[] f = randfloat(n); float[] w = fillfloat(1.0f,n); if (r.nextBoolean()) { for (int i=n/4; i<3*n/4; ++i) f[i] = f[0]; } MedianFinder mf = new MedianFinder(n); float ew = mf.findMedian(w,f); float eu = mf.findMedian(f); assertEquals(ew,eu); } } @Test public void testWeighted() { Random r = new Random(); int ntest = 100; for (int itest=0; itest<ntest; ++itest) { int n = 1+(r.nextBoolean()?r.nextInt(100):r.nextInt(10)); float[] w = randfloat(n); float[] f = randfloat(n); int[] k = rampint(0,1,n); quickIndexSort(f,k); float wsum = 0.0f; float wtotal = sum(w); int i; for (i=0; i<n && wsum<0.5f*wtotal; ++i) wsum += w[k[i]]; float qslow = f[k[i-1]]; MedianFinder mf = new MedianFinder(n); float qfast = mf.findMedian(w,f); assertEquals(qslow,qfast); } }
### Question: RecursiveGaussianFilter { public void apply00(float[][] x, float[][] y) { _filter.applyXN(0,x,y); _filter.applyNX(0,y,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }### Answer: @Test public void test2() { float sigma = 10.0f; int n1 = 1+2*(int)(sigma*4.0f); int n2 = n1+2; int k1 = (n1-1)/2; int k2 = (n2-1)/2; float[][] x = zerofloat(n1,n2); float[][] y = zerofloat(n1,n2); x[k2][k1] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply00(x,y); for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { float gi = gaussian(sigma,i1-k1,i2-k2); assertEquals(gi,y[i2][i1],tolerance); } } }
### Question: RecursiveGaussianFilter { public void apply000(float[][][] x, float[][][] y) { _filter.applyXXN(0,x,y); _filter.applyXNX(0,y,y); _filter.applyNXX(0,y,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }### Answer: @Test public void test3() { float sigma = 10.0f; int n1 = 1+2*(int)(sigma*4.0f); int n2 = n1+2; int n3 = n2+2; int k1 = (n1-1)/2; int k2 = (n2-1)/2; int k3 = (n3-1)/2; float[][][] x = zerofloat(n1,n2,n3); float[][][] y = zerofloat(n1,n2,n3); x[k3][k2][k1] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply000(x,y); for (int i3=0; i3<n3; ++i3) { for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { float gi = gaussian(sigma,i1-k1,i2-k2,i3-k3); assertEquals(gi,y[i3][i2][i1],tolerance); } } } }
### Question: SymmetricTridiagonalFilter { private static SymmetricTridiagonalFilter makeRandomFilter() { java.util.Random r = new java.util.Random(); float af,ai,al,b; boolean aeq2b = r.nextBoolean(); boolean abneg = r.nextBoolean(); boolean afzs = r.nextBoolean(); boolean alzs = r.nextBoolean(); if (aeq2b && afzs==true && alzs==true) { if (r.nextBoolean()) { afzs = false; } else { alzs = false; } } b = r.nextFloat(); ai = 2.0f*b; if (!aeq2b) ai += max(0.001,r.nextFloat())*b; if (abneg) ai = -ai; af = ai; al = ai; if (afzs) af = ai+b; if (alzs) al = ai+b; return new SymmetricTridiagonalFilter(af,ai,al,b); } SymmetricTridiagonalFilter( double af, double ai, double al, double b); void apply(float[] x, float[] y); void apply1(final float[][] x, final float[][] y); void apply2(final float[][] x, final float[][] y); void apply1(final float[][][] x, final float[][][] y); void apply2(final float[][][] x, final float[][][] y); void apply3(float[][][] x, float[][][] y); void applyInverse(float[] x, float[] y); void applyInverse1(final float[][] x, final float[][] y); void applyInverse2(float[][] x, float[][] y); void applyInverse1(final float[][][] x, final float[][][] y); void applyInverse2(final float[][][] x, final float[][][] y); void applyInverse3(float[][][] x, float[][][] y); static void test1Simple(); static void test2Simple(); static void test3Simple(); static void test1Random(); static void test2Random(); static void test3Random(); static void main(String[] args); }### Answer: @Test private static SymmetricTridiagonalFilter makeRandomFilter() { java.util.Random r = new java.util.Random(); float af,ai,al,b; boolean aeq2b = r.nextBoolean(); boolean abneg = r.nextBoolean(); boolean afzs = r.nextBoolean(); boolean alzs = r.nextBoolean(); if (aeq2b && afzs==true && alzs==true) { if (r.nextBoolean()) { afzs = false; } else { alzs = false; } } b = r.nextFloat(); ai = 2.0f*b; if (!aeq2b) ai += max(0.001,r.nextFloat())*b; if (abneg) ai = -ai; af = ai; al = ai; if (afzs) af = ai+b; if (alzs) al = ai+b; return new SymmetricTridiagonalFilter(af,ai,al,b); }
### Question: LocalShiftFinder { public void find1( int min1, int max1, float[] f, float[] g, float[] u) { findShifts(min1,max1,f,g,u,null,null); } LocalShiftFinder(double sigma); LocalShiftFinder(double sigma1, double sigma2); LocalShiftFinder(double sigma1, double sigma2, double sigma3); void setInterpolateDisplacements(boolean enable); void find1( int min1, int max1, float[] f, float[] g, float[] u); void find1( int min1, int max1, float[] f, float[] g, float[] u, float[] c, float[] d); void find1( int min1, int max1, float[][] f, float[][] g, float[][] u); void find2( int min2, int max2, float[][] f, float[][] g, float[][] u); void find1( int min1, int max1, float[][][] f, float[][][] g, float[][][] u); void find2( int min2, int max2, float[][][] f, float[][][] g, float[][][] u); void find3( int min3, int max3, float[][][] f, float[][][] g, float[][][] u); void shift1(float[] du, float[] u1, float[] h); void shift1(float[][] du, float[][] u1, float[][] u2, float[][] h); void shift2(float[][] du, float[][] u1, float[][] u2, float[][] h); void shift1( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void shift2( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void shift3( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void whiten(float[][] f, float[][] g); void whiten(double sigma, float[][] f, float[][] g); void whiten(float[][][] f, float[][][] g); void whiten(double sigma, float[][][] f, float[][][] g); }### Answer: @Test public void testCosine() { float w = 0.02f*2.0f*FLT_PI; int n1 = 1001; float shift = 10.0f; float sigma = 8.0f*shift; float[] f = cos(rampfloat(w*shift,w,n1)); float[] g = cos(rampfloat(0.0f,w,n1)); float[] u = new float[n1]; float[] c = new float[n1]; float[] d = new float[n1]; int min1 = -2*(int)shift; int max1 = 2*(int)shift; LocalShiftFinder lsf = new LocalShiftFinder(shift); lsf.find1(min1,max1,f,g,u,c,d); for (int i1=n1/4; i1<3*n1/4; ++i1) { assertEquals(shift,u[i1],0.02f); assertEquals(1.0f,c[i1],0.02f); assertEquals(1.0f,d[i1],0.02f); } }
### Question: ArrayQueue { public E first() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }### Answer: @Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueFirstElementThrowsException() { aq.first(); }
### Question: Projector { public AxisScale getScale() { return _scaleType; } Projector(double v0, double v1); Projector(double v0, double v1, AxisScale scale); Projector(double v0, double v1, double u0, double u1); Projector(double v0, double v1, double u0, double u1, AxisScale s); Projector(Projector p); double u(double v); double v(double u); double u0(); double u1(); double v0(); double v1(); AxisScale getScale(); boolean isLinear(); boolean isLog(); void merge(Projector p); double getScaleRatio(Projector p); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testAutoLinear() { Projector p = new Projector(0.0, 100, 0.0, 1.0); assertTrue(p.getScale() == AxisScale.LINEAR); }
### Question: ArrayQueue { public E remove() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; ++_first; if (_first==_length) _first = 0; --_size; if (_size*3<_length) resize(_size*2); return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }### Answer: @Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueRemoveElementThrowsException() { aq.remove(); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float get() { return f(_ai.get()); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testDefaultConstructor() { assertEquals(0.0,af.get(),epsilon); } @Test public void testConstructorSingleParameter() { float expected = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected); assertEquals(expected,af.get(),epsilon); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final void set(float value) { _ai.set(i(value)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testSet() { float expected = RANDOM.nextFloat(); af.set(expected); assertEquals(expected, af.get(),epsilon); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float addAndGet(float delta) { for (;;) { int iexpect = _ai.get(); float expect = f(iexpect); float update = expect+delta; int iupdate = i(update); if (_ai.compareAndSet(iexpect,iupdate)) return update; } } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testAddAndGet() { float expected = 0.0f; float actual; for (int i=0; i<10; ++i) { float nf = RANDOM.nextFloat(); expected += nf; actual = af.addAndGet(nf); assertEquals(expected, actual,epsilon); } }
### Question: CleanFormatter extends Formatter { @Override public synchronized String format(LogRecord record) { String message = formatMessage(record); if (message == null) return null; if (message.length() == 0) return message; message = Localize.filter(message, record.getResourceBundle()); if (message.endsWith("\\")) { message = message.substring(0,message.length()-1); } else if (message.matches("^\\s*("+NL+")?$")) { } else { message = message +NL; } Level level = record.getLevel(); if (level.equals(Level.INFO)) { } else if (level.equals(Level.WARNING)) { if (!message.contains("WARNING")) { message = prependToLines(s_prefix+level+": ", message); } else { message = s_prefix+message; } } else if (level.equals(Level.SEVERE)) { message = prependToLines(level+": ", message); if (!lastLevel.equals(Level.SEVERE)) { message = s_prefix + "**** SEVERE WARNING **** ("+ record.getSourceClassName()+ "." + record.getSourceMethodName()+" "+ getTimeStamp(record.getMillis())+" "+ "#" + record.getThreadID() + ")"+NL+ message; } } else if (level.equals(Level.FINE) || level.equals(Level.FINER) || level.equals(Level.FINEST)) { String shortPackage = record.getLoggerName(); int index = shortPackage.lastIndexOf('.'); if (index>0) shortPackage = shortPackage.substring(index+1); message = prependToLines (level+" "+shortPackage+": ", message); } else { message = prependToLines (level+ " " + s_time_formatter.format(new Date()) + " "+ record.getLoggerName()+": ", message); } if (record.getThrown() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); message +=sw.toString(); } lastLevel = level; return message; } static void setWarningPrefix(String prefix); @Override synchronized String format(LogRecord record); static String prependToLines(String prepend, String lines); }### Answer: @Test public void testFormatter() { CleanHandler.setDefaultHandler(); Logger logger = Logger.getLogger("edu.mines.jtk.util.CleanFormatter"); CleanFormatter cf = new CleanFormatter(); String[] messages = new String[] {"one", "two", "three"}; Level[] levels = new Level[] {Level.INFO, Level.WARNING, Level.SEVERE}; String[] s = new String[3]; for (int i=0; i<messages.length; ++i) { LogRecord lr = new LogRecord(levels[i], messages[i]); lr.setSourceClassName("Class"); lr.setSourceMethodName("method"); s[i] = cf.format(lr); assertTrue(s[i].endsWith(messages[i]+NL)); logger.fine("|"+s[i]+"|"); } assertTrue(s[0].equals("one"+NL)); assertTrue(s[1].equals("WARNING: two"+NL)); assertTrue(s[2].matches("^\\*\\*\\*\\* SEVERE WARNING \\*\\*\\*\\* "+ "\\(Class.method \\d+-\\d+ #.*\\)"+NL+ "SEVERE: three"+NL+"$")); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final boolean compareAndSet(float expect, float update) { return _ai.compareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testCompareAndSet() { af.compareAndSet(1.0f,2.0f); assertEquals(0.0f,af.get()); af.compareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final boolean weakCompareAndSet(float expect, float update) { return _ai.weakCompareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testWeakCompareAndSet() { af.weakCompareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float incrementAndGet() { return addAndGet(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testIncrementAndGet() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.incrementAndGet(); assertEquals((float)(i+1),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float decrementAndGet() { return addAndGet(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testDecrementAndGet() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.decrementAndGet(); assertEquals((float)(i-1),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float getAndIncrement() { return getAndAdd(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndIncrement() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndIncrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float getAndDecrement() { return getAndAdd(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndDecrement() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndDecrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } }
### Question: AtomicFloat extends Number implements java.io.Serializable { public final float getAndSet(float value) { return f(_ai.getAndSet(i(value))); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndSet() { float expected0 = RANDOM.nextFloat(); float expected1 = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected0); float actual0 = af.getAndSet(expected1); float actual1 = af.get(); assertEquals(expected0,actual0,epsilon); assertEquals(expected1,actual1,epsilon); }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double get() { return d(_al.get()); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testDefaultConstructor() { assertEquals(0.0,ad.get(),epsilon); } @Test public void testConstructorSingleParameter() { double expected = RANDOM.nextDouble(); AtomicDouble ad = new AtomicDouble(expected); assertEquals(expected,ad.get(),epsilon); }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final void set(double value) { _al.set(l(value)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testSet() { double expected = RANDOM.nextDouble(); ad.set(expected); assertEquals(expected, ad.get(),epsilon); }
### Question: CleanFormatter extends Formatter { public static String prependToLines(String prepend, String lines) { if (lines == null) return null; if (prepend == null) return lines; StringBuilder result = new StringBuilder(); boolean hasFinalNL = lines.endsWith(NL); StringTokenizer divided = new StringTokenizer(lines, NL); while (divided.hasMoreTokens()) { result.append(prepend); result.append(divided.nextToken()); if (divided.hasMoreTokens() || hasFinalNL) result.append(NL); } return result.toString(); } static void setWarningPrefix(String prefix); @Override synchronized String format(LogRecord record); static String prependToLines(String prepend, String lines); }### Answer: @Test public void testPrepend() { String lines = CleanFormatter.prependToLines("a","bbb"+NL+"ccc"); assertTrue(lines.equals("abbb"+NL+"accc")); }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double addAndGet(double delta) { for (;;) { long lexpect = _al.get(); double expect = d(lexpect); double update = expect+delta; long lupdate = l(update); if (_al.compareAndSet(lexpect,lupdate)) return update; } } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testAddAndGet() { double expected = 0.0; for (int i=0; i<10; ++i) { double nd = RANDOM.nextDouble(); expected += nd; double actual = ad.addAndGet(nd); assertEquals(expected, ad.get(),epsilon); } }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final boolean compareAndSet(double expect, double update) { return _al.compareAndSet(l(expect),l(update)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testCompareAndSet() { ad.compareAndSet(1.0,2.0); assertEquals(0.0,ad.get()); ad.compareAndSet(0.0,1.0); assertEquals(1.0,ad.get()); }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final boolean weakCompareAndSet(double expect, double update) { return _al.weakCompareAndSet(l(expect),l(update)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testWeakCompareAndSet() { ad.weakCompareAndSet(0.0,1.0); assertEquals(1.0,ad.get()); }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double incrementAndGet() { return addAndGet(1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testIncrementAndGet() { double val; for (int i=0; i<10; ++i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.incrementAndGet(); assertEquals((double)(i+1),val,1.0E-8); val = ad.get(); assertEquals((double)(i+1),val,1.0E-8); } }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double decrementAndGet() { return addAndGet(-1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testDecrementAndGet() { double val = 10.0; ad.set(val); for (int i=10; i>0; --i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.decrementAndGet(); assertEquals((double)(i-1),val,1.0E-8); val = ad.get(); assertEquals((double)(i-1),val,1.0E-8); } }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double getAndIncrement() { return getAndAdd(1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndIncrement() { double val; for (int i=0; i<10; ++i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.getAndIncrement(); assertEquals((double)(i ),val,1.0E-8); val = ad.get(); assertEquals((double)(i+1),val,1.0E-8); } }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double getAndDecrement() { return getAndAdd(-1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndDecrement() { double val = 10.0; ad.set(val); for (int i=10; i>0; --i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.getAndDecrement(); assertEquals((double)(i ),val,1.0E-8); val = ad.get(); assertEquals((double)(i-1),val,1.0E-8); } }
### Question: AtomicDouble extends Number implements java.io.Serializable { public final double getAndSet(double value) { return d(_al.getAndSet(l(value))); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer: @Test public void testGetAndSet() { double expected0 = RANDOM.nextDouble(); double expected1 = RANDOM.nextDouble(); AtomicDouble ad = new AtomicDouble(expected0); double actual0 = ad.getAndSet(expected1); double actual1 = ad.get(); assertEquals(expected0,actual0,epsilon); assertEquals(expected1,actual1,epsilon); }
### Question: Localize { public Localize(final Class<?> clazz) { this(clazz, null); } Localize(final Class<?> clazz); Localize(final Class<?> clazz, final String resourceBundleName); Localize(final Class<?> clazz, final String resourceBundleName, final Locale locale); String format(final String key, final Object... args); static ResourceBundle getResourceBundle(final Class<?> clazz, String resourceBundleName, Locale locale); static String getMessage(final Throwable throwable); @Override String toString(); static String filter(String message, ResourceBundle catalog); @Deprecated static String filter(String message, Class<?> resourceClass); static String timeWords(long seconds); }### Answer: @Test public void testLocalize() { { final Localize dfault = new Localize(LocalizeTest.class); final String sDefault = dfault.format("msg1", 3.14, 42); assertEquals("A number 3.14000 here, and another #42",sDefault); } { final Localize fr = new Localize(LocalizeTest.class, null, Locale.FRENCH); final int i = 42; final String sFr = fr.format("msg1", 3.14, i); assertTrue("Un nombre 3,14000 ici, et un autre #42".equals(sFr) || "Un nombre 3.14000 ici, et un autre #42".equals(sFr)); } { final Localize alt = new Localize(LocalizeTest.class, "LocalizeTestAlt"); final String s = alt.format("msg1", 3.14, 42); assertEquals("A custom file with number 3.14000, and another #42",s); } { final Localize alt = new Localize(LocalizeTest.class, "LocalizeTestAlt"); final String s = alt.format("No property just a format with number %g.", 3.14); assertEquals("No property just a format with number 3.14000.",s); } { final Localize alt = new Localize(LocalizeTest.class, "DoesNotExist"); final String s = alt.format("A number %g.", 3.14); assertEquals("A number 3.14000.",s); } { final Localize alt = new Localize(LocalizeTest.class); final String s = alt.format("Ignored number.", 3.14); assertEquals("Ignored number.",s); } }
### Question: Localize { public static String getMessage(final Throwable throwable) { if (throwable.getCause() == null) { final String localizedMessage = throwable.getLocalizedMessage(); if (localizedMessage != null) { return localizedMessage; } final String message = throwable.getMessage(); if (message != null) { return message; } return throwable.toString(); } final String causeToString = throwable.getCause().toString(); final String localized = throwable.getLocalizedMessage(); if (localized == null || localized.equals(causeToString)) { return getMessage(throwable.getCause()); } return localized; } Localize(final Class<?> clazz); Localize(final Class<?> clazz, final String resourceBundleName); Localize(final Class<?> clazz, final String resourceBundleName, final Locale locale); String format(final String key, final Object... args); static ResourceBundle getResourceBundle(final Class<?> clazz, String resourceBundleName, Locale locale); static String getMessage(final Throwable throwable); @Override String toString(); static String filter(String message, ResourceBundle catalog); @Deprecated static String filter(String message, Class<?> resourceClass); static String timeWords(long seconds); }### Answer: @Test public static void testLocalizeThrowable() { final IOException ioException = new IOException("ioe"); assertEquals("ioe",Localize.getMessage(ioException)); { final IllegalArgumentException e = new IllegalArgumentException(ioException); assertEquals("ioe",Localize.getMessage(e)); } { final String better = "Bad argument: " + ioException.getLocalizedMessage(); final IllegalArgumentException e = new IllegalArgumentException(better, ioException); assertEquals(better,(Localize.getMessage(e))); } { final IllegalArgumentException e = new IllegalArgumentException(null,ioException); assertEquals("ioe",Localize.getMessage(e)); } { final IllegalArgumentException e = new IllegalArgumentException("foo",ioException); assertEquals("foo",Localize.getMessage(e)); } { final IllegalArgumentException e = new IllegalArgumentException("foo",null); assertEquals("foo",Localize.getMessage(e)); } { final IllegalArgumentException e = new IllegalArgumentException(); assertEquals("java.lang.IllegalArgumentException",Localize.getMessage(e)); } { final IllegalArgumentException e = new IllegalArgumentException(null,null); assertEquals("java.lang.IllegalArgumentException",Localize.getMessage(e)); } }
### Question: RTree extends AbstractSet<Object> { public Iterator<Object> iterator() { return new RTreeIterator(); } RTree(int ndim, int nmin, int nmax); RTree(int ndim, int nmin, int nmax, Boxer boxer); int size(); void clear(); boolean isEmpty(); boolean add(Object object); int addPacked(Object[] objects); boolean remove(Object object); boolean contains(Object object); Iterator<Object> iterator(); int getLevels(); Object[] findOverlapping(float[] min, float[] max); Object[] findOverlapping(Box box); Object[] findInSphere(float[] center, float radius); Object findNearest(float[] point); Object[] findNearest(int k, float[] point); float getLeafArea(); float getLeafVolume(); void dump(); void validate(); }### Answer: @Test public void testIterator() { RTree rt = new RTree(3,4,12); int n = 100; for (int i=0; i<n; ++i) rt.add(randomBox(0.2f)); Iterator<Object> rti = rt.iterator(); Object box = rti.next(); rt.remove(box); rt.add(box); boolean cmeThrown = false; try { rti.next(); } catch (ConcurrentModificationException cme) { cmeThrown = true; } assertTrue(cmeThrown); Object[] boxs = rt.toArray(); int nbox = boxs.length; for (int ibox=0; ibox<nbox; ++ibox) { boolean removed = rt.remove(boxs[ibox]); assertTrue(removed); } }
### Question: Localize { public static String timeWords(long seconds) { if (seconds == 0) { return filter("0 ${seconds}", Localize.class); } String result = ""; long minutes = seconds/60; long hours = minutes/60; long days = hours/24; seconds %= 60; minutes %= 60; hours %= 24; if (days >= 10) { if (hours >=12) ++days; hours = minutes = seconds = 0; } else if (hours >= 10 || days > 0) { if (minutes >=30) { ++hours; days += hours/24; hours %= 24; } minutes = seconds = 0; } else if (minutes >= 10 || hours > 0) { if (seconds >=30) { ++minutes; hours += minutes/60; minutes %= 60; } seconds = 0; } if (seconds != 0) result = " " + seconds + " ${second"+ ((seconds>1)?"s}":"}") + result; if (minutes != 0) result = " " + minutes + " ${minute"+ ((minutes>1)?"s}":"}") + result; if (hours != 0) result = " " + hours + " ${hour" + ((hours>1)?"s}":"}") + result; if (days != 0) result = " " + days + " ${day" + ((days>1)?"s}":"}") + result; return filter(result.trim(), Localize.class); } Localize(final Class<?> clazz); Localize(final Class<?> clazz, final String resourceBundleName); Localize(final Class<?> clazz, final String resourceBundleName, final Locale locale); String format(final String key, final Object... args); static ResourceBundle getResourceBundle(final Class<?> clazz, String resourceBundleName, Locale locale); static String getMessage(final Throwable throwable); @Override String toString(); static String filter(String message, ResourceBundle catalog); @Deprecated static String filter(String message, Class<?> resourceClass); static String timeWords(long seconds); }### Answer: @Test public static void testLocalizeOld() throws Exception { { long seconds =(29L + 60*(9)); String words = timeWords(seconds); assertEquals(words,"9 minutes 29 seconds"); } { long seconds =(29L + 60*(10)); String words = timeWords(seconds); assertEquals(words,"10 minutes"); } { long seconds =(30L + 60*(10)); String words = timeWords(seconds); assertEquals(words,"11 minutes"); } { long seconds =(29L + 60*(29 + 60*(9))); String words = timeWords(seconds); assertEquals(words,"9 hours 29 minutes"); } { long seconds =(30L + 60*(30 + 60*(9))); String words = timeWords(seconds); assertEquals(words,"9 hours 31 minutes"); } { long seconds =(30L + 60*(30 + 60*(10))); String words = timeWords(seconds); assertEquals(words,"11 hours"); } { long seconds =(30L + 60*(30 + 60*(11 +24*9))); String words = timeWords(seconds); assertEquals(words,"9 days 12 hours"); } { long seconds =(30L + 60*(30 + 60*(11 +24*10))); String words = timeWords(seconds); assertEquals(words,"10 days"); } { long seconds =(0L + 60*(0 + 60*(12 +24*10))); String words = timeWords(seconds); assertEquals(words,"11 days"); } { long seconds = 3600L * 2; String words = timeWords(seconds); assertEquals(words,"2 hours"); } { long seconds = 3600L * 2 - 1; String words = timeWords(seconds); assertEquals(words,"2 hours"); } { long seconds = 3600L * 24 * 2; String words = timeWords(seconds); assertEquals(words,"2 days"); } { long seconds = 3600L * 24 * 2 - 1; String words = timeWords(seconds); assertEquals(words,"2 days"); } }
### Question: Almost implements Serializable, Comparator<Number> { public double divide(final double top, final double bottom, final boolean limitIsOne) { return divide(top, bottom, (limitIsOne) ? 1.0 : 0.0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testSafeDivision() { double big = 0.01 * Float.MAX_VALUE; assertEquals(-0.5, a.divide(-1.0, 2.0, 0.0)); assertEquals(-0.5, a.divide( 1.0,-2.0, 0.0)); assertEquals( 1.0, a.divide( 0.0, 0.0, 1.0)); assertEquals( 1.0, a.divide(-1.0,-1.0, 1.0)); assertEquals( 1.0, a.divide(-1.0,-1.0, true)); assertEquals( 1.0, a.divide(1.0E-18,1.0E-18,1.0)); assertEquals( big, a.divide( 1.0, 0.0, 1.0)); }
### Question: Almost implements Serializable, Comparator<Number> { public double reciprocal(final double value) { return divide(1.0, value, 0.0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testReciprocal() { assertEquals(0.5, a.reciprocal(2.0)); }
### Question: Almost implements Serializable, Comparator<Number> { public boolean between(final double x, final double x1, final double x2) { return ((cmp(x, x1) * cmp(x, x2)) <= 0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testBetween() { assertTrue(a.between(1., 0., 2.)); assertTrue(a.between(-1., 0., -2.)); assertTrue(a.between(-1., -0.5, -2.)); assertTrue(a.between(1., 1.000000000001, 2.)); assertTrue(a.between(-1., -1.000000000001, -2.)); }
### Question: Almost implements Serializable, Comparator<Number> { public int outside(final double x, final double x1, final double x2) { int i = 0; if (between(x, x1, x2)) { i = 0; } else if (between(x1, x, x2)) { i = -1; } else if (between(x2, x, x1)) { i = 1; } return i; } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testOutside() { assertEquals(0,a.outside(1., 0., 2.)); assertEquals(0,a.outside(1., 0.5, 2.)); assertEquals(0,a.outside(-1., 0., -2.)); assertEquals(0,a.outside(-1., -0.5, -2.)); assertEquals(-1,a.outside(-1., -1.1, -2.)); assertEquals( 1,a.outside(-1., -0.5, -0.9)); assertEquals(0,a.outside(1., 1.000000000001, 2.)); }
### Question: Almost implements Serializable, Comparator<Number> { @Override public int compare(final Number n1, final Number n2) { return cmp(n1.doubleValue(), n2.doubleValue()); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testCompare() { assertTrue (a.cmp(1., 0.) > 0); assertTrue (a.cmp(0., 1.) < 0); assertEquals(0,a.cmp(1., 1.)); assertEquals(0,a.cmp(0., 0.)); assertEquals(0,a.cmp(1., 1.000000000001)); Integer i = 1; Integer j = 1; assertEquals(0,a.compare(i,j)); }
### Question: Almost implements Serializable, Comparator<Number> { public boolean zero(double r) { if (r < 0.0) { r = -r; } return (r < _minValue); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testZero() { assertTrue (a.zero(0.)); assertTrue (a.zero(a.getMinValue()/2.)); assertFalse(a.zero(a.getMinValue()*2.)); }
### Question: Almost implements Serializable, Comparator<Number> { public double getEpsilon() { return _epsilon; } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testEpsilon() { assertNotEquals(1.,1.+a.getEpsilon()); assertNotEquals(1.,1.-a.getEpsilon()); }
### Question: Almost implements Serializable, Comparator<Number> { public double getMinValue() { return _minValue; } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test public void testGetMinValue() { assertNotEquals(0.,a.getMinValue()); assertTrue (a.getMinValue()/2.>0.); }
### Question: ArgsParser { public static boolean toBoolean(String s) throws OptionException { s = s.toLowerCase(); if (s.equals("true")) return true; if (s.equals("false")) return false; throw new OptionException("the value "+s+" is not a valid boolean"); } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test(expectedExceptions = ArgsParser.OptionException.class) public void testBooleanConverterShouldThrowException() throws Exception { ArgsParser.toBoolean("true"); ArgsParser.toBoolean("Foo"); }
### Question: Almost implements Serializable, Comparator<Number> { public boolean equal(final double r1, final double r2) { return (cmp(r1, r2) == 0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void testNaNsThrowsException() { Almost.FLOAT.equal(0,Float.NaN); Almost.FLOAT.equal(0,Double.NaN); }
### Question: ParameterSet implements Cloneable, Externalizable { public Object clone() throws CloneNotSupportedException { try { ParameterSet ps = (ParameterSet)super.clone(); ps._parent = null; ps._pars = new LinkedHashMap<String, Parameter>(); ps._parsets = new LinkedHashMap<String, ParameterSet>(); return ps.replaceWith(this); } catch (CloneNotSupportedException e) { throw new InternalError(); } } ParameterSet(); ParameterSet(String name); private ParameterSet(String name, ParameterSet parent); Object clone(); ParameterSet replaceWith(ParameterSet parset); String getName(); void setName(String name); Parameter getParameter(String name); ParameterSet getParameterSet(String name); Parameter addParameter(String name); ParameterSet addParameterSet(String name); boolean getBoolean(String name, boolean defaultValue); int getInt(String name, int defaultValue); long getLong(String name, long defaultValue); float getFloat(String name, float defaultValue); double getDouble(String name, double defaultValue); String getString(String name, String defaultValue); boolean[] getBooleans(String name, boolean[] defaultValues); int[] getInts(String name, int[] defaultValues); long[] getLongs(String name, long[] defaultValues); float[] getFloats(String name, float[] defaultValues); double[] getDoubles(String name, double[] defaultValues); String[] getStrings(String name, String[] defaultValues); String getUnits(String name, String defaultUnits); void setBoolean(String name, boolean value); void setInt(String name, int value); void setLong(String name, long value); void setFloat(String name, float value); void setDouble(String name, double value); void setString(String name, String value); void setBooleans(String name, boolean[] values); void setInts(String name, int[] values); void setLongs(String name, long[] values); void setFloats(String name, float[] values); void setDoubles(String name, double[] values); void setStrings(String name, String[] values); void setUnits(String name, String units); ParameterSet copyTo(ParameterSet parent); ParameterSet copyTo(ParameterSet parent, String name); ParameterSet moveTo(ParameterSet parent); ParameterSet moveTo(ParameterSet parent, String name); void remove(); void remove(String name); int countParameters(); int countParameterSets(); void clear(); ParameterSet getParent(); Iterator<Parameter> getParameters(); Iterator<ParameterSet> getParameterSets(); void fromString(String s); String toString(); boolean equals(Object o); int hashCode(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); }### Answer: @Test public void testClone() { ParameterSet root = new ParameterSet("root"); String s1 = root.toString(); ParameterSet foo = root.addParameterSet("foo"); foo.addParameter("bar"); try { ParameterSet temp = (ParameterSet)root.clone(); temp.remove("foo"); root.replaceWith(temp); String s2 = root.toString(); assertTrue(s1.equals(s2)); } catch (CloneNotSupportedException e) { assertTrue(false); } }
### Question: UnitSphereSampling { private static void testSymmetry(UnitSphereSampling uss) { int mi = uss.getMaxIndex(); for (int i=1,j=-i; i<=mi; ++i,j=-i) { float[] p = uss.getPoint(i); float[] q = uss.getPoint(j); assert p[0]==-q[0]; assert p[1]==-q[1]; assert p[2]==-q[2]; } int npoint = 10000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); float[] q = {-p[0],-p[1],-p[2]}; int i = uss.getIndex(p); int j = uss.getIndex(q); if (p[2]==0.0f) { assert i+j==mi+1; } else { assert -i==j; } } } UnitSphereSampling(); UnitSphereSampling(int nbits); int countSamples(); int getMaxIndex(); float[] getPoint(int index); int getIndex(float x, float y, float z); int getIndex(float[] xyz); int[] getTriangle(float x, float y, float z); int[] getTriangle(float[] xyz); float[] getWeights(float x, float y, float z, int[] iabc); float[] getWeights(float[] xyz, int[] iabc); static short[] encode16(float[] x, float[] y, float[] z); static short[][] encode16(float[][] x, float[][] y, float[][] z); static short[][][] encode16( float[][][] x, float[][][] y, float[][][] z); static void main(String[] args); }### Answer: @Test public void testSymmetry() { testSymmetry(8); testSymmetry(16); }
### Question: UnitSphereSampling { private static void testInterpolation(UnitSphereSampling uss) { int mi = uss.getMaxIndex(); int nf = 1+2*mi; float[] fi = new float[nf]; for (int i=1; i<=mi; ++i) { float[] p = uss.getPoint( i); float[] q = uss.getPoint(-i); fi[i ] = func(p[0],p[1],p[2]); fi[nf-i] = func(q[0],q[1],q[2]); } float emax = 0.0f; float[] pmax = null; int npoint = 10000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int[] iabc = uss.getTriangle(p); float[] wabc = uss.getWeights(p,iabc); int ia = iabc[0], ib = iabc[1], ic = iabc[2]; float wa = wabc[0], wb = wabc[1], wc = wabc[2]; if (ia<0) { ia = nf+ia; ib = nf+ib; ic = nf+ic; } float fa = fi[ia], fb = fi[ib], fc = fi[ic]; float f = func(p[0],p[1],p[2]); float g = wa*fa+wb*fb+wc*fc; float e = abs(g-f); if (e>emax) { emax = e; pmax = p; } } trace("emax="+emax); dump(pmax); } UnitSphereSampling(); UnitSphereSampling(int nbits); int countSamples(); int getMaxIndex(); float[] getPoint(int index); int getIndex(float x, float y, float z); int getIndex(float[] xyz); int[] getTriangle(float x, float y, float z); int[] getTriangle(float[] xyz); float[] getWeights(float x, float y, float z, int[] iabc); float[] getWeights(float[] xyz, int[] iabc); static short[] encode16(float[] x, float[] y, float[] z); static short[][] encode16(float[][] x, float[][] y, float[][] z); static short[][][] encode16( float[][][] x, float[][][] y, float[][][] z); static void main(String[] args); }### Answer: @Test public void testInterpolation() { testInterpolation(16,0.0001f); }
### Question: UnitSphereSampling { private static void testTriangle(UnitSphereSampling uss) { int npoint = 1000000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int i = uss.getIndex(p); int[] abc = uss.getTriangle(p); int ia = abc[0], ib = abc[1], ic = abc[2]; float[] q = uss.getPoint(i); float[] qa = uss.getPoint(ia); float[] qb = uss.getPoint(ib); float[] qc = uss.getPoint(ic); float d = distanceOnSphere(p,q); float da = distanceOnSphere(p,qa); float db = distanceOnSphere(p,qb); float dc = distanceOnSphere(p,qc); if (i!=ia && i!=ib && i!=ic) { trace("d="+d+" da="+da+" db="+db+" dc="+dc); dump(p); dump(q); dump(qa); dump(qb); dump(qc); assert false:"i equals ia or ib or ic"; } } } UnitSphereSampling(); UnitSphereSampling(int nbits); int countSamples(); int getMaxIndex(); float[] getPoint(int index); int getIndex(float x, float y, float z); int getIndex(float[] xyz); int[] getTriangle(float x, float y, float z); int[] getTriangle(float[] xyz); float[] getWeights(float x, float y, float z, int[] iabc); float[] getWeights(float[] xyz, int[] iabc); static short[] encode16(float[] x, float[] y, float[] z); static short[][] encode16(float[][] x, float[][] y, float[][] z); static short[][][] encode16( float[][][] x, float[][][] y, float[][][] z); static void main(String[] args); }### Answer: @Test public void testTriangle() { testTriangle(8); testTriangle(16); }
### Question: ArgsParser { public static double toDouble(String s) throws OptionException { try { return Double.valueOf(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid double"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test(expectedExceptions = ArgsParser.OptionException.class) public void testDoubleConverterShouldThrowException() throws Exception { ArgsParser.toDouble("1.986"); ArgsParser.toDouble("Foo"); }
### Question: ArgsParser { public static float toFloat(String s) throws OptionException { try { return Float.valueOf(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid float"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test(expectedExceptions = ArgsParser.OptionException.class) public void testFloatConverterShouldThrowException() throws Exception { ArgsParser.toFloat("1.986"); ArgsParser.toFloat("Foo"); }
### Question: ArgsParser { public static int toInt(String s) throws OptionException { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid int"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test(expectedExceptions = ArgsParser.OptionException.class) public void testIntConverterShouldThrowException() throws Exception { ArgsParser.toInt("1986"); ArgsParser.toInt("Foo"); }
### Question: BrentMinFinder { public double findMin(double a, double b, double tol) { double x = a+GSI*(b-a); double v = x; double w = x; double fx = f(x); double fv = fx; double fw = fx; double d = 0.0; double e = 0.0; for (double xm = 0.5*(a+b), tol1 = EPS*abs(x)+tol/3.0, tol2 = 2.0*tol1; abs(x-xm) > tol2-0.5*(b-a); xm = 0.5*(a+b), tol1 = EPS*abs(x)+tol/3.0, tol2 = 2.0*tol1) { boolean gsstep = abs(e)<=tol1; if (!gsstep) { double r = (x-w)*(fx-fv); double q = (x-v)*(fx-fw); double p = (x-v)*q-(x-w)*r; q = 2.0*(q-r); if (q>0.0) p = -p; q = abs(q); r = e; e = d; if (abs(p)<abs(0.5*q*r) && p>q*(a-x) && p<q*(b-x)) { d = p/q; double u = x+d; if ((u-a)<tol2 || (b-u)<tol2) d = (xm>=x)?tol1:-tol1; } else { gsstep = true; } } if (gsstep) { e = (x>=xm)?a-x:b-x; d = GSI*e; } double u = x+(abs(d)>=tol1?d:d>=0.0?tol1:-tol1); double fu = f(u); if (fu<=fx) { if (u>=x) a = x; else b = x; v = w; w = x; x = u; fv = fw; fw = fx; fx = fu; } else { if (u<x) a = u; else b = u; if (fu<=fw || w==x) { v = w; w = u; fv = fw; fw = fu; } else if (fu<=fv || v==x || v==w) { v = u; fv = fu; } } } return x; } BrentMinFinder(Function f); double f(double x); double findMin(double a, double b, double tol); }### Answer: @Test public void testSimple() { BrentMinFinder bmf = new BrentMinFinder(new BrentMinFinder.Function() { public double evaluate(double x) { return x*(x*x-2.0)-5.0; } }); double xmin = bmf.findMin(0.0,1.0,1.0e-5); trace("xmin="+xmin); assertEquals(0.81650,xmin,0.00001); } @Test public void testMinFinder() { MinFunc1 f1 = new MinFunc1(); f1.findMin(0.0,1.0); MinFunc2 f2 = new MinFunc2(); f2.findMin(2.0,3.0); MinFunc3 f3 = new MinFunc3(); f3.findMin(-1.0,3.0); MinFunc4 f4 = new MinFunc4(); f4.findMin(-1.0,3.0); }
### Question: ArgsParser { public static long toLong(String s) throws OptionException { try { return Long.parseLong(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid long"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test(expectedExceptions = ArgsParser.OptionException.class) public void testLongConverterShouldThrowException() throws Exception { ArgsParser.toLong("1986"); ArgsParser.toLong("Foo"); }
### Question: BrentZeroFinder { public double findZero(double a, double b, double tol) { double fa = _f.evaluate(a); double fb = _f.evaluate(b); return findZero(a,fa,b,fb,tol); } BrentZeroFinder(Function f); double f(double x); double findZero(double a, double b, double tol); double findZero( double a, double fa, double b, double fb, double tol); }### Answer: @Test public void testForsythe() { ZeroFunc1 f1 = new ZeroFunc1(); f1.findZero(2.0,3.0); ZeroFunc2 f2 = new ZeroFunc2(); f2.findZero(-1.0,3.0); ZeroFunc3 f3 = new ZeroFunc3(); f3.findZero(-1.0,3.0); }
### Question: BoundingBoxTree { public Node getRoot() { return _root; } BoundingBoxTree(int minSize, float[] xyz); BoundingBoxTree(int minSize, float[] x, float[] y, float[] z); Node getRoot(); }### Answer: @Test public void testRandom() { int minSize = 10; int n = 10000; float[] x = randfloat(n); float[] y = randfloat(n); float[] z = randfloat(n); BoundingBoxTree bbt = new BoundingBoxTree(minSize,x,y,z); BoundingBoxTree.Node root = bbt.getRoot(); test(root,minSize,x,y,z); }
### Question: DMatrixChd { public double det() { return _det; } DMatrixChd(DMatrix a); boolean isPositiveDefinite(); DMatrix getL(); double det(); DMatrix solve(DMatrix b); }### Answer: @Test public void testSimple() { DMatrix a = new DMatrix(new double[][]{ {1.0, 1.0}, {1.0, 4.0}, }); test(a); DMatrixChd chd = new DMatrixChd(a); assertEqualFuzzy(3.0,chd.det()); }
### Question: DMatrixLud { public double det() { Check.argument(_m==_n,"A is square"); return _det; } DMatrixLud(DMatrix a); boolean isSingular(); DMatrix getL(); DMatrix getU(); DMatrix getP(); int[] getPivotIndices(); double det(); DMatrix solve(DMatrix b); }### Answer: @Test public void testSimple() { DMatrix a = new DMatrix(new double[][]{ {0.0, 2.0}, {3.0, 4.0}, }); test(a); DMatrixLud lud = new DMatrixLud(a); assertEqualFuzzy(-6.0,lud.det()); }
### Question: DMatrixQrd { public boolean isFullRank() { for (int j=0; j<_n; ++j) { if (_qr[j+j*_m]==0.0) return false; } return true; } DMatrixQrd(DMatrix a); boolean isFullRank(); DMatrix getQ(); DMatrix getR(); DMatrix solve(DMatrix b); }### Answer: @Test public void testRankDeficient() { DMatrix a = new DMatrix(new double[][]{ {0.0, 0.0}, {3.0, 4.0}, }); DMatrixQrd qrd = new DMatrixQrd(a); assertFalse(qrd.isFullRank()); }
### Question: DMatrixSvd { public double cond() { return _s[0]/_s[_mn-1]; } DMatrixSvd(DMatrix a); DMatrix getU(); DMatrix getS(); double[] getSingularValues(); DMatrix getV(); DMatrix getVTranspose(); double norm2(); double cond(); int rank(); }### Answer: @Test public void testCond() { DMatrix a = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, }); int m = a.getM(); int n = a.getN(); DMatrixSvd svd = new DMatrixSvd(a); double[] s = svd.getSingularValues(); double smax = max(s); assertEqualExact(s[0],smax); double smin = min(s); assertEqualExact(s[min(m,n)-1],smin); double cond = svd.cond(); assertEqualExact(smax/smin,cond); }
### Question: ArgsParser { public ArgsParser(String[] args, String shortOpts) throws OptionException { _args = args; _shortOpts = shortOpts; _longOpts = new String[0]; init(); } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer: @Test public void testArgsParser() { String[][] args = { {"-a3.14","-b","foo"}, {"-a","3.14","-b","foo"}, {"--alpha","3.14","--beta","foo"}, {"--a=3.14","--b","foo"}, {"--a=3.14","--b","foo"}, }; for (String[] arg:args) { float a = 0.0f; boolean b = false; try { String shortOpts = "ha:b"; String[] longOpts = {"help","alpha=","beta"}; ArgsParser ap = new ArgsParser(arg,shortOpts,longOpts); String[] opts = ap.getOptions(); String[] vals = ap.getValues(); for (int i=0; i<opts.length; ++i) { String opt = opts[i]; String val = vals[i]; if (opt.equals("-h") || opt.equals("--help")) { assertTrue(false); } else if (opt.equals("-a") || opt.equals("--alpha")) { a = ArgsParser.toFloat(val); } else if (opt.equals("-b") || opt.equals("--beta")) { b = true; } } String[] otherArgs = ap.getOtherArgs(); assertTrue(otherArgs.length==1); assertTrue(otherArgs[0].equals("foo")); assertTrue(a==3.14f); assertTrue(b); } catch (ArgsParser.OptionException e) { assertTrue("no exceptions: e="+e.getMessage(),false); } } }