id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
105357633_1 | class RootResource {
@GET
@PermitAll
public APIRootResponse get(@Context SecurityContext context) {
final Map<String, APIRestLink> links = new HashMap<>();
links.put("v1", new APIRestLink(URI.create(Constants.HTTP_V1_ROOT)));
return new APIRootResponse(links);
}
}
class RootRe... | final RootResource resource = new RootResource();
final APIRootResponse response = resource.get(TestHelpers.generateSecureSecurityContext());
assertHasKeyWithValue(
response.getLinks(),
"v1",
Constants.HTTP_V1_ROOT);
}
} |
105537880_0 | class MyFirstActor extends AbstractActor {
static public Props props() {
return Props.create(MyFirstActor.class, () -> new MyFirstActor());
}
@Override public Receive createReceive();
static ActorSystem actorSystem;
static final String HELLO_WORLD;
}
class MyFirstActorTest {
static... | final TestKit probe = new TestKit(actorSystem);
final ActorRef myFirstActor = actorSystem.actorOf(MyFirstActor.props());
myFirstActor.tell(new Greeting(HELLO_WORLD), probe.getRef());
final Greeting greeting = probe.expectMsgClass(Greeting.class);
assertEquals(HELLO_WORLD, greetin... |
105551486_0 | class Calculator implements ICalculator {
@Override
public String add(int... values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return format(sum);
}
private String format(int value);
@Override public String multiply(int... values);
@O... | assertEquals("3", mCalculator.evaluate(Matchers.anyString()));
final String result = mCalculator.add(1,2);
assertEquals("3", result);
when(mCalculator.evaluate(Matchers.anyString())).thenReturn("5");
assertEquals("5", mCalculator.evaluate(Matchers.anyString()));
}
} |
105563335_413 | class OpenApiConnectorGenerator extends ConnectorGenerator {
@Override
protected final String determineConnectorName(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) {
final OpenApiModelInfo modelInfo = parseSpecification(connectorSettings, APIValidationContext.NONE... | final Oas20Document openApiDoc = new Oas20Document();
assertThat(generator.determineConnectorName(ApiConnectorTemplate.SWAGGER_TEMPLATE, createSettingsFrom(openApiDoc))).isEqualTo("unspecified");
final Oas20Info info = (Oas20Info) openApiDoc.createInfo();
openApiDoc.info = info;
... |
105571183_39 | class Empty extends ERE {
@Override
public ERE derive(Symbol s) {
return empty;
}
private Empty();
static public Empty get();
@Override public EREType getEREType();
@Override public boolean equals(Object o);
@Override public int compareTo(Object o);
@Override public ERE c... | ERE derived = empty.derive(Symbol.get("test"));
assertEquals(empty, derived);
}
} |
105585951_4 | class Url62 {
static UUID decode(String id) {
BigInteger decoded = Base62.decode(id);
return UuidConverter.toUuid(decoded);
}
static String encode(UUID uuid);
}
class Url62Test {
@Test
public void shouldExplodeWhenContainsIllegalCharacters() {
| assertThatThrownBy(() -> Url62.decode("Foo Bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("contains illegal characters");
}
} |
105662144_0 | class StringUtils {
public static String getPreview(String text, int linesCount, boolean ignoreEmptyLines, Integer maxLength) {
if (maxLength != null && maxLength < 0) {
throw new IllegalArgumentException("maxLength can't be negative");
}
if (text == null) {
return ... | String text = getResourceText("Script.groovy");
String preview = StringUtils.getPreview(text, 2, true, Integer.MAX_VALUE);
assertEquals("package com.icthh.xm.lep.script\\n\\ndef description = \"'Logic Extension Point 2017'\"", preview);
preview = StringUtils.getPreview(text, 2, false, I... |
105692222_4 | class Siteswap implements Comparable<Siteswap>, Iterable<Byte>, Serializable {
public static Siteswap mergeCompatible(Siteswap s1, Siteswap s2) {
Siteswap i1 = s1.toInterface().toPattern();
Siteswap i2 = s2.toInterface().toPattern();
if (!s2.rotateToInterface(i1)) {
return null;
}
int length = 2 * s1.per... | Siteswap s1 = new Siteswap("86277");
Siteswap s2 = new Siteswap("6787a");
Siteswap merged = Siteswap.mergeCompatible(s1, s2);
assertEquals(merged, null);
}
} |
105770301_1 | class ExecShellScriptWorkItemHandler extends AbstractLogOrThrowWorkItemHandler {
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
try {
RequiredParameterValidator.validate(this.getClass(), workItem);
String shellScriptLocation = (String) workItem.getParame... | TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("ShellScriptLocation", "src/test/resources/TestScript.sh");
workItem.setParameter("TimeoutInMillis", "10");
ExecShellScriptWorkItemHandler handler = new Exec... |
105789039_1 | class DiffMutationFilterFactory implements MutationInterceptorFactory {
@Override
public MutationInterceptor createInterceptor(InterceptorParameters params) {
Optional<String> path = params.getString(fileParameter);
return new DiffMutationFilter(DiffInfo.fromFile(path.orElse(defaultPath)));
... | DiffMutationFilterFactory diffMutationFilterFactory = new DiffMutationFilterFactory();
MutationInterceptor diffMutationFilter = diffMutationFilterFactory
.createInterceptor(makeFor("file", "LICENSE"));
assertEquals(InterceptorType.FILTER, diffMutationFilter.type());
}
} |
105940648_2 | class ClusterStatus {
public static boolean isZookeeperReady(String zkConnectString, int timeoutMs) {
log.debug("Check if Zookeeper is ready: {} ", zkConnectString);
ZooKeeper zookeeper = null;
try {
CountDownLatch waitForConnection = new CountDownLatch(1);
boolean isSaslEnabled = false;
... | assertThat(
ClusterStatus.isZookeeperReady(this.kafka.getZookeeperConnectString(), 10000))
.isTrue();
}
} |
105987593_7 | class LotteryMachine {
List<String> draw(List<String> emails) {
System.out.println("Draw for the seed: " + getSeed());
Random rnd = new Random(getSeed());
Set<String> winners = new HashSet<>();
while (winners.size() < Math.min(winnersCount, emails.size())) {
int index = ... | LotteryMachine machine = new LotteryMachine(2);
List<String> result = machine.draw(Collections.singletonList("test"));
Assert.assertEquals(1, result.size());
}
} |
106015269_215 | class JmsPoolJMSContext implements JMSContext, AutoCloseable {
@Override
public TemporaryTopic createTemporaryTopic() {
try {
return getSession().createTemporaryTopic();
} catch (JMSException jmse) {
throw JMSExceptionSupport.createRuntimeException(jmse);
}
}... | JMSContext context = cf.createContext();
assertNotNull(context.createTemporaryTopic());
context.close();
try {
context.createTemporaryTopic();
fail("Should not be able to create resource when context is closed");
} catch (IllegalStateRuntimeException isre... |
106220562_1 | class LambdaServer implements HttpServer {
@Override
public ReadStream<HttpServerRequest> requestStream() {
return null;
}
public LambdaServer(Vertx vertx, Context context, InputStream input, OutputStream output);
@Override public boolean isMetricsEnabled();
@Override public HttpServ... | context.assertNull(server.requestStream());
}
} |
106416016_0 | class LoggerFactory {
public synchronized void useCommonsLogging() {
setImplementation(JakartaCommonsLoggingImpl.class);
}
public Logger getLog(Class<?> aClass);
public Logger getLog(String logger);
public synchronized void useCustomLogging(Class<? extends Logger> clazz);
public synchr... | LoggerFactory.useCommonsLogging();
Logger log = LoggerFactory.getLog(Object.class);
logSomething(log);
assertThat(log, instanceOf(JakartaCommonsLoggingImpl.class));
}
} |
106459683_1 | class CoffeeHouseApp implements Terminal {
static void applySystemProperties(final Map<String, String> opts) {
opts.forEach((key, value) -> {
if (key.startsWith("-D")) System.setProperty(key.substring(2), value);
});
}
public CoffeeHouseApp(final ActorSystem system);
publ... | System.setProperty("c", "");
Map<String, String> opts = new HashMap<>();
opts.put("a", "1");
opts.put("-Dc", "2");
CoffeeHouseApp.applySystemProperties(opts);
assertThat(System.getProperty("c")).isEqualTo("2");
}
} |
106559097_0 | class NowPlayingInteractor {
public Observable<Result> processAction(Observable<Action> actions) {
return actions.compose(transformActionIntoResults);
}
@SuppressWarnings("checkstyle:magicnumber") public NowPlayingInteractor(@NonNull ServiceController serviceControllerIn, @NonNull FilterTransform... | //
//Arrange
//
TestObserver<Result> testObserver;
NowPlayingInteractor nowPlayingInteractor = new NowPlayingInteractor(mockServiceController, filterTransformer);
List<MovieInfo> movieInfoList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
movieIn... |
106559436_73 | class LocationCollectionClient implements SharedPreferences.OnSharedPreferenceChangeListener {
static boolean uninstall() {
boolean uninstalled = false;
synchronized (lock) {
if (locationCollectionClient != null) {
locationCollectionClient.locationEngineController.onDestroy();
locationC... | assertThat(LocationCollectionClient.uninstall()).isFalse();
}
} |
106613119_506 | class DefaultAtlasModuleInfo implements AtlasModuleInfo, AtlasModuleInfoMXBean {
@Override
public String toString() {
return "DefaultAtlasModuleInfo [name=" + name + ", uri=" + uri + ", sourceSupported=" + sourceSupported
+ ", targetSupported=" + targetSupported + ", moduleClass=" + mod... | assertNotNull(module.toString());
}
} |
106668916_1 | class JazonList {
public List<JsonExpectationInput> list() {
return list;
}
public JazonList(Predicate<?>... predicates);
public JazonList(Object... objects);
public JazonList with(Object object);
public JazonList with(Predicate<T> predicate);
}
class JazonListTest {
@Test
... | // given
JazonList jazonList = new JazonList(null, null);
// when
List<JsonExpectationInput> list = jazonList.list();
// then
assertEquals(2, list.size());
assertEquals(new PredicateExpectationInput<>(null), list.get(0));
}
} |
106681970_1048 | class ContentSummary implements Writable {
@Override
public String toString() {
return toString(true);
}
@Deprecated public ContentSummary();
@Deprecated public ContentSummary(long length, long fileCount, long directoryCount);
@Deprecated public ContentSummary(
long length, long fileCount, lo... | long length = Long.MAX_VALUE;
long fileCount = 222222222;
long directoryCount = 33333;
long quota = 222256578;
long spaceConsumed = 1073741825;
long spaceQuota = 1;
ContentSummary contentSummary = new ContentSummary.Builder().length(length).
fileCount(fileCount).directoryCount(direc... |
106730885_1 | class Hooks {
public static void Before(Object... args) {
addHook(args, true, false);
}
public static void World(Closure body);
public static void After(Object... args);
public static void AfterStep(Object... args);
public static void BeforeStep(Object... args);
private static void... | try {
Hooks.Before("TAG", 10D, 100, new MethodClosure(this, "dummyClosureCall"), 0.0);
fail("CucumberException was not thrown");
} catch (CucumberException e) {
assertEquals("An argument of the type java.lang.Double found, Before only allows the argument types " +
... |
106811067_44 | class ProcessCreatedEventHandler implements QueryEventHandler {
@Override
public String getHandledEvent() {
return ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name();
}
public ProcessCreatedEventHandler(ProcessInstanceRepository processInstanceRepository);
@Override public void han... | //when
String handledEvent = handler.getHandledEvent();
//then
assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name());
}
} |
106813148_35 | class CompleteTaskCmdExecutor extends AbstractCommandExecutor<CompleteTaskPayload> {
public CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) {
this.taskAdminRuntime = taskAdminRuntime;
}
public CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime);
@Override public TaskResult ... | Map<String, Object> variables = new HashMap<>();
CompleteTaskPayload completeTaskPayload = new CompleteTaskPayload("taskId",
variables);
assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskPayload.c... |
106817657_51 | class FeelParser {
public static Either<ValidationResult.Builder.ElementStep, FeelExpression> parse(final CharSequence charSequence) {
try {
return Eithers.right(PARSER.parse(charSequence));
} catch (final ParserException e) {
return Eithers.left(ValidationResult.init.messag... | final FeelExpression expression = FeelParser.PARSER.parse("\"x.y.z=false\"");
final FeelExpression expectedExpression = FeelExpressions.StringLiteral("x.y.z=false");
assertEquals(expectedExpression, expression);
}
} |
106841635_350 | class Schema {
private Schema(Builder builder) {
this.fieldNames = builder.fields.stream().map(Field::name).collect(toList());
this.fields = ImmutableList.copyOf(builder.fields);
this.optionalFields = ImmutableSet.copyOf(builder.optionalFields);
this.constraints = ImmutableList.copy... | Exception e = assertThrows(InvalidSchemaException.class,
() -> schema(field("name", string()),
field("config", union("type"))
));
assertEquals("Discriminator attribute 'type' not present.", e.getMessage());
}
} |
106872676_7 | class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (O... | env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))... |
106921925_3 | class AuditConsumerChannelHandlerImpl implements AuditConsumerChannelHandler {
@SuppressWarnings("unchecked")
@Override
@StreamListener(AuditConsumerChannels.AUDIT_CONSUMER)
public void receiveCloudRuntimeEvent(@Headers Map<String, Object> headers, CloudRuntimeEvent<?, ?>... events) {
if (event... | //given
CloudRuntimeEvent cloudRuntimeEvent = mock(CloudRuntimeEventImpl.class);
when(cloudRuntimeEvent.getEventType()).thenReturn(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED);
EventToEntityConverter converter = mock(EventToEntityConverter.class);
when(converters.getConvert... |
106984925_0 | class LoginViewModel extends BaseViewModel {
public void login() {
if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) {
AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!");
return;
}
String auth = StringUtils.ge... | String pass = "abc";
User user = sampleUser(1L);
String token = StringUtils.getBasicAuth(user.getLogin(), pass);
when(githubService.login(any())).thenReturn(successResponse(user));
when(userManager.startUserSession(any(), any())).thenReturn(null);
viewModel.setUserName... |
107071531_0 | class ReflectionUtil {
public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) {
if (args.size() == 0 && method.getParameterCount() == 0) {
return Collections.emptyList();
}
List<String> argsOut = new ArrayList<>();
if (... | // Given a method with only one param, pick out that param without the others
List<String> inputStr = Arrays.asList("1", "nextMethod", "param", "param2");
Method testClass1234 = ReflTestClass.ReflSubClass.class.getMethod("get1234", int.class);
List<String> out = ReflectionUtil.getArgsFor... |
107095945_3 | class DownloadRunnable implements Runnable {
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
FileDownloadConnection connection = null;
final long beginOffset = connectTask.getProfile().currentOffset;
boolean isConnected = false;
... | final FileDownloadConnection connection = mock(FileDownloadConnection.class);
when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_PRECON_FAILED);
when(mockConnectTask.connect()).thenReturn(connection);
downloadRunnable.run();
// retry first.
verify(mock... |
107103226_93 | class Card extends StripeJsonModel implements StripePaymentSource {
@NonNull
@Override
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<>();
map.put(FIELD_NAME, name);
map.put(FIELD_ADDRESS_CITY, addressCity);
map.put(FIELD_ADDRESS_COUNTRY, addressC... | try {
JSONObject rawJsonObject = new JSONObject(JSON_CARD);
Map<String, Object> rawMap = StripeJsonUtils.jsonObjectToMap(rawJsonObject);
Card expectedCard = buildEquivalentJsonCard();
JsonTestUtils.assertMapEquals(rawMap, expectedCard.toMap());
} catch (JS... |
107150826_3 | class Address extends ByteArray {
public static Address from(byte[] address) {
return new Address(new ByteArray(address));
}
public Address(ByteArray byteArray);
public static Address from(String address);
@Override public String toString();
private static Address address;
private static String a... | String hexStr = "795c64c6eee9164539d679354f349779a04f57cb";
byte[] addressBytes = new BigInteger(
"111100101011100011001001100011011101110111010010001011001000101001110011101011001111001001101010100111100110100100101110111100110100000010011110101011111001011",
2).toByteArray();
Address addr... |
107165228_4 | class FileResolver {
static File resolveNextMigrationFile(File migrationDir) {
Optional<Path> lastFile = resolveExistingMigrations(migrationDir, true, false)
.stream()
.findFirst();
Long fileIndex = lastFile.map((Path input) -> FILENAME_PATTERN.matcher(input.getFileName().toString()))
.map(matcher ... | // given
File migrationsDir = tempFolder.newFolder();
migrationsDir.toPath().resolve("v1__jpa2ddl.sql").toFile().createNewFile();
migrationsDir.toPath().resolve("v2__my_description.sql").toFile().createNewFile();
// when
File file = FileResolver.resolveNextMigrationFile(migrationsDir);
// then
assertT... |
107220808_44 | class Paths {
public static Path of(String... segments) {
if (segments.length == 0) {
return ImmutablePath.EMPTY;
}
PathBuilder pathBuilder = new PathBuilder();
for (String segment : segments) {
pathBuilder.splitAndAdd(segment, false);
}
return ImmutablePath.create(pathBuilder);... | assertEquals(Paths.of("/"), Paths.of("\\"));
assertEquals(Paths.of("/path"), Paths.of("\\path"));
assertEquals(Paths.of("/path/"), Paths.of("\\path\\"));
}
} |
107254605_1 | class OpenIBANValidationClient extends RestGatewaySupport implements IBANValidationClient {
@Override
public IBANValidationResult validate(String iban) {
return getRestTemplate().getForObject(URL_TEMPLATE, IBANValidationResult.class, iban);
}
@Autowired
private OpenIBANValidationClient cl... |
mockRestServiceServer
.expect(requestTo("https://openiban.com/validate/NL28XXXX389242218?getBIC=true&validateBankCode=true"))
.andRespond(withSuccess(new ClassPathResource("NL28XXXX389242218-result.json"), MediaType.APPLICATION_JSON));
IBANValidationResult result = clie... |
107304223_8 | class Base62Encoder implements Encoder<ByteBuffer, String> {
@Override
public String encode(final ByteBuffer unencodedData) {
final int maxBytes = unencodedData.limit();
final StringBuilder sb = new StringBuilder();
int bitSource = nextByte(unencodedData);
int unencodedBits = b... | final ByteBuffer byteBuffer = ByteBuffer.allocate(1);
byteBuffer
.put((byte) 0xF0)
.flip();
assertThat(encoder.encode(byteBuffer), is("8A"));
}
} |
107325380_12 | class RestrictConflictMergeBehaviourImpl implements MergeBehaviour<SyncObject> {
@Override
public MergeResult<SyncObject> resolveDiff(Class<? extends SyncObject> clazz, SyncObject local, SyncObject foreign) {
return revolveConflict(local, foreign);
}
private MergeResult<SyncObject> revolveConflict(SyncObject so... | SyncObject localObj = getSyncObject(SimpleObjectMother.createInstance(VALID_UUID, TEST_VALUE));
SyncObject foreignObj = getSyncObject(SimpleObjectMother.createInstance(VALID_UUID, TEST_VALUE_2));
MergeResult actual = conflictMergeBehaviour.resolveDiff(SyncObject.class, localObj, foreignObj);
Assert.assertTrue(a... |
107375180_161 | class PropertyElementDescriptors {
public ElementDescriptor getDescriptor(Object pmo) {
ElementDescriptor descriptor = findDescriptor(pmo);
descriptor.addAspectDefinitions(additionalAspects);
return descriptor;
}
PropertyElementDescriptors(String pmoPropertyName);
public int... | PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.DUAL_PMO_PROPERTY);
Assertions.assertThrows(IllegalStateException.class, () -> {
descriptors.getDescriptor(new TestPmo());
});
}
} |
107386062_5 | class DefaultTypedConfigurationManager extends ConfigurationManagerWrapper implements TypedConfigurationManager {
@Override
public <T> TypedProperty<T> getProperty(String key, ValueParser<T> valueParser) {
return new DefaultTypedProperty<T>(getProperty(key), valueParser);
}
public DefaultType... | MyConfigurationManager myManager = new MyConfigurationManager();
DefaultTypedProperty<Long> p = (DefaultTypedProperty<Long>) myManager.getProperty("long", "iKey", "9999999a");
assertNull(null, p.typedValue());
p = (DefaultTypedProperty<Long>) myManager.getProperty("long", "iKey", null);
... |
107436391_5 | class SlingshotUtil {
public static String getUserId(final Resource resource) {
final String prefix = SlingshotConstants.APP_ROOT_PATH + "/";
String id = null;
if ( resource.getPath().startsWith(prefix) ) {
final int areaEnd = resource.getPath().indexOf('/', prefix.length());
... |
Resource resource = context.resourceResolver().getResource("/content/slingshot/users");
assertThat(SlingshotUtil.getUserId(resource), nullValue());
}
} |
107437722_133 | class CombinedProperties implements Map<String, Object> {
@Override
public final Object get(Object key) {
if (key == null) {
return null;
}
final ComputedPropertyParameter computedPropertyParameter = new ComputedPropertyParameter((String) key);
log.trace("Getting v... | final String expected = "Test Asset";
final String actual = (String) combinedProperties.get(TitleImpl.NAME);
assertEquals(expected, actual);
}
} |
107457897_1 | class StaggeredAnimationGroup extends Group {
@VisibleForTesting
final int[] filterNonZeroIds(int[] allIds) {
int nonZeroIdsCount = 0;
for (int id : allIds) {
if (id != 0) {
nonZeroIdsCount++;
}
}
if (nonZeroIdsCount == allIds.length) {
... | //given
StaggeredAnimationGroup spiedGroup = prepareSpiedGroup();
int[] testIds = new int[]{1, 2, 3, 4};
//when
int[] filtered = spiedGroup.filterNonZeroIds(testIds);
//then
assertThat(filtered).asList().containsExactly(1, 2, 3, 4).inOrder();
}
} |
107465031_0 | class Library {
public boolean someLibraryMethod() {
return true;
}
}
class LibraryTest {
@Test
public void testSomeLibraryMethod() {
| final Library classUnderTest = new Library();
assertThat(classUnderTest.someLibraryMethod()).isTrue();
}
} |
107473189_9 | class Reflection {
public static @Nullable Method getMethod(@Nullable Class<?> clazz, String methodName) {
if (clazz == null) {
return null;
}
try {
return clazz.getMethod(methodName);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
... | assertThat(Reflection.getMethod(String.class, "thereWillNeverBeMethodWithThisName"))
.isNull();
}
} |
107511723_92 | class HttpRequest {
public Optional<byte[]> getBody() {
if (bodyCache != null) {
return bodyCache;
}
synchronized (this) {
if (bodyCache != null) {
return bodyCache;
}
return bodyCache = doGetBody();
}
}
privat... | final AtomicInteger counter = new AtomicInteger();
final HttpRequest httpRequest =
new HttpRequest("foo", "GET", emptyList(), emptyMap(), null, emptyMap(), (a, b) -> {
assertEquals(0, counter.getAndIncrement());
return Optional.of(new byte[0]);
... |
107515570_1 | class WechatMessageHandler implements MessageHandler<WechatMessage> {
@Override
public WechatMessage handle(JsonObject result) {
// WechatMessage msg = new WechatMessage();
WechatMessage msg = gson.fromJson(result, WechatMessage.class);
msg.setRaw(result.toString());
return msg;... | String json = p.getProperty("m.init");
WechatMessage msg = (WechatMessage) handler.handle(json);
assertEquals(WechatMessage.MSGTYPE_STATUSNOTIFY, msg.MsgType);
System.out.println(msg.getText());
assertEquals("@b07a26ddbe1bc6a60c2d6f5cbe4c8581", msg.FromUserName);
... |
107554429_150 | class StreamConnection implements Closeable {
@Override
public int hashCode() {
return streamConnectionId.hashCode();
}
public StreamConnection(final InterledgerAddress receiverAddress, final SharedSecret sharedSecret);
public StreamConnection(final StreamConnectionId streamConnectionId);
public Un... | StreamConnection identicalStreamConnection = new StreamConnection(StreamConnectionId.of("foo"));
assertThat(streamConnection.hashCode()).isEqualTo(identicalStreamConnection.hashCode());
StreamConnection nonIdenticalStreamConnection = new StreamConnection(StreamConnectionId.of("foo1"));
assertThat(strea... |
107559907_4 | class Interval {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Interval other = (Interval) obj;
if (endDate == null) {
... | // given
Interval interval1 = new Interval(LocalDate.of(2017, 1, 14), LocalTime.of(10, 00), LocalDate.of(2017, 1, 15), LocalTime.of(23, 00));
Interval interval2 = new Interval(LocalDate.of(2017, 1, 14), LocalTime.of(10, 00), LocalDate.of(2017, 1, 15), LocalTime.of(23, 00));
// when
... |
107591789_1 | class JsonParser {
public static <T> T deserialize(String json, Class<T> type) {
try {
return new ObjectMapper().readValue(json,type);
}
catch (Exception ex) {
log.error(ex.getMessage(),ex);
}
return null;
}
public static String serialize(Obj... | String jsonRole = getJsonRole(getDefaultRole());
Role expectedRole = getDefaultRole();
Role role = JsonParser.deserialize(jsonRole,Role.class);
assertTrue(role.getId().equals(expectedRole.getId()));
assertTrue(role.getName().equals(expectedRole.getName()));
}
} |
107655600_15 | class MultipartUtils {
public static List<MultiPartSpecification> convertToMultipart(List<Map<String, String>> parts) {
return parts.stream()
.map(part -> {
final MultiPartSpecification specification;
final String name = part.get(TestCaseUtils.JSON_FIELD_MULTIPA... | final List<Map<String, String>> parts = ImmutableList.of(
ImmutableMap.of(
TestCaseUtils.JSON_FIELD_MULTIPART_NAME, "simpleField",
TestCaseUtils.JSON_FIELD_MULTIPART_VALUE, "simpleValue"
)
);
final List<MultiPartSpecification> spec = Multi... |
107676801_25 | class SecretSourceResolver {
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
}
public SecretSourceResolver(ConfigurationContext configurationContext)... | environment.set("base64", "foo");
environment.set("file", "foo");
assertThat(resolve("${base64}"), equalTo("foo"));
assertThat(resolve("${file}"), equalTo("foo"));
}
} |
107785408_7 | class RuntimeSampler {
public static ObjectMapper objectMapper() {
return new ObjectMapper()
// Property visibility
.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS)
.setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoD... | String expectedJson = "{\"aBoolean\":false,\"booleanWrapper\":false,\"bytePrimitive\":0,\"byteWrapper\":0,\"charPrimitive\":\"\\u0000\",\"charWrapper\":\"\\u0000\",\"doublePrimitive\":0.0,\"doubleWrapper\":0.0,\"floatPrimitive\":0.0,\"floatWrapper\":0.0,\"intPrimitive\":0,\"intWrapper\":0,\"longPrimitive\":0,\"... |
107839447_17 | class Matrix implements Serializable {
public Matrix plusTo(@NonNull Matrix matrix) {
checkNotNull(matrix);
return Matrix.plusTo(this, matrix);
}
private Matrix(double[] array, int row, int col);
public int[] shape();
public double[] getArray();
public double[][] getArrays(... | final Matrix a = Matrix.array(new double[]{
1, 2, 3, 4, 5, 6
}, 3);
final Matrix b = Matrix.array(new double[]{
6, 5, 4, 3, 2, 1
}, 3);
final Matrix c = a.plusTo(b);
assertSame(c, a);
assertArrayEquals(a.getArray(), new double[]{... |
107873649_2 | class ConfigManager {
List<FillOption> getOptions() {
final List<FillOption> savedOptions = readConfigsFromStore();
final List<FillOption> result = new ArrayList<>(fillConfig.getOptions().size() + savedOptions.size());
result.addAll(savedOptions);
result.addAll(fillConfig.getOptions... | when(store.read(eq(ConfigManager.ORDER))).thenReturn(Arrays.asList("n1", "n2"));
when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Collections.singletonList("v1"));
when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Arrays.asList("v1", "v2", "v3"));
assertEq... |
107914762_0 | class StripPrefixFilter extends HttpInboundSyncFilter {
@Override
public boolean shouldFilter(HttpRequestMessage msg) {
for (String target: prefixPatterns) {
if (msg.getPath().matches(target)) {
return true;
}
}
return false;
}
public St... | StripPrefixFilter filter = new StripPrefixFilter(Arrays.asList("/path1/.*"));
assertThat(filter.shouldFilter(sampleHttpMessage("/path1/testRemaining?query1=val1"))).isTrue();
assertThat(filter.shouldFilter(sampleHttpMessage("/path2/testRemaining?query1=val1"))).isFalse();
}
} |
107930307_0 | class SagaInstanceFactory {
public <SagaData> SagaInstance create(Saga<SagaData> saga, SagaData data) {
SagaManager<SagaData> sagaManager = (SagaManager<SagaData>)sagaManagers.get(saga);
if (sagaManager == null)
throw new RuntimeException(("No SagaManager for " + saga));
return sagaManager.create(... |
when(sagaManager.create(sagaData1)).thenReturn(expectedSi1);
when(sagaManager.create(sagaData2)).thenReturn(expectedSi2);
SagaInstance si1 = sagaInstanceFactory.create(saga, sagaData1);
assertEquals(expectedSi1, si1);
verify(sagaManagerFactory, times(1)).make(saga);
SagaInstance si2 = sagaIns... |
108043571_0 | class ExtensibleFirefoxDriver extends FirefoxDriver {
public void uninstallAddon(AddonUninstallRequest request) throws IOException {
addonSupport.uninstallAddon(request);
}
public ExtensibleFirefoxDriver(GeckoDriverService service, FirefoxOptions options);
public void installAddon(AddonInsta... | File sampleExtensionZipFile = buildSampleExtension();
AddonInstallRequest installRequest = AddonInstallRequest.fromFile(sampleExtensionZipFile, AddonPersistence.TEMPORARY);
BehaviorVerifier<Void> verifier = (driver, baseUri) -> {
AddonUninstallRequest uninstallRequest = AddonUninstal... |
108180205_0 | class SPAlgorithms {
public static List<Path> kShortestPaths(Graph g, Node origin, Node destination, Integer K) throws Exception{
List<Path> A = new LinkedList<Path>();
PriorityQueue<Path> B = new PriorityQueue<Path>();
A.add(SPAlgorithms.dijkstra(g, origin,destination));
if (A.get(0) == null) throw new Excep... |
List<Path> shortPath = null;
try {
shortPath = SPAlgorithms.kShortestPaths(graph, A, D,3);
} catch (Exception e) {
// TODO Auto-generated catch block
fail(e);
}
Path abd = new Path(); abd.add(AB); abd.add(BD);
Path acd = new Path(); acd.add(AC); acd.add(CD);
Path abcd = new Path(); abcd.add(AB... |
108181481_18 | class Gateway {
public static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback) {
if (callback == null) {
return false;
}
if (requestCode == REQUEST_3D_SECURE) {
if (resultCode == Activity.RESULT_OK) {
... | assertFalse(Gateway.handle3DSecureResult(0, 0, null, null));
}
} |
108511089_7 | class MudrodEngine {
public void startLogIngest() {
DiscoveryEngineAbstract wd = new WeblogDiscoveryEngine(props, es, spark);
wd.preprocess();
wd.process();
LOG.info("Logs have been ingested successfully");
}
public MudrodEngine();
public ESDriver startESDriver();
public SparkDriver startS... | fail("Not yet implemented"); // TODO
}
} |
108538904_1 | class SimilarityParser extends QParser {
public Query parse() throws SyntaxError {
//
// parse query string into terms -> use analyzer pipeline
//
final IndexSchema schema = req.getSchema();
String defaultField = QueryParsing.getDefaultField(schema, getParam(CommonParams.D... |
// arrange
QParser parser = new SimilarityParser("first second",new ModifiableSolrParams(),mockCorrectParams,req("first second"));
// act
Query luceneQuery = parser.parse();
// assert
Assert.assertEquals(BooleanQuery.class, luceneQuery.getClass());
BooleanQuery... |
108542665_125 | class AbstractValueSpecifier implements ValueSpecifier<B> {
@Override
public final B value(String value) {
setValue(value);
return builder;
}
protected AbstractValueSpecifier(B builder, Attribute.Name name);
@Override public final B value(Integer value);
@Override public fina... | ValueBuilder valueBuilder = new ValueBuilder();
String name = "attr-name";
ValueBuilder builder = valueBuilder.withAttribute(Attribute.Name.valueOf(name)).value(Instant.EPOCH);
assertNotNull(builder);
}
} |
108706261_0 | class LogoEnvPLS extends AbstractLocalStateOfEnvironment implements Cloneable {
@Override
public Object clone() {
Set<TurtlePLSInLogo>[][] turtleSet = new Set[this.width][this.height];
Set<Mark>[][] markSet = new Set[this.width][this.height];
for(int x = 0; x < this.width; x++) {
for(int y = 0; y < this.... | LogoEnvPLS e2 = (LogoEnvPLS) e1.clone();
assertEquals(e1, e2);
assertNotSame(e1,e2);
assertEquals(e1.getClass(),e2.getClass());
}
} |
108730056_24 | class Slf4JOutput implements Output {
@Override
public void write(final LogContext log) {
final LogLevel level = log.level();
final Throwable throwable = log.throwable();
final ArrayList<Throwable> suppressedThrowables = log.suppressedThrowables();
if (throwable != null && supp... | final Exception exception = new Exception();
when(logger.isWarnEnabled()).thenReturn(true);
when(ctx.level()).thenReturn(LogLevel.WARN);
when(ctx.throwable()).thenReturn(exception);
output.write(ctx);
Mockito.verify(logger).warn(anyString(), eq(exception));
}
} |
108986590_1 | class Loader {
public abstract void load() throws Exceptionpublic abstract void load() throws Exception;
public abstract void load() throws Exception Loader(final String databaseName, final SparkSession spark, final DatabaseStatistics statistics);
public abstract void load() throws Exception String getValidHiveName... | final Settings settings = new Settings.Builder("testingDB").build();
final DatabaseStatistics statistics = new DatabaseStatistics("testingDB");
final VerticalPartitioningLoader vp_loader = new VerticalPartitioningLoader(settings, spark, statistics);
vp_loader.load();
final Dataset<Row> tables_list = spark.sql... |
108987781_0 | class FileService {
@Transactional
public List listAllFiles(){
return fileDao.listAllFiles();
}
@Autowired public void setFileDao(FileDao fileDao);
public boolean insert(File file);
@Transactional public boolean deleteFile(int id);
@Autowired
private FileService fileService;
... | List files = fileService.listAllFiles();
File file = (File)files.get(0);
assertEquals(files.isEmpty(), false);
}
} |
109141516_0 | class Telemetry {
public synchronized static Telemetry getInstance() {
// If sTelemetryInstance is not initialized, telemetry will be disabled.
if (sTelemetryInstance == null) {
new Builder().build();
}
return sTelemetryInstance;
}
private Telemetry(final Buil... | Telemetry telemetry = Telemetry.getInstance();
Assert.assertNotNull(telemetry);
}
} |
109154869_141 | class SetDataType extends CollectionDataType {
@Override
public boolean is_abstract() {
return false;
}
public SetDataType(DataType inner_type, AnyType any);
public static final String build_set_name(DataType inner);
public static SetDataType set_of(DataType inner, PrimitiveScope pscope);
@Override public ... | assertEquals("set<b>", m_set_type.name());
assertTrue(m_set_type.sub_of(m_scope.any()));
assertFalse(m_set_type.is_abstract());
assertEquals(m_type, m_set_type.inner_type());
}
} |
109219866_0 | class Services {
public static Services getDefault() {
return INSTANCE;
}
public Services(Require require, Global global, Worker worker);
public void postInit(Algorithms newAlgorithms);
public BigInteger factorial(int value);
end end;
}
class ServicesTest {
end end;
@T... | String n = Services.getDefault().algorithms.ruby(3);
assertEquals("Factorial of 3", "6", n);
}
} |
109246147_11 | class ValidateUtils {
@NonNull
static List<String> validatePromptParams(@NonNull Mode mode, @NonNull Goldfinger.PromptParams params) {
List<String> errors = new ArrayList<>();
if (!(params.dialogOwner() instanceof Fragment) && !(params.dialogOwner() instanceof FragmentActivity)) {
... | Goldfinger.PromptParams params = new Goldfinger.PromptParams.Builder(activity)
.title(TITLE)
.deviceCredentialsAllowed(true)
.build();
assertTrue(ValidateUtils.validatePromptParams(Mode.AUTHENTICATION, params).isEmpty());
}
} |
109294216_4 | class PhotoRepository implements PhotoDataSource {
@Override
public void savePhoto(@NonNull Photo photo) {
photoLocalDataSource.savePhoto(photo);
cachedPhotos.put(photo.getPhotoId(), photo);
}
public PhotoRepository(@NonNull PhotoDataSource photoRemoteDataSource,
... | final Photo photo = new Photo(1, 10, "a");
repository.savePhoto(photo);
verify(remoteDataSource, never()).savePhoto(photo);
verify(localDataSource, times(1)).savePhoto(photo);
assertThat(repository.cachedPhotos.size(), is(1));
}
} |
109329697_14 | class ZawgyiDetector {
public double getZawgyiProbability(String input, boolean verbose) {
return model.predict(input, verbose);
}
public ZawgyiDetector();
ZawgyiDetector(InputStream inStream);
public double getZawgyiProbability(String input);
private static ZawgyiDetector detector;
}
class Zaw... | // Digits/numerals are ignored and treated like non-Myanmar code points.
assertThat(detector.getZawgyiProbability("၉၆.၀ kHz")).isNegativeInfinity();
assertThat(detector.getZawgyiProbability("၂၄၀၉ ဒဂုန်"))
.isEqualTo(detector.getZawgyiProbability("ဒဂုန်"));
}
} |
109339072_9 | class Operand {
public Operand(OperandType type, int value) {
this.type = type;
this.value = value;
}
public Operand(OperandType type, int value);
public Operand(OperandType type, int value, int data);
public Operand(String text, RegisterSet registerSet, int line);
public O... |
RegisterSet registerSet = new DefaultRegisterSet();
HashMap<String, Character> labels = new HashMap<>(10);
labels.put("label1", (char) 10);
labels.put("label2", (char) 20);
labels.put("label3", (char) 30);
labels.put("label4", (char) 40);
//Valid operands
... |
109361137_91 | class WXImage extends WXComponent<ImageView> {
@WXComponentProp(name = Constants.Name.RESIZE)
public void setResize(String resize) {
(getHostView()).setScaleType(getResizeMode(resize));
}
@Deprecated public WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean i... | ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class));
mWXImage.mHost = imageView;
mWXImage.setResize("cover");
ImageView.ScaleType scaleType = mWXImage.getHostView().getScaleType();
assertEquals(scaleType, ImageView.ScaleType.CENTER_CROP);
}
} |
109377658_13 | class TypeUtils {
public static double string2Double(String str, double defaultValue) {
try {
if (!StringUtils.isBlank(str)) {
return Double.parseDouble(str);
}
} catch (NumberFormatException ex) {
if (logger.isWarnEnabled()) {
log... | assertEquals(0, TypeUtils.string2Double(null, 0), 5);
assertEquals(0, TypeUtils.string2Double("", 0), 5);
assertEquals(0, TypeUtils.string2Double("0", 0), 5);
assertEquals(0.1, TypeUtils.string2Double("0.1", 0), 5);
assertEquals(1.1234, TypeUtils.string2Double("1.1234", 0), 5);
... |
109394368_32 | class User {
public void setUserId(int userId) {
this.userId = userId;
}
public User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Loca... | user2.setUserId(12121);
assertEquals(12121, user2.getUserId());
}
} |
109401796_2 | class FeatureServiceImpl {
private FeatureExtension[] mergeExtensions(Feature f1, Feature f2, MergeContext ctx) {
Map<String,FeatureExtension> extensions = new HashMap<>(f1.getExtensions());
Map<String,FeatureExtension> addExtensions = new HashMap<>();
for (Map.Entry<String,FeatureExtensio... | BuilderFactory bf = Features.getBuilderFactory();
URL res1 = getClass().getResource("/features/test-exfeat1.json");
Feature f1;
try (Reader r = new InputStreamReader(res1.openStream())) {
f1 = Features.readFeature(r);
}
URL res2 = getClass().getResource("/fe... |
109413088_0 | class ReflectionHelper {
static <T> T instantiate(Class<T> type, Object... args) {
try {
if (args.length == 0) {
//return type.newInstance(); //deprecated
return type.getDeclaredConstructor().newInstance();
} else {
Class<?>[] classes ... | TestClass testClass = ReflectionHelper.instantiate(TestClass.class);
Assert.assertEquals(0, testClass.getA());
Assert.assertEquals("", testClass.getS());
Assert.assertEquals(1, ReflectionHelper.instantiate(TestClass.class, 1).getA());
Assert.assertEquals("A", ReflectionHelper.in... |
109754092_3 | class AuditLogDirectParser implements AuditCommandParser {
@Override
public AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException {
Matcher m = MESSAGE_ONLY_PATTERN.matcher(inputLine.toString());
if (!m.find()) {
throw new IOException("Unable to find val... | Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser", "listStatus", "sourcePath", "null");
AuditReplayCommand expected =
new AuditReplayCommand(1000, "fakeUser", "listStatus", "sourcePath", "null", "0.0.0.0");
assertEquals(expected, parser.parse(in, IDENTITY_FN));
}
} |
109754107_0 | class ParallelProcessor implements AutoCloseable, BatchIterator<R> {
@Override
public long skip(long count) {
long skipped = 0;
while (skipped < count) {
try {
if (!ensureBuffer()) {
return skipped; // end of results
}
} catch (InterruptedException e) {
Thread.... | DummyProcessor dp = new DummyProcessor(false);
for (int i = 0; i < 10000; i += 5) {
Integer res = dp.nextInterruptable();
assertEquals(i, (int) res);
dp.skip(4);
}
}
} |
109774858_2 | class LRUCache {
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
head = new Node(-1, -1);
tail = new Node(-1, -1);
head.next = tail;
tail.prev = head;
}
public LRUCache(int capacity);
public Integer lookup(Integer key);
private void pushToHead(Node ... | final int capacity = 8;
final Map<Integer, Integer> map = new HashMap<>();
final List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
final LRUCache cache = new LRUCache(capacity);
list.forEach(i -> {
cache.insert(i, i);
});
//FIRST TWO HAVE BEEN REPLACED
assertNull(... |
109902579_117 | class ServiceHost implements ServiceRequestSender {
public ServiceHost setPublicUri(URI publicUri) {
this.state.publicUri = publicUri;
clearUriAndLogPrefix();
return this;
}
protected ServiceHost();
public static ServiceHost create(String... args);
public ServiceHost init... | setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
thr... |
109917787_31 | class TopicClusterSubCommand implements SubCommand {
@Override
public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toS... | TopicClusterSubCommand cmd = new TopicClusterSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, c... |
109999895_30 | class Guard implements Internal<Guard<S, T>, T> {
public static <T> Guard<Chain<T>, T> call(@NonNull Callable<T> callable) {
return new Guard<>(new Chain<T>(null, InternalConfiguration.getInstance(null)).access(),
callable);
}
private Guard(Proxy<S, T> proxy, Exception error);
... |
final TestClass[] result = {new TestClass()};
Guard.call(new Callable<TestClass>()
{
@Override
public TestClass call() throws Exception {
result[0].text = "!";
return result[0];
}
});
assertEquals("!", result[0... |
110054572_6 | class Root {
public State getState() {
return state;
}
public Root(State state);
@Override public String toString();
@Override public boolean equals(Object o);
@Override public int hashCode();
@Rule public MockitoRule rule;
@Mock RxCmdShell.Builder shellBuilder;
@Mock Rx... | when(shell.open()).thenReturn(Single.just(shellSession));
when(shellSession.submit(any(Cmd.class))).thenAnswer(invocation -> Single.just(new Cmd.Result(invocation.getArgument(0), Cmd.ExitCode.TIMEOUT, new ArrayList<>(), new ArrayList<>())));
Root.Builder builder = new Root.Builder().timeout(100... |
110117973_41 | class ParallelQueryBuilder implements Serializable {
protected static List<String> queriesForBounds(
long min, long max, int parallelism, String splitColumn, QueryBuilder queryBuilder) {
List<QueryRange> ranges = generateRanges(min, max, parallelism);
return ranges.stream()
.map(
... | final List<String> actual = ParallelQueryBuilder.queriesForBounds(1, 2, 2, "sp", QUERY_FORMAT);
assertThat(
actual,
Matchers.is(
Lists.newArrayList(
format("%s AND sp >= %s AND sp < %s", QUERY_BASE, 1, 2),
format("%s AND sp >= %s AND sp <= %s", QUERY_... |
110121462_2 | class PathUtils {
public static void removeRecursive(final Path path) throws IOException {
Files.walkFileTree(
path,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
throws IOException {
... | final Path root = Files.createDirectory(fs.getPath("/", "root"));
final Path unrelated = Files.write(root.resolve("unrelated"), new byte[] {0x0f});
final Path dir = Files.createDirectory(root.resolve("dir"));
Files.write(dir.resolve("a"), new byte[] {0x00});
Files.write(dir.resolve("b"), new byte[]... |
110164590_0 | class AuthUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repository.findOne(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
... |
final User user = new User();
when(repository.findOne(any())).thenReturn(user);
UserDetails loaded = service.loadUserByUsername("Username");
assertEquals(user, loaded);
}
} |
110344150_1 | class SelectIndexDataActivity extends BaseActivity {
public static int randomizedSelect(int[] a, int p, int r, int i) {
if (p == r) {
return a[p];//这种情况就是数组内只有一个元素
}
// 查找p r中间点 q
int q = randomizedPartition(a, p, r);
// 这里都是基于游标的,因为k是第几个,所以要加 1
int k = q... |
int a[]={2,5,3,0,2,3,0,3};
int result= selectIndexDataActivity.randomizedSelect(a,0,a.length-1,3);//产生第三小的数
System.out.println("快速选择算法求出的,第"+3+"个最小数是:"+result);
assertEquals(2,result);
}
} |
110449600_0 | class AddAnimalPresenter extends BasePresenter<AddAnimalContract.View> implements AddAnimalContract.Presenter<AddAnimalContract.View> {
@Override
public void addNewDog(DogFirebase dogFirebase) {
firebaseRepository.addNew(dogFirebase);
}
public AddAnimalPresenter(Repository.Firebase<DogFireba... | InMemoryDogRepository repository = InMemoryDogRepository.getInstance();
AddAnimalPresenter presenter = new AddAnimalPresenter(repository);
presenter.attachView(mockView);
presenter.addNewDog(new DogFirebase());
assertThat(repository.getCachedDogs().size(), is(1));
}
} |
110454850_13 | class EditMessageMedia extends SendableInputFileInlineRequest<Message> {
public static EditMessageMediaBuilder forMessage(AudioMessage message) {
Objects.requireNonNull(message, "audio message cannot be null");
return builder()
.chatId(message.getChat().getChatId())
... | EditMessageMedia expected = EditMessageMedia.forMessage(videoMessageMock).build();
EditMessageMedia actual = videoMessageMock.toEditMediaRequest().build();
assertEquals(expected, actual);
}
} |
110526820_8 | class ReferenceIdOverrider implements ReferenceOverrider {
@Override
public void override(UserTask userTask) {
String oldFormKey = userTask.getFormKey();
String newFormKey = modelIdentifiers.get(oldFormKey);
if (newFormKey != null) {
userTask.setFormKey(newFormKey);
... | UserTask userTask = new UserTask();
userTask.setFormKey("oldFormKey");
referenceIdOverrider.override(userTask);
assertThat(userTask.getFormKey()).isEqualTo("newFormKey");
}
} |
110547066_3 | class RemoveUnusedDefinitions implements Consumer<Swagger> {
@Override
public void accept(Swagger swagger) {
int initial = swagger.getDefinitions().size();
Pruner pruner = new Pruner(buildHierarchy(swagger));
while(pruner.hasPruneable()) {
Stream<String> prune = pruner.prune... | int initial = swagger.getDefinitions().size();
Map<String, Path> paths = swagger.getPaths().entrySet().stream()
.filter(p -> !p.getKey().startsWith("/c")).collect(toMap());
swagger.setPaths(paths);
new RemoveUnusedDefinitions().accept(swagger);
assertEquals(init... |
110686293_62 | class LocationUtil {
public static List<Location> getLocationsBetween(List<Location> locationList, long minimumTimestamp, long maximumTimestamp) {
List<Location> matchingLocations = new ArrayList<>();
for (Location location : locationList) {
if (location.getTimestamp() < minimumTimestam... | final Location firstLocation = LocationTest.SOCCER_FIELD_TOP_LEFT;
final Location secondLocation = LocationTest.SOCCER_FIELD_TOP_RIGHT;
final Location thirdLocation = LocationTest.SOCCER_FIELD_BOTTOM_LEFT;
firstLocation.setTimestamp(0);
secondLocation.setTimestamp(1);
thi... |
110719900_2 | class CommonUtils {
public static boolean isEmailValid(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = ... | assertFalse(CommonUtils.isEmailValid(NO_AT_THE_RATE));
}
} |
110837893_0 | class FileTaskAccessor implements TaskAccessor {
@Override
public List<Task> loadTasks() {
List<Task> tasks = new ArrayList<>();
// 1. 获取task配置文件
File[] taskFiles = FileAccessSupport.getTaskFiles(DEFAULT_TASK_PATH);
// 2. 解析task配置文件
for (File taskFile : taskFiles) {
... | List<Task> tasks = fileTaskLoader.loadTasks();
Assert.assertEquals(1, tasks.size());
}
} |
110988186_211 | class KleinbergSmallWorldGraphGenerator implements GraphGenerator<V, E, V> {
@Override
public void generateGraph(
Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap)
{
/*
* Special cases
*/
if (n == 0) {
return;
} else ... | final long seed = 5;
GraphGenerator<Integer, DefaultEdge, Integer> gen =
new KleinbergSmallWorldGraphGenerator<>(5, 2, 3, 2, seed);
Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class);
gen.generateGraph(g, new IntegerVertexFactory(), null);
... |
110995785_4 | class ValueSets extends AbstractValueSets<ValueSet, ValueSets> {
public static ValueSets getEmpty(SparkSession spark) {
Dataset<ValueSet> emptyValueSets = spark.emptyDataset(VALUE_SET_ENCODER)
.withColumn("timestamp", lit(null).cast("timestamp"))
.as(VALUE_SET_ENCODER);
return new ValueSets... |
ValueSets valueSets = ValueSets.getEmpty(spark)
.withValueSetsFromDirectory("src/test/resources/json/valuesets");
ValueSet marriedValueSet = valueSets.getValueSet(
"urn:cerner:bunsen:valueset:married_maritalstatus",
"0.0.1");
Assert.assertNotNull(marriedValueSet);
Assert.asser... |
111026852_397 | class ResponseConverter implements Function<Sc2Api.Response, Response> {
@Override
public Response apply(Sc2Api.Response sc2ApiResponse) {
require("sc2api response", sc2ApiResponse);
if (sc2ApiResponse.getErrorCount() > 0) {
return ResponseError.from(sc2ApiResponse);
}
... | assertThat(new ResponseConverter().apply(sc2ApiResponseWithReplayInfo()))
.as("creates ResponseReplayInfo instance from sc2api response")
.isInstanceOf(ResponseReplayInfo.class);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.