id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
79723681_1
class OpenApiEndpointSource implements EndpointSource { @Override public Iterable<Endpoint> listEndpoints() { List<Endpoint> endpoints = new ArrayList<>(); String basePath = findBasePath(); Map<String, Path> paths = OpenApiHelper.openApi3.getPaths(); if(log.isInfoEnabled()) l...
OpenApiEndpointSource source = new OpenApiEndpointSource(); Iterable<EndpointSource.Endpoint> endpoints = source.listEndpoints(); // Extract a set of string representations of endpoints Set<String> endpointStrings = StreamSupport .stream(endpoints.spliterator(), false) ...
79736675_14
class WitchCore { public void doBind(Object target, ViewFinder viewFinder) { Object viewHolder = getOrCreateViewHolder(target, viewFinder); TargetViewBinder targetViewBinder = getOrCreateBinder(target, viewFinder); targetViewBinder.bind(viewHolder, viewFinder, target); if (loggingE...
// When core.doBind(target, viewFinder); // Then verify(viewFinder).putViewHolder(same(target.getClass()), same(viewHolderFromFactory)); verify(targetViewBinderFromFactory).bind(same(viewHolderFromFactory), same(viewFinder), same(target)); } }
79741030_15
class Creator { protected static int getSetBitOffset(final int mask, final int bitIndex) { int count = 0; // index of the next bit seen being set int workingMask = mask; // the left unseen bits are set int low = Integer.numberOfTrailingZeros(workingMask); workingMask >>>...
int v = Creator.getSetBitOffset(3, 1); assertEquals(1, v); } }
79750743_0
class GroupSummaryMessageExtractor extends BasicMessageExtractor { @Override public CharSequence[] getTitleAndText(String appPackageName, Bundle extras, int notificationFlags) { DebugLog debugLog = getDebugLog(); if (isLoggingEnabled()) { debugLog.writeLog("Entered GroupSummaryMessa...
MessageExtractor extractor = new GroupSummaryMessageExtractor(true); assertTitleAndTextEqual("Alice", null, getTitleAndText(extractor, REGULAR, "Alice", "Hello there!")); assertTitleAndTextEqual("Alice", "Hello there!", getTitleAndText(extractor, SUMMARY, "Alice...
79943898_35
class OnPostViewClickListener implements OnViewClickListener { @Override public void onViewClick(final View sharedElementView, final Post post) { final Intent intent = new Intent(activity.getApplicationContext(), PostActivity.class); intent.putExtras(getExtras(post)); final ActivityOpti...
onPostViewClickListener.onViewClick(viewMock, post); final ShadowActivity shadowActivity = Shadows.shadowOf(postsActivity); final Intent intent = shadowActivity.peekNextStartedActivityForResult().intent; assertThat(intent.getComponent()).isEqualTo(new ComponentName(postsActivity, PostAc...
79946335_11
class ReduceByKey extends StateAwareWindowWiseSingleInputOperator< IN, IN, IN, KEY, Pair<KEY, OUT>, W, ReduceByKey<IN, KEY, VALUE, OUT, W>> { public static <IN> KeyByBuilder<IN> of(Dataset<IN> input) { return new KeyByBuilder<>("ReduceByKey", input); } @SuppressWarnings("unchecked") ReduceB...
Flow flow = Flow.create("TEST"); Dataset<String> dataset = Util.createMockDataset(flow, 2); ReduceByKey.of(dataset) .keyBy(s -> s) .valueBy(s -> 1L) .reduceBy(n -> StreamSupport.stream(n.spliterator(), false).mapToLong(Long::new).sum()) .output(); ReduceByKey reduce = (...
79994161_2
class RxOkuki { public static Observable<Place> onAnyPlace(Okuki okuki) { return Observable.create(new OnGlobalPlaceOnSubscribe(okuki)); } private RxOkuki(); public static Observable<P> onPlace(Okuki okuki, Class<P> clazz); public static Observable<Place> onBranch(Okuki okuki, Class<B> c...
TestSubscriber<Place> testObserver = TestSubscriber.create(); RxOkuki.onAnyPlace(okuki).subscribe(testObserver); verify(okuki).addGlobalListener(isA(GlobalListener.class)); testObserver.unsubscribe(); verify(okuki).removeGlobalListener(isA(GlobalListener.class)); } }
80027205_4
class TimeData { static byte[] timezoneWithDstOffset(Calendar time) { // See https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.local_time_information.xml // UTC-1:00 = -4 // UTC+0:00 = 0 // UTC+1:00 = 4 int timezone = time.ge...
Calendar bst = Calendar.getInstance(TimeZone.getTimeZone("UTC")); bst.set(Calendar.MONTH, Calendar.JUNE); bst.set(Calendar.DST_OFFSET, ONE_HOUR); assertArrayEquals( new byte[] {0, 4}, TimeData.timezoneWithDstOffset(bst) ); } }
80043676_185
class ZclAttribute { public Future<CommandResult> reportValue(Object value) { return cluster.reportAttribute(id, dataType, value); } public ZclAttribute(); public ZclAttribute(final ZclCluster cluster, final int id, final String name, final ZclDataType dataType, final boolean man...
ZclCluster cluster = Mockito.mock(ZclCluster.class); ZclAttribute attribute = new ZclAttribute(cluster, 123, "Test Name", ZclDataType.UNSIGNED_8_BIT_INTEGER, false, false, false, false); Integer value = Integer.valueOf(888); attribute.reportValue(value); Mockito....
80046613_1
class VcapParser implements EnvironmentPostProcessor { VcapResult parse(String vcapServices) { VcapResult result = new VcapResult(); List<VcapPojo> results = new ArrayList<VcapPojo>(); log("VcapParser.parse: vcapServices = " + vcapServices); if (vcapServices != null) { try { JSONObject json = ...
Resource resource = new ClassPathResource("/vcap2.json"); String content; try { content = new String(Files.readAllBytes(Paths.get(resource.getURI()))); VcapResult result = parser.parse(content); VcapPojo[] pojos = result.getPojos(); assertNotNull(pojos); assertEquals(1, pojos.length); VcapPoj...
80087888_5
class MongolCode { public static String getSuffixYinUnU(Gender previousWordGender, char previousWordLastChar) { if (isVowel(previousWordLastChar)) { return Suffix.YIN; } else if (previousWordLastChar == Uni.NA) { if (previousWordGender == Gender.MASCULINE) { ...
char wordLastChar = MongolCode.Uni.OE; String result = MongolCode.getSuffixYinUnU(MongolCode.Gender.MASCULINE, wordLastChar); String expected = MongolCode.Suffix.YIN; assertEquals(expected, result); } }
80098624_35
class HumanCoffeeNetUser extends AbstractCoffeeNetUser { @Override public boolean isCoffeeNetAdmin() { return getAuthorities().contains(new SimpleGrantedAuthority("ROLE_COFFEENET-ADMIN")); } public HumanCoffeeNetUser(String username, String email, Collection<GrantedAuthority> authorities); ...
HumanCoffeeNetUser sut = new HumanCoffeeNetUser("username", "email@coffeenet", emptyList()); assertThat(sut.isCoffeeNetAdmin(), is(false)); } }
80161946_0
class Client { public List<Object> fetchAndProcessData(String dateTime) throws UnirestException { Optional<JsonNode> data = loadProviderJson(dateTime); System.out.println("data=" + data); if (data != null && data.isPresent()) { JSONObject jsonObject = data.get().getObject(); int value = 100 ...
String date = "2013-08-16T15:31:20+1000"; stubFor(get(urlPathEqualTo("/provider.json")) .withQueryParam("validDate", matching(".+")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"test\": \"NO\", \"validDate\": \"" + d...
80179724_33
class RequiredPropAnnotator implements Annotator { static void annotate( PsiElement element, BiConsumer<Collection<String>, PsiReferenceExpression> errorHandler, Function<PsiMethodCallExpression, PsiClass> generatedClassResolver) { if (element instanceof PsiDeclarationStatement) { Arrays....
testHelper.getPsiClass( psiClasses -> { assertEquals(2, psiClasses.size()); PsiClass underTest = psiClasses.get(0); PsiClass component = psiClasses.get(1); // For testing environment Function<PsiMethodCallExpression, PsiClass> resolver = psiM...
80192374_0
class LoginPresenter extends BasePresenter<V> implements LoginMvpPresenter<V> { @Override public void onServerLoginClick(String email, String password) { //validate email and password if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); ret...
String email = "dummy@gmail.com"; String password = "password"; LoginResponse loginResponse = new LoginResponse(); doReturn(Observable.just(loginResponse)) .when(mMockDataManager) .doServerLoginApiCall(new LoginRequest .ServerLog...
80196099_77
class ProxyMessageDecoder { public void parse(InputStream is) throws Exception { LOG.trace("parse()"); String baseContentType = HttpFields.valueParameters(contentType, null); if (faultAllowed && baseContentType.equalsIgnoreCase(TEXT_XML)) { parseFault(is); } else if (ba...
String contentType = MimeUtils.mpMixedContentType("xtop1357783211hcn1yiro"); ProxyMessageDecoder decoder = createDecoder(contentType); decoder.parse(getMessage("normal-soapfault.request")); assertNotNull(callback.getFault()); } }
80207578_4
class XSLTService { public String generateSimpleReport(String simpleReport) { try { return SimpleReportFacade.newFacade().generateHtmlReport(simpleReport); } catch (Exception e) { LOG.error("Error while generating simple report : " + e.getMessage(), e); return null; } } public String generateSimpleC...
JAXBContext context = JAXBContext.newInstance(XmlSimpleReport.class.getPackage().getName()); Unmarshaller unmarshaller = context.createUnmarshaller(); Marshaller marshaller = context.createMarshaller(); JAXBElement<XmlSimpleReport> unmarshal = (JAXBElement<XmlSimpleReport>) unmarshaller.unmarshal(new File("src...
80228150_178
class UpdatePortGroupTask extends TransactionalTask { public UpdatePortGroupTask create(SecurityGroup sg, NetworkElementImpl portGroup) { UpdatePortGroupTask task = new UpdatePortGroupTask(); task.securityGroup = sg; task.portGroup = portGroup; task.apiFactoryService = this.apiFacto...
// Arrange. SecurityGroup sg = registerSecurityGroup(1L, "projectId", "projectName", 1L, "sgName"); sg.addSecurityGroupMember(newSGMWithPort(1L, OPENSTACK_ID)); NetworkElementImpl portGroup = createPortGroup(OPENSTACK_ID); ostRegisterPorts(sg); String domainId = UUID.ra...
80229651_1
class SetupAndExecuteCanariesStage implements StageDefinitionBuilder { protected Duration calculateLifetime( Instant start, Instant endTime, CanaryAnalysisExecutionRequest canaryAnalysisExecutionRequest) { Duration lifetime; if (endTime != null) { lifetime = Duration.ofMinutes(start....
long lifetimeInMinutes = 5L; Instant now = Instant.now(); Instant later = null; CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder().lifetimeDurationMins(5L).build(); Duration actual = stage.calculateLifetime(now, later, request); Duration expected = Duratio...
80231323_0
class MediaIDHelper { public static String createMediaID(String musicID, String... categories) { StringBuilder sb = new StringBuilder(); if (categories != null) { for (int i=0; i < categories.length; i++) { if (!isValidCategory(categories[i])) { throw...
fail(MediaIDHelper.createMediaID(null, "BY|GENRE/2", "Classic 70's")); } }
80324891_4
class TitleModel extends AbstractComponentModel { @Override protected String getIdPrefix() { return ID_PREFIX; } @PostConstruct private void initModel(); public String getTitle(); public String getType(); private static final String MOCK_JSON; private static final String TEST_...
underTest = context.request().adaptTo(TitleModel.class); assertEquals("title", underTest.getIdPrefix()); } }
80376233_1
class Longitude implements Serializable { @Override public String toString() { return String.format(Locale.ENGLISH, "%f", value); } public Longitude(Double value); public Longitude(Integer value); public Double value(); @Override public int hashCode(); @Override public boolean equa...
Longitude l = new Longitude(-0.000066); assertEquals("-0.000066", l.toString()); } }
80403715_2
class Presenter implements Contract.Presenter { @Override public void onStart() { setLoading(); binder.bind(getAnimals(), this::setAnimals, this::setError, this::setComplete); } public Presenter(@NonNull Repository repository, @NonNull Contract.View view, @NonNul...
// given ServiceException exception = new ServiceException(); when(repository.fetchResponse(any())).thenReturn(Single.error(exception)); // when presenter.onStart(); // then verify(view).setViewState(ViewState.Error.create(R.string.error_message)); } }
80451996_127
class ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public int getCurrentDataVersion() { int result = RedirectorConstants.NO_MODEL_NODE_VERSION; if (isCacheUsageAllowed()) { ChildData data = cache.getCurrentData(); if (data != null ...
testee = new ZkNodeCacheWrapper(client, "/test", null); doThrow(new DataSourceConnectorException()).when(client).getNodeVersion(anyString()); int result = testee.getCurrentDataVersion(); Assert.assertEquals(NO_MODEL_NODE_VERSION, result); } }
80485636_1
class Utils { public static DateTime convertLocalToDTSafely(LocalDateTime localDateTime) { DateTime convertedDT = null; try { convertedDT = localDateTime.toDateTime(); } catch (IllegalInstantException e) { boolean failed = true; int iteration = 1; ...
DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles")); Assert.assertEquals(LocalDateTime.parse("2018-03-11T03:04:00").toDateTime(DateTimeZone.getDefault()), Utils.convertLocalToDTSafely(LocalDateTime.parse("2018-03-11T02:04:00"))); Assert.assertEquals(LocalDateTime...
80501529_5
class LogServiceProtoUtil { public static LogServiceRequestProto toReadLogRequestProto(LogName name, long start, int total) { LogNameProto logNameProto = LogNameProto.newBuilder().setName(name.getName()).build(); ReadLogRequestProto.Builder builder = ReadLogRequestProto.newBuilder(); builder.setL...
LogName name = LogName.of("test"); long start = 100; int total = 5; LogServiceRequestProto proto = LogServiceProtoUtil.toReadLogRequestProto(name, start, total); ReadLogRequestProto request = proto.getReadNextQuery(); assertEquals(name.getName(), request.getLogName().getName()); assertEqual...
80550868_1
class EventDeserializer implements Deserializer<CoffeeEvent> { @Override public CoffeeEvent deserialize(final String topic, final byte[] data) { try (ByteArrayInputStream input = new ByteArrayInputStream(data)) { final JsonObject jsonObject = Json.createReader(input).readObject(); ...
final CoffeeEvent actual = cut.deserialize(null, data.getBytes(StandardCharsets.UTF_8)); assertEventEquals(actual, expected); } }
80550971_13
class RegexFileFilter implements ParcelableFileFilter { @Override public boolean accept(File pathname) { String pathToMatch = matchAbsolutePath ? pathname.getAbsolutePath() : pathname.getName(); return pattern.matcher(pathToMatch).matches(); } public RegexFileFilter(String regex, bool...
when(file.getName()).thenReturn("testMe.java"); assertTrue(regexFileFilter.accept(file)); } }
80563893_7
class LoadGenerator extends ContainerLifeCycle { public CompletableFuture<Void> begin() { if (logger.isDebugEnabled()) { logger.debug("generating load, {}", config); } return proceed().thenCompose(x -> { CompletableFuture[] futures = new CompletableFuture[config.getT...
prepare(new TestHandler()); AtomicLong requests = new AtomicLong(); AtomicLong resources = new AtomicLong(); LoadGenerator loadGenerator = new LoadGenerator.Builder() .port(connector.getLocalPort()) .httpClientTransportBuilder(clientTransportBuilder) ...
80605895_2
class EventHubCollector extends CollectorComponent { @Override public CheckResult check() { try { // make sure compute doesn't throw an exception Future<?> registrationFuture = lazyRegisterEventProcessorFactoryWithHost.get(); registrationFuture.get(); // make sure registration succeeded ...
EventHubCollector collector = new EventHubCollector(new LazyFuture()); assertThat(collector.check().ok()).isTrue(); assertThat(registration).isCompleted(); } }
80643997_41
class RxFirebaseUser { @CheckResult @NonNull public static Completable updateEmail(@NonNull FirebaseUser user, @NonNull String email) { return Completable.create(new UserUpdateEmailOnSubscribe(user, email)); } private RxFirebaseUser(); @CheckResult @NonNull public static Completable delete(@NonNul...
mockNotSuccessfulVoidResult(new IllegalStateException()); when(mockFirebaseUser.updateEmail("foo@bar.com")).thenReturn(mockVoidTaskResult); TestObserver obs = TestObserver.create(); RxFirebaseUser.updateEmail(mockFirebaseUser, "foo@bar.com").subscribe(obs); callOnComplete(mockVoidTaskResult); ...
80644284_26
class HoverEvent implements Examinable, HoverEventSource<V>, StyleBuilderApplicable { @Deprecated public static <V> @NonNull HoverEvent<V> of(final @NonNull Action<V> action, final @NonNull V value) { return new HoverEvent<>(action, value); } private HoverEvent(final @NonNull Action<V> action, final @Non...
final HoverEvent.ShowEntity se0 = HoverEvent.ShowEntity.of(Key.key("cow"), UUID.randomUUID()); assertEquals(Key.key("cow"), se0.type()); final HoverEvent.ShowEntity se1 = se0.type(Key.key("chicken")); assertEquals(Key.key("cow"), se0.type()); // original should be unmodified assertEquals(Key.key("ch...
80648908_1
class OrdersConnector { public OrderResponse chargeChard() { ResponseEntity<String> orderResponse = request(ordersHost, "/process-order"); return new OrderResponse(orderResponse); } @Autowired public OrdersConnector( @Value("${orders.host}") String ordersHost, Rest...
doReturn(ResponseEntity.badRequest().body("invalid content")).when(restTemplate).getForEntity("http://" + orders + "/process-order", String.class); OrderResponse response = this.subject.chargeChard(); OrderResponse expectedResponse = new OrderResponse(false, "unable to process order, please tr...
80652674_2
class ImageComponent { public static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall) { StaticMarkerAnnotation markerOrigin = new StaticMarkerAnnotation.Builder() .setName(com.mapbox.services.Constants.PIN_LARGE) .setPosition(origin...
// From https://www.mapbox.com/api-playground/#/directions String geometry = "}jllF~_euMm@C?xC}B@?l@e@FItAaAhCaAH?ZqD`BaH@CpCe@f@ye@zTDZ_Bv@"; Position whiteHouse = Position.fromCoordinates(-77.0365, 38.8977); Position dupontCircle = Position.fromCoordinates(-77.04341, 38.90962); ...
80717362_9
class ExecutorProgressListener implements ProgressListener, Runnable { @Override public void onProgress(long done, long total) { if (!pending || done == total) { this.done = done; this.total = total; try { pending = true; executor.exec...
testListener.onProgress(1, 1000); verifyZeroInteractions(delegateListener); verify(targetExecutor).execute(any(Runnable.class)); } }
80814228_44
class UserController { @RequestMapping(value = "/handle81") public String handle81(@RequestParam("user") User user, ModelMap modelMap) { modelMap.put("user", user); return "/user/showUser"; } @Autowired public void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) public M...
RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("user", "tom:123456:tomson"); String html = restTemplate.postForObject( "http://localhost:8080/chapter17/user/handle81.html", form, Str...
80822758_27
class AnnotationUtils { public static Set<Label> getLabels(final AnnotatedElement annotatedElement) { return getLabels(annotatedElement.getDeclaredAnnotations()); } private AnnotationUtils(); public static Set<Link> getLinks(final AnnotatedElement annotatedElement); public static Set<Lin...
final Set<Label> labels = getLabels(RepeatableAnnotations.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple(EPIC_LABEL_NAME, "e1"), tuple(EPIC_LABEL_NAME, "e2") ); }...
80874891_1
class ArtifactSizeEnforcerRule implements EnforcerRule { @Override public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { if (skip) { return; } String packaging = getPackaging(helper); if (!SUPPORTED_PACKAGE_TYPES.contains(packaging)) { helper .getLog()...
tempFolder.newFile(SAMPLE_ARTIFACT_FILE_NAME); ArtifactSizeEnforcerRule enforcer = new ArtifactSizeEnforcerRule(); try { enforcer.execute(defaultMockhelper); } catch (EnforcerRuleException e) { fail("Failed to discover artifact."); } } }
80993243_1
class InterfaceCodeGenerator { public Map<File, String> analyze(boolean _ignoreDtd) throws Exception { if (_ignoreDtd) { // if dtd validation is disabled (default) docFac.setValidating(false); docFac.setNamespaceAware(true); docFac.setFeature("http://xml.org/sax/features...
String objectPath = "/"; String busName = "org.freedesktop.NetworkManager.Device.Wireless"; boolean ignoreDtd = true; Logger logger = LoggerFactory.getLogger(InterfaceCodeGenerator.class); if (!StringUtils.isBlank(busName)) { String introspectionData = FileIoUtil.r...
81002077_166
class ClassUtil extends UtilityClass { public static Optional<Class<?>> superclass(Class<?> aClass) { return Optional.ofNullable(aClass.getSuperclass()); } @SuppressWarnings("unchecked") public static Class<T> forObject(T value); public static Optional<Class<?>> forName(String className); ...
Optional<Class<?>> result = ClassUtil.superclass(TestingTargetBase.class); assertThat(result, is(Optional.of(Object.class))); } }
81016276_22
class LogicalAnd extends BinaryOperation { @Override public String toString() { return "(" + getLeft() + " && " + getRight() + ")"; } public LogicalAnd(Expression left, Expression right, int line, int charPositionInLine); @Override public T accept(ExpressionVisitor<T, C> visitor, C conte...
final String EXPECTED_RESULT = "(1 && 2)"; QLParser parser = ASTBuilder.getQlParser("1&&2"); LogicalAnd expression = (LogicalAnd) ASTBuilder.getExpression(parser); assertEquals(EXPECTED_RESULT, expression.toString()); } }
81052983_1
class FactMap implements NameValueReferableMap<T> { @Override public boolean containsValue(Object value) { return _facts.containsValue(value); } public FactMap(Map<String, NameValueReferable<T>> facts); @SafeVarargs public FactMap(NameValueReferable<T>... facts); public FactMap(); @Override publ...
Map<String, Object> map = Mockito.mock(Map.class); FactMap factMap = new FactMap(map); Mockito.when(map.containsValue("value1")).thenReturn(true); Mockito.when(map.containsValue("value2")).thenReturn(false); Assert.assertTrue(factMap.containsValue("value1")); Assert.assertFalse(factMap.contains...
81102463_439
class RestAuthRedirectCallbackHandler extends AbstractRestAuthCallbackHandler<RedirectCallback> { public RedirectCallback convertFromJson(RedirectCallback callback, JsonValue jsonCallback) { throw new RestAuthException(Response.Status.INTERNAL_SERVER_ERROR, new UnsupportedOperationException( ...
//Given //When restAuthRedirectCallbackHandler.convertFromJson(null, null); //Then fail(); } }
81125398_41
class GroupCountsResult implements QueryResult { @Override public int hashCode() { return this.items.hashCode(); } private GroupCountsResult(final List<GroupCount> items); public static GroupCountsResult create(final List<GroupCount> items); @Override public int getType(); @Overr...
assertEquals(createSampleResult().hashCode(), createSampleResult().hashCode()); } }
81128415_1
class HrrsUrlEncodedFormHelper { public HttpRequestPayload extractUrlEncodedFormPayload(HttpServletRequest request, String defaultEncoding) { byte[] encodedFormParameterBytes = encodeFormParameters(request, defaultEncoding); return ImmutableHttpRequestPayload .newBuilder() ...
HttpServletRequest request = mock(HttpServletRequest.class); String encoding = "ASCII"; when(request.getCharacterEncoding()).thenReturn(encoding); when(request.getQueryString()).thenReturn("y=y1"); when(request.getParameterNames()).thenReturn(Collections.enumeration(Arrays.asList...
81143147_48
class EmptyUri implements Uri { @Override public Optional<? extends Fragment> fragment() { return absent(); } @Override public Optional<? extends Scheme> scheme(); @Override public Optional<? extends Authority> authority(); @Override public Path path(); @Override public Optiona...
assertFalse(new EmptyUri().fragment().isPresent()); } }
81166660_0
class ToggleJsonNode { public static JsonNode fromString(String json) { try { return DEFAULT_OBJECT_READER.readTree(json); } catch (IOException err) { return MissingNode.getInstance(); } } public static JsonNode findByKey(Iterator<JsonNode> iterator, String key); public static boolean ...
final JsonNode node = ToggleJsonNode.fromString("{\"foo\": 4, \"bar\": true}"); assertThat(node.isMissingNode()).isFalse(); assertThat(node.fieldNames()).containsOnly("foo", "bar"); assertThat(node.path("foo").intValue()).isEqualTo(4); assertThat(node.path("bar").booleanValue()).isTrue(); } }
81175234_41
class CommodityImgServiceImlpl implements ICommodityImgService { @Override public boolean deleteImage(Long id) { return commodityImg.deleteByPrimaryKey(id) > 0; } @Override public boolean addImage(CommodityImg commodImg); @Override public CommodityImg selectImg(Long id); @Override publ...
boolean b = commodImg.deleteImage(1l); Assert.assertTrue(b); //测试完成 可用 } }
81186751_13
class FinagleAdjuster extends Adjuster { @Override protected Span adjust(Span span) { if (applyTimestampAndDuration()) { return ApplyTimestampAndDuration.apply(span); } return span; } FinagleAdjuster(); public static Builder newBuilder(); abstract boolean applyTimestampAndDuration(); ...
Iterable<Span> adjusted = adjuster.adjust(TestObjects.TRACE); assertThat(adjusted).containsExactlyElementsOf(TestObjects.TRACE); } }
81201370_26
class SubscribeCommand extends SingleCharacteristicsCommand { @Override protected void onError(int error) { finish(CommandResult.createErrorResult(characteristicUUID, error)); } SubscribeCommand(@Type int type, UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); @Overr...
setupDescriptorSuccess(); subscribeCommand.execute(device, operationCommandObserver, gatt); subscribeCommand.onError(BluetoothGatt.GATT_FAILURE); verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE); } }
81201685_18
class PrefixTokenizer implements MultiAutoCompleteTextView.Tokenizer { @Override public int findTokenStart(CharSequence text, int cursor) { // base case: empty string if (text.length() == 0) { return 0; } // iterate back until we find the prefix char separat...
assertThat(tokenizer.findTokenStart(" @:", 3), is(1)); assertThat(tokenizer.findTokenStart(" :@", 3), is(1)); assertThat(tokenizer.findTokenStart(" :test1@test2", 3), is(1)); assertThat(tokenizer.findTokenStart(" :test1 @test2", 9), is(8)); } }
81304886_25
class TextCleaner { public String cleanInlineCode(Object input) { String output = clean(input, false).replace('\n', ' '); if(output.indexOf('`') != -1) { String prepend = ""; if(output.charAt(0) == '`') { prepend = " "; } String append = ""; if(output.charAt(output.length()-1) == '`') { app...
Assert.assertEquals("```` ``t```i`ck` ````", BASIC.cleanInlineCode("``t`&#96;`i`ck`")); } }
81385470_3
class SmartcarAuth { public void addClickHandler(final Context context, final View view) { addClickHandler(context, view, (new AuthUrlBuilder()).build()); } public SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); public Sma...
// Setup mocks Context context = mock(Context.class); View view = mock(View.class); // Execute methods SmartcarAuth smartcarAuth = new SmartcarAuth( "client123", "scclient123://test", new String[] {"read_odometer", "read_vin"}, ...
81436550_3
class Driver { public void processOne() throws DriverException, CloseException { Request request; try { request = this.reader.read(); } catch (CloseException ex) { throw ex; } catch (Exception ex) { final Response response = createFatalResponse(ex...
final String input = "garbage"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); f...
81464391_3
class UserController { @RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody User userByFullname(@RequestParam("fullname") String fullname) { return repository.findByFullname(fullname); } ...
mockMvc.perform(get("/user?fullname={fullname}", "Samed Düzçay")) .andExpect(status().isOk()) .andExpect( content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.username", is("samed"))) .andExpect(jsonPa...
81464583_17
class FeedRow { public static int[] fromYearFormat(String yearFormat) { String[] parts = yearFormat.split("/"); if (parts.length != 2) { throw new IllegalArgumentException("Given string is not in expected format: " + yearFormat); } int[] intParts = {Integer.parseInt(par...
String year = "-30/2000"; int[] yearPair = {-30, 2000}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); year = "0/0"; yearPair = new int[]{0, 0}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); thrown.expect(IllegalArgumentException.class)...
81467673_18
class AdbMonitor { static String readPacket(ByteBuffer input) { if (input.remaining() < LENGTH_FIELD_SIZE) { return null; } // each packet contains 4 bytes representing the String length in hexa, followed by a list of device states, one per line; // each line contains: t...
String data = "00300123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n", result); } }
81500686_0
class DeepLinkAnnotationCompiler extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("[FlowR]: generating deep Link Handler..."); MethodSpec.Builder constructorBuilder = generateConstructor(); ...
assertAbout(javaSources()) .that(Arrays.asList(TEST_DEEP_LINK_FRAGMENT, TEST_DEEP_LINK_HANDLER)) .processedWith(new DeepLinkAnnotationCompiler()) .compilesWithoutError() .and() .generatesSources(TEST_DEEP_GENERATED_HANDLER); } }
81569594_24
class Expression { public Object eval(Object scope) { try { return valueExpression.getValue(new XLContext(scope)); } catch (ELException ele) { return null; // unresolved element yields null value } } public Expression(String expression); @SuppressWarni...
Expression expr = new Expression("${1==1}"); Object o = expr.eval(null); // no scope required for non-resolving expression assertThat(o).isInstanceOf(Boolean.class); assertThat(o).isEqualTo(true); } }
81587412_4
class System { public static SystemBuilder builder() { return new SystemBuilder(); } public System(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); public System(String name, Collection<ComponentRelationships> rels); public static System of(Stri...
System actual = System.builder().name(NAME).componentRelationships(new HashSet<>()).errors(new HashSet<>()) .build(); Assertions.assertThat(System.empty(NAME)).isEqualTo(actual); } }
81611630_13
class ContentDisposition { public static ContentDisposition parse(String contentDisposition) { List<String> parts = tokenize(contentDisposition); String type = parts.get(0); String name = null; String filename = null; Charset charset = null; Long size = null; ...
String header = "form-data; name=\"f\"; filename=\"image-for-upload.jpeg\""; ContentDisposition d = ContentDisposition.parse(header); System.out.format("parsed: %s%n", d); assertEquals("type", "form-data", d.getType()); assertEquals("name", "f", d.getName()); assertEquals...
81617098_147
class HttpsUsageImpl implements IBestPractice { @Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { /* * Reset these total numbers before each test-run due to bean being * singleton. */ totalNumConnectionsCurrentTrace = 0; totalNumHttpConnectionsCurrentTrace = 0; Li...
PacketAnalyzerResult pktAnalyzerResult = resultTestSetup(5); HttpsUsageResult httpsUsageResult = (HttpsUsageResult) httpsUsageImpl.runTest(pktAnalyzerResult); List<HttpsUsageEntry> httpsUsageEntries = httpsUsageResult.getResults(); assertEquals(2, httpsUsageEntries.size()); if (httpsUsageEntries.get(0).getIPA...
81649451_0
class PosTagger { public synchronized List<Conll> tagging(List<String> tokens, FragmentationType fragmentationType) throws ClassifierModelNotFoundException, IncorrectTokenException { AdvancedTokenHandler<Conll> tokenHandler = new StatefulTokenHandler(fragmentationType); try { ...
String text = "Отменить подписку на канал \"ByDaniel \u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\u200E\"?"; List<String> tokens = this.tokenizer.tokenization(text); List<Conll> conlls = this.tagger.tagging(tokens, FragmentationType.NO_FRAGMENTATION); Assert.assertFalse(conlls....
81653189_6
class Shortbread { @TargetApi(25) public static void create(@NonNull Context context) { if (Build.VERSION.SDK_INT < 25) { return; } if (generated == null) { try { generated = Class.forName("shortbread.ShortbreadGenerated"); create...
when(intent.hasExtra("shortbread_method")).thenReturn(false); ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut = null; Shortbread.create(activity); assertNull(ShortbreadGenerated.activityThatWasPassedToCallMethodShortcut); } }
81678042_0
class LintRegistry extends IssueRegistry { @Override public List<Issue> getIssues() { return ImmutableList.of(AndroidLogDetector.ISSUE, HardcodedColorsDetector.ISSUE, DirectMaterialPaletteColorUsageDetector.ISSUE, NonMaterialColorsDetector.ISSUE); } ...
int size = lintRegistry.getIssues().size(); assertThat(size).isEqualTo(NUMBER_OF_EXISTING_DETECTORS); } }
81799714_4
class WebAppCache { public List<WebappInfo> getAppBarWebInfos(String serverName) { return getAppBarWebInfos(serverName, null); } public WebAppCache(Supplier<Collection<ComponentConfig>> supplier); public List<WebappInfo> getAppBarWebInfos(String serverName, String menuName); public Optio...
WebappInfo wInfo0 = new WebappInfo.Builder().server("foo").title("foo").create(); wInfos.add(wInfo0); WebappInfo wInfo1 = new WebappInfo.Builder().server("foo").title("foo").position("14").create(); wInfos.add(wInfo1); // Ensure that there is no collision. assertThat(wac...
81880059_4
class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServiceBrokerApiVersionException { if (version != null && !anyVersionAllowed()) { String apiVersion = request.getHeader(version.getBro...
String header = "header"; String version = "version"; String notVersion = "not_version"; when(brokerApiVersion.getBrokerApiVersionHeader()).thenReturn(header); when(brokerApiVersion.getApiVersions()).thenReturn(version); when(request.getHeader(header)).thenReturn(notVersion); BrokerApiVersionIntercepto...
81897811_0
class JSPackagerWebSocketClient implements WebSocketListener { @Override public void onMessage(ResponseBody response) throws IOException { if (response.contentType() != WebSocket.TEXT) { FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType()); return; ...
final JSPackagerWebSocketClient.JSPackagerCallback callback = mock(JSPackagerWebSocketClient.JSPackagerCallback.class); final JSPackagerWebSocketClient client = new JSPackagerWebSocketClient("ws://not_needed", callback); client.onMessage(ResponseBody.create(WebSocket.TEXT, "{\"version\": 1, \"ta...
81928401_1
class JSONBeanUtil { public static String mapToJSONBean(final Map<String,Object> map) { final JSONObject obj = new JSONObject(); for (String key : map.keySet()) { if (! key.startsWith("#")) { //don't include Camel stats obj.put(key, map.get(key)); } ...
ObjectMapper mapper = new ObjectMapper(); SimpleOutputBean bean = new SimpleOutputBean(); bean.setC(50); String jsonBeanExcpected = mapper.writeValueAsString(bean); Map<String,Object> map = new HashMap<>(); map.put("c", 50); map.put("#update-count-1",0); ...
81932909_9
class CircleView extends View { @Override protected void dispatchDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(defaultColor); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); canvas.drawCircle(mCenterX, mCenterY, mRadius, paint); if(m...
ActivityController<Activity> activityController = Robolectric.buildActivity(Activity.class).create().start().resume() .visible(); Activity activity = activityController.get(); CircleView mView = new CircleView(activity); mView.setCenterY(2); mView.setCenterX(3...
82177245_4
class TimeFormatter implements StringFormatter<Long> { @Override public String format(Long millis) { long diff = System.currentTimeMillis() - millis; if (diff < TimeUnit.HOURS.toMillis(1)) { return resolver.get(R.string.label_minutes, Math.max(1, TimeUnit.MILLISECONDS.toMinutes(diff))); } i...
long yesterday = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1); String formatted = new SimpleDateFormat("MMM dd").format(new Date(yesterday)); assertThat(formatter.format(yesterday)).isEqualTo(formatted); } }
82179206_55
class HurlStack implements HttpStack { @SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_...
TestRequest.Head request = new TestRequest.Head(); assertEquals(request.getMethod(), Method.HEAD); HurlStack.setConnectionParametersForRequest(mMockConnection, request); assertEquals("HEAD", mMockConnection.getRequestMethod()); assertFalse(mMockConnection.getDoOutput()); } ...
82273737_4
class SpinedBuffer extends AbstractSpinedBuffer implements Consumer<E>, Iterable<E> { public Spliterator<E> spliterator() { class Splitr implements Spliterator<E> { // The current spine index int splSpineIndex; // Last spine index final int lastSpineIndex; ...
public void testIntLastSplit(int[] array, SpinedBuffer.OfInt sb) { Spliterator.OfInt spliterator = sb.spliterator(); Spliterator.OfInt split = spliterator.trySplit(); long splitSizes = (split == null) ? 0 : split.getExactSizeIfKnown(); long lastSplitSize = spliterator.getExactSizeIfK...
82304453_8
class FileBase implements File { @Override public final void write(String data) throws IOException { Files.write(this.path(), data.getBytes()); } public FileBase(Directory directory, String file); public FileBase(String directory, String file); public FileBase(Path directory, String...
final FileBase file = new FileBase(testFolder.getRoot().getAbsolutePath(), "ccc"); file.write("dasd"); MatcherAssert.assertThat(Files.exists(file.path()), Matchers.is(true)); } }
82313272_0
class ObjectClassNameBuilder { public String build() { final StringBuilder nameBuilder = new StringBuilder(); Collections.reverse(enclosingClassSimpleNames); for (String enclosingClassSimpleName : enclosingClassSimpleNames) { nameBuilder.append(enclosingClassSimpleName).append("...
final String objectClassName = new ObjectClassNameBuilder("TargetClass").build(); assertEquals("TargetClass_Retainer", objectClassName); } }
82348984_46
class FloatCoder extends BaseCoder<Float> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue) { state.putFloat(key, fieldValue); } private FloatCoder mCoder; } class FloatCoderTest extends BaseCoder<Float> { private FloatCoder mCoder;...
Float expectedValue = 9.0f; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getFloat(randomKey())); } }
82384202_23
class MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public int release(String path, int fileHandle) { logger.info("release({}, {})", fileHandle, path); FileChannel fileChannel = openFiles.remove(fileHandle); if (fileChannel == null) { return -ErrorCodes.EBADF(); } safeClose(fileC...
// Given FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar),...
82398873_3
class TodoService { public boolean edit(TodoEntity entity) { if(todoDAO.findById(entity.getId()) == null) return false; TodoEntity existingTodoEntity = todoDAO.findByName(entity.getName()); if(existingTodoEntity!=null && existingTodoEntity.getId()!=entity.getId()) return false; if...
TodoEntity alreadyExistingTodo = new TodoEntity(); alreadyExistingTodo.setId(1); alreadyExistingTodo.setStatus(TodoStatusType.OPEN); alreadyExistingTodo.setName("Test already existing name"); TodoEntity todoToEdit = new TodoEntity(); todoToEdit.setId(1); todoToEd...
82427374_36
class RoleConversionService { public Role convert(RoleRepresentation representation) { Role role = new Role(representation.getName()); role.setDescription(representation.getDescription()); return role; } public RoleRepresentation convert(Role role); public Role convert(RoleRepresentation representation, Rol...
RoleRepresentation representation = RoleDSL.role().build(); Role role = roleConversionService.convert(representation); assertThat(role.getName()).isEqualTo(representation.getName()); assertThat(role.getDescription()).isEqualTo(representation.getDescription()); } }
82468869_5
class RpcRouterConfig { public String getHandlerPackage() { return handlerPackage; } public RpcRouterConfig(); public String getDescription(); public void setDescription(String description); public void setHandlerPackage(String handlerPackage); public String getJsonPath(); pu...
String configName = "rpc-router-false-package"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); List<String> handlers; try (ScanResult scanResult = new ClassGraph() .whitelistPackages(config.getHandle...
82477856_2
class StringMethods { public static boolean containsIgnoreCase(String str, String searchStr) { if (str != null && searchStr != null) { int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; ++i) { if (str.regionMatches(true,...
assertThat(containsIgnoreCase("STRING1", "StRiNg1"), is(true)); assertThat(containsIgnoreCase("STRING1", "StRiNg12"), is(false)); } }
82480345_2
class PlaylistParser { public static Playlist parse(final InputStream inputStream) { if (inputStream == null) { throw new IllegalArgumentException("Input stream is null!"); } List<Playlist.Track> tracks = new ArrayList<>(); int version = -1, entries = -1; Buffer...
// Arrange, act Playlist playlist = PlaylistParser.parse(TEST_PLS, ENCODING_ASCII); // Verify assertNotNull(playlist); assertEquals(TEST_PLAYLIST_SIZE, playlist.getTracks().size()); assertEquals(TEST_PLAYLIST_VERSION, playlist.getVersion()); } }
82595458_5
class SpecificBlockingRestKiqrClientImpl implements SpecificBlockingKiqrClient<K,V> { @Override public Map<K, V> getAllKeyValues() { return genericClient.getAllKeyValues(store, keyClass, valueClass, keySerde, valueSerde); } public SpecificBlockingRestKiqrClientImpl(String host, int port, Stri...
Map<String, Long> results = new HashMap<>(); results.put("key1", 6L); when(clientMock.getAllKeyValues(any(), eq(String.class), eq(Long.class), any(), any())).thenReturn(results); Map<String, Long> result = unitUnderTest.getAllKeyValues(); assertThat(result.size(), is(equalTo(1...
82604742_339
class GroupNameRule extends ValidNameRule { @Override protected MessageResponseStatus getMessageResponseStatus() { return FaultType.INVALID_GROUP_NAME; } public GroupNameRule(final String theName); @Override protected String getMessage(); @Override public void validate(); privat...
final MessageResponseStatus messageResponseStatus = rule.getMessageResponseStatus(); assertEquals("InvalidGroupName", messageResponseStatus.getMessage()); } }
82722869_3
class SimpleLogger implements Log { public void debug(Object message) { out.println(message); } public void debug(Object message, Throwable th); public void error(Object message); public void error(Object message, Throwable th); public void fatal(Object message); public void fatal(Object message, Throwable t...
testee.debug(object); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); } }
82764073_6
class DataManager { public Single<List<Topic>> getUserTopics(String userLogin, int offset) { return mService.getUserTopics(buildAuthorization(), userLogin, offset, PAGE_LIMIT) .compose(applySingleSchedulers()); } public DataManager(@NonNull OkHttpClient client, @NonNull Preference...
TestObserver<List<Topic>> testObserver = mDataManager.getUserTopics("xshengcn", 0).test() .await(); testObserver.assertNoErrors(); testObserver.assertComplete(); } }
82809641_2
class OpenTracingHelper extends Helper { public Tracer getTracer() { if (tracer == null) { // Initialize on first use initTracer(); } return tracer; } public OpenTracingHelper(Rule rule); private boolean allowInstrumentedTracer(); protected void in...
System.setProperty("io.opentracing.contrib.agent.allowInstrumentedTracer", "true"); try { OpenTracingHelper helper = new OpenTracingHelper(null); Tracer tracer = helper.getTracer(); assertNotNull(tracer); tracer.buildSpan("test2"); } catch(DummyT...
82821845_17
class TsDumpFileUtils { @VisibleForTesting static FreqBandwidth getFreqAndBandwidth(File file) { if (!"ts".equals(getExtension(file))) return null; String[] parts = file.getName().toLowerCase().split("_"); if (parts.length != 4) return null; if (!"mux".equals(parts[0])) return n...
TsDumpFileUtils.FreqBandwidth res = TsDumpFileUtils.getFreqAndBandwidth(new File(ROOT, "mux_506000000_8000000_randomSuffix.ts")); assertThat(res.freq, is(506_000_000L)); assertThat(res.bandwidth, is(8_000_000L)); } }
82903968_0
class LoginController { public String login(UserForm userForm) { log.debug("LoginController.login {}", userForm); try { if (userForm == null) { return "ERROR"; } else if (loginService.login(userForm)) { return "OK"; } else { ...
loginController.login(userForm); verify(loginService).login(userForm); verifyNoMoreInteractions(loginService); } }
82906551_114
class URL implements Serializable { public String getPath() { return path; } protected URL(); public URL(String protocol, String host, int port); public URL(String protocol, String host, int port, String[] pairs); public URL(String protocol, String host, int port, Map<String, String> parameters); public ...
URL url = new URL("dubbo", "localhost", 20880, "////path"); assertEquals("path", url.getPath()); } }
82968973_37
class RadialSort extends DistancedSort { @Override public PointF getDistancePoint(ViewGroup parent, List<View> children) { PointF distancePoint; switch (position) { case TOP_LEFT: distancePoint = new PointF(0, 0); break; case TOP_MIDDLE: ...
radialSort = new RadialSort(/*interObjectDelay=*/0, /*reversed=*/false, RadialSort.Position.MIDDLE); // fake a width and height of 20, this will be double the expected value Mockito.when(mockParent.getHeight()).thenReturn(20); Mockito.when(mockParent.getWi...
82982240_0
class PopupBridge extends BrowserSwitchFragment { @SuppressLint("SetJavaScriptEnabled") public static PopupBridge newInstance(AppCompatActivity activity, WebView webView) throws IllegalArgumentException { return newInstance((FragmentActivity)activity, webView); } public PopupBridge(); @S...
Exception thrownException = null; AppCompatTestActivity appCompatTestActivity = Robolectric.setupActivity(AppCompatTestActivity.class); WebView webView = new WebView(appCompatTestActivity); try { PopupBridge.newInstance(null, webView); } catch (IllegalArgumentExceptio...
83002023_5
class BrowserSwitchConfig { Intent createIntentForBrowserSwitchActivityQuery(String returnUrlScheme) { String browserSwitchUrl = String.format("%s://", returnUrlScheme); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserSwitchUrl)); intent.addCategory(Intent.CATEGORY_DEFAULT);...
when(context.getApplicationContext()).thenReturn(applicationContext); when(applicationContext.getPackageName()).thenReturn("sample.package.name"); String returnUrlScheme = "sample.package.name.browserswitch"; Intent result = sut.createIntentForBrowserSwitchActivityQuery(returnUrlScheme)...
83122389_1
class UpdateIntelliJSdksTask extends DefaultTask { @TaskAction public void exec() throws IOException { Path userHome = Paths.get(System.getProperty("user.home")); final List<Path> intelliJFolders; try (var files = Files.list(userHome)) { intelliJFolders = files .filter( ...
Path intelliJFolder = Files.createDirectories(testUserHome.resolve(".IntelliJIdea2019.1")); task.exec(); assertNoExistingConfig(intelliJFolder); } }
83137916_20
class InitialRegistrationImpl { @Activate protected void activate(final Map<String, Object> props) throws ServiceException { logger.debug("activate(): props = {}", props); this.filterRoots = PropertiesUtil.toStringArray(props.get(PROP_FILTER_ROOTS), null); if (this.filterRoots == null) { throw new ServiceE...
/* Prepare data. */ assertEquals(0, this.baseDir.list().length); createTempFiles(SYNC_FILTER_FN); this.props.put(InitialRegistrationImpl.PROP_OVERWRITE_CONFIG_FILES, true); /* Invoke method. */ this.initialRegistration.activate(this.props); /* Check its results. */ FileAssert.assertEquals(getResource(...
83186903_1
class ReflectTool { public static <T> String tryGetGeneric(T t) { ParameterizedType pt = null; Type[] types = t.getClass().getGenericInterfaces(); if (types.length != 0 && types[0] instanceof ParameterizedType) { pt = (ParameterizedType) types[0]; } else { Ty...
String cls; List<String> list = new ArrayList<>(); cls = ReflectTool.tryGetGeneric(list); assertEquals(cls, null); Mark<List<String>> mark = new Mark<List<String>>() { }; cls = ReflectTool.tryGetGeneric(mark); assertEquals(cls, "java.util.List<java.lang....
83256557_8
class Preconditions { public static boolean checkWidget(Observer<?> observer, Widget widget) { if (null == widget) { observer.onError(new NullPointerException("The given widget was null")); return false; } else if (widget.isDisposed()) { observer.onError(new IllegalStateException("The given widget is dip...
TestObserver<?> testObserver = getEmptySubscribedTestObserver(); AtomicBoolean atomic = new AtomicBoolean(false); Thread thread = new Thread(() -> { boolean checkWidget = Preconditions.checkWidget(testObserver, shell); assertThat(checkWidget, is(false)); testObserver.assertError(IllegalStateException...
83275514_27
class ConsumerGatewayUtil { public static String removeResponseTag(String message) { String responsePrefix = ""; // Regex for reponse tag's namespace prefix String regex = ".*<(\\w+:)*(\\w+R|r)esponse.*?>.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = patter...
String source = "<testServiceResponse xmlns=\"http://test.com/ns\"><ts1:wrapper xmlns:ts1=\"http://test.com/ns2\"><ts1:param1>value1</ts1:param1><ts1:param2>value2</ts1:param2></ts1:wrapper></testServiceResponse>"; String result = "<ts1:wrapper xmlns:ts1=\"http://test.com/ns2\"><ts1:param1>value1</ts1:p...
83414665_11
class MergeMentionOverlapResolution implements MentionOverlapResolutionRepository { @Override public final List<Entity> resolveMentionOverlapping( final Map<AnnotatorConfig, List<Entity>> documents) { final List<Entity> finalEntities = new ArrayList<>(); for (final Map.Entry<AnnotatorConfig, List<En...
final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United State...
83457980_12
class PRNG extends Random { public float nextFloat(final float origin, final float bound) { return nextFloat(origin, bound, this); } protected PRNG(final long seed); protected PRNG(); public int nextInt(final int origin, final int bound); public long nextLong(final long origin, final long bound); public l...
final float min = 10; final float max = 100000; for (int i = 0; i < 1000; ++i) { final float value = prng.nextFloat(min, max); Assert.assertTrue(value < max); Assert.assertTrue(value >= min); } } }