method2testcases
stringlengths
118
3.08k
### Question: SshShellTerminalDelegate implements Terminal { @Override public InputStream input() { return delegate().input(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void input() throws Exception { del.input(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public OutputStream output() { return delegate().output(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void output() throws Exception { del.output(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public Attributes enterRawMode() { return delegate().enterRawMode(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void enterRawMode() throws Exception { del.enterRawMode(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public boolean echo() { return delegate().echo(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void echo() throws Exception { del.echo(); } @Test public void echoBis() throws Exception { del.echo(false); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public Attributes getAttributes() { return delegate().getAttributes(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getAttributes() throws Exception { del.getAttributes(); }
### Question: DemoCommand extends AbstractHealthIndicator { @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") public String admin() { return "Finally an administrator !!"; } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file( @ShellOption(defaultValue = ShellOption.NULL) File file, @ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer: @Test void admin() { cmd.admin(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public void setAttributes(Attributes attributes) { delegate().setAttributes(attributes); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void setAttributes() throws Exception { del.setAttributes(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public Size getSize() { return delegate().getSize(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getSize() throws Exception { del.getSize(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public void setSize(Size size) { delegate().setSize(size); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void setSize() throws Exception { del.setSize(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public void flush() { delegate().flush(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void flush() throws Exception { del.flush(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public String getType() { return delegate().getType(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getType() throws Exception { del.getType(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public boolean puts(InfoCmp.Capability capability, Object... objects) { return delegate().puts(capability, objects); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void puts() throws Exception { del.puts(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public boolean getBooleanCapability(InfoCmp.Capability capability) { return delegate().getBooleanCapability(capability); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getBooleanCapability() throws Exception { del.getBooleanCapability(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public Integer getNumericCapability(InfoCmp.Capability capability) { return delegate().getNumericCapability(capability); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getNumericCapability() throws Exception { del.getNumericCapability(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public String getStringCapability(InfoCmp.Capability capability) { return delegate().getStringCapability(capability); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getStringCapability() throws Exception { del.getStringCapability(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public Cursor getCursorPosition(IntConsumer intConsumer) { return delegate().getCursorPosition(intConsumer); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void getCursorPosition() throws Exception { del.getCursorPosition(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public boolean hasMouseSupport() { return delegate().hasMouseSupport(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void hasMouseSupport() throws Exception { del.hasMouseSupport(); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public boolean trackMouse(MouseTracking mouseTracking) { return delegate().trackMouse(mouseTracking); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void trackMouse() throws Exception { del.trackMouse(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public MouseEvent readMouseEvent() { return delegate().readMouseEvent(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void readMouseEvent() throws Exception { del.readMouseEvent(); } @Test public void readMouseEventBis() throws Exception { del.readMouseEvent(null); }
### Question: SshShellTerminalDelegate implements Terminal { @Override public void close() throws IOException { delegate().close(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer: @Test public void close() throws Exception { del.close(); }
### Question: DemoCommand extends AbstractHealthIndicator { @ShellMethod("Confirmation command") public String conf() { return helper.confirm("Are you sure ?") ? "Great ! Let's do it !" : "Such a shame ..."; } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file( @ShellOption(defaultValue = ShellOption.NULL) File file, @ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer: @Test void conf() { assertEquals("Great ! Let's do it !", cmd.conf()); }
### Question: DemoCommand extends AbstractHealthIndicator { @ShellMethod("Welcome command") public String welcome() { helper.printInfo("You are now in the welcome command"); String name = helper.read("What's your name ?"); return "Hello, '" + name + "' !"; } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file( @ShellOption(defaultValue = ShellOption.NULL) File file, @ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer: @Test void welcome() { assertEquals("Hello, 'y' !", cmd.welcome()); }
### Question: DemoCommand extends AbstractHealthIndicator { public Availability adminAvailability() { if (!helper.checkAuthorities(Collections.singletonList("ADMIN"))) { return Availability.unavailable("admin command is only for an admin users !"); } return Availability.available(); } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file( @ShellOption(defaultValue = ShellOption.NULL) File file, @ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer: @Test void noAvailability() { assertFalse(cmd.adminAvailability().isAvailable()); }
### Question: UserNetworkProcessor { static UploadNetworkEngineResponseDto computeStats(SymMatrix network) { UploadNetworkEngineResponseDto response = new UploadNetworkEngineResponseDto(); int numInteractions = 0; double minVal = Double.POSITIVE_INFINITY; double maxVal = Double.NEGATIVE_INFINITY; MatrixCursor cursor = network.cursor(); while (cursor.next()) { double val = cursor.val(); if (val == 0d) { continue; } numInteractions += 1; if (val > maxVal) { maxVal = val; } if (val < minVal) { minVal = val; } } numInteractions = numInteractions/2; response.setNumInteractions(numInteractions); response.setMinValue(minVal); response.setMaxValue(maxVal); return response; } UserNetworkProcessor(DataCache cache, String tempDirname); UploadNetworkEngineResponseDto process(UploadNetworkEngineRequestDto request); }### Answer: @Test public void testComputeStats() { System.out.println("computeStats"); SymMatrix network = Config.instance().getMatrixFactory().symSparseMatrix(5); System.out.println("type of SymMatrix class: " + network.getClass().getName()); network.set(1, 2, 1.5); network.set(2, 3, .8); UploadNetworkEngineResponseDto result = UserNetworkProcessor.computeStats(network); assertNotNull(result); assertEquals( 2, result.getNumInteractions()); assertEquals( .8, result.getMinValue(), 10e-8); assertEquals(1.5, result.getMaxValue(), 10e-8); }
### Question: UserDataPrecomputer { protected void checkNetwork(long id) throws ApplicationException { if (id >= 0) { throw new ApplicationException("not a valid id for a user network: " + id); } if (networkIds.containsId(id)) { throw new ApplicationException("a network with the id " + id + " already exists in the users data set"); } } UserDataPrecomputer(String namespace, int organismId, DataCache cache, ProgressReporter progress); void load(); void loadInit(); boolean loadInitPrecomputed(); void save(); void addNetwork(long networkId, SymMatrix m); void reallocKtK(); void reallocKtT(); void updateKtT(long networkId, SymMatrix network); void removeNetwork(int networkId); void removeOrganism(); }### Answer: @Test (expected=ApplicationException.class) public void testCheckNetworkInvalidId() throws Exception { System.out.println("checkNetworkInvalidId"); String namespace = "user1"; int organismId = 1; int id = 1; Map<Integer, Integer> userColumnMap = new HashMap<Integer, Integer>(); userColumnMap.put(-1, 0); userColumnMap.put(-2, 1); userColumnMap.put(-5, 2); UserDataPrecomputer instance = new UserDataPrecomputer(namespace, organismId, cacheBuilder.getCache(), NullProgressReporter.instance()); instance.checkNetwork(id); }
### Question: UserDataPrecomputer { public void load() throws ApplicationException { try { info = cache.getDatasetInfo(organismId); networkIds = cache.getNetworkIds(namespace, organismId); hasPrecomputedData = loadPrecomputed(); } catch (ApplicationException e) { loadInit(); } } UserDataPrecomputer(String namespace, int organismId, DataCache cache, ProgressReporter progress); void load(); void loadInit(); boolean loadInitPrecomputed(); void save(); void addNetwork(long networkId, SymMatrix m); void reallocKtK(); void reallocKtT(); void updateKtT(long networkId, SymMatrix network); void removeNetwork(int networkId); void removeOrganism(); }### Answer: @Test public void testLoad() throws Exception { System.out.println("load"); String namespace = "user1"; int organismId = 1; UserDataPrecomputer instance = new UserDataPrecomputer(namespace, organismId, cacheBuilder.getCache(), NullProgressReporter.instance()); instance.load(); assertNotNull(instance.userKtK); assertNotNull(instance.userKtT); assertEquals(3, instance.userKtT.length); assertNotNull(instance.userKtT[0]); assertNotNull(instance.userKtT[1]); assertNotNull(instance.userKtT[2]); }
### Question: UserDataPrecomputer { public void loadInit() throws ApplicationException { NetworkIds coreNetworkIds = cache.getNetworkIds(Data.CORE, organismId); networkIds = coreNetworkIds.copy(namespace); hasPrecomputedData = loadInitPrecomputed(); } UserDataPrecomputer(String namespace, int organismId, DataCache cache, ProgressReporter progress); void load(); void loadInit(); boolean loadInitPrecomputed(); void save(); void addNetwork(long networkId, SymMatrix m); void reallocKtK(); void reallocKtT(); void updateKtT(long networkId, SymMatrix network); void removeNetwork(int networkId); void removeOrganism(); }### Answer: @Test public void testLoadInit() throws Exception { System.out.println("loadInit"); String namespace = "user1"; int organismId = 1; UserDataPrecomputer instance = new UserDataPrecomputer(namespace, organismId, cacheBuilder.getCache(), NullProgressReporter.instance()); instance.loadInit(); assertNotNull(instance.userKtK); assertNotNull(instance.userKtT); assertEquals(3, instance.userKtT.length); assertNotNull(instance.userKtT[0]); assertNotNull(instance.userKtT[1]); assertNotNull(instance.userKtT[2]); }
### Question: UidGenerator { public synchronized long getNegativeUid() { return --lastId; } private UidGenerator(); static UidGenerator getInstance(); synchronized long getApplicationWideUid(); synchronized long getNextNegativeUid(); synchronized long getNextUidForSession(String sessionId); synchronized long getNegativeUid(); }### Answer: @Test public void testGetNegativeUid() { long uid1 = UidGenerator.getInstance().getNegativeUid(); long uid2 = UidGenerator.getInstance().getNegativeUid(); assertTrue("uid is negative:" + uid1, uid1 < 0); assertTrue("uid min test: " + uid1, uid1 > Integer.MIN_VALUE); assertTrue("uid max test:" + uid1, uid1 < Integer.MAX_VALUE); assertTrue("uid is negative:" + uid2, uid2 < 0); assertTrue("uid min test: " + uid2, uid2 > Integer.MIN_VALUE); assertTrue("uid max test:" + uid2, uid2 < Integer.MAX_VALUE); assertNotSame("ID must be unique", uid1, uid2); }
### Question: IdentVac extends H2Vac { public void process(String filename, String sep) throws SQLException { readCSV(filename, a("ID", "SYMBOL", "SOURCE"), sep); countRecordsRead(); cleanMissing(); findDups(); dropDups(); countEmUp(); } IdentVac(String dbName); void countRecordsRead(); void cleanMissing(); void findDups(); void dropDups(); void countEmUp(); void process(String filename, String sep); }### Answer: @Test public void testFileName() throws Exception { String filename = getResourceFile("/" + IDENTIFIERS_FILENAME); IdentVac vac = new IdentVac("test1"); vac.process(filename, "\t"); assertEquals(15, vac.numRecordsRead); assertEquals(2, vac.numMissing); assertEquals(1, vac.numDups); assertEquals(5, vac.numIds); assertEquals(11, vac.numSymbols); assertEquals(3, vac.numSources); assertNotNull(vac.sourceCounts); for (Object[] i: vac.sourceCounts) { for (Object j: i) { System.out.print(j.toString()); System.out.print(" "); } System.out.println(""); } }
### Question: BuildServiceImpl implements BuildService { @Override public void build(DataSetContext context, long organismId) throws DatamartException { try { setNotOk(context); buildGenericDb(context, organismId); buildLuceneIndex(context, organismId); buildEngineData(context, organismId); setOk(context); } catch (Exception e) { throw new DatamartException("failed to build dataset", e); } } @Override void delete(DataSetContext context); @Override void refresh(DataSetContext context, long organismId); @Override void build(DataSetContext context, long organismId); DatamartToGenericDb getDm2gdb(); void setDm2gdb(DatamartToGenericDb dm2gdb); DatamartDb getDmdb(); void setDmdb(DatamartDb dmdb); List<Long> loadNodeIds(NodeCursor cursor, ProgressReporter progress); static IMania getMania(DataSetContext context, boolean memCacheEnabled); void resourceToFile(String resourceName, String outputPath); boolean isOk(DataSetContext context); void setOk(DataSetContext context); void setNotOk(DataSetContext context); }### Answer: @Test public void testBuild() throws Exception { DataSetContext context = dataSetManagerService.getContext(testDataBuilder.testOrganismId); builder.build(context, testDataBuilder.testOrganismId); }
### Question: ResourceNamingServiceImpl implements ResourceNamingService { public static String simplifyName(String name) { String fixed = name.replaceAll(" ", "_"); fixed = fixed.replaceAll("[^0-9a-zA-Z_\\-\\.]", ""); return fixed; } @Override String getName(Network network); @Override String getName(Identifiers identifiers); @Override String getName(Organism organism, AttributeMetadata attributeMetadata); @Override String getName(Organism organism, DataFile dataFile); static String simplifyName(String name); static final String IDENTS; static final String NETWORKS; static final String ATTR_META; }### Answer: @Test public void testSimplifyName() { assertEquals("xyz.txt", simplifyName("xyz.txt")); assertEquals("_ab_CD0-5.txt", simplifyName(" ab_CD0-5().txt")); }
### Question: PubmedServiceImpl implements PubmedService { @Override public PubmedInfo getInfo(long pubmedId) throws DatamartException { try { Document document = getDoc(pubmedId); return getInfo(document); } catch (Exception e) { throw new DatamartException("failed to get pubmed id", e); } } @Override PubmedInfo getInfo(long pubmedId); Document getDoc(long pubmedId); PubmedInfo getInfo(Document document); static final String PUBMED_URL; }### Answer: @Test public void test() throws Exception { long pubmedId = 20576703; PubmedInfo pubmedInfo = pubmedService.getInfo(pubmedId); assertNotNull(pubmedInfo); assertEquals("The GeneMANIA prediction server: biological network integration for gene prioritization and predicting gene function.", pubmedInfo.title); assertEquals("2010", pubmedInfo.year); assertEquals("Warde-Farley", pubmedInfo.faln); assertEquals("Morris", pubmedInfo.laln); }
### Question: GenericDbSchema extends HashMap<String, ArrayList<String>> { public void load() throws IOException { CSVReader reader = new CSVReader(new FileReader(filename), '\t'); List<String[]> records = reader.readAll(); for (String[] record: records) { String fileType = record[0]; ArrayList<String> fields = new ArrayList<String>(Arrays.asList(record)); fields.remove(0); put(fileType, fields); } } GenericDbSchema(String filename); void load(); Record record(String fileType); Parser parser(String fileType, File file, String encoding, char sep); }### Answer: @Test public void testLoad() throws Exception { String schemaFilename = getClass().getResource("/SCHEMA.txt").getFile(); GenericDbSchema schema = new GenericDbSchema(schemaFilename); schema.load(); assertEquals(16, schema.size()); assertEquals(2, schema.get("TAGS").size()); assertEquals("ID", schema.get("TAGS").get(0)); }
### Question: GenericDbSchema extends HashMap<String, ArrayList<String>> { public Record record(String fileType) { return this.new Record(fileType); } GenericDbSchema(String filename); void load(); Record record(String fileType); Parser parser(String fileType, File file, String encoding, char sep); }### Answer: @Test public void testRecord() throws Exception { String schemaFilename = getClass().getResource("/SCHEMA.txt").getFile(); GenericDbSchema schema = new GenericDbSchema(schemaFilename); schema.load(); Record record = schema.record("ORGANISMS"); record.set("ID", 1); record.set("NAME", "test"); record.set("TAXONOMY_ID", "2112"); try { record.set("This is not a valid field", "so this shouldn't work"); fail("assigned to invalid field"); } catch (IllegalArgumentException e) {} assertEquals("test", record.get("NAME")); assertEquals("", record.get("DESCRIPTION")); assertEquals("1\ttest\t\t\t\t2112\n", record.toString()); try { record.set("INVALID", "THIS BETTER FAIL"); fail("expected exception"); } catch (Exception e) {} }
### Question: GenericDbSchema extends HashMap<String, ArrayList<String>> { public Parser parser(String fileType, File file, String encoding, char sep) throws DatamartException { return this.new Parser(fileType, file, encoding, sep); } GenericDbSchema(String filename); void load(); Record record(String fileType); Parser parser(String fileType, File file, String encoding, char sep); }### Answer: @Test public void testParser() throws Exception { String schemaFilename = getClass().getResource("/SCHEMA.txt").getFile(); GenericDbSchema schema = new GenericDbSchema(schemaFilename); schema.load(); String organismsFilename = getClass().getResource("/ORGANISMS.txt").getFile(); Parser parser = schema.parser("ORGANISMS", new File(organismsFilename), "UTF8", '\t'); int i=0; for (Record record: parser) { i+=1; if (i == 4) { assertEquals(record.get("NAME"), "H. sapiens"); } } parser.close(); assertEquals(7, i); }
### Question: MultiOPCSymMatrix extends AbstractMatrix implements SymMatrix { public double get(int row, int col) { double val = matrix.get(row, col); for (OuterProductComboSymMatrix combo: this.combos) { val += combo.get(row, col); } return val; } MultiOPCSymMatrix(SymMatrix matrix, OuterProductComboSymMatrix... combos); int numRows(); int numCols(); double get(int row, int col); void set(int row, int col, double val); void scale(double a); void setAll(double a); MatrixCursor cursor(); void add(Matrix B); void add(double a, Matrix B); double elementSum(); double elementMultiplySum(Matrix m); void CG(Vector x, Vector y); void QR(Vector x, Vector y); Vector rowSums(); Vector columnSums(); void rowSums(double[] result); void columnSums(double[] result); void setToMaxTranspose(); void multAdd(double alpha, Vector x, Vector y); void mult(Vector x, Vector y); Matrix subMatrix(int[] rows, int[] cols); void add(int i, int j, double alpha); void transMult(double[] x, double[] y); void compact(); void multAdd(double alpha, double[] x, double[] y); void mult(double[] x, double[] y); void multAdd(double[] x, double[] y); SymMatrix subMatrix(int[] rowcols); void setDiag(double alpha); void dotDivOuterProd(Vector x); void addOuterProd(double[] x); double sumDotMultOuterProd(double[] x); SymMatrix getMatrix(); OuterProductComboSymMatrix[] getCombos(); }### Answer: @Test public void testGet() throws Exception { OuterProductComboSymMatrix m = new OuterProductComboSymMatrix(a, w, false); MultiOPCSymMatrix m2 = new MultiOPCSymMatrix(c, m); assertEquals(2.14855000000000, m2.get(2,3), 1e-5); }
### Question: DoubleDiagonalMatrix extends AbstractMatrix { public void multAdd(double alpha, Vector x, Vector y) { throw new MatricksException("Not implemented"); } DoubleDiagonalMatrix(int size); DoubleDiagonalMatrix(Vector data); int numRows(); int numCols(); double get(int row, int col); void set(int row, int col, double val); void scale(double a); void setAll(double a); MatrixCursor cursor(); void add(Matrix B); void add(double a, Matrix B); double elementSum(); double elementMultiplySum(Matrix m); void CG(Vector x, Vector y); void QR(Vector x, Vector y); Vector rowSums(); Vector columnSums(); void rowSums(double[] result); void columnSums(double[] result); void setToMaxTranspose(); void multAdd(double alpha, Vector x, Vector y); void mult(Vector x, Vector y); Matrix subMatrix(int[] rows, int[] cols); void add(int i, int j, double alpha); void mult(double [] x, double [] y); void multAdd(double[] x, double[] y); void transMult(double[] x, double[] y); void compact(); }### Answer: @Test public void testMultAdd() { int size = 10; double [] x = new double[size]; double [] y = new double[size]; DenseDoubleVector vector = new DenseDoubleVector(size); for (int i=0; i<size; i++) { vector.set(i, i); x[i] = i; y[i] = 2*i; } DoubleDiagonalMatrix matrix = new DoubleDiagonalMatrix(vector); matrix.multAdd(x, y); for (int i=0; i<size; i++) { double expected = 2*i + i*i; assertEquals(expected, y[i], 1e-7d); } }
### Question: FlexDoubleArray implements Serializable { public double get(int index) { int pos = Utils.binarySearch(indices, index, 0, used); if (pos >= 0) { return data[pos]; } else { return 0; } } FlexDoubleArray(); FlexDoubleArray(int size); FlexDoubleArray(int size, int nz); int getSize(); int nnz(); double get(int index); void set(int index, double val); MatrixCursor cursor(); double dot(DenseDoubleVector v); double dot(double [] v); void add(double alpha, DenseDoubleVector v); void scale(final double alpha); void dotDiv(final double alpha, double [] x); void dotDiv(final double [] x); void add(FlexDoubleArray x); void addTo(double [] x); void add(final double alpha, FlexDoubleArray x); void add(final int index, final double val); double elementSum(); double dot(FlexDoubleArray x); void compact(); static final int FIRST_ALLOC_SIZE; }### Answer: @Test public void testGet() { System.out.println("get"); int index = 0; FlexDoubleArray instance = new FlexDoubleArray(); double expResult = 0.0d; double result = instance.get(index); assertEquals(expResult, result, 0.0); }
### Question: FlexDoubleArray implements Serializable { public void set(int index, double val) throws MatricksException { int pos = Utils.myBinarySearch(indices, index, 0, used); if (pos >= 0) { data[pos] = val; } else { insert(-pos-1, index, val); } } FlexDoubleArray(); FlexDoubleArray(int size); FlexDoubleArray(int size, int nz); int getSize(); int nnz(); double get(int index); void set(int index, double val); MatrixCursor cursor(); double dot(DenseDoubleVector v); double dot(double [] v); void add(double alpha, DenseDoubleVector v); void scale(final double alpha); void dotDiv(final double alpha, double [] x); void dotDiv(final double [] x); void add(FlexDoubleArray x); void addTo(double [] x); void add(final double alpha, FlexDoubleArray x); void add(final int index, final double val); double elementSum(); double dot(FlexDoubleArray x); void compact(); static final int FIRST_ALLOC_SIZE; }### Answer: @Test public void testSet() throws Exception { System.out.println("set"); int size = 10; double offset = 500.0d; double val = 1.0F; FlexDoubleArray instance = new FlexDoubleArray(size, 1); for (int i=0; i<size; i++) { instance.set(i, offset+i); } for (int i=0; i<size; i++) { assertEquals((double) offset+i, instance.get(i), 10e-10); } }
### Question: FlexDoubleArray implements Serializable { public MatrixCursor cursor() { return new FlexDoubleArrayCursor(); } FlexDoubleArray(); FlexDoubleArray(int size); FlexDoubleArray(int size, int nz); int getSize(); int nnz(); double get(int index); void set(int index, double val); MatrixCursor cursor(); double dot(DenseDoubleVector v); double dot(double [] v); void add(double alpha, DenseDoubleVector v); void scale(final double alpha); void dotDiv(final double alpha, double [] x); void dotDiv(final double [] x); void add(FlexDoubleArray x); void addTo(double [] x); void add(final double alpha, FlexDoubleArray x); void add(final int index, final double val); double elementSum(); double dot(FlexDoubleArray x); void compact(); static final int FIRST_ALLOC_SIZE; }### Answer: @Test public void testCursor() throws Exception { System.out.println("cursor"); FlexDoubleArray instance = new FlexDoubleArray(10); instance.set(3, 30d); instance.set(5, 50d); MatrixCursor result = instance.cursor(); assertNotNull(result); assertTrue(result.next()); assertEquals(0, result.col()); assertEquals(3, result.row()); assertEquals(30d, result.val(), 0.000001d); assertTrue(result.next()); assertEquals(0, result.col()); assertEquals(5, result.row()); assertEquals(50d, result.val(), 0.000001d); assertFalse(result.next()); }
### Question: FlexDoubleArray implements Serializable { public double dot(DenseDoubleVector v) { return dot(v.data); } FlexDoubleArray(); FlexDoubleArray(int size); FlexDoubleArray(int size, int nz); int getSize(); int nnz(); double get(int index); void set(int index, double val); MatrixCursor cursor(); double dot(DenseDoubleVector v); double dot(double [] v); void add(double alpha, DenseDoubleVector v); void scale(final double alpha); void dotDiv(final double alpha, double [] x); void dotDiv(final double [] x); void add(FlexDoubleArray x); void addTo(double [] x); void add(final double alpha, FlexDoubleArray x); void add(final int index, final double val); double elementSum(); double dot(FlexDoubleArray x); void compact(); static final int FIRST_ALLOC_SIZE; }### Answer: @Test public void testDot() throws Exception { FlexDoubleArray x = new FlexDoubleArray(10); x.set(0, 10); x.set(1, 11); x.set(3, 13); x.set(5, 15); x.set(9, 19); FlexDoubleArray y = new FlexDoubleArray(10); y.set(0, 10); y.set(1, 11); y.set(5, 15); y.set(8, 18); y.set(9, 19); double result = x.dot(y); assertEquals(807, result, 1e-10); }
### Question: Outer2View extends AbstractMatrix implements Matrix { @Override public void set(int row, int col, double val) throws MatricksException { throw new RuntimeException("read-only"); } Outer2View(FlexFloatArray backing, int [] rowIndices, int [] columnIndices, double scale, boolean zeroDiag); static Outer2View fromColumn(Matrix backingMatrix, int backingColumn,int [] rowIndices, int [] columnIndices, double scale, boolean zeroDiag); @Override int numRows(); @Override int numCols(); @Override double get(int row, int col); @Override void set(int row, int col, double val); @Override MatrixCursor cursor(); @Override void mult(double[] x, double[] y); }### Answer: @Test public void test() throws Exception{ FlexFloatColMatrix m = new FlexFloatColMatrix(4, 5); m.set(1, 0, 1); m.set(3, 0, 1); OuterProductFlexFloatSymMatrix m2 = new OuterProductFlexFloatSymMatrix(4, m.getColumn(0), 1, false); double sum = m2.elementSum(); assertEquals(4d, sum, 0d); int [] rowIndices = {0,1,2}; int [] colIndices = {0,1}; Outer2View m3 = new Outer2View(m.getColumn(0), rowIndices, colIndices, 1d, false); sum = m3.elementSum(); assertEquals(1d, sum, 0d); m3 = new Outer2View(m.getColumn(0), rowIndices, colIndices, 0.5d, false); sum = m3.elementSum(); assertEquals(0.5d, sum, 0d); try { m3 = new Outer2View(m.getColumn(0), rowIndices, colIndices, 0.5d, true); fail("wasn't expecting to get here, maybe you wanna finish this test?"); } catch (RuntimeException e) { } }
### Question: OuterProductSymFloatMatrix extends AbstractMatrix implements OuterProductSymMatrix { public OuterProductSymFloatMatrix(float [] data) { this.data = data; this.size = data.length; } OuterProductSymFloatMatrix(float [] data); OuterProductSymFloatMatrix(int size); int numRows(); int numCols(); double get(int row, int col); void set(int pos, double val); void set(int row, int col, double val); void scale(double a); void setAll(double a); MatrixCursor cursor(); void add(Matrix B); void add(double a, Matrix B); double elementSum(); double elementMultiplySum(Matrix m); double elementMultiplySum(OuterProductSymFloatMatrix m); void CG(Vector x, Vector y); void QR(Vector x, Vector y); Vector rowSums(); Vector columnSums(); void rowSums(double[] result); void columnSums(double[] result); void setToMaxTranspose(); void multAdd(double alpha, Vector x, Vector y); void mult(Vector x, Vector y); Matrix subMatrix(int[] rows, int[] cols); void add(int i, int j, double alpha); void transMult(double[] x, double[] y); void compact(); void multAdd(double alpha, double[] x, double[] y); void mult(double[] x, double[] y); void multAdd(double[] x, double[] y); SymMatrix subMatrix(int[] rowcols); void setDiag(double alpha); void dotDivOuterProd(Vector x); void addOuterProd(double[] x); double sumDotMultOuterProd(double[] x); }### Answer: @Test public void testOuterProductSymFloatMatrix() { int size = 10; SymMatrix m = new OuterProductSymFloatMatrix(size); assertEquals(size, m.numRows()); assertEquals(size, m.numCols()); assertEquals(0.0d, m.get(0, 0), 0d); }
### Question: OuterProductSymFloatMatrix extends AbstractMatrix implements OuterProductSymMatrix { public void set(int pos, double val) { data[pos] = (float) val; } OuterProductSymFloatMatrix(float [] data); OuterProductSymFloatMatrix(int size); int numRows(); int numCols(); double get(int row, int col); void set(int pos, double val); void set(int row, int col, double val); void scale(double a); void setAll(double a); MatrixCursor cursor(); void add(Matrix B); void add(double a, Matrix B); double elementSum(); double elementMultiplySum(Matrix m); double elementMultiplySum(OuterProductSymFloatMatrix m); void CG(Vector x, Vector y); void QR(Vector x, Vector y); Vector rowSums(); Vector columnSums(); void rowSums(double[] result); void columnSums(double[] result); void setToMaxTranspose(); void multAdd(double alpha, Vector x, Vector y); void mult(Vector x, Vector y); Matrix subMatrix(int[] rows, int[] cols); void add(int i, int j, double alpha); void transMult(double[] x, double[] y); void compact(); void multAdd(double alpha, double[] x, double[] y); void mult(double[] x, double[] y); void multAdd(double[] x, double[] y); SymMatrix subMatrix(int[] rowcols); void setDiag(double alpha); void dotDivOuterProd(Vector x); void addOuterProd(double[] x); double sumDotMultOuterProd(double[] x); }### Answer: @Test(expected=MatricksException.class) public void testSet() { int size = 10; OuterProductSymMatrix m = new OuterProductSymFloatMatrix(size); m.set(1, 5d); assertEquals(25d, m.get(1,1), 0d); assertEquals(0d, m.get(0,0), 0d); m.set(0, 0, 1d); }
### Question: Utils { public static int binarySearch(int[] index, int key, int begin, int end) { end--; while (begin <= end) { int mid = (end + begin) >> 1; if (index[mid] < key) { begin = mid + 1; } else if (index[mid] > key) { end = mid - 1; } else { return mid; } } return -1; } static int binarySearch(int[] index, int key, int begin, int end); static int myBinarySearch(int[] indices, int key, int begin, int end); }### Answer: @Test public void testBinarySearch() { System.out.println("binarySearch"); int[] index = {10, 11, 12, 13, 14}; int key = 12; int begin = 0; int end = 5; int expResult = 2; int result = Utils.binarySearch(index, key, begin, end); assertEquals(expResult, result); } @Test public void testBinaryLast() { System.out.println("binarySearch"); int[] index = {10, 11, 12, 13, 14}; int key = 14; int begin = 0; int end = 5; int expResult = 4; int result = Utils.binarySearch(index, key, begin, end); assertEquals(expResult, result); } @Test public void testBinarySearchNotFound() { System.out.println("binarySearch"); int[] index = {10, 13, 15, 17, 19}; int key = 14; int begin = 0; int end = 5; int expResult = -1; int result = Utils.binarySearch(index, key, begin, end); assertEquals(expResult, result); }
### Question: EnrichmentCategoryBuilder extends AbstractEngineApp { @Override public void process() throws Exception { if (orgId != -1) { throw new ApplicationException("single organism processing not implemented"); } for (Organism organism: organismMediator.getAllOrganisms()) { processOrganism(organism); } } String getAnnoDir(); void setAnnoDir(String annoDir); long getOrgId(); void setOrgId(long orgId); void logParams(); @Override void init(); @Override void process(); void processOrganism(Organism organism); static void main(String[] args); }### Answer: @Test @Ignore public void testProcess() throws Exception { String TEST_FILENAME = cacheBuilder.getCacheDir() + File.separator + "test_categories.txt"; buildTestCategoryFile(TEST_FILENAME, 5); EnrichmentCategoryBuilder builder = new EnrichmentCategoryBuilder(); builder.setOrgId(org1Id); builder.setCacheDir(cacheBuilder.getCacheDir()); builder.setCache(cacheBuilder.getCache()); builder.process(); assertTrue("one day, we'll have real tests here!", true); }
### Question: NetworkNormalizer { public static void sparsifyRowsTopKPositives(Matrix m, int k) { for (int i = 0; i < m.numRows(); i++) { Vector v = MatrixUtils.extractRowToVector(m, i); int[] indices = MatrixUtils.getIndicesForSortedValues(v); for (int j = k; j < indices.length; j++) { if (v.get(indices[j]) > 0) { m.set(i, indices[j], 0); } else { break; } } } } String getOutType(); void setOutType(String outType); static void main(String[] args); String getInFilename(); void setInFilename(String inFilename); String getOutFilename(); void setOutFilename(String outFilename); String getLogFilename(); void setLogFilename(String logFilename); String getSynFilename(); void setSynFilename(String synFilename); String getNormalize(); void setNormalize(String normalize); boolean isNormalizationEnabled(); void setNormalizationEnabled(boolean isNormalizationEnabled); void process(); Matrix loadNetwork(Reader source, char delim, int sourceColNum, int targetColNum, int weightColNum); static void sparsifyRowsTopKPositives(Matrix m, int k); void writeNetwork(); }### Answer: @Test public void testSparsify() { Matrix data = new CompColMatrix(new DenseMatrix(new double [][] {{1,2,3,4},{6,4,2,5},{7,8,9,0}})); Matrix expectedResult = new CompColMatrix(new DenseMatrix(new double[][] {{0,0,3,4},{6,0,0,5},{0,8,9,0}})); NetworkNormalizer.sparsifyRowsTopKPositives(data, 2); Utils.elementWiseCompare(expectedResult, data, 0d); }
### Question: LabelWriter { List<LabelResult> sortResults(Vector label, Vector discriminant, Collection<Integer> labelIndices, NodeIds nodeIds) throws ApplicationException { List<LabelResult> list = new ArrayList<LabelResult>(); for (int index : labelIndices) { long nodeId = nodeIds.getIdForIndex(index); Node node = nodeMediator.getNode(nodeId, organismId); Gene gene = getPreferredGene(node); list.add(new LabelResult(gene.getSymbol(), label.get(index), discriminant.get(index))); } Collections.sort(list); return list; } LabelWriter(String basePath, NodeMediator nodeMediator, long organismId); void write(String queryName, int fold, Vector label, Vector discriminant, Collection<Integer> labelIndices, NodeIds nodeIds); }### Answer: @Test public void testSort() throws Exception { File outfile = tempFolder.newFile("LabelWriterTest.txt"); writer = new LabelWriter(outfile.getPath(), mediator, organismId); Vector label = new DenseVector(new double[] { 0, 1, 0, 1 }); Vector discriminant = new DenseVector(new double[] { 2, 1, 1, 0 }); List<Integer> labelIndices = new ArrayList<Integer>(); labelIndices.add(3); labelIndices.add(1); labelIndices.add(2); labelIndices.add(0); NodeIds nodeIds = new NodeIds(organismId); nodeIds.setNodeIds(new long[] { 0, 1, 2, 3 }); List<LabelResult> results = writer.sortResults(label, discriminant, labelIndices, nodeIds); Assert.assertEquals("3", results.get(0).getName()); Assert.assertEquals("2", results.get(1).getName()); Assert.assertEquals("1", results.get(2).getName()); Assert.assertEquals("0", results.get(3).getName()); }
### Question: Mania2 implements IMania { @Override public String getVersion() { return Config.instance().getVersion(); } Mania2(DataCache cache); @Override RelatedGenesEngineResponseDto findRelated(RelatedGenesEngineRequestDto request); @Override ListNetworksEngineResponseDto listNetworks(ListNetworksEngineRequestDto request); @Override UploadNetworkEngineResponseDto uploadNetwork(UploadNetworkEngineRequestDto request); RemoveNetworkEngineResponseDto removeUserNetworks(RemoveNetworkEngineRequestDto request); @Override void clearMemCache(); @Override String getVersion(); @Override EnrichmentEngineResponseDto computeEnrichment(EnrichmentEngineRequestDto request); @Override AddOrganismEngineResponseDto addOrganism(AddOrganismEngineRequestDto request); @Override AddAttributeGroupEngineResponseDto addAttributeGroup(AddAttributeGroupEngineRequestDto request); @Override ListAttributeGroupsEngineResponseDto listAttributes(ListAttributeGroupsEngineRequestDto request); @Override RemoveAttributeGroupEngineResponseDto removeAttributeGroup(RemoveAttributeGroupEngineRequestDto request); @Override AddEnrichmentAttributesEngineResponseDto addOntology(AddEnrichmentAttributesEngineRequestDto request); @Override NetworkCombinationResponseDto getCombinedNetwork(NetworkCombinationRequestDto request); }### Answer: @Test public void testVersion() { IMania mania = new Mania2(null); String version = mania.getVersion(); System.out.println("version: " + version); assertNotNull(version); assertFalse(version.equalsIgnoreCase(Constants.UNKNOWN_VERSION)); }
### Question: FeatureList extends ArrayList<Feature> { public void validate() throws ApplicationException { HashSet<Feature> uniq = new HashSet<Feature>(); uniq.addAll(this); if (uniq.size() != this.size()) { throw new ApplicationException("the feature list contains duplicates"); } } FeatureList(); FeatureList(int size); FeatureList(FeatureList featureList, boolean addBias); void validate(); Collection<FeatureList> group(); int indexOf(Feature feature); void addBias(); void removeBias(); boolean hasBias(); }### Answer: @Test public void test() throws Exception { Feature f1 = new Feature(NetworkType.ATTRIBUTE_VECTOR, 1, 10); Feature f2 = new Feature(NetworkType.SPARSE_MATRIX, 1, 10); FeatureList list = new FeatureList(); list.add(f1); list.add(f2); list.validate(); Collections.sort(list); Iterator<Feature> iter = list.iterator(); assertEquals(NetworkType.SPARSE_MATRIX, iter.next().getType()); assertEquals(NetworkType.ATTRIBUTE_VECTOR, iter.next().getType()); assertFalse(iter.hasNext()); HashSet<Feature> featureSet = new HashSet<Feature>(); featureSet.addAll(list); assertEquals(2, featureSet.size()); featureSet.addAll(list); assertEquals(2, featureSet.size()); } @Test(expected = ApplicationException.class) public void testDuplicate() throws Exception { Feature f1 = new Feature(NetworkType.ATTRIBUTE_VECTOR, 1, 10); Feature f2 = new Feature(NetworkType.ATTRIBUTE_VECTOR, 1, 10); FeatureList list = new FeatureList(); list.add(f1); list.add(f2); list.validate(); }
### Question: CombineNetworksOnly { public static SymMatrix combine(FeatureWeightMap weightMap, String namespace, long organismId, DataCache cache, ProgressReporter progress) throws ApplicationException { return combineWithAdder(weightMap, namespace, organismId, cache,progress); } static SymMatrix combine(FeatureWeightMap weightMap, String namespace, long organismId, DataCache cache, ProgressReporter progress); static Logger logger; }### Answer: @Test public void testCombineFeatures() throws ApplicationException { SymMatrix result = CombineNetworksOnly.combine(getFeatureWeightMap(getFeatures()), Data.CORE, config.getOrg1Id(), cacheBuilder.getCache(), NullProgressReporter.instance()); assertNotNull(result); }
### Question: AverageByNetworkCalculator extends AbstractNetworkWeightCalculator { protected static FeatureWeightMap average(FeatureList features) { FeatureWeightMap weightMap = new FeatureWeightMap(); int n = features.size(); if (features.hasBias()) { n = n - 1; } double weight = 1.0d / n; for (Feature feature: features) { if (feature.getType() != NetworkType.BIAS) { weightMap.put(feature, weight); } } return weightMap; } AverageByNetworkCalculator(String namespace, DataCache cache, Collection<Collection<Long>> networkIds, Collection<Long> attributeGroupIds, long organismId, Vector label, int attributesLimit, ProgressReporter progress); void process(); @Override String getParameterKey(); static final String PARAM_KEY_FORMAT; }### Answer: @Test public void testAverage() { System.out.println("average"); Map<Integer, Long> IndexToNetworkMap = new HashMap<Integer, Long>(); for (int i=0; i<config.getOrg1NetworkIds().length; i++) { IndexToNetworkMap.put(i, config.getOrg1NetworkIds()[i]); } Map<Long, Double> result = AverageByNetworkCalculator.averageNetworksOnly(IndexToNetworkMap); assertNotNull(result); assertEquals(config.getOrg1NetworkIds().length, result.size()); for (Double weight: result.values()) { assertEquals(1d/config.getOrg1NetworkIds().length, weight, .000001d); } }
### Question: SparseBinaryToNetwork { protected void countNonZerosPerFeature(List<int[]> profileData) { numNonZerosPerFeature = new int[numFeatures]; for (int [] g: profileData) { for (int i=0; i<g.length; i++) { numNonZerosPerFeature[g[i]] += 1; } } } SparseBinaryToNetwork(int numGenes, int numFeatures); void convert(List<int[]> profileData, int k); Matrix convertToInteractionMatrix(); int dump(PrintWriter writer, String[] geneNames); }### Answer: @Test public void testCountNonZerosPerFeature() { int numFeatures = 10; int [] g1 = {2,4}; int [] g2 = {3,4,9}; int [] g3 = {}; Vector<int[]> profileData = new Vector<int[]>(); profileData.add(g1); profileData.add(g2); profileData.add(g3); int numGenes = profileData.size(); SparseBinaryToNetwork p2n = new SparseBinaryToNetwork(numGenes, numFeatures); p2n.countNonZerosPerFeature(profileData); assertNotNull(p2n.numNonZerosPerFeature); assertEquals(10, p2n.numNonZerosPerFeature.length); assertEquals(0, p2n.numNonZerosPerFeature[0]); assertEquals(0, p2n.numNonZerosPerFeature[1]); assertEquals(1, p2n.numNonZerosPerFeature[2]); assertEquals(1, p2n.numNonZerosPerFeature[3]); assertEquals(2, p2n.numNonZerosPerFeature[4]); assertEquals(0, p2n.numNonZerosPerFeature[5]); assertEquals(0, p2n.numNonZerosPerFeature[6]); assertEquals(0, p2n.numNonZerosPerFeature[7]); assertEquals(0, p2n.numNonZerosPerFeature[8]); assertEquals(1, p2n.numNonZerosPerFeature[9]); }
### Question: SparseBinaryToNetwork { protected void computeFactors() { pf = new double[numFeatures]; nf = new double[numFeatures]; ppf = new double[numFeatures]; pnf = new double[numFeatures]; nnf = new double[numFeatures]; for (int i=0; i<numFeatures; i++) { double mean = (1.0 * numNonZerosPerFeature[i]) / numGenes; if (mean == 0) { continue; } pf[i] = -Math.log(mean); nf[i] = Math.log(1-mean); ppf[i] = pf[i]*pf[i]; pnf[i] = pf[i]*nf[i]; nnf[i] = nf[i]*nf[i]; } } SparseBinaryToNetwork(int numGenes, int numFeatures); void convert(List<int[]> profileData, int k); Matrix convertToInteractionMatrix(); int dump(PrintWriter writer, String[] geneNames); }### Answer: @Test public void testComputeFactors() { int numFeatures = 10; int [] g1 = {2,4}; int [] g2 = {3,4,9}; int [] g3 = {}; Vector<int[]> profileData = new Vector<int[]>(); profileData.add(g1); profileData.add(g2); profileData.add(g3); int numGenes = profileData.size(); SparseBinaryToNetwork p2n = new SparseBinaryToNetwork(numGenes, numFeatures); p2n.countNonZerosPerFeature(profileData); p2n.computeFactors(); assertNotNull(p2n.nnf); assertNotNull(p2n.pnf); assertNotNull(p2n.ppf); }
### Question: SparseBinaryToNetwork { protected void computeCorrelations(List<int[]> profileData, int k) { int numGenes = profileData.size(); topInteractions = new KHeap[numGenes]; for (int i=0; i<numGenes; i++) { topInteractions[i] = new KHeap(k); } System.out.println("computing correlations"); for (int i=0; i<numGenes; i++) { for (int j=0; j<i; j++) { double weight = computeCorrelation(profileData.get(i), profileData.get(j)); topInteractions[i].offer(j, weight); topInteractions[j].offer(i, weight); } } System.out.println("done"); } SparseBinaryToNetwork(int numGenes, int numFeatures); void convert(List<int[]> profileData, int k); Matrix convertToInteractionMatrix(); int dump(PrintWriter writer, String[] geneNames); }### Answer: @Test public void testComputeCorrelations() { int numFeatures = 10; int [] g1 = {2,4}; int [] g2 = {3,4,9}; int [] g3 = {}; Vector<int[]> profileData = new Vector<int[]>(); profileData.add(g1); profileData.add(g2); profileData.add(g3); int numGenes = profileData.size(); SparseBinaryToNetwork p2n = new SparseBinaryToNetwork(numGenes, numFeatures); p2n.countNonZerosPerFeature(profileData); p2n.computeFactors(); p2n.computeNegBaseline(); p2n.computeCorrelation(g1, g2); }
### Question: ObjectSelector { public ObjectSelector<T> lt(double v) { ObjectSelector<T> result = new ObjectSelector<T>(); final int n = scores.size(); for (int i=0; i<n; i++) { if (scores.get(i) < v) { result.add(elements.get(i), scores.get(i)); } } return result; } void add(T element, Double score); void add(List<T> elements, double [] scores); void add(FeatureList features, DenseVector scores); @SuppressWarnings("unchecked") void add(ObjectSelector<Feature> list); int size(); ObjectSelector<T> selectLevelledSmallestScores(int n, int maxSize); DenseVector toDenseVector(); ObjectSelector<T> lt(double v); ObjectSelector<T> le(double v); ObjectSelector<T> gt(double v); ObjectSelector<T> ge(double v); ArrayList<T> getElements(); ArrayList<Double> getScores(); T getElement(int i); double getScore(int i); }### Answer: @Test public void testLt() { ObjectSelector<Integer> selector = new ObjectSelector<Integer>(); selector.add(1, 10.0); selector.add(2, 20.0); ObjectSelector<Integer> result = selector.lt(20.0); assertEquals(2, selector.size()); assertEquals(1, result.size()); assertEquals(1, (int) result.getElement(0)); assertEquals(10.0d, result.getScore(0), 0d); }
### Question: Logging { public static String duration(long start, long end) { long duration = end - start; long millis = duration % 1000; long secs = duration / 1000; long mins = secs / 60; secs = secs % 60; return String.format("%d minutes %d seconds %d millis", mins, secs, millis); } static String duration(long start, long end); }### Answer: @Test public void testDuration() { assertEquals("0 minutes 0 seconds 0 millis", Logging.duration(10, 10)); assertEquals("0 minutes 0 seconds 155 millis", Logging.duration(100000, 100155)); assertEquals("3 minutes 15 seconds 395 millis", Logging.duration(555555555, 555750950)); assertEquals("200 minutes 15 seconds 395 millis", Logging.duration(555555555, 567570950)); }
### Question: KHeap { public int popLE(double threshold) { int numPopped = 0; if (getWeight(0) <= threshold && additionalData != null) { numPopped = additionalData.size()/2; additionalData = null; } boolean popped = true; while (popped & size > 0 && getWeight(0) <= threshold) { popped = pop(); if (popped) { numPopped += 1; } } return numPopped; } KHeap(int maxSize); KHeap(int maxSize, boolean extensible); boolean offer(final int id, final double weight); int size(); void dump(); long getId(final int i); double getWeight(final int i); int getExtensionSize(); boolean pop(); int popLE(double threshold); }### Answer: @Test public void testPopLE() { KHeap heap = new KHeap(3, true); heap.offer(1, 1); heap.offer(2, 2); heap.offer(3, 1); heap.offer(4, 1); heap.offer(5, 0); assertEquals(4, heap.size()); int numPopped = heap.popLE(0); assertEquals(0, numPopped); assertEquals(4, heap.size()); numPopped = heap.popLE(1d); assertEquals(3, numPopped); assertEquals(1, heap.size()); assertEquals(2d, heap.getWeight(0), 0d); }
### Question: AbstractPearson implements Correlation { public static double getZeroRank(Vector v){ if ( v instanceof DenseVector ){ return 0; } else if ( v instanceof SparseVector ){ int numZeroes = v.size() - ((SparseVector) v).getUsed(); if ( numZeroes == 0 ) { return 0; } else { return (double) ( (1 + numZeroes) * numZeroes ) / (2 * numZeroes); } } else { throw new RuntimeException( "unexpected vector type of " + v.getClass().getName() ); } } double computeCorrelations(int i, int j); void init(ProfileData data); double getThresholdValue(); static double getZeroRank(Vector v); static final double MIN_STDEV; }### Answer: @Test public void testGetZeroRank(){ Vector v = new DenseVector(new double[]{1, 2, 3, 4, 5}); assertEquals( AbstractPearson.getZeroRank(v), 0.0, 0d ); v = new SparseVector(5, new int[]{2, 3}, new double[]{1,1}); assertEquals( AbstractPearson.getZeroRank(v), 2.0, 0d); v = new SparseVector(5, new int[]{2}, new double[]{1}); assertEquals( AbstractPearson.getZeroRank(v), 2.5, 0d); }
### Question: NetworkMemCache { public void clear() { softCache.clear(); } NetworkMemCache(); static NetworkMemCache instance(); Matrix get(int organismId, int networkId); Matrix get(String namespace, int organismId, int networkId); void put(int organismId, int networkId, Matrix network); void put(String namespace, int organismId, int networkId, Matrix network); void clear(); void compact(); static final String CORE; }### Answer: @Test public void testClear() { System.out.println("clear"); int organismId = 1; int networkId = 3; NetworkMemCache instance = NetworkMemCache.instance(); instance.clear(); Matrix expResult = null; Matrix result = instance.get(organismId, networkId); assertEquals(expResult, result); Matrix m = new DenseMatrix(5, 5); instance.put(organismId, networkId ,m); result = instance.get(organismId, networkId); assertEquals(m, result); instance.clear(); result = instance.get(organismId, networkId); assertEquals(null, result); }
### Question: NetworkMemCache { public void compact() { for (String key: softCache.keySet()) { SoftReference<Matrix> ref = softCache.get(key); if (ref == null) { softCache.remove(key); } else if (ref.get() == null) { softCache.remove(key); } } } NetworkMemCache(); static NetworkMemCache instance(); Matrix get(int organismId, int networkId); Matrix get(String namespace, int organismId, int networkId); void put(int organismId, int networkId, Matrix network); void put(String namespace, int organismId, int networkId, Matrix network); void clear(); void compact(); static final String CORE; }### Answer: @Test public void testCompact() { System.out.println("compact"); int organismId = 1; int networkId = 3; NetworkMemCache instance = NetworkMemCache.instance(); instance.clear(); Matrix expResult = null; Matrix result = instance.get(organismId, networkId); assertEquals(expResult, result); Matrix m = new DenseMatrix(5, 5); instance.put(organismId, networkId ,m); result = instance.get(organismId, networkId); assertEquals(m, result); instance.compact(); result = instance.get(organismId, networkId); }
### Question: MemObjectCache implements IObjectCache { public String getCacheDir() throws ApplicationException { return underlyingCache.getCacheDir(); } MemObjectCache(IObjectCache underlyingCache); String getCacheDir(); void put(String [] key, Object value, boolean isVolatile); Object get(String [] key, boolean isVolatile); void remove(String [] key); boolean exists(String[] key); List<String[]> list(String[] key); static final String CORE; }### Answer: @Test public void testVolatileObjects() throws Exception { FileSerializedObjectCache fileCache = new FileSerializedObjectCache(cacheBuilder.getCacheDir()); MemObjectCache memCache = new MemObjectCache(fileCache); DataCache dcache = cacheBuilder.getCache(); NetworkIds networkIds = dcache.getNetworkIds(Data.CORE, org1Id); assertNotNull(networkIds); int numNetworks = networkIds.getNetworkIds().length; NetworkIds userNetworkIds = networkIds.copy("user1"); dcache.putNetworkIds(userNetworkIds); DataCache dcache2 = new DataCache(new FileSerializedObjectCache(cacheBuilder.getCacheDir())); long SILLY_NETWORK_TEST_VALUE = 55; userNetworkIds.setNetworkIds(new long[] {SILLY_NETWORK_TEST_VALUE}); dcache2.putNetworkIds(userNetworkIds); NetworkIds userNetworkIds2 = dcache.getNetworkIds("user1", org1Id); assertNotNull(userNetworkIds2); assertEquals(1, userNetworkIds2.getNetworkIds().length); assertEquals(SILLY_NETWORK_TEST_VALUE, userNetworkIds2.getNetworkIds()[0]); }
### Question: MemObjectCache implements IObjectCache { public void remove(String [] key) throws ApplicationException { memCache.remove(makeMemCacheKey(key)); underlyingCache.remove(key); } MemObjectCache(IObjectCache underlyingCache); String getCacheDir(); void put(String [] key, Object value, boolean isVolatile); Object get(String [] key, boolean isVolatile); void remove(String [] key); boolean exists(String[] key); List<String[]> list(String[] key); static final String CORE; }### Answer: @Test public void testRemove() throws Exception { FileSerializedObjectCache fileCache = new FileSerializedObjectCache(cacheBuilder.getCacheDir()); MemObjectCache memCache = new MemObjectCache(fileCache); DataCache dcache = cacheBuilder.getCache(); NetworkIds networkIds = dcache.getNetworkIds(Data.CORE, org1Id); assertNotNull(networkIds); dcache.removeData(networkIds); try { NetworkIds networkIds2 = dcache.getNetworkIds(Data.CORE, org1Id); fail("removing object should have given error"); } catch (ApplicationException e) { } }
### Question: FileSerializedObjectCache implements IObjectCache { public boolean exists(String[] key) throws ApplicationException { if (key == null || key.length == 0) { throw new ApplicationException("null or empty object key"); } String filename = getFilename(key); File file = new File(filename); return file.exists(); } FileSerializedObjectCache(String cacheDir, boolean zipEnabled); FileSerializedObjectCache(String cacheDir); String getCacheDir(); String getFilename(String [] key); String getSubdirname(String [] key, int len); void putObject(String subdir, String key, Object value); void put(String [] key, Object value, boolean isVolatile); Object get(String [] key, boolean isVolatile); void remove(String [] key); boolean exists(String[] key); List<String[]> list(String[] key); }### Answer: @Test public void testExists() throws Exception { IObjectCache cache = new FileSerializedObjectCache(tempDir.getTempDir()); String [] key = {"A", "B.txt"}; cache.put(key, key, true); assertFalse(cache.exists(new String[] {"C"})); assertFalse(cache.exists(new String[] {"A", "C.txt"})); assertTrue(cache.exists(key)); }
### Question: FileSerializedObjectCache implements IObjectCache { public List<String[]> list(String[] key) throws ApplicationException { if (key == null || key.length == 0) { throw new ApplicationException("null or empty object key"); } List<String[]> result = new ArrayList<String[]>(); String dirName = getSubdirname(key, key.length); File dir = new File(dirName); if (!dir.isDirectory()) { return result; } File[] entries = dir.listFiles(); for (File entry: entries) { result.add(fileToKey(entry)); } return result; } FileSerializedObjectCache(String cacheDir, boolean zipEnabled); FileSerializedObjectCache(String cacheDir); String getCacheDir(); String getFilename(String [] key); String getSubdirname(String [] key, int len); void putObject(String subdir, String key, Object value); void put(String [] key, Object value, boolean isVolatile); Object get(String [] key, boolean isVolatile); void remove(String [] key); boolean exists(String[] key); List<String[]> list(String[] key); }### Answer: @Test public void testList() throws Exception { IObjectCache cache = new FileSerializedObjectCache(tempDir.getTempDir()); String [] key = {"A", "B.txt"}; cache.put(key, key, true); List<String[]> result; result = cache.list(new String[] {"C"}); assertNotNull(result); assertEquals(0, result.size()); result = cache.list(new String[] {"A"}); assertNotNull(result); assertEquals(1, result.size()); String[] childKey = result.get(0); assertEquals(2, childKey.length); assertEquals("A", childKey[0]); assertEquals("B.txt", childKey[1]); }
### Question: ComputeEnrichment { public static double computeHyperGeo(double x, double N, double n, double k) { double h = Gamma.logGamma(k+1) - Gamma.logGamma(k-x+1) - Gamma.logGamma(x+1) + Gamma.logGamma(N-k+1) - Gamma.logGamma(N-k-n+x+1) - Gamma.logGamma(n-x+1) - Gamma.logGamma(N+1) + Gamma.logGamma(N-n+1) + Gamma.logGamma(n+1); return Math.exp(h); } ComputeEnrichment(DataCache cache, EnrichmentEngineRequestDto request); EnrichmentEngineResponseDto process(); static double computeHyperGeo(double x, double N, double n, double k); static double computeCumulHyperGeo(double x, double N, double n, double k); static DenseVector computeFDRqval(int N, DenseVector pvals); }### Answer: @Test public void testHyperGeo() { double N = 20; double k = 6; double n = 7; double x = 4; double p = ComputeEnrichment.computeHyperGeo(x, N, n, k); assertEquals(7.04334e-2, p, 1e-6); }
### Question: ComputeEnrichment { public static double computeCumulHyperGeo(double x, double N, double n, double k) { double p = 0; double upperBound = Math.min(n, k); for (double i=x; i<=upperBound; i++) { p += computeHyperGeo(i, N, n, k); } return p; } ComputeEnrichment(DataCache cache, EnrichmentEngineRequestDto request); EnrichmentEngineResponseDto process(); static double computeHyperGeo(double x, double N, double n, double k); static double computeCumulHyperGeo(double x, double N, double n, double k); static DenseVector computeFDRqval(int N, DenseVector pvals); }### Answer: @Test public void testCumulHyperGeo() { double N = 20; double k = 6; double n = 7; double x = 4; double p = ComputeEnrichment.computeCumulHyperGeo(x, N, n, k); assertEquals(7.76573e-2, p, 1e-6); }
### Question: ComputeEnrichment { public static DenseVector computeFDRqval(int N, DenseVector pvals) { DenseVector ranks = pvals.copy(); MatrixUtils.rank(ranks); DenseVector ordered = new DenseVector(pvals.size()); for (int i=0; i<ranks.size(); i++) { int p = (int) Math.round(ranks.get(i))-1; ordered.set(p, pvals.get(i)); } DenseVector qval = new DenseVector(pvals.size()); double minSoFar = Double.MAX_VALUE; for (int i=ranks.size()-1; i>=0; i--) { double p = ordered.get(i); int m = i+1; minSoFar = Math.min(minSoFar, N*p/m); qval.set(i, minSoFar); } DenseVector unOrderedqval = new DenseVector(pvals.size()); for (int i=0; i<unOrderedqval.size(); i++) { int p = (int) Math.round(ranks.get(i))-1; unOrderedqval.set(i, qval.get(p)); } return unOrderedqval; } ComputeEnrichment(DataCache cache, EnrichmentEngineRequestDto request); EnrichmentEngineResponseDto process(); static double computeHyperGeo(double x, double N, double n, double k); static double computeCumulHyperGeo(double x, double N, double n, double k); static DenseVector computeFDRqval(int N, DenseVector pvals); }### Answer: @Test public void testComputeFDRqval() { double[] data = {.5, .3, .8, .02, .1}; DenseVector pval = new DenseVector(data); DenseVector qval = ComputeEnrichment.computeFDRqval(10, pval); assertNotNull(qval); System.out.println(qval); }
### Question: StrMatchUtils { public static boolean isMatch(String str, String exp) { int strIndex = 0; int expIndex = 0; int starIndex = -1; while (strIndex < str.length()) { char pkgChar = str.charAt(strIndex); char expChar = expIndex < exp.length() ? exp.charAt(expIndex) : '\0'; if (pkgChar == expChar) { strIndex++; expIndex++; } else if (expChar == '*') { starIndex = expIndex; expIndex++; } else if (starIndex != -1) { expIndex = starIndex + 1; strIndex++; } else { return false; } } while (expIndex < exp.length() && exp.charAt(expIndex) == '*') { expIndex++; } return expIndex == exp.length(); } private StrMatchUtils(); static boolean isMatch(String str, String exp); }### Answer: @Test public void testIsMatch() { Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "cn.myperf4j*abc")); Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*abc")); Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*a*c")); Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "*.myperf4j*ac")); Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "a*.myperf4j*ac")); Assert.assertFalse(isMatch("cn.myperf4j.config.abc", "a*.myperf4j.a*")); }
### Question: InfluxDbClient { public boolean createDatabase() { HttpRequest req = new HttpRequest.Builder() .url(url + "/query") .header("Authorization", authorization) .post("q=CREATE DATABASE " + database) .build(); try { HttpResponse response = httpClient.execute(req); Logger.info("InfluxDbClient create database '" + database + "' response.status=" + response.getStatus()); if (response.getStatus().statusClass() == SUCCESS) { return true; } } catch (IOException e) { Logger.error("InfluxDbClient.createDatabase(): e=" + e.getMessage(), e); } return false; } InfluxDbClient(Builder builder); boolean createDatabase(); boolean writeMetricsAsync(final String content); }### Answer: @Test public void testBuildDatabase() { boolean database = influxDbClient.createDatabase(); System.out.println(database); }
### Question: InfluxDbClient { public boolean writeMetricsAsync(final String content) { try { ASYNC_EXECUTOR.execute(new ReqTask(content)); return true; } catch (Throwable t) { Logger.error("InfluxDbClient.writeMetricsAsync(): t=" + t.getMessage(), t); } return false; } InfluxDbClient(Builder builder); boolean createDatabase(); boolean writeMetricsAsync(final String content); }### Answer: @Test public void testWrite() throws InterruptedException { boolean write = influxDbClient.writeMetricsAsync( "cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000\n" + "cpu_load_short,host=server02,region=us-west value=0.96 1434055562000000000"); System.out.println(write); TimeUnit.SECONDS.sleep(3); }
### Question: HttpHeaders { public void set(String name, String value) { List<String> values = headers.get(name); if (values == null) { values = new ArrayList<>(1); headers.put(name, values); } else { values.clear(); } values.add(value); } HttpHeaders(int size); HttpHeaders(Map<String, List<String>> headers); String get(String name); List<String> getValues(String name); void set(String name, String value); void add(String name, String value); List<String> names(); Map<String, List<String>> headers(); static HttpHeaders defaultHeaders(); }### Answer: @Test public void testSet() { HttpHeaders headers = new HttpHeaders(2); headers.set("Connection", "close"); headers.set("Connection", "Keep-Alive"); headers.set("Accept-Encoding", "gzip, deflate"); Assert.assertEquals("Keep-Alive", headers.get("Connection")); Assert.assertEquals("gzip, deflate", headers.get("Accept-Encoding")); Assert.assertEquals(Collections.singletonList("Keep-Alive"), headers.getValues("Connection")); Assert.assertEquals(Collections.singletonList("gzip, deflate"), headers.getValues("Accept-Encoding")); }
### Question: HttpHeaders { public void add(String name, String value) { List<String> values = headers.get(name); if (values == null) { values = new ArrayList<>(1); headers.put(name, values); } values.add(value); } HttpHeaders(int size); HttpHeaders(Map<String, List<String>> headers); String get(String name); List<String> getValues(String name); void set(String name, String value); void add(String name, String value); List<String> names(); Map<String, List<String>> headers(); static HttpHeaders defaultHeaders(); }### Answer: @Test public void testAdd() { HttpHeaders headers = new HttpHeaders(2); headers.set("Connection", "Keep-Alive"); headers.add("Connection", "close"); Assert.assertEquals("Keep-Alive", headers.get("Connection")); Assert.assertEquals(Arrays.asList("Keep-Alive", "close"), headers.getValues("Connection")); }
### Question: HttpRequest { public String getFullUrl() { if (StrUtils.isNotEmpty(fullUrl)) { return fullUrl; } return fullUrl = createFullUrl(); } HttpRequest(Builder builder); HttpMethod getMethod(); HttpHeaders getHeaders(); Map<String, List<String>> getParams(); byte[] getBody(); String getPath(); String getUrl(); String getFullUrl(); String getParam(String key); Boolean getBoolParam(String key); @Override String toString(); }### Answer: @Test public void testFullUrlWithoutProtocol() { HttpRequest req0 = new HttpRequest.Builder() .url("localhost:8086/write") .params(MapUtils.of("k1", singletonList("v1"))) .get() .build(); Assert.assertEquals("http: HttpRequest req1 = new HttpRequest.Builder() .url("localhost:8086/write?") .params(MapUtils.of("k1", singletonList("v1"))) .get() .build(); Assert.assertEquals("http: HttpRequest req2 = new HttpRequest.Builder() .url("localhost:8086/write?k1=v1") .params(MapUtils.of("k2", singletonList("v2"))) .post("abcd") .build(); Assert.assertEquals("http: } @Test public void testFullUrlWithProtocol() { HttpRequest req0 = new HttpRequest.Builder() .url("http: .params(MapUtils.of("k1", singletonList("v1"))) .get() .build(); Assert.assertEquals("http: HttpRequest req1 = new HttpRequest.Builder() .url("http: .params(MapUtils.of("k1", singletonList("v1"))) .get() .build(); Assert.assertEquals("http: HttpRequest req2 = new HttpRequest.Builder() .url("https: .params(MapUtils.of("k2", singletonList("v2"))) .post("abcd") .build(); Assert.assertEquals("https: }
### Question: HttpClient { public HttpResponse execute(HttpRequest request) throws IOException { HttpURLConnection urlConn = createConnection(request); urlConn.connect(); HttpHeaders headers = new HttpHeaders(urlConn.getHeaderFields()); HttpRespStatus status = HttpRespStatus.valueOf(urlConn.getResponseCode()); if (SUCCESS.contains(status.code())) { return new HttpResponse(status, headers, toBytes(urlConn.getInputStream())); } else { return new HttpResponse(status, headers, toBytes(urlConn.getErrorStream())); } } HttpClient(Builder builder); HttpResponse execute(HttpRequest request); }### Answer: @Test public void testGet() { HttpRequest req = new HttpRequest.Builder() .url("http: .get() .build(); try { HttpResponse resp = httpClient.execute(req); HttpHeaders headers = resp.getHeaders(); System.out.println("Status=" + resp.getStatus()); System.out.println("Connection=" + headers.get("Connection")); System.out.println(resp.getBodyString()); } catch (Exception e) { e.printStackTrace(); } } @Test public void testPost() { Map<String, List<String>> params = MapUtils.createHashMap(2); params.put("db", Collections.singletonList("http")); HttpRequest req = new HttpRequest.Builder() .url("localhost:8686/write") .params(params) .post("cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000\n" + "cpu_load_short,host=server02,region=us-west value=0.96 1434055562000000000") .build(); for (int i = 0; i < 10; i++) { try { HttpResponse resp = httpClient.execute(req); Assert.assertEquals(OK, resp.getStatus()); Assert.assertEquals(RESPONSE_BODY, resp.getBodyString()); } catch (Exception e) { e.printStackTrace(); } } }
### Question: DateUtils { public static boolean isSameDay(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } private DateUtils(); static boolean isSameDay(Date date1, Date date2); static boolean isSameHour(Date date1, Date date2); static boolean isSameMinute(Date date1, Date date2); }### Answer: @Test public void testSameDay() { Assert.assertTrue(isSameDay(new Date(), new Date())); Assert.assertFalse(isSameDay(new Date(), new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))); }
### Question: DateUtils { public static boolean isSameMinute(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE); } private DateUtils(); static boolean isSameDay(Date date1, Date date2); static boolean isSameHour(Date date1, Date date2); static boolean isSameMinute(Date date1, Date date2); }### Answer: @Test public void testSameMinute() { Assert.assertTrue(isSameMinute(new Date(), new Date())); Assert.assertFalse(isSameMinute(new Date(), new Date(System.currentTimeMillis() + 60 * 1000))); }
### Question: DateUtils { public static boolean isSameHour(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY); } private DateUtils(); static boolean isSameDay(Date date1, Date date2); static boolean isSameHour(Date date1, Date date2); static boolean isSameMinute(Date date1, Date date2); }### Answer: @Test public void testSameHour() { Assert.assertTrue(isSameHour(new Date(), new Date())); Assert.assertFalse(isSameHour(new Date(), new Date(System.currentTimeMillis() + 60 * 60 * 1000))); }
### Question: BukkitDLUpdaterService { public ArtifactDetails fetchArtifact(String slug) throws IOException { URL url = new URL("http", host, API_PREFIX_ARTIFACT + slug + "/"); InputStreamReader reader = null; try { URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); reader = new InputStreamReader(connection.getInputStream()); Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, dateDeserializer).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); return gson.fromJson(reader, ArtifactDetails.class); } finally { if (reader != null) { reader.close(); } } } BukkitDLUpdaterService(String host); ArtifactDetails getArtifact(String slug, String name); ArtifactDetails fetchArtifact(String slug); ArtifactDetails.ChannelDetails getChannel(String slug, String name); ArtifactDetails.ChannelDetails fetchChannel(String slug); }### Answer: @Test(expected=IOException.class) public void testHostNotFound() throws IOException { BukkitDLUpdaterService service = new BukkitDLUpdaterService("404.example.org"); service.fetchArtifact("rb"); } @Test(expected=FileNotFoundException.class) public void testArtifactNotFound() throws IOException { BukkitDLUpdaterService service = new BukkitDLUpdaterService("dl.bukkit.org"); service.fetchArtifact("meep"); } @Test public void testArtifactExists() throws IOException { BukkitDLUpdaterService service = new BukkitDLUpdaterService("dl.bukkit.org"); assertThat(service.fetchArtifact("latest-dev"), is(not(nullValue()))); }
### Question: NestedRadioGroupManager { public void initCheckedId(int value) { checkedId = value; initialCheckedId = value; } NestedRadioGroupManager(); void initCheckedId(int value); int getCheckedId(); void addNestedRadioButton(NestedRadioButton nestedRadioButton); void check(@IdRes int id); @TargetApi(Build.VERSION_CODES.O) void onProvideAutofillStructure(ViewStructure structure); void clearCheck(); void setOnCheckedChangeListener(OnCheckedChangeListener listener); }### Answer: @Test public void initCheckedId() { int initialId = 12345; nestedRadioGroupManager.initCheckedId(initialId); assertEquals(initialId, nestedRadioGroupManager.checkedId); assertEquals(initialId, nestedRadioGroupManager.initialCheckedId); }
### Question: NestedRadioGroupManager { public void addNestedRadioButton(NestedRadioButton nestedRadioButton) { radioButtons.put(nestedRadioButton.getId(), nestedRadioButton); if (checkedId == nestedRadioButton.getId()) { protectFromCheckedChange = true; setCheckedStateForView(checkedId, true); protectFromCheckedChange = false; setCheckedId(nestedRadioButton.getId()); } nestedRadioButton.setOnCheckedChangeListener(childOnCheckedChangeListener); } NestedRadioGroupManager(); void initCheckedId(int value); int getCheckedId(); void addNestedRadioButton(NestedRadioButton nestedRadioButton); void check(@IdRes int id); @TargetApi(Build.VERSION_CODES.O) void onProvideAutofillStructure(ViewStructure structure); void clearCheck(); void setOnCheckedChangeListener(OnCheckedChangeListener listener); }### Answer: @Test public void addNestedRadioButton() { int radioButtonId = 12345; NestedRadioButton nestedRadioButton = mock(NestedRadioButton.class); when(nestedRadioButton.getId()).thenReturn(radioButtonId); nestedRadioGroupManager.addNestedRadioButton(nestedRadioButton); verify(nestedRadioButton).setOnCheckedChangeListener(nestedRadioGroupManager.childOnCheckedChangeListener); }
### Question: NestedRadioGroupManager { public void check(@IdRes int id) { if (id != -1 && (id == checkedId)) { return; } if (checkedId != -1) { setCheckedStateForView(checkedId, false); } if (id != -1) { setCheckedStateForView(id, true); } setCheckedId(id); } NestedRadioGroupManager(); void initCheckedId(int value); int getCheckedId(); void addNestedRadioButton(NestedRadioButton nestedRadioButton); void check(@IdRes int id); @TargetApi(Build.VERSION_CODES.O) void onProvideAutofillStructure(ViewStructure structure); void clearCheck(); void setOnCheckedChangeListener(OnCheckedChangeListener listener); }### Answer: @Test public void check() { int initialCheckId = 12345; int newCheckId = 54321; nestedRadioGroupManager.initCheckedId(initialCheckId); nestedRadioGroupManager.check(newCheckId); verify(nestedRadioGroupManager).setCheckedStateForView(initialCheckId, false); verify(nestedRadioGroupManager).setCheckedStateForView(newCheckId, true); verify(nestedRadioGroupManager).setCheckedId(newCheckId); }
### Question: JwtAuthenticationProvider implements AuthenticationProvider { @Override public boolean supports(Class<?> authentication) { return JwtAuthenticationToken.class.isAssignableFrom(authentication); } @Override boolean supports(Class<?> authentication); @Override Authentication authenticate(Authentication authentication); }### Answer: @Test public void supportsShouldReturnFalse() { JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(); Assert.assertFalse(jwtAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)); } @Test public void supportsShouldReturnTrue() { JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(); Assert.assertFalse(jwtAuthenticationProvider.supports(JwtAuthenticationFilter.class)); }
### Question: AuthController { @GetMapping("/token") public ApiToken token() throws JOSEException { final DateTime dateTime = DateTime.now(); JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder(); jwtClaimsSetBuilder.expirationTime(dateTime.plusMinutes(120).toDate()); jwtClaimsSetBuilder.claim("APP", "SAMPLE"); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), jwtClaimsSetBuilder.build()); signedJWT.sign(new MACSigner(SecurityConstant.JWT_SECRET)); return new ApiToken(signedJWT.serialize()); } @GetMapping("/token") ApiToken token(); }### Answer: @WithMockSaml(samlAssertFile = "/saml-auth-assert.xml") @Test public void testAuthController() throws JOSEException { final AuthController authController = new AuthController(); final ApiToken apiToken = authController.token(); Assert.assertNotNull(apiToken); Assert.assertTrue(apiToken.getToken().length() > 0); }
### Question: HTMLStripUtil { public static String stripHTML(String html) { if (html != null) { Document doc = Jsoup.parse(Jsoup.clean(html, Whitelist.relaxed())); return convertNodeToText(doc.body()); } return null; } static String stripHTML(String html); }### Answer: @Test public void shouldWorkForNullString() { assertEquals(null, HTMLStripUtil.stripHTML(null)); } @Test public void shouldWorkForEmptyString() { assertEquals("", HTMLStripUtil.stripHTML("")); } @Test public void shouldStripHTML() { String html = "<p><h1>Title</h1>Dummy<br><i>text</i></p><p><ul><li>A<li>B<li>C</ul</p>"; assertEquals("Title Dummy text A B C", HTMLStripUtil.stripHTML(html)); } @Test public void shouldIgnoreScript() { String html = "<div>There is<script>var x = {};</script> no script</div>"; assertEquals("There is no script", HTMLStripUtil.stripHTML(html)); }
### Question: MessageParser { public static String normalizeSubject(String subject) { String s = subject; if (s != null) { s = s.replaceAll("\\[.*?\\][^$]","") .replaceAll("^\\s*(-*\\s*[a-zA-Z]{2,3}:\\s*)*","") .replaceAll("\\s+[a-zA-Z]{2,3}:","") .replaceAll("^\\s*-\\s*","") .replaceAll("\\s+"," ") .trim(); } return s; } private MessageParser(); static MessageBuilder getMessageBuilder(); static Mail parse(Message message); static Mail parse(Message message, /*Map<String, String> data,*/ String idsuffix); static Map<String, Field> getMessageHeaders(Message message); static Author extractValue(MailboxListField field); static List<String> extractValue(AddressListField field); static Date extractValue(DateTimeField field); static String extractValue(UnstructuredField field); static String normalizeSubject(String subject); final static DateTimeFormatter defaultDatePrinter; }### Answer: @Test public void subjectNormalizationShouldPass() { assertEquals("Test subject", MessageParser.normalizeSubject(" [] [x x] Re: Vor: Test RE: subject ")); assertEquals("Test subject", MessageParser.normalizeSubject(" Re: Fw: [] [x x] Test RE: [x] [] subject ")); assertEquals("Web Container Integration testing (WCI)", MessageParser.normalizeSubject("Re: [gatein-dev] Web Container Integration testing (WCI)")); assertEquals("Type Substitution doesn't work with Schema2Java Client a [Re: this should stay here]", MessageParser.normalizeSubject("[jbossws-users] [JBossWS] - Re: [another-tag] Fw: Type Substitution doesn't work with\tSchema2Java Client a [Re: this should stay here]")); assertEquals("Multiple Assignment of a task in - jBPM4", MessageParser.normalizeSubject("[jbpm-users] [jBPM Users] - [JBPM4] Multiple Assignment of a task in - jBPM4")); }
### Question: StringUtil { public static String getProjectName(String mailListName, String mailListCategory) { if (mailListCategory == null || mailListCategory.trim().isEmpty()) { return mailListName; } if (mailListName != null && !mailListName.trim().isEmpty()) { String name = mailListName.trim(); String category = "-"+mailListCategory.trim(); if (name.length() > category.length()) { if (name.endsWith(category)) { return name.substring(0, name.length() - category.length()); } } } return mailListName; } static String decodeFilenameSafe(String encoded); static URLInfo getInfo(String encoded); static String getProjectName(String mailListName, String mailListCategory); }### Answer: @Test public void testProjectName() { assertEquals(null, StringUtil.getProjectName(null, "")); assertEquals(" ", StringUtil.getProjectName(" ", null)); assertEquals(" ", StringUtil.getProjectName(" ", "")); assertEquals("a-b", StringUtil.getProjectName("a-b", " ")); assertEquals("a-b", StringUtil.getProjectName("a-b", "")); assertEquals("a-b", StringUtil.getProjectName("a-b", null)); assertEquals("a-b", StringUtil.getProjectName("a-b-c", "c")); assertEquals("a-b_c", StringUtil.getProjectName("a-b_c", "c")); }
### Question: StringUtils { public static boolean isEmpty(String str) { return str == null || str.trim().length() == 0; } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer: @Test public void testEmpty() { Assert.assertTrue(StringUtils.isEmpty("")); Assert.assertTrue(StringUtils.isEmpty(null)); Assert.assertFalse(StringUtils.isEmpty("aaa")); }
### Question: PortSelectUtils { public synchronized static int selectAvailablePort(int defaultPort, int maxLength) { for (int i = defaultPort; i < defaultPort + maxLength; i++) { try { if (available(i)) { return i; } } catch (IllegalArgumentException e) { } } return -1; } synchronized static int selectAvailablePort(int defaultPort, int maxLength); static final int MIN_PORT_NUMBER; static final int MAX_PORT_NUMBER; }### Answer: @Test public void selectSinglePort() { try (ServerSocket ss = new ServerSocket(1234)) { int port = PortSelectUtils.selectAvailablePort(1234, 1); AssertUtils.isTrue(port == -1, "Select Error Port."); } catch (IOException ex) { } } @Test public void selectMaximumPort() { int port = PortSelectUtils.selectAvailablePort(65555, 10); AssertUtils.isTrue(port == -1, "Select Error Port."); } @Test public void selectMinimumPort() { int port = PortSelectUtils.selectAvailablePort(1050, 100); AssertUtils.isTrue(port == PortSelectUtils.MIN_PORT_NUMBER, "Select Error Port."); } @Test public void selectUnusedPort() { int port = PortSelectUtils.selectAvailablePort(1234, 100); AssertUtils.isTrue(port == 1234, "Select Error Port."); } @Test public void selectUsedPort() { try (ServerSocket ss = new ServerSocket(1234)) { int port = PortSelectUtils.selectAvailablePort(1234, 100); AssertUtils.isTrue(port == 1235, "Select Error Port."); } catch (IOException ex) { } }
### Question: FileUtils { public static String getCompatiblePath(String path) { if (System.getProperty("os.name").toLowerCase().indexOf("window") > -1) { return path.replace("\\", "/"); } return path; } static String sha1Hash(File file); static File createTempDir(String subPath); static void copyInputStreamToFile(final InputStream source, final File destination); static String getCompatiblePath(String path); }### Answer: @Test public void testGetCompatiblePath() { String winPath = FileUtils.getCompatiblePath("C:\\a\\b\\c"); Assert.assertTrue(winPath.contains("/")); String macPath = FileUtils.getCompatiblePath("/a/b/c"); Assert.assertTrue(winPath.contains(macPath)); }
### Question: AssertUtils { public static void assertNotNull(Object instance, String msg) { if (instance == null) { throw new IllegalArgumentException(msg); } } static void assertNotNull(Object instance, String msg); static void assertNull(Object instance, String msg); static void isTrue(final boolean expression, final String message, final Object... values); static void isFalse(final boolean expression, final String message, final Object... values); }### Answer: @Test(expected = IllegalArgumentException.class) public void testAssertNotNullNull() { String msg = "object is null"; try { AssertUtils.assertNotNull(null, msg); } catch (Exception e) { Assert.assertTrue(e instanceof IllegalArgumentException); Assert.assertTrue(e.getMessage().contains(msg)); throw e; } } @Test public void testAssertNotNullNotNull() { AssertUtils.assertNotNull(new Object(), "object is null"); }
### Question: AssertUtils { public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } static void assertNotNull(Object instance, String msg); static void assertNull(Object instance, String msg); static void isTrue(final boolean expression, final String message, final Object... values); static void isFalse(final boolean expression, final String message, final Object... values); }### Answer: @Test public void testAssertIsTrue() { AssertUtils.isTrue(true, "Exception %s", "error"); try { AssertUtils.isTrue(false, "Exception %s", "error"); } catch (IllegalArgumentException ex) { Assert.assertTrue("Exception error".equals(ex.getMessage())); } }
### Question: AssertUtils { public static void isFalse(final boolean expression, final String message, final Object... values) { if (expression) { throw new IllegalArgumentException(String.format(message, values)); } } static void assertNotNull(Object instance, String msg); static void assertNull(Object instance, String msg); static void isTrue(final boolean expression, final String message, final Object... values); static void isFalse(final boolean expression, final String message, final Object... values); }### Answer: @Test public void testAssertIsFalse() { AssertUtils.isFalse(false, "Exception %s", "error"); try { AssertUtils.isFalse(true, "Exception %s", "error"); } catch (IllegalArgumentException ex) { Assert.assertTrue("Exception error".equals(ex.getMessage())); } }
### Question: ParseUtils { public static void parseResourceAndStem(Set<String> candidates, Set<String> prefixStems, Set<String> suffixStems, Set<String> resources) { for (String candidate : candidates) { if (candidate.equals(Constants.RESOURCE_STEM_MARK)) { continue; } if (candidate.endsWith(Constants.RESOURCE_STEM_MARK)) { prefixStems.add(candidate.substring(0, candidate.length() - Constants.RESOURCE_STEM_MARK.length())); } else if (candidate.startsWith(Constants.RESOURCE_STEM_MARK)) { suffixStems.add(candidate.substring(Constants.RESOURCE_STEM_MARK.length())); } else { resources.add(candidate); } } } static void parsePackageNodeAndStem(Set<String> candidates, Set<String> stems, Set<String> nodes); static void parseResourceAndStem(Set<String> candidates, Set<String> prefixStems, Set<String> suffixStems, Set<String> resources); }### Answer: @Test public void testParseUtils() { ParseUtils.parseResourceAndStem(candidates, stems, suffixStems, resources); Assert.assertTrue(stems.size() == 1 && stems.contains("spring/")); Assert.assertTrue(resources.size() == 1 && resources.contains("spring.xsd")); Assert.assertTrue(suffixStems.size() == 1 && suffixStems.contains(".xsd")); }
### Question: MainMethodRunner { public Object run() throws Exception { Class<?> mainClass = Thread.currentThread().getContextClassLoader() .loadClass(this.mainClassName); Method mainMethod = mainClass.getDeclaredMethod("main", String[].class); return mainMethod.invoke(null, new Object[] { this.args }); } MainMethodRunner(String mainClass, String[] args); Object run(); }### Answer: @Test public void testRunner() { MainMethodRunner mainMethodRunner = new MainMethodRunner(MainClass.class.getName(), new String[] { "10" }); try { mainMethodRunner.run(); Assert.assertTrue(MainMethodRunnerTest.count == 10); } catch (Exception e) { Assert.assertNull(e); } }
### Question: ArkContainer { public Object start() throws ArkRuntimeException { AssertUtils.assertNotNull(arkServiceContainer, "arkServiceContainer is null !"); if (started.compareAndSet(false, true)) { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { stop(); } })); prepareArkConfig(); reInitializeArkLogger(); arkServiceContainer.start(); Pipeline pipeline = arkServiceContainer.getService(Pipeline.class); pipeline.process(pipelineContext); System.out.println("Ark container started in " + (System.currentTimeMillis() - start) + " ms."); } return this; } ArkContainer(ExecutableArchive executableArchive); ArkContainer(ExecutableArchive executableArchive, LaunchCommand launchCommand); static Object main(String[] args); Object start(); void prepareArkConfig(); List<URL> getProfileConfFiles(String... profiles); void reInitializeArkLogger(); boolean isStarted(); void stop(); boolean isRunning(); ArkServiceContainer getArkServiceContainer(); PipelineContext getPipelineContext(); }### Answer: @Test public void testStart() throws ArkRuntimeException { String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; ArkContainer arkContainer = (ArkContainer) ArkContainer.main(args); Assert.assertTrue(arkContainer.isStarted()); arkContainer.stop(); }
### Question: StringUtils { public static boolean isSameStr(String a, String b) { if (a == null && b != null) { return false; } if (a == null && b == null) { return true; } return a.equals(b); } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer: @Test public void testSameStr() { Assert.assertTrue(StringUtils.isSameStr(null, null)); Assert.assertFalse(StringUtils.isSameStr(null, "")); Assert.assertFalse(StringUtils.isSameStr(null, "a")); Assert.assertFalse(StringUtils.isSameStr("aa", null)); Assert.assertFalse(StringUtils.isSameStr("aa", "")); Assert.assertFalse(StringUtils.isSameStr("aa", "a")); Assert.assertTrue(StringUtils.isSameStr("aa", "aa")); }
### Question: ArkContainer { public void stop() throws ArkRuntimeException { AssertUtils.assertNotNull(arkServiceContainer, "arkServiceContainer is null !"); if (stopped.compareAndSet(false, true)) { arkServiceContainer.stop(); } } ArkContainer(ExecutableArchive executableArchive); ArkContainer(ExecutableArchive executableArchive, LaunchCommand launchCommand); static Object main(String[] args); Object start(); void prepareArkConfig(); List<URL> getProfileConfFiles(String... profiles); void reInitializeArkLogger(); boolean isStarted(); void stop(); boolean isRunning(); ArkServiceContainer getArkServiceContainer(); PipelineContext getPipelineContext(); }### Answer: @Test public void testStop() throws Exception { ArkContainer arkContainer = new ArkContainer(new ExecutableArkBizJar(new JarFileArchive( new File((jarURL.getFile()))))); arkContainer.start(); arkContainer.stop(); Assert.assertFalse(arkContainer.isRunning()); }
### Question: PluginCommandProvider implements CommandProvider { @Override public boolean validate(String command) { return new PluginCommand(command).isValidate(); } @Override String getHelp(); @Override String handleCommand(String command); @Override boolean validate(String command); }### Answer: @Test public void testPluginCommandFormat() { PluginCommandProvider pluginCommandProvider = new PluginCommandProvider(); Assert.assertFalse(pluginCommandProvider.validate(" plugin ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -h ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -m pluginA ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -s pluginB pluginA ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -d plugin* ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -m -d -s plugin* ")); Assert.assertTrue(pluginCommandProvider.validate(" plugin -msd pluginA ")); Assert.assertFalse(pluginCommandProvider.validate(" plu")); Assert.assertFalse(pluginCommandProvider.validate(" plugin -h pluginA ")); Assert.assertFalse(pluginCommandProvider.validate(" plugin -hm pluginA ")); Assert.assertFalse(pluginCommandProvider.validate(" plugin -mb pluginA ")); Assert.assertFalse(pluginCommandProvider.validate(" plugin -m -b pluginA ")); Assert.assertFalse(pluginCommandProvider.validate(" plugin -m ")); }
### Question: ArkServiceContainer { public void start() throws ArkRuntimeException { if (started.compareAndSet(false, true)) { ClassLoader oldClassLoader = ClassLoaderUtils.pushContextClassLoader(getClass() .getClassLoader()); try { LOGGER.info("Begin to start ArkServiceContainer"); injector = Guice.createInjector(findServiceModules()); for (Binding<ArkService> binding : injector .findBindingsByType(new TypeLiteral<ArkService>() { })) { arkServiceList.add(binding.getProvider().get()); } Collections.sort(arkServiceList, new OrderComparator()); for (ArkService arkService : arkServiceList) { LOGGER.info(String.format("Init Service: %s", arkService.getClass().getName())); arkService.init(); } ArkServiceContainerHolder.setContainer(this); ArkClient.setBizFactoryService(getService(BizFactoryService.class)); ArkClient.setBizManagerService(getService(BizManagerService.class)); ArkClient.setInjectionService(getService(InjectionService.class)); ArkClient.setEventAdminService(getService(EventAdminService.class)); ArkClient.setArguments(arguments); LOGGER.info("Finish to start ArkServiceContainer"); } finally { ClassLoaderUtils.popContextClassLoader(oldClassLoader); } } } ArkServiceContainer(String[] arguments); void start(); T getService(Class<T> clazz); void stop(); boolean isStarted(); boolean isRunning(); }### Answer: @Test public void testStart() { arkServiceContainer.start(); Assert.assertTrue(arkServiceContainer.isStarted()); Assert.assertTrue(arkServiceContainer.isRunning()); }