id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
36456716_250
class VM { public void step(Program program) { if (CONFIG.vmTrace()) { program.saveOpTrace(); } try { OpCode op = OpCode.code(program.getCurrentOp()); if (op == null) { throw Program.Exception.invalidOpCode(program.getCurrentOp()); ...
VM vm = new VM(); program = new Program(Hex.decode("614444639999666603"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000099992222"; vm.step(program); vm.step(program); vm.step(program); DataWord item1 = program.stackPop(...
36461471_5
class DGRN { boolean edgePropagatesSignal(Edge edge) throws KeySelectorException { // returns true if the given node has a signal that should be passed along the given edge // assuming single-step weight-threshold-gate drain // check if src node has enough potential to traverse edge ...
// tests when signal should propagate DGRN dgrn = getMockDGRN_twoNode(); List<Edge> edges = dgrn.graph.getAllEdges(); Assert.assertEquals(edges.size(), 1); // only 1 edge in this graph Edge edge = edges.get(0); // init state: // (1) -2-> (0) Assert.assert...
36476378_1
class DfsUtil { public static Set<Path> listFiles(FileSystem hdfs, Path path, boolean recurse, boolean filterMetaData) throws IOException { Set<Path> files = new HashSet<>(); try { RemoteIterator<LocatedFileStatus> filesIterator = hdfs.listFiles(path, recurse); while (filesIterator.hasNext())...
assertEquals(0, DfsUtil.listFiles(dfsServer.getFileSystem(), dfsServer.getPath("/tmq/t"), false, false).size()); assertEquals(0, DfsUtil.listFiles(dfsServer.getFileSystem(), dfsServer.getPath("/tmq/t"), false, false).size()); assertEquals(0, DfsUtil.listFiles(dfsServer.getFileSystem(), dfsServer.getPath("/t...
36483902_22
class DateRange implements Comparable<DateRange> { public DateRange rounded(long interval) { if (interval <= 0) { return this; } return new DateRange(start - start % interval, end - (end % interval)); } public DateRange(long start, long end); public long start();...
final DateRange range = new DateRange(0, 0); assertTrue(range == range.rounded(-1)); } }
36487440_42
class OAuth2AuthenticationHandler implements AuthenticationHandler { @Override public String name() { return AUTHENTICATION_HANDLER_NAME; } @Override public boolean canHandle(AuthenticationContext context); private String readToken(Request request); @Override public int order(); @O...
Assert.assertEquals(OAuth2AuthenticationHandler.AUTHENTICATION_HANDLER_NAME, authenticationHandler.name()); } }
36518071_10
class UserServiceImpl implements UserService { @Override @Transactional(rollbackFor = Throwable.class) public User createUser(User userTemplate) throws FieldValidationException { Preconditions.checkArgument(userTemplate != null, "userTemplate is required"); validateUser(userTemplate); User userToCreate = ne...
UserServiceImpl fixture = UserServiceImplFactory.createUsersServiceImpl(); User user = UserFactory.createNewUserTemplate(); user.setEmail(null); fixture.createUser(user); fail(); } }
36524737_0
class AdapterReferenceCollector { static <T, A extends BindingCollectionAdapter<T>> WeakReference<A> createRef(A adapter, ObservableList<T> items, ObservableList.OnListChangedCallback callback) { if (thread == null || !thread.isAlive()) { thread = new PollReferenceThread(); thread.s...
BindingCollectionAdapter adapter = mock(BindingCollectionAdapter.class); ObservableList items = mock(ObservableList.class); ObservableList.OnListChangedCallback callback = mock(ObservableList.OnListChangedCallback.class); WeakReference ref = AdapterReferenceCollector.createRef(adapter, i...
36564453_7
class SmartLock extends Lock implements CredentialStore, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { void onCredentialsRetrieved(final Activity activity, final Credential credential) { Log.v(TAG, "Credentials : " + credential.getName()); String email = credenti...
smartLock.onCredentialsRetrieved(activity, credential); verify(apiClient).login(eq(EMAIL), eq(PASSWORD), anyMapOf(String.class, Object.class), any(AuthenticationCallback.class)); } }
36572522_0
class MyParcelable implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { Postman.writeToParcel(this, dest); } public MyParcelable(); public MyParcelable(String myString); @Override public int describeContents(); } class MyParcelableTest { @Tes...
Object o = new Object(); boolean exceptionCaught = false; try { Postman.writeToParcel(o, Parcel.obtain()); } catch (PostmanException e) { exceptionCaught = true; assertTrue("expected cause to be of type ClassNotFoundException but found " + ...
36600590_10
class ITCHSession implements Closeable { public int receive() throws IOException { int bytes = channel.read(rxBuffer); if (bytes <= 0) return bytes; rxBuffer.flip(); while (parse()); rxBuffer.compact(); if (rxBuffer.position() == rxBuffer.capacity())...
client.requestInstrumentDirectory(); while (serverEvents.collect().size() != 1) server.receive(); assertEquals(asList(new InstrumentDirectoryRequest()), serverEvents.collect()); } }
36603494_1
class PagedDataProvider extends AbstractDataProvider<T, F> { public PagingControls getPagingControls() { return pagingControls; } public PagedDataProvider(DataProvider<T, F> dataProvider); public PagedDataProvider(DataProvider<T, F> dataProvider, int pageLength); @Override public boolean isInMemory(); @Ove...
PagingControls controls = pagedDP.getPagingControls(); Assert.assertEquals(0, controls.getPageNumber()); controls.previousPage(); Assert.assertEquals(0, controls.getPageNumber()); } }
36614714_5
class Commands { public static byte[] getReadPumpCommand(final byte[] serial) { byte[] data = new byte[]{ 0x01, // head 0x00, // head (byte) 0xA7, // 167 0x01, // 1 0x00, // Serial 0x00, // Serial ...
byte[] output = new byte[] { 0x01, 0x00, (byte) 0xA7, 0x01, 0x66, 0x54, 0x55, (byte) 0x80, 0x00, 0x00, 0x02, 0x01, 0x00, (byte) 0x8D, 0x5B, 0x00 }; byte[] serial = new byte[] { 0x66,0x54,0x55 }; byte[] generated = Commands.getReadPumpCommand(serial); as...
36649267_29
class Packager { public static boolean validateBag(File dir) throws Exception { boolean isValid = false; Bag bag = new BagReader().read(dir.toPath()); BagVerifier bv = new BagVerifier(); try { bv.isValid(bag, false); isValid = true; } ...
final String TEST_FILE1 = "item.pdf"; final String TEST_FILE2 = "banjo.jpg"; final String TEST_FILE_WITH_SPACE = "peacock butterfly.jpeg"; final String EMPTY_DIR_NAME = "emptydir"; final String CHILD_DIR_NAME = "childdir"; final String CHILD_DIR_WITH_SPACE = "second child...
36657331_1
class AddController { protected static Person personFromRequest(String json) { AddPersonRequest apr = JsonUtils.getAPRFromJson(json); Person p = AddPersonRequest.toPerson(apr); return p; } @POST @Consumes(MediaType.TEXT_PLAIN) public Response handle(String json); protected static void addToGlobalList(Perso...
Person p = AddController.personFromRequest(json); Config.cc.putPerson(p); Person p2 = Config.cc.getPerson("JOHN SMITH"); assertTrue(p2 != null); assertTrue(p2.name.equals("JOHN SMITH")); assertTrue(p2.role.equals(Role.DEV)); assertTrue(p2.resumeInfo != null); assertTrue(p2.qaResponses.get(0).equals("ans...
36664864_9
class BulkManager implements Runnable { @VisibleForTesting @SuppressWarnings("checkstyle:designforextension") protected URI getUri() throws URISyntaxException { String baseURL = config.baseURL; if (!baseURL.endsWith("/")) { baseURL += "/"; } String url = baseURL...
DataSiftConfig config = new DataSiftConfig(); config.baseURL = "http://in.example.com/"; config.sourceID = "SOURCEID"; config.port = 42; config.username = "USER"; config.apiKey = "APIKEY"; BulkManager b = new BulkManager(config, null, null, null); try { ...
36765917_1
class KeywordStatistics { public Map<String, Long> extract(String text, List<String> keywords) { Map<String, Long> result = Maps.newHashMap(); keywords.forEach(new Consumer<String>() { @Override public void accept(String keyword) { if (text.contains(keyword))...
//setup String message = "Poker poker poker poker poker poker"; //act Map<String, Long> result = testObj.extract(message, Lists.newArrayList("Poker","Tournament")); //assert assertNotNull(result); assertThat(result, Matchers.allOf(hasEntry(is("Poker"), is(1L))))...
36781255_0
class EmailNotificationServiceImpl implements EmailNotificationService { public void sendPodcastAdditionConfirmation(final String name, final String email, final String podcastUrl) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @SuppressWarnings({ "rawtypes", "unchecked" }) public void pre...
emailNotificationService.sendPodcastAdditionConfirmation("Gigi", "gigi@podcastpedia.org", "feed.xxx"); Mailbox inbox = Mailbox.get("gigi@podcastpedia.org"); assert(inbox.size()==1); assert(inbox.get(0).getSubject().equals(EMAIL_SUBJECT)); Address[] addresses = inbox.get(0).getFrom(); assert(addresses[0]...
36793280_136
class RetryTransformer implements FlowableTransformer<T, T>, ObservableTransformer<T, T>, SingleTransformer<T, T>, CompletableTransformer, MaybeTransformer<T, T> { public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); } private RetryTransformer(Retry re...
RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("testName", config); given(helloWorldService.returnHelloWorld()) .willReturn("ret...
36807893_16
class IDBuilder { public static int parseGeneratorId(byte[] id) { assertNotNullEightBytes(id); return parseGeneratorIdNoChecks(id); } public static byte[] build(Blueprint blueprint); public static Blueprint parse(byte[] id); public static int parseSequenceId(byte[] id); public ...
byte[] id = new byte[8]; id[6] = 0x0f; id[7] = (byte) (0x0f << 4); byte[] clone = id.clone(); assertThat(parseGeneratorId(id), is(255)); assertThat(id, is(clone)); } }
36812061_1
class SurgicalRoutingRequestTransformer implements LoadBalancerRequestTransformer { @Override public HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) { Map<String, String> metadata = instance.getMetadata(); if (metadata.containsKey(CF_APP_GUID) && metadata.containsKey(CF_INSTANCE_INDEX...
Map<String, String> metadata = new HashMap<>(); metadata.put("cfAppGuid", "123"); metadata.put("cfInstanceIndex", "4"); when(instance.getMetadata()).thenReturn(metadata); HttpRequest transformedRequest = transformer.transformRequest(request, instance); assertThat(transformedRequest.getHeaders().get("foo")...
36816840_5
class StringUtils { public static String removeNonNumeric(String text) { return text.replaceAll("[^0-9]", ""); } public static boolean isNumeric(String maybeNumeric); public static boolean validateCNPJ(String CNPJ); public static String reverseString(String str); public static void app...
Assert.assertEquals(removeNonNumeric("3515 1222 8436 4200 0195 6500 1000 0018 1214 0002 0216"), "35151222843642000195650010000018121400020216"); Assert.assertEquals(removeNonNumeric("22.843.642/0001-95"),"22843642000195"); } }
36817565_0
class ApiGeneratorUtils { public static List<ApiImplementor> getAllImplementors() { List<ApiImplementor> imps = new ArrayList<>(); ApiImplementor api; imps.add(new AlertAPI(null)); api = new AntiCsrfAPI(null); api.addApiOptions(new AntiCsrfParam()); imps.add(api);...
// Given / When Map<String, ApiImplementor> generatorApis = ApiGeneratorUtils.getAllImplementors().stream() .collect(Collectors.toMap(ApiImplementor::getPrefix, Function.identity())); // Then for (Entry<String, ApiImplementor> entry : coreApis.entr...
36819131_4
class AllJUnitReports { public int getTotalFailures() { return totalFailures; } public AllJUnitReports(String pageTitle, List<TestSuiteModel> allTestSuites); public List<TestSuiteModel> getAllTestSuites(); public String getPageTitle(); public String getTotalTime(); public int get...
assertEquals(reports.getTotalFailures(), 7); } }
36827833_5
class RgbLedBatchProcessor implements Processor { @Override public void process(final Exchange exchange) throws Exception { final Message msg = exchange.getIn(); final StringBuffer pwmBatch = new StringBuffer(); final String[] batchLines = msg.getBody(String.class).split("\n"); final Obj...
final Exchange ex = new DefaultExchange(ctx); final Message msg = ex.getIn(); config.resetRgbLeds(); msg.setBody("65535;r;50\n0;g;100\n1;g;100"); processor.process(ex); Assert.assertEquals(msg.getBody(), "0x00;0;2047\n" + "0x00;3;2047\n" + "0x00;6;2047\n" ...
36857422_14
class LoginViewModel extends ViewModel { void onLoginClick(@Nullable FABProgressCircle fabCircle) { if (!isSiteValid()) { return; } if (fabCircle != null) { fabCircle.show(); } triggerLogin(); } LoginViewModel(UserManager userManager, Rest...
viewModel.url.set("Junk"); viewModel.onLoginClick(null); assertThat(viewModel.urlError.get()).isEqualTo(ERROR_URL_INVALID); } }
36873773_585
class DownloadResponse { public String getFirstHeader(final ResponseHeader responseHeader) { for (final Header header : mHeaders) { if (header.getName().equalsIgnoreCase(responseHeader.getKey())) { return header.getValue(); } } return null; } ...
assertEquals("testCustomEvent", subject.getFirstHeader(ResponseHeader.CUSTOM_EVENT_NAME)); assertEquals("http://example.com/", subject.getFirstHeader(ResponseHeader.CLICK_TRACKING_URL)); assertEquals("http://mopub.com/", subject.getFirstHeader(ResponseHeader.FAIL_URL)); assertNull(subjec...
36882032_1
class Authority implements GrantedAuthority { @Override public int hashCode() { return authority.hashCode(); } private Authority(); public Authority(String authority); public Authority(String authority, String description); @Id @GeneratedValue public Long getId(); public vo...
Authority userAuthority = new Authority("user"); Authority adminAuthority = new Authority("admin"); assertThat(userAuthority.hashCode(), not(equalTo(adminAuthority.hashCode()))); assertThat(userAuthority.hashCode(), equalTo(new Authority("user").hashCode())); } }
36906356_32
class FeatureSection implements Section { @Override public String render(CukedoctorDocumentBuilder docBuilder, I18nLoader i18n, DocumentAttributes documentAttributes) { final FeatureRenderer renderer = FeatureSection.featureRenderer.get(); renderer.setI18n(i18n); renderer.setDocumentAtt...
final Feature feature = FeatureBuilder.instance().aFeatureWithNoScenarios(); final FeatureSection section = new FeatureSection(feature); final String expected = "[[Feature-name, Feature name]]" + newLine() + "= *Feature name*" + newLine() + newLine() + ...
36953044_19
class Stream implements Iterable<T> { public <R> R reduce(R initial, Func2<R, T, R> accumulator) { R value = initial; for (T anIt : this) value = accumulator.call(value, anIt); return value; } public static Stream<T> stream(final T[] array); public static Stream<T> ...
assertFalse(Stream.of().reduce(null).isPresent()); assertEquals((Integer) 9, Stream.of(9).reduce(null).get()); assertFalse(null, Stream.of(null, null, null).reduce(new Func2<Object, Object, Object>() { @Override public Object call(Object value1, Object value2) {return n...
36960637_540
class TimestampTracker { @VisibleForTesting static void registerTimestampForTracking( Clock clock, MetricsManager metricsManager, String shortName, Supplier<Long> supplier) { metricsManager.registerMetric( TimestampTracker.class, shortName, Tr...
when(mockClock.getTick()).thenReturn(0L, CACHE_INTERVAL_NANOS - 1, CACHE_INTERVAL_NANOS + 1); AtomicLong timestampValue = new AtomicLong(0L); TimestampTracker.registerTimestampForTracking( mockClock, metricsManager, FAKE_METRIC, timestampValue::incrementAndGet); assertTh...
37007492_11
class CassandraIdSupplier implements IdSupplier<Long> { @Override public Long next() { return range(1)[0]; } public CassandraIdSupplier(Session session, String keySpace); long[] range(long size); long latest(); @Mock Session session; @Mock Row row; @Mock List<Row> rows...
assertThat(ids.next(), is(equalTo(1L))); } }
37063452_115
class SqoopIDFUtils { public static String toText(String string) { boolean escaped = false; StringBuilder sb = new StringBuilder(); int i; // Remove the trailing and starting quotes. string = removeQuotes(string); // Decode for (i = 0; i < string.length(); ++i) { char c = string.c...
String test = "'\\n'"; String expectedString = new String(new char[] { 0x0A }); String toString = toText(test); assertEquals(toString, expectedString); } }
37063524_6
class ConfigManager { public void onNewConfigsFromScheduler(List<LogstashConfig> hostInfo, List<LogstashConfig> dockerInfo) { LOGGER.info("onNewConfigsFromScheduler, {}\n-------\n{}", dockerInfo, hostInfo); this.dockerInfo = dockerInfo; this.hostInfo = hostInfo; LOGGER.info(...
List<LogstashConfig> dockerFrameworks = asLogstashConfigList(framework1, framework2, framework3); List<LogstashConfig> hostFrameworks = asLogstashConfigList(hostFramework); configureAsRunningFrameworks(framework1); configManager.onNewConfigsFromScheduler(hostFrameworks, doc...
37125392_45
class DeepExperimentBuilder extends AbstractBuilder { @Override public DeepExperimentBuilder preprocessing(AnalysisEngineDescription preprocessing) { super.preprocessing(preprocessing); return this; } public DeepExperimentBuilder(); public DeepExperimentBuilder machineLearningBac...
builder.preprocessing(AnalysisEngineFactory.createEngineDescription(NoOpAnnotator.class)); assertTrue(builder.preprocessing != null); } }
37128954_67
class BluetoothConnector implements BluetoothServerThread.Listener, BluetoothClientThread.Listener { public synchronized void stopListeningForIncomingConnections() { if (mServerThread != null) { Log.i(TAG, "stopListeningForIncomingConnections: Stopping..."); mIsStoppingServer = true...
Field serverThreadField = mBluetoothConnector.getClass() .getDeclaredField("mServerThread"); serverThreadField.setAccessible(true); Field stoppingServerField = mBluetoothConnector.getClass() .getDeclaredField("mIsStoppingServer"); stoppingServerField.setA...
37147644_29
class TemplateEncoder extends Encoder<Object> { @Override public void write(Object value, OutputStream outputStream) throws IOException { write(value, outputStream, Locale.getDefault()); } public TemplateEncoder(URL url); public TemplateEncoder(URL url, Charset charset); public Map<...
TemplateEncoder encoder = new TemplateEncoder(getClass().getResource("format1.txt")); String result; try (StringWriter writer = new StringWriter()) { encoder.write(4.5, writer); result = writer.toString(); } assertEquals("4.50", result); } }
37148584_2
class AbstractCharacterTerminatedMessageProtocol extends AbstractMessageProtocol { public boolean clientSendsToken() { return true; } public AbstractCharacterTerminatedMessageProtocol(Socket socket, char recordTerminator); @Override protected void writeMessage(String message); @Override public String readMes...
setupProtcolWithMessageAndExitToken("ANY", "XXX"); assertTrue( protocol.clientSendsToken() ); } }
37149914_1
class PortalPropertiesPrettierPortlet extends MVCPortlet { public void prettify(ActionRequest request, ActionResponse response) throws IOException, PortletException { String prettyProperties = prettify(request); request.setAttribute("portalPrettyProperties", prettyProperties); } public void serveResource(...
MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); PortalPropertiesPrettierPortlet portlet = createMockBuilder( PortalPropertiesPrettierPortlet.class).addMockedMethod( "prettify", PortletRequest.class).createMock(); String expected = "expected";...
37256706_12
class HighlightDataMap implements Map<String, HighlightData> { @Override public boolean containsKey(Object key) { return map.containsKey(key); } public HighlightDataMap(); public HighlightDataMap(int initialCapacity); @Override public int size(); @Override public boolean isE...
assertThat(highlightDataMap.containsKey("key1"), is(true)); } }
37286678_3
class DeepLinkAnnotatedElement { String getUri() { return uri; } DeepLinkAnnotatedElement(String annotation, Element element, DeepLinkEntry.Type type); DeepLinkEntry.Type getAnnotationType(); TypeElement getAnnotatedElement(); String getMethod(); Element getElement(); @Mock TypeElement ele...
DeepLinkAnnotatedElement annotatedElement = new DeepLinkAnnotatedElement( "airbnb://example.com/{foo}/bar", element, DeepLinkEntry.Type.CLASS); assertThat(annotatedElement.getUri()).isEqualTo("airbnb://example.com/{foo}/bar"); } }
37293168_20
class GameOfLife implements RainbowInputController.RainbowInteractionListener, OnCellUpdatedCallback2D, RainbowDrawer.PointDetectedListener { @Override public void onPointDetected(float px, float py, float x, float y) { int cellX = (int) (x / CELL_SIZE); int cellY = (int) (y / CELL_SIZE); ...
givenThatAutomataHasAllCellsDead(); assertThat(gameOfLifeAutomata.getCells()[ANY_CELL_X][ANY_CELL_Y]).isEqualTo(DEAD); gameOfLife.onPointDetected(ANY_CELL_X, ANY_CELL_Y, ANY_CELL_X, ANY_CELL_Y); assertThat(gameOfLifeAutomata.getCells()[ANY_CELL_X][ANY_CELL_Y]).isEqualTo(ALIVE); } ...
37299113_0
class Tracker { public void add(TimeEntry entry) { entries.add(entry); } public void remove(TimeEntry entry); public int size(); public TimeEntry get(int index); @Autowired private Tracker tracker; } class TrackerTest { @Autowired private Tracker tracker; @Test ...
TimeEntry entry = new TimeEntry(); entry.setDescription("Entry Test"); entry.setRate(80.0f); entry.setTime(3); tracker.add(entry); assertTrue(tracker.size() > 0); } }
37318294_19
class CreditCardRegexValidatorService extends BasicAbstractRegexValidatorService { @Override public boolean validate(String cc) { cc = NON_DIGIT.matcher(cc).replaceAll(""); if (isRepeated(cc)) { return false; } int sum = 0; boolean odd = false; for (i...
String tituloEleitor = "4369811367191812"; assertFalse(service.validate(tituloEleitor)); } }
37418050_9
class SELECT extends SqlRootNode { public FROM FROM(@NonNull String tableName) { return new FROM(this, tableName); } public SELECT(@NonNull String... columns); @Override public String getSql(); public FROM FROM(@NonNull String... tableNames); } class SelectTest { @Test public void testSelectFromN...
int tests = 100; int columns = 5; for (int i = 0; i < tests; i++) { Columns c = new Columns(columns); String tableName = "table" + i; String whereClause = "col1=val1 AND col2=val2"; String groupBy = "col" + i; String tableToJoin = "TableName" + i; String sql = new SEL...
37421395_11
class BisectBoundaryHelper { public static BisectStep getNextStep(BisectStep step, boolean isSuccess) { return isSuccess ? later(step.getLeft(), step.getRight()) : earlier(step.getLeft(), step.getRight()); } private BisectBoundaryHelper(); public static BisectStep firstStep(int number); ...
BisectStep actual = BisectBoundaryHelper.getNextStep(new BisectStep(0, 0), true); assertNull(actual); actual = BisectBoundaryHelper.getNextStep(new BisectStep(0, 0), false); assertNull(actual); } }
37447498_36
class GlucoseRanges { public String colorFromReading(double reading) { if (reading < HYPO_LIMIT) { // hypo limit 70 return "purple"; } else if (reading > HYPER_LIMIT) { // hyper limit 200 return "red"; } else if (reading < userMin) { ...
assertTrue(glucoseRanges.colorFromReading(90).equals("blue")); } }
37462781_28
class Variable extends Element implements TypedElement { public final T getInitialValue() { return this.initialValue.orNull(); } protected Variable(final Type type, final String id, final T initialValue); public Variable(final Type type, final String id); public final String getId(); ...
Variable v = Variable.create(Type.BOOL, "test", null); assertEquals(null, v.getInitialValue()); Variable w = Variable.create(Type.BOOL, "test", "true"); assertEquals(true, w.getInitialValue()); } }
37475020_14
class Misc { public static boolean doubleEquals(final double a, final double b, final double epsilon) { final double diff = Math.abs(a - b); return diff < epsilon || (Double.isNaN(diff) && a == b); // Handle the case where a = b = Double.POSITIVE_INFINITY or a = b = Double.N...
final double a = 0.00001; final double b = 0.00001; assertTrue(Misc.doubleEquals(a, b, 0.00001)); } }
37485046_17
class KNNClassifier extends Classifier { public int getNumFeatures() { return model.numFeatures; } public KNNClassifier(int k, int numFeatures); public KNNClassifier(Object objModel); @Override public boolean train(List<FeatureVector> data); @Override public int classify(FeatureVector featureVector); @Ove...
assertEquals("KnnClassifier.getNumFeatures failed", knnClassifier.getNumFeatures(),numFeatures); } }
37507175_40
class CamundaBpmConfiguration { @Bean @ConditionalOnMissingBean(ProcessEngineConfigurationImpl.class) public ProcessEngineConfigurationImpl processEngineConfigurationImpl(List<ProcessEnginePlugin> processEnginePlugins) { final SpringProcessEngineConfiguration configuration = CamundaSpringBootUtil.springProce...
CamundaBpmConfiguration camundaBpmConfiguration = new CamundaBpmConfiguration(); List<ProcessEnginePlugin> processEnginePlugins = createUnordedList(); ProcessEngineConfigurationImpl processEngineConfigurationImpl = camundaBpmConfiguration.processEngineConfigurationImpl(processEnginePlugins); CompositeP...
37523659_1
class BooksListPresenter extends MvpBasePresenter<BooksListView> { public void loadBooks(final boolean pullToRefresh) { if(isViewAttached()) { getView().showLoading(pullToRefresh); } dataFetcher.getBooks(new DataCallback<Book[]>() { @Override public vo...
//Given presenter = new BooksListPresenter(dataFetcher); presenter.attachView(view); boolean pullToRefresh = true; //When presenter.loadBooks(pullToRefresh); //Then ArgumentCaptor<DataCallback> dataCallbackArg = ArgumentCaptor.forClass(DataCallback.class...
37629393_2
class ConfigFieldsDefiner extends PrototypicalClassAdapter { private ConfigFieldsDefiner( int classWriterFlags, String className, ConfigClassScanner configScanner, Map<String, ?> config) { super(classWriterFlags, className); this.configScanner = configScanner; this.config = conf...
final String field = "UNDEFINED"; final String value = "blah"; Map<String, String> config = new HashMap<>(); config.put(field, value); byte[] bytecode = ConfigFieldsDefiner.define(className, classFile, config); ConfigClassScanner configClassScanner = runClassScanner(className, nul...
37632768_1
class Searcher { public SearchResult search(String term) { if (term == null || term.trim().isEmpty()) { LOGGER.debug("No query term supplied, returning empty results."); return new SearchResult(); } THROTTLE.acquire(); String normalizedTerm = term.toLowerCa...
setupMock(); Searcher searcher = new Searcher(new ConferenceSessionLoader(getConfiguration())); SearchResult result = searcher.search("clojure"); assertNotNull(result); assertTrue(result.getResults().size() > 0); } }
37656718_2
class CXFClientConfigurer extends ConfigHelper { @Override public void setConfigProperties(Object client, String configFile, String configName) { Class<?> clazz = !(client instanceof Dispatch) ? client.getClass() : null; ClientConfig config = readConfig(configFile, configName, clazz, (BindingProvider...
Bus bus = null; try { bus = BusFactory.newInstance().createBus(); BusFactory.setThreadDefaultBus(bus); Service service = Service.create(this.getClass().getResource("META-INF/TestService.wsdl"), new QName("http://www.openuri.org/2004/04/HelloWorld", "EndpointService")); ...
37672572_3
class Recast { public static void clearUnwalkableTriangles(Context ctx, float walkableSlopeAngle, float[] verts, int nv, int[] tris, int nt, int[] areas) { float walkableThr = (float) Math.cos(walkableSlopeAngle / 180.0f * Math.PI); float norm[] = new float[3]; for (int i = 0;...
float walkableSlopeAngle = 45; float verts[] = { 0, 0, 0, 1, 0, 0, 0, 0, -1 }; int nv = 3; int walkable_tri[] = { 0, 1, 2 }; int unwalkable_tri[] = { 0, 2, 1 }; int nt = 1; Context ctx = new Context(); { int areas[] = { 42 }; Recas...
37712296_2
class RootBeer { public boolean detectPotentiallyDangerousApps() { return detectPotentiallyDangerousApps(null); } public RootBeer(Context context); public boolean isRooted(); @Deprecated public boolean isRootedWithoutBusyBoxCheck(); public boolean isRootedWithBusyBoxCheck(); publ...
RootBeer rootBeer = new RootBeer(getMockedContext(null)); rootBeer.setLogging(false); // Should be false as no packages detected assertFalse(rootBeer.detectPotentiallyDangerousApps()); rootBeer = new RootBeer(getMockedContext(Const.knownDangerousAppsPackages[0])); root...
37720965_35
class SubscriptionMapper { public Subscription convert(SubscriptionEntity subscriptionEntity) { final Subscription subscriptionItem = new Subscription(); subscriptionItem.setId(subscriptionEntity.getId()); subscriptionItem.setApi(subscriptionEntity.getApi()); subscriptionItem.setApp...
Instant now = Instant.now(); Date nowDate = Date.from(now); //init subscriptionEntity = new SubscriptionEntity(); subscriptionEntity.setApi(SUBSCRIPTION_API); subscriptionEntity.setApplication(SUBSCRIPTION_APPLICATION); subscriptionEntity.setClientId(SUBS...
37728390_15
class GeomVectorField extends GeomField { public Bag getObjectsWithinDistance(final Geometry g, final double dist) { Bag nearbyObjects = new Bag(); Envelope e = g.getEnvelopeInternal(); e.expandBy(dist); List<?> gList = spatialIndex.query(e); // However, the JTS QuadTr...
System.out.println("getObjectsWithinDistance"); GeomVectorField instance = new GeomVectorField(); addEvenlySpacedPoints(100, 100, 10, instance); MasonGeometry testPoint = new MasonGeometry(createPoint(50,50)); Bag result = instance.getObjectsWithinDistance(testPoint, 10.0); ...
37775708_0
class Helper { public static String removeNonPrintableChars(@Nullable final String s) { if (null == s || s.isEmpty()) return ""; StringBuilder newString = new StringBuilder(s.length()); for (int offset = 0; offset < s.length(); ) { int codePoint = s.codePointAt(offset); ...
assertEquals("a", Helper.removeNonPrintableChars("\uF8FFa")); assertEquals("a", Helper.removeNonPrintableChars("\uDC00a")); assertEquals("a", Helper.removeNonPrintableChars("\u000Ea")); assertEquals("a", Helper.removeNonPrintableChars("\u200Ea")); assertEquals("a", Helper.removeN...
37788075_21
class RollingLatency extends AbstractMetrics<T> implements WritableLatency<T>, Rolling<PartitionedLatency<T>> { @Override public IntervalIterator<PartitionedLatency<T>> intervals() { return rolling.intervalsWithDefault(noOpLatency); } public RollingLatency(Class<T> clazz, int buckets, long na...
IntervalIterator iterator = mock(IntervalIterator.class); when(baseMetrics.intervalsWithDefault(eq(2000L), any(NoOpLatency.class))).thenReturn(iterator); IntervalIterator<PartitionedLatency<TimeoutableResult>> intervals = latencies.intervals(2000L); assertSame(iterator, intervals); ...
37791069_1
class SDP { public static SDPScheme parse(String sdp) { SDPReader reader = new SDPReader(sdp); SDPRawRecord record; // // Session // int version = reader.readVersion(); String originator = reader.readRecord('o').getValue(); String sessionName = reade...
SDPScheme sdpScheme = SDP.parse(sdp2); String serialized = sdpScheme.toSDP().replace("\r", ""); // assertEquals(sdp2, serialized); } }
37796696_56
class DataTable { public DataTable subTable(int fromRow, int fromColumn) { return subTable(fromRow, fromColumn, height(), width()); } private DataTable(List<List<String>> raw, TableConverter tableConverter); public static DataTable create(List<List<String>> raw); public static DataTable ...
DataTable table = createSimpleTable(); assertThrows(IndexOutOfBoundsException.class, () -> table.subTable(0, 0, 4, 1)); } }
37816257_153
class JdbcWrapper { public DataSource createDataSourceProxy(DataSource dataSource) { return createDataSourceProxy(null, dataSource); } private JdbcWrapper(Counter sqlCounter); void initServletContext(ServletContext context); public static int getUsedConnectionCount(); public static int getActiveConnectionC...
// on fait le ménage au cas où TestMonitoringSpringInterceptor ait été exécuté juste avant cleanUp(); assertTrue("getBasicDataSourceProperties0", JdbcWrapper.getBasicDataSourceProperties().isEmpty()); assertEquals("getMaxConnectionCount0", -1, JdbcWrapper.getMaxConnectionCount()); final org.apache.tomca...
37853715_0
class OptionAssertion { public void assertIsNone() { if (!actual.isNone()) { throw fail("Option was not None"); } } OptionAssertion(@NotNull final Option<T> actual); @NotNull public OptionAssertion<T> assertIsSome(); @NotNull public OptionAssertion<T> assertValue(@No...
new OptionAssertion<Object>(Option.none()).assertIsNone(); } }
37879810_24
class DefaultAuditContext implements AuditContext { @Override public String getContextValue() { return value; } public DefaultAuditContext(String name, String value); @Override public String getContextName(); @Override public String toString(); } class DefaultAuditContextTest { @Test public void test...
DefaultAuditContext context = new DefaultAuditContext("name", "value"); assertEquals("value", context.getContextValue()); } }
37984143_69
class PagedIterator implements Iterator<E>, Iterable<E> { @Override public void remove () { if (currentElement == null) { throw new IllegalStateException (); } result = result.subList (index, result.size ()); index = 0; pageable.delete (currentElement); cur...
// Initial mutable list List<Integer> list = new ArrayList<> (); list.addAll (Arrays.asList (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // Elements to remove from initial list: at least test first and last. List<Integer> removed = Arrays.asList (0, 1, 5, 8 ,9); int intial_list_size = lis...
38044291_0
class Ed25519DsaSigner implements DsaSigner { @Override public Signature sign(final byte[] data) { if (!this.getKeyPair().hasPrivateKey()) { throw new CryptoException("cannot sign without private key"); } // Hash the private key to improve randomness. final byte[] hash = Hashes.sha3_512(ArrayUtils.toByte...
final String dataHex = "010100000100009803555e0020000000f5496c59ff336ae2d497140f0ad48306092beeda0d36c31c7373103956c9026180841e000000000063a95e002800000054435550565143373754414d4837514b504650354f5433544c5556344a59525056364345474a585700ca9a3b000000001900000001000000110000004669727374205445535421205965616821"; final b...
38080174_77
class RpcStrategySharding implements RpcStrategy { @Nullable @Override public RpcSender createSender(RpcClientConnectionPool pool) { List<RpcSender> subSenders = list.listOfNullableSenders(pool); int activeSenders = 0; for (RpcSender subSender : subSenders) { if (subSender != null) { activeSenders++; ...
RpcClientConnectionPoolStub pool = new RpcClientConnectionPoolStub(); RpcSenderStub connection2 = new RpcSenderStub(); RpcSenderStub connection3 = new RpcSenderStub(); int shardsAmount = 3; ShardingFunction<Integer> shardingFunction = item -> item % shardsAmount; RpcStrategy shardingStrategy = sharding(shar...
38108174_3
class AndroidRxBus implements Bus { public static AndroidRxBus create() { return create(new AndroidQueueCache()); } private AndroidRxBus(RxBus.QueueCache cache, RxBus.Logger logger); public static AndroidRxBus create(RxBus.QueueCache cache); public static AndroidRxBus create(RxBus.Logger...
Bus bus = AndroidRxBus.create(); assertNotNull(bus); } }
38152816_7
class LanguageIndex { public Set<LanguageDirection> getLanguages() { return languages; } private LanguageIndex(Map<SimpleLanguageDirection, List<LanguageDirection>> index, Map<String, List<LanguageRule>> rules, Map<LanguageDirection, LanguageBridge> pivots); public int size(); public Lan...
LanguageIndex index = new LanguageIndex.Builder() .add(lp("it en")) .add(lp("en it")) .build(false); assertEquals(lpset("it en", "en it"), index.getLanguages()); index = new LanguageIndex.Builder() .add(lp("it en")) ...
38174524_7
class EventBusAddressMessageMapping { public static <REQUEST extends com.google.protobuf.Message, RESPONSE extends com.google.protobuf.Message> Builder<REQUEST, RESPONSE> builder() { return new Builder<>(); } private EventBusAddressMessageMapping(); public void validate(); public JsonObj...
final EventBusAddressMessageMapping<GetVerticleDeployments.Request, GetVerticleDeployments.Response> mapping = EventBusAddressMessageMapping.<GetVerticleDeployments.Request, GetVerticleDeployments.Response>builder() .address("/xyz") .requestDefaultInstance(GetVerticleDeployments....
38195479_4
class WeatherData { public boolean checkQuality(String quality) { return (!quality.equals("") && ALLOWEDQUALITY.contains(quality)); } public WeatherData(LocalDateTime dateTime, String[] data); public abstract String[] combineValues(); public abstract Reading getReading(WeatherVar whichVa...
assertTrue(wd.checkQuality("Y")); assertTrue(wd.checkQuality("N")); assertTrue(wd.checkQuality("S")); assertTrue(wd.checkQuality("F")); assertFalse(wd.checkQuality("I")); assertFalse(wd.checkQuality("")); } }
38215053_0
class HOCRFileReader { public String readHOCRFile(final String pathOfHOCRFile) throws DCMAApplicationException { final StringBuffer infoHOCRFile = new StringBuffer(); synchronized (object) { String errMsg = null; if (null == pathOfHOCRFile || RegexConstants.EMPTY.equals(pathOfHOCRFile)) { errMsg = "Inv...
Boolean isSuccess = Boolean.FALSE; try { String hicrReaderObj = HOCRFileReader.getInstance().readHOCRFile( "E:\\file\\111\\output1024.html"); if (null == hicrReaderObj || "".equals(hicrReaderObj)) { isSuccess = Boolean.FALSE; } else { isSuccess = Boolean.TRUE; } } catch (DCMAApplicationE...
38218145_182
class AddMembersController extends AbstractCommandController { public void setGroupsController(TabbedGroupController groupsController) { this.groupsController = groupsController; } public AddMembersController(); public GroupsEditorContext getEditorContext(HttpServletRequest req); private void addSelection(Ht...
try { TabbedGroupController tc = new TabbedGroupController(); TabConfig tabConfig = new TabConfig(); tabConfig.setViewName("groups"); List<Tab> tabs = getTabList(); tabConfig.setTabs(tabs); tc.setTabConfig(tabConfig); tc.setDefaultCommandClass(org.webcurator.ui.groups.command.DefaultCommand.c...
38261859_9
class MetaDataUtils { @Nullable public static String getSharedPermission(Context context) { Bundle metaData = getMetaData(context); return getMetaValue(metaData, APP_SHARED_PERMISSION); } private MetaDataUtils(); @Nullable public static String getSharedAuthorityMatcher(Context context); @Nullable ...
String expected = "com.owlr.PERMISSION"; when(bundle.getString(MetaDataUtils.APP_SHARED_PERMISSION)).thenReturn(expected); assertThat(MetaDataUtils.getSharedPermission(context)).isEqualTo(expected); } }
38307113_24
class Main { int run(String[] args) { initJCommander(); try { parseParams(jc, args); if (help) { printUsage(null); return EXIT_CODE_OK; } if (debug) { initializeDebugLogging(); } ...
main.run(new String[]{"install"}); String output = outputStream.toString("UTF-8"); assertTrue(output.contains("Usage: install [options]")); } }
38307688_3
class MostToLeastDerivedPlaceTypeComparator implements Comparator<TypeElement> { @Override public int compare(TypeElement o1, TypeElement o2) { return realComparator.compare(o1, o2); } private int getHierarchyDepth(TypeElement typeElement); @Rule public CompilationRule compilationRule; private MostTo...
TypeElement[][] places = { {place3, place4}, // place3 and place4 both extend directly from place1 {place1, place2}, // place1 and place2 both extend directly from place }; for (TypeElement[] pair : places) { assertThat(comparator.compare(pair[0], pair[1])) .named(String.format("...
38311906_265
class EventSubscriberClass extends ModelClass<S> implements EventReceiverClass, SubscribingClass { @Override public ImmutableSet<SubscriberMethod> subscribersOf(EventClass eventClass, MessageClass originClass) { return delegate.handlersOf(eventClass, originClass); } private EventSubscribe...
ImmutableSet<SubscriberMethod> methods = subscriberClass.subscribersOf( EventClass.from(SpeakerJoined.class), EmptyClass.instance()); assertThat(methods).hasSize(1); SubscriberMethod actual = getFirst(methods, null); assertThat(actual.rawMethod()) .isEqualTo(...
38357506_0
class Significance { public static boolean testCorrelations(double correlation1, double correlation2, int n1, int n2, double alpha) throws MathException { double p = getSignificance(correlation1, correlation2, n1, n2); if (p <= alpha) { return true; } ...
assertTrue(testCorrelations(0.5, 0.74, 68, 68, 0.2)); assertTrue(testCorrelations(0.5, 0.74, 68, 68, 0.1)); assertTrue(testCorrelations(0.5, 0.74, 68, 68, 0.05)); assertFalse(testCorrelations(0.5, 0.74, 68, 68, 0.01)); assertTrue(testCorrelations(0.5, 0.7, 100, 100, 0.1)); ...
38417079_18
class ProductFlavorCombo { @NonNull public static <S extends DimensionAware & Named> List<ProductFlavorCombo<S>> createCombinations( @Nullable List<String> flavorDimensions, @NonNull Iterable<S> productFlavors) { List <ProductFlavorCombo<S>> result = Lists.newArrayList(); ...
try { ProductFlavorCombo.createCombinations( ImmutableList.of(DIMENSION1, DIMENSION2), ImmutableList.of(f1d1)); fail("Expected to throw"); } catch (RuntimeException ignore) { } } }
38443009_4
class CipherHelper { public static String encrypt(String text) { String base64EncryptedString = ""; if (!StringUtils.isBlank(text)) { try { String secretKey = getSecretKey(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] dige...
assertEquals(CipherHelper.encrypt(""), ""); } }
38443555_124
class RemoveAllNotificationsMutation implements DataFetcher<Boolean> { @Override public Boolean get(DataFetchingEnvironment environment) { final String username = environment.getArgument("username"); if (Strings.isNullOrEmpty(username)) { throw new GraphQLValidationError("username cannot be empty"); ...
when(environment.getArgument("username")).thenReturn("test"); final Boolean actual = mutation.get(environment); verify(store).removeAll(eq("test")); assertThat(actual).isTrue(); } }
38482121_116
class ClientRendered implements BitbucketRendered { public final String getType() { return type; } public ClientRendered(); public ClientRendered(final ClientRendered other); public void setType(String type); @Override public final String getMarkup(); public final void setMa...
String string1 = "{\"type\":\"rendered\"}"; ClientRendered rendered1 = jsonb.fromJson(string1, ClientRendered.class); assertEquals("rendered", rendered1.getType()); } }
38484146_8
class SqsMessagePoller { @Scheduled(fixedDelay = 1) // SUPPRESS CHECKSTYLE bug? public void loop() { // NOPMD - cc List<Message> messages = reveiveMessages(); if (messages.isEmpty()) { log.trace("No SQS message received"); return; } log.debug("{} SQS messages are received", messages.size()); messages...
// setup Message msg1 = createMessage(1); DeleteMessageRequest expectedDmr = createDeleteMessageRequest(1); when(sqs.receiveMessage(any(ReceiveMessageRequest.class))).thenReturn(receiveMessageResultOf(msg1)); doAnswer(createHeavyJobAnswer(4, true)).when(messageHandler).accept(any(Message.class)); // exercis...
38503932_0
class Examples extends Activity { public Instant now() { return Instant.now(); } @Override protected void onCreate(Bundle savedInstanceState); public ZonedDateTime hereAndNow(); } class ExamplesTest { @Test public void one() {
Examples activity = Robolectric.setupActivity(Examples.class); Instant now = activity.now(); assertNotNull(now); } }
38569235_8
class ConfirmationService { public Confirmation addConfirmation(@NotNull final String username, final long encounterId) { Confirmation newConfirmation = new Confirmation(); newConfirmation.setUser(userService.getDukeEncountersUser(username)); newConfirmation.setDate(new Date()); new...
given(userService.getDukeEncountersUser(anyString())).willReturn(testUser()); given(encounterService.getEncounterById(anyLong())).willReturn(testEncounter(1)); given(repository.save(any(Confirmation.class))).willReturn(testConfirmation()); Confirmation confirmation = service.addConfirmat...
38597960_45
class FormDatas { public FormDatas toRight() { return toRight( 0 ); } private FormDatas( Control control ); public static FormDatas attach( Control control ); public FormDatas toLeft(); public FormDatas toLeft( int margin ); public FormDatas atLeftTo( Control control ); public FormDatas atLeftTo...
FormDatas actual = attach( control ).toRight(); assertThat( actual ).isAttachedToRight( DENOMINATOR, 0 ); } }
38705594_523
class HL7DateTimeFormat { public static DateTimeFormatter forPrecision(Precision p) { switch (p) { case MILLISECOND: return dateTime(); case SECOND: return PointInTimeFormat.forPattern("yyyyMMddHHmmss"); case MINUTE: return...
PointInTime t = new PointInTime(1975, 7, 23, 10, 23, 55, 123); Assert.assertEquals("1975", HL7DateTimeFormat.forPrecision(Precision.YEAR).print(t)); Assert.assertEquals("197507", HL7DateTimeFormat.forPrecision(Precision.MONTH).print(t)); Assert.assertEquals("19750723", HL7DateTimeFormat....
38706431_2
class Utils { public static void unsubscribe(Subscription subscription) { if (subscription != null && !subscription.isUnsubscribed()) { subscription.unsubscribe(); } } private Utils(); public static void openPlayStorePage(Context context); public static void openPriva...
Subscription subscription = Mockito.mock(Subscription.class); Utils.unsubscribe(subscription); verify(subscription, times(1)).unsubscribe(); verify(subscription, times(1)).isUnsubscribed(); } }
38710489_1
class ManifestGenerator { public String generateJson(Manifest manifest) throws JsonProcessingException { ObjectMapper mapper = new IiifPresentationApiObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(manifest); return json; } public ManifestGenerator(); pub...
String urlPrefix = "http://localhost:10000/test"; Manifest manifest = new ManifestImpl(URI.create(urlPrefix + "/demo/bookreader/manifest.json"), new PropertyValueSimpleImpl("Walters MS 168")); List<Sequence> sequences = new ArrayList<>(); manifest.setSequences(sequences); Sequence seq1 = new Seque...
38710494_0
class BasicTransactionAssistanceFactoryImpl implements BasicTransactionAssistanceFactory { @Override public TransactionAssistant getTransactionAssistant() throws ResourceException { //enlist a new resource into the transaction. it will be delisted, when its closed. final CommitRollbackCallback commitRollbackCall...
CommitRollbackCallback callback = new CommitRollbackCallback() { private static final long serialVersionUID = 1L; @Override public void rollback(String txid) throws Exception { } @Override public void commit(String txid) throws Exception { } }; final UserTransactionManager tm = mock(UserTr...
38743792_67
class SQLTask extends Task { public static Instance run(Odps odps, String sql) throws OdpsException { String project = odps.getDefaultProject(); if (project == null) { throw new OdpsException("default project required."); } return run(odps, project, sql, "AnonymousSQLTask", null, null, "sql"); ...
Instance i = SQLTask.run(odps, odps.getDefaultProject(), "select * from src;", "testsql", null, null, 3); assertEquals(i.getPriority(), 3); } }
38755419_7
class Utilities { public static String completeDate(String date) { if (date.endsWith("-")) { date = date.substring(0, date.length()-1); } String val = ""; if (date.length() < 4) { return val; } else if (date.length() == 4) { val = date + ...
assertThat(Utilities.completeDate("2015"), is("2015-12-31")); } }
38829639_38
class Quantity implements Serializable { @Override public String toString() { StringBuilder b = new StringBuilder(); if (getAmount() != null) { b.append(getAmount()); } if (getFormat() != null) { b.append(getFormat()); } return b.toString(); } public Quantity(); public ...
assertEquals(".5Mi", new Quantity(".5Mi").toString()); assertEquals("1", new Quantity("1").toString()); assertEquals("129e6", new Quantity("129e6").toString()); assertEquals("0.001m", new Quantity("0.001m").toString()); assertEquals("1Ki", new Quantity("1Ki").toString()); assertEquals("32Mi", ne...
38830174_1
class PostPresenter extends BasePresenter { public void loadPostIdList(String storyTypeUrl) { mCompositeSubscription.add(mDataManager.getPostList(storyTypeUrl) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<List<Long>>() {...
when(mDataManager.getPostList("test")).thenReturn(Observable.just(makePostIdList(5))); mPresenter.loadPostIdList("test"); verify(mPostView).hideSwipeRefresh(); } }
38846457_2
class KotlinScriptEngine extends AbstractScriptEngine implements ScriptEngine, Compilable { @Override public Bindings createBindings() { return new SimpleBindings(); } public KotlinScriptEngine(KotlinScriptEngineFactory factory); @Override public CompiledScript compile(String script); @Override public Objec...
assertNotNull(engine.createBindings()); } }
38883479_7
class NormalizerNR1_5 implements NormalizationRule { @Override public Set<IntegerAxiom> apply(IntegerAxiom axiom) { Objects.requireNonNull(axiom); Set<IntegerAxiom> ret = Collections.emptySet(); if (axiom instanceof IntegerEquivalentClassesAxiom) { ret = applyRule((IntegerEquivalentClassesAxiom) axiom); }...
Set<IntegerAnnotation> annotations = new TreeSet<>(); IntegerOntologyObjectFactory factory = new IntegerOntologyObjectFactoryImpl(); NormalizerNR1_5 normalizer = new NormalizerNR1_5(factory); IntegerObjectProperty r = factory.getDataTypeFactory().createObjectProperty( factory.getEntityManager().createNamed...
38917208_1839
class SetError { public static Builder builder() { return new Builder(); } @VisibleForTesting SetError(Type type, Optional<String> description, Optional<ImmutableSet<MessageProperty>> properties); protected SetError(SetError setError); @JsonSerialize public String getType(); @JsonSe...
ImmutableSet<MessageProperty> props = ImmutableSet.of(MessageProperty.attachedMessages); SetError expected = new SetError(SetError.Type.ERROR, Optional.of("description"), Optional.of(props)); SetError setError = SetError.builder() .type(SetError.Type.ERROR) .des...
38935102_44
class Utils { @Nullable public static Point2D findRectEdgeIntersection(@Nonnull final Rectangle2D rect, final double outboundX, final double outboundY) { final int detectedSide = rect.outcode(outboundX, outboundY); if ((detectedSide & (Rectangle2D.OUT_TOP | Rectangle2D.OUT_BOTTOM)) != 0) { final boo...
final Rectangle2D rect = new Rectangle2D.Double(50, 50, 100, 50); assertEquals(new Point2D.Double(100d, 50d), Utils.findRectEdgeIntersection(rect, 100d, 25d)); assertEquals(new Point2D.Double(100d, 100d), Utils.findRectEdgeIntersection(rect, 100d, 125d)); assertEquals(new Point2D.Double(50d, 75d), Util...
38952211_1
class InsertSort { public static void mysort(Comparable[] a) { int sortedSize = 1; int length = a.length; //剩下未排序的队列 for (int i = 1; i < length; i++) { Comparable insertObject = a[i]; int insertIndex = sorte...
Integer[] sortIntegerArray = { 1, 2, 5, 4, 3 }; Integer[] resultArray = { 1, 2, 3, 4, 5 }; InsertSort.mysort(sortIntegerArray); Assert.assertArrayEquals(sortIntegerArray, resultArray); } }