id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
76209402_8 | class Timestamp implements Comparable<Timestamp>, Cloneable {
public long toLong()
{
long longRepresentation = this.wallTime;
longRepresentation = longRepresentation << 16;
//longRepresentation = (longRepresentation & 0xFFFFFFFFFFFF0000L);
longRepresentation = (longRepresentatio... | Timestamp t = new Timestamp();
long tLong = t.toLong();
Timestamp t2 = t.add(1, (short)0);
long t2Long = t2.toLong();
Timestamp t3 = t.add(0, (short)1);
long t3Long = t3.toLong();
//make sure the order holds in 64-bit notation
assertTrue(tLong < t2Long);
... |
76267363_172 | class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
if (executor instanceof InitializingBean) {
InitializingBean bean = (InitializingBean) executor;
bean.after... | Throwable caught = catchThrowable(() -> {
executor.afterPropertiesSet();
verify(task, never()).afterPropertiesSet();
});
assertThat(caught).isNull();
}
} |
76278501_46 | class RewardUtils {
public static Pair<Integer, String> shippingSummary(final @NonNull Reward reward) {
final String shippingType = reward.shippingType();
if (!RewardUtils.isShippable(reward) || shippingType == null) {
return null;
}
switch (shippingType) {
case Reward.SHIPPING_TYPE_ANY... | final Reward rewardWithNullShipping = RewardFactory.reward()
.toBuilder()
.shippingType(null)
.build();
assertNull(RewardUtils.shippingSummary(rewardWithNullShipping));
final Reward rewardWithNoShipping = RewardFactory.reward();
assertNull(RewardUtils.shippingSummary(rewardWithNoShipp... |
76279202_0 | class Serialization {
public static byte[] readDEROctetString(byte[] input)
throws SerializationException {
return readDEROctetString(new ByteArrayInputStream(input));
}
private Serialization();
public static byte[] readDEROctetString(InputStream input);
public static byte[][... | byte[] in, expected;
in = new byte[] {
0x04, // TAG
0x06, // length
0x01, 0x02, 0x03, 0x04, 0x05, 0x05 // data
};
expected = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x05 };
assertEqualByteArrays(expected, Serialization.readDEROctetString(in... |
76284858_0 | class AnnotationProcessor extends AbstractProcessor {
@Override
public synchronized void init(final ProcessingEnvironment processingEnv) {
super.init(processingEnv);
versionCode = processingEnv.getOptions().get(OPTION_VERSION_CODE);
versionName = processingEnv.getOptions().get(OPTION_V... | annotationProcessor.init(processingEnvironment);
verify(processingEnvironment).getMessager();
}
} |
76307760_18 | class AnagramDictionary {
@VisibleForTesting
static boolean isAnagram(String first, String second) {
//
// Your code here
//
return true;
}
public AnagramDictionary(InputStream wordListStream);
public boolean isGoodWord(String word, String base);
public ArrayL... | assertTrue(AnagramDictionary.isAnagram("a", "a"));
}
} |
76332085_0 | class GtidSourceOffset implements SourceOffset {
public static GtidSourceOffset parse(String offset) {
// offset can be either json object or simple gtid-set
if (offset.trim().startsWith("{")) {
try {
return mapper.readValue(offset, GtidSourceOffset.class);
} catch (IOException e) {
... | assertThat(new GtidSourceOffset(gtidSet1), is(GtidSourceOffset.parse(gtidSet1)));
}
} |
76341709_2 | class LibConvertNumberUtils {
public final static long convert2Long(Object value, long defaultValue) {
if (value == null || "".equals(value.toString().trim())) {
return defaultValue;
}
try {
return Long.valueOf(value.toString());
} catch (Exception e) {
... | System.out.println("START: convert2Long");
Assert.assertEquals(6l,LibConvertNumberUtils.convert2Long(i,0l));
Assert.assertEquals(8l,LibConvertNumberUtils.convert2Long(l,0l));
Assert.assertEquals(3l,LibConvertNumberUtils.convert2Long(f,0l));
Assert.assertEquals(9l,LibConvertNumbe... |
76346666_34 | class DocumentRelationBuilderByKey implements DocumentRelationBuilder {
@Override
public Relationship buildRelation(Node parent, Node child, DocumentRelationContext context) {
String documentKey = context.getDocumentKey();
if(StringUtils.isBlank(documentKey))
{
return null;
}
RelationshipType relatio... | context.setDocumentKey("key");
Node parent = db.createNode();
parent.setProperty("type", "album");
Node child = db.createNode();
child.setProperty("type", "artist");
Relationship rel = this.docrel.buildRelation(parent, child, context);
Assert.assertEquals(parent.getId(), rel.getStartNode().getId... |
76375829_76 | class Servo implements AutoCloseable {
public void setAngleRange(double minAngle, double maxAngle) throws IOException {
if (minAngle >= maxAngle) {
throw new IllegalArgumentException("minAngle must be less than maxAngle");
}
mMinAngle = minAngle;
mMaxAngle = maxAngle;
... | Servo servo = new Servo(mPwm);
final double minAngle = -100, maxAngle = 100;
servo.setAngleRange(minAngle, maxAngle);
assertEquals(minAngle, servo.getMinimumAngle(), EPSILON);
assertEquals(maxAngle, servo.getMaximumAngle(), EPSILON);
}
} |
76405311_76 | class MatchBody extends BaseMatchRule {
@Override
public boolean test(RecordedHttpRequest incomingRequest, RecordedHttpRequest expectedRequest) {
String charSet1 = incomingRequest.getCharset();
String charSet2 = expectedRequest.getCharset();
RecordedHttpBody incomingBody = incomingRequest.getHttpBody()... | RecordedStringHttpBody stringHttpBody1 = new RecordedStringHttpBody("abc");
RecordedStringHttpBody stringHttpBody2 = new RecordedStringHttpBody("abcd");
RecordedHttpRequest recordedHttpRequest1 = new RecordedHttpRequest(null, null, null, stringHttpBody1);
RecordedHttpRequest recordedHttpRequest2 = new R... |
76431952_1 | class WindowIfChanged {
public static <T, K> Observable<GroupedObservable<K, T>> create(Observable<T> upstream,
Function<? super T, ? extends K> keySelector) {
return new WindowIfChangedObservable<>(upstream, keySelector);
}
private WindowIfChanged();
private final Function<Message, String> userSe... | Observable<Message> messages = Observable.just(new Message("Bob", "Hello"));
final AtomicInteger seen = new AtomicInteger();
WindowIfChanged.create(messages, userSelector)
.switchMap(
new Function<GroupedObservable<String, Message>, Observable<Notification<String>>>() {
@Ov... |
76436183_1 | class LindenSchemaBuilder {
public static LindenSchema build(File schemaFile) throws Exception {
Preconditions.checkNotNull(schemaFile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(schemaFile);
dom.getD... | String schemaPath = TestLindenSchemaBuilder.class.getResource("/test_builder_schema.xml").getPath();
LindenSchema schema = LindenSchemaBuilder.build(new File(schemaPath));
Assert.assertEquals("aid", schema.getId());
Assert.assertEquals(9, schema.getFieldsSize());
Assert.assertTrue(schema.getFields(... |
76474200_71 | class TablePathUtils {
public static Option<Path> getTablePath(FileSystem fs, Path path) throws HoodieException, IOException {
LOG.info("Getting table path from path : " + path);
FileStatus fileStatus = fs.getFileStatus(path);
Path directory = fileStatus.isFile() ? fileStatus.getPath().getParent() : fil... | Path metadataFolder = new Path(tablePath, HoodieTableMetaClient.METAFOLDER_NAME);
Option<Path> inferredTablePath = TablePathUtils.getTablePath(fs, metadataFolder);
assertEquals(tablePath, inferredTablePath.get());
}
} |
76488267_34 | class Filters {
public static List<Track> mergeTracks(final List<Track> tracks) {
final List<TrackSegment> segments = tracks.stream()
.flatMap(Track::segments)
.collect(toUnmodifiableList());
return tracks.isEmpty()
? List.of()
: List.of(
tracks.get(0).toBuilder()
.segments(segments)
.b... | final GPX gpx = nextGPX(new Random(1)).toBuilder()
.addTrack(nextTrack(new Random(2)))
.addTrack(nextTrack(new Random(3)))
.addTrack(nextTrack(new Random(4)))
.build();
final GPX merged = gpx.toBuilder()
.trackFilter()
.listMap(Filters::mergeTracks)
.filter(Track::nonEmpty)
.build()
.... |
76591624_9 | class ErrorException extends RuntimeException {
public final int getCode() {
return code;
}
public ErrorException(final int code);
public ErrorException(final int code, @Nullable final String message);
public ErrorException(final int code, @Nullable final Throwable cause);
public ErrorException(final int ... | // Act:
final ErrorException exception = new ErrorException(2, "Fatal error!");
// Assert:
assertThat(exception.getCode(), is(2));
assertThat(exception.getMessage(), is("Fatal error!"));
assertThat(exception.getCause(), is(nullValue()));
}
} |
76600904_140 | class AccountResourceImpl {
@POST
@Path("/login")
public Response login(@HeaderParam("Authorization") String authHeader) {
if (StringUtils.isBlank(authHeader)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Optional<Pair<String, String>> auth = process... | accountResource.uriInfo = new ResteasyUriInfo("account/login", "", "");
String header = "hmac test:testing";
when(accountService.authenticate("test", "testing")).thenReturn(Optional
.empty());
Response response = accountResource.login(header);
assertThat(response.get... |
76604873_18 | class SharedPreferencesWrapper implements SharedPreferences {
@Override @Nullable public String getString(@NonNull final String key, @Nullable final String defValue) {
return preferences.getString(key, defValue);
}
public SharedPreferencesWrapper(@NonNull final SharedPreferences preferences);
@NonNull public ... | // Arrange:
final SharedPreferences mockPreferences = mock(SharedPreferences.class);
final SharedPreferencesWrapper wrapper = new SharedPreferencesWrapper(mockPreferences);
// Act:
wrapper.getString(PREF_KEY, "Slovakia");
// Assert:
verify(mockPreferences).getString(PREF_KEY, "Slovakia");
verifyNoMoreIn... |
76634121_13 | class CompositeReadableBuffer implements ReadableBuffer {
public CompositeReadableBuffer append(byte[] array) {
validateAppendable();
if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array must not be empty or null");
}
if (currentArray == ... | CompositeReadableBuffer empty = new CompositeReadableBuffer();
CompositeReadableBuffer buffer = new CompositeReadableBuffer();
try {
buffer.append(empty);
fail("Should not be able to append an empty composite");
} catch (IllegalArgumentException iae) {}
}
} |
76667858_0 | class ServiceModel {
public EntityResult<V> get(K id) throws RestDslException {
return serviceDao.get(ServiceQuery.byId(id));
}
public ServiceModel(PersistentServiceDao<V, K> serviceDao);
protected PersistentServiceDao<V, K> getServiceDao();
public V getOne(K id);
public EntityResult... | Mockito.when(mockedDao.get(Mockito.any()))
.thenReturn(new EntityResult<>(Collections.emptyList(), 0L));
model.get((Long) null);
Mockito.verify(mockedDao, Mockito.never())
.get(Mockito.any());
}
} |
76684377_50 | class SimpleListAdapter extends BaseListAdapter<A, VH, I> implements
SimpleAdapter<I> {
@Override public void registerOnDataSetSwapListener(@NonNull final OnDataSetSwapListener<List<I>> listener) {
if (listeners == null) {
this.listeners = new SwappableDataSetAdapterListeners<>();
}
this.listeners.register... | // Arrange:
final SimpleAdapterDataSet<String> mockDataSet = mock(TestDataSet.class);
final SimpleListAdapter<TestAdapter, ViewHolder, String> adapter = new TestAdapter(context, mockDataSet);
final OnDataSetSwapListener mockListener = mock(OnDataSetSwapListener.class);
final List<String> items = Collections.e... |
76684614_12 | class ItemSwipeHelper extends RecyclerViewItemHelper<ItemSwipeHelper.Interactor> {
public boolean restoreHolder(@NonNull final RecyclerView.ViewHolder viewHolder, @Direction final int direction) {
return restoreHolder(viewHolder, direction, null);
}
public ItemSwipeHelper();
private ItemSwipeHelper(final Inte... | // Arrange:
final RecyclerView mockRecyclerView = mock(RecyclerView.class);
final View itemView = new View(context);
final TestHolder mockViewHolder = createMockHolder(mockRecyclerView, itemView, 0);
when(mockViewHolder.getInteractiveView(ItemSwipeHelper.INTERACTION)).thenReturn(null);
final ItemSwipeHelper... |
76877282_1 | class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
List<Map.Entry<K, V>> sorted = Stream.of(list).sortBy(Map.Entry::getValue).toList();
Map<K, V> result = new LinkedHashMap... | Map<String, String> sorted = MapUtil.sortByValue(ru_map);
Map.Entry<String, String> entry = sorted.entrySet().iterator().next();
String value = entry.getValue();
Assert.assertTrue(value.equals("Азеррбайджан"));
}
} |
77005273_1 | class Cluster {
public void shutdown() {
LOG.debug("Shutting down RpcServer and MembershipService");
rpcServer.shutdown();
membershipService.shutdown();
sharedResources.shutdown();
this.hasShutdown = true;
}
private Cluster(final IMessagingServer rpcServer,
... | useStaticFd = true;
final int numNodes = 50;
final int numFailingNodes = 12;
final Endpoint seedEndpoint = Utils.hostFromParts("127.0.0.1", basePort);
createCluster(numNodes, seedEndpoint);
verifyCluster(numNodes);
// Fail the first 3 nodes.
final Set<Endp... |
77008449_0 | class ReplicationQueueHealthCheck implements HealthCheck {
@Override
public Result execute() {
FormattingResultLog resultLog = new FormattingResultLog();
if(agentManager.getAgents().isEmpty()) {
resultLog.info("No agents configured");
}
for (Map.Entry<String, Agent... | when(agent1.isValid()).thenReturn(false);
when(agent2.isValid()).thenReturn(false);
Result result = healthCheck.execute();
assertEquals("Status should be OK", Result.Status.OK, result.getStatus());
assertEquals("Result should be ok", true, result.isOk());
}
} |
77030088_45 | class Asn1BerParser {
public static <T> T parse(ByteBuffer encoded, Class<T> containerClass)
throws Asn1DecodingException {
BerDataValue containerDataValue;
try {
containerDataValue = new ByteBufferBerDataValueReader(encoded).readDataValue();
} catch (BerDataValueFor... | assertEquals(2, parse("3006300430003000", SequenceWithSequenceOf.class).values.size());
}
} |
77066767_41 | class TimedSummaryNotifier implements Runnable {
protected String createMessage(int nrAnalyzedBuilds, int nrRepairAttempts, int nrOfBuildsWithPatches, int[] nrOfPatchesPerTool, Date now) {
String message = "Summary email from Repairnator. \n\n";
message += "This summary contains the operations of ... | int[] patchesPerTool = {1, 5, 10, 15, 20};
Date now = new Date();
String message = notifier.createMessage(100, 15, 51, patchesPerTool, now);
String testMessage = "Summary email from Repairnator. \n\n"
+ "This summary contains the operations of Repairnator between "
... |
77143465_33 | class JacksonStyle extends AnnotatorStyle {
@Override
public void processSubTypeRule(TypeSpec.Builder typeSpec, TypeModel typeModel) {
SubTypeModel subTypeModel = typeModel.getSubTypes();
AnnotationSpec.Builder typeInfoAnnotation = AnnotationSpec.builder(JsonTypeInfo.class)
.ad... | TypeSpec.Builder builder = TypeSpec.classBuilder("Test");
TypeModel model = mock(TypeModel.class);
Map<String, String> subTypes = new HashMap<>();
subTypes.put("A", "com.flipkart.lyrics.A");
subTypes.put("B", "com.flipkart.lyrics.B");
SubTypeModel subTypeModel = mock(Sub... |
77145569_121 | class IntermediateNavigationProperty extends IntermediateModelElement implements
IntermediateNavigationPropertyAccess, JPAAssociationAttribute {
@Override
public List<String> getProtectionPath(final String claimName) throws ODataJPAModelException {
return new ArrayList<>(0);
}
IntermediateNavigation... | final IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertTrue(property.getProtectionPath("Bla").isEmpty());
}
} |
77168103_6 | class LifecycleScopes {
public static <E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
}
private LifecycleScopes();
public static CompletableSource resolveScopeFromLifecycle(
... | TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED);
final RuntimeException expected = new RuntimeException("Expected");
AutoDisposePlugins.setOutsideScopeHandler(
e -> {
// Throw it back
throw expected;
});
testSource(resolveSco... |
77321473_0 | class Automator extends Item implements Serializable {
void update(double delta) {
if (!enabled || itemLevel == 0) return;
tickTimer += delta;
while (tickTimer >= actualTickRate) {
tickTimer -= actualTickRate;
generator.process();
}
}
private Autom... | World world = new World();
System.out.println("update()");
Currency c = new Currency.Builder(world)
.build();
Generator g = new Generator.Builder(world)
.generate(c)
.build();
g.upgrade();
Automator a = new Automator.Build... |
77385607_83 | class GraphApp {
public void deleteElements() {
try {
if (g == null) {
return;
}
LOGGER.info("deleting elements");
// note that this will succeed whether or not pluto exists
g.V().has("name", "pluto").drop().iterate();
... | app.createElements();
app.deleteElements();
assertFalse(g.V().has("name", "pluto").hasNext());
assertFalse(g.V().has("name", "jupiter").both("brother").has("name", "pluto").hasNext());
}
} |
77403831_1 | class Pcf8574 implements AutoCloseable {
public int readByte() {
if (device == null) return 0;
byte[] buffer = new byte[]{0};
try {
device.read(buffer, 1);
} catch (IOException e) {
// ignore
}
return buffer[0];
}
@VisibleForTesting Pcf8574(I2cDevice device);
public sta... | pcf8574.readByte();
Mockito.verify(device).read(Matchers.any(byte[].class), Matchers.eq(1));
}
} |
77405221_59 | class IsJsonNull extends AbstractJsonNodeMatcher<NullNode> {
public static Matcher<JsonNode> jsonNull() {
return INSTANCE;
}
private IsJsonNull();
@SuppressWarnings("unused") public static Matcher<JsonNode> jsonNull(final NullNode value);
@Override protected boolean matchesNode(NullNode node, Descript... | final Matcher<JsonNode> sut = jsonNull();
final StringDescription description = new StringDescription();
sut.describeMismatch(NF.textNode("goat"), description);
assertThat(description.toString(), is(
"was not a null node, but a string node"
));
}
} |
77435673_0 | class AbstractStatisticsTSDBLoader {
public void load() throws IOException {
if (cleanDatabaseOnLoad) {
doCreateEmptyDatabase();
}
statValueCache.clear();
statValueEmpty.clear();
final StatArchiveReader reader =
new StatArchiveReader(new File[] { archiveFileName }, statFilters, false);
for (Obj... |
TestMeasurementLoader testLoader = new TestMeasurementLoader(false,
new File("src/test/resources/myStatisticsArchiveFile.gfs"), "SERVER666");
testLoader.load();
assertEquals("SERVER666", testLoader.geodeMemberName);
assertEquals("src/test/resources/myStatisticsArchiveFile.gfs", testLoader.archiveFileName... |
77481567_34 | class StrategyExpertAdvisor implements ExpertAdvisor<C>, OrderEventListener {
@Override
public void newData(final C candleStick) {
strategy.update(candleStick);
switch (currentState) {
case TRY_CREATE:
currentOrder = creator.checkMarketEntry(this);
if... | cut.newData(EXEMPLARY_CANDLE_STICK);
verify(calculator).update(EXEMPLARY_CANDLE_STICK);
}
} |
77492072_172 | class MementoResource {
public Link filterLinkParams(final Link link) {
return filterLinkParams(link, !includeMementoDates);
}
public MementoResource(final ServiceBundler trellis, final boolean includeMementoDates);
public ResponseBuilder getTimeMapBuilder(final SortedSet<Instant> mementos, ... | final MementoResource mr = new MementoResource(null, false);
final Link link = fromUri("http://example.com/resource/memento/1").rel(MEMENTO)
.param(DATETIME, ofInstant(now(), UTC).format(RFC_1123_DATE_TIME)).build();
assertFalse(mr.filterLinkParams(link).getParams().containsKey(DATET... |
77541577_2 | class LogzioSender {
public void send(JsonObject jsonMessage) {
// Return the json, while separating lines with \n
logsQueue.enqueue(jsonMessage.toString().getBytes(StandardCharsets.UTF_8));
}
private LogzioSender(HttpsRequestConfiguration httpsRequestConfiguration, int drainTimeout, bool... | String token = "aBcDeFgHiJkLmNoPqRsT";
String type = random(8);
String loggerName = "simpleByteArrayAppending";
int drainTimeout = 2;
String message1 = "Testing.." + random(5);
String message2 = "Warning test.." + random(5);
LogzioSender.Builder testSenderBuilde... |
77671214_1 | class Example {
public Example() {
this(100);
}
public Example();
public Example(int maximum);
public static void main(String[] args);
public Set<Integer> getPrimes(Region<Integer, String> region, Execution execution);
}
class ExampleTest {
@Test
public void testExample() throws Exception {
| Example example = new Example(10);
Region<Integer, String> region = mock(Region.class);
List<Integer> primes = Arrays.asList(1, 2, 3, 5, 7);
ResultCollector resultCollector = mock(ResultCollector.class);
when(resultCollector.getResult()).thenReturn(primes);
Execution execution = mock(Execution.... |
77675033_0 | class AbstractGrpcServerFactory implements GrpcServerFactory {
protected void configureServices(final T builder) {
final Set<String> serviceNames = new LinkedHashSet<>();
// support health check
if (this.properties.isHealthServiceEnabled()) {
builder.addService(this.healthStatu... | final GrpcServerProperties properties = new GrpcServerProperties();
properties.setReflectionServiceEnabled(false);
final NettyGrpcServerFactory serverFactory = new NettyGrpcServerFactory(properties, emptyList());
serverFactory.healthStatusManager = new HealthStatusManager();
se... |
77759012_13 | class Slugs {
public static String toSlug(String text) {
if (null == text) {
return null;
}
Matcher m = pattern.matcher(text);
String result = m.replaceAll("-");
if (result.endsWith("-")) {
// Remove the last char if it's a dash
result = r... | String in = "2016-01-01 My Post?";
String result = Slugs.toSlug(in);
String expected = "2016-01-01-my-post";
assertEquals(expected, result);
}
} |
77796833_7 | class Arguments {
public boolean matches(Object... arguments) {
int length = argumentMatchers.size();
if (length != arguments.length)
return false;
else
for (int i = 0; i < length; i++) {
ArgumentMatcher matcher = argumentMatchers.get(i);
... | List<ArgumentMatcher<?>> arguments = Arrays.asList(
new EqualsMatcher<>(intValue),
new EqualsMatcher<>(stringValue),
new EqualsMatcher<>(nullValue)
);
assertTrue(new Arguments(arguments).matches(1, stringValue, nullValue));
}
} |
77809403_6 | class TraceQueue {
public List<Span> consume() throws InterruptedException {
List<Span> rc;
synchronized (this) {
// wait for an available span
while (spans == null) {
wait();
}
rc = spans;
spans = null;
}
return rc;
}
public void supply(Span span);
priva... | long start = System.currentTimeMillis();
new Thread() {
@Override
@SneakyThrows
public void run() {
sleep(500);
addTraces(2);
}
}.start();
queue.consume();
long total = System.currentTimeMillis() - start;
Assert.assertTrue(total>=500);
}
} |
77825195_26 | class AdyenCheckCaptureAction extends AbstractWaitableAction<OrderProcessModel> {
@Override
public String execute(final OrderProcessModel process) {
LOG.debug("Process: " + process.getCode() + " in step " + getClass().getSimpleName());
final OrderModel order = process.getOrder();
if (... | PaymentTransactionModel adyenTransaction = createAdyenTransaction();
List<PaymentTransactionEntryModel> transactionEntries = new ArrayList<>();
transactionEntries.add(createAuthorizedEntry());
transactionEntries.add(createCaptureReceivedEntry());
transactionEntries.add(createCap... |
77831813_6 | class MigrationsFilter implements Iterable<MigrationFile> {
@Override
public Iterator<MigrationFile> iterator() {
return origin.iterator();
}
MigrationsFilter(
@NonNull final Iterable<? extends MigrationFile> origin,
final int versionStart,
final int versionEnd
);... | final Iterator<MigrationFile> iter = new MigrationsFilter(
Arrays.asList(
new MigrationFileFake(2),
new MigrationFileFake(3),
new MigrationFileFake(4),
new MigrationFileFake(5)
),
3,
5
).itera... |
77838408_49 | class AsyncDirectClientAuthenticator {
public final CompletableFuture<List<U>> authenticate(final List<AsyncClient<? extends Credentials, U>> currentClients,
final C context,
final AsyncProfileManager<U, C> manager) {
final Stream<AsyncClient<? extends Credentials... |
final AsyncDirectClientAuthenticator<TestProfile, AsyncWebContext> authenticator = new AsyncDirectClientAuthenticator<>(AsyncProfileSave.SINGLE_PROFILE_SAVE,
new AsyncSaveProfileToSessionDecision(true), new AsyncLoadProfileFromSessionDecision());
final AsyncWebContext webContext = webCo... |
77841232_34 | class MediaScanServiceImpl implements MediaScanService {
@Override
public Map<Path, List<Media>> retrieveFiles() {
log.info("Scanning for directories in {}", scanConfig.base_input_dir());
return scannerProvider.get()
.searchIn(scanConfig.base_input_dir())
.withRecursion(... | assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> subject.retrieveFiles());
}
} |
77936449_6 | class EJB_03_rollback {
public void createTwo(boolean rollback, String first, String second) {
Foo foo = new Foo(first);
Foo bar = new Foo(second);
em.persist(foo);
em.persist(bar);
if(rollback) {
ctx.setRollbackOnly(); //none should get persisted, as we rollb... |
String first = "first";
String second = "second";
assertFalse(queriesEJB.isInDB(first));
assertFalse(queriesEJB.isInDB(second));
ejb.createTwo(true,first,second); //should rollback
assertFalse(queriesEJB.isInDB(first));
assertFalse(queriesEJB.isInDB(second));
... |
78016530_0 | class SuperFactory {
public <T> T create(String fullName, Class<T> clazz) {
IndraFactory<T> factory;
if (fullName != null) {
String[] parts = fullName.split(IndraFactory.FACTORY_SEPARATOR);
String item;
if (parts.length > 1) {
factory = getFactor... | SuperFactory sf = new SuperFactory();
RelatednessFunction func = sf.create("cosine", RelatednessFunction.class);
Assert.assertTrue(func != null);
Assert.assertEquals(CosineRelatednessFunction.class, func.getClass());
}
} |
78045492_1 | class WebViewOverlay implements WebViewOverlayAPI {
public String getUrl(String baseUrl, HashMap<String, String> params) throws WebViewOverlayException {
String finalUrl = null;
if (baseUrl instanceof String) {
if (params == null || params.isEmpty()) {
return baseUrl;
... | String url = "https://ptyagicodecamp.github.io";
HashMap<String, String> params = new HashMap<>();
params.put("param1", "1234");
params.put("param2", "testParam");
String expectedUrl = "https://ptyagicodecamp.github.io/?param1=1234¶m2=testParam";
String actualUrl = "... |
78055963_4 | class CustomOperation extends BaseOperation {
@Override
public byte[] toBytes() {
byte[] feeBytes = fee.toBytes();
byte[] payerBytes = payer.toBytes();
List<Byte> requiredAuthsSerialized = new LinkedList<>();
if (this.requiredAuths != null) {
for (UserAccount userAcc... | CustomOperation customOperation1 = new CustomOperation(fee, payer, operationId, requiredAuths, shortData);
byte[] serialized1 = customOperation1.toBytes();
assertArrayEquals(EXPECTED_SERIALIZED_BYTES_1, serialized1);
// test with some long data string to check if data length is serializ... |
78089297_36 | class UnErasureCodingAction extends ErasureCodingBase {
@Override
public void init(Map<String, String> args) {
super.init(args);
this.conf = getContext().getConf();
this.srcPath = args.get(FILE_PATH);
this.ecPolicyName = REPLICATION_POLICY_NAME;
if (args.containsKey(EC_TMP)) {
this.ecTmpP... | String testDir = "/test_dir";
dfs.mkdirs(new Path(testDir));
dfs.setErasureCodingPolicy(new Path(testDir), ecPolicy.getName());
// create test file, its EC policy should be consistent with parent dir, i.e., ecPolicy.
String srcPath = testDir + "/ec_file";
createTestFile(srcPath, 1000);
dfsCl... |
78224452_1 | class ChatPresenter extends Presenter<ChatPresenter.View> {
@Override
public void attachView(View view) {
super.attachView(view);
if (messages.size() == 0) {
oldMessagesDisposable = chatService.getMessages()
.repeatWhen(o -> o.concatMap(v -> Observable.interval(... | when(chatServiceMock.getMessages()).thenReturn(Observable.just(testMessages));
when(chatServiceMock.addMessage(chatMessageCaptor.capture())).thenReturn(Observable.just(testMessages.get(0)));
when(chatPresenterViewMock.getNewMessage()).thenReturn(Observable.just(testMessageString));
chat... |
78267831_15 | class Cell {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cell other = (Cell) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public Cell(... | System.out.println("equals");
Object obj = null;
Cell instance = new Cell(2,3,State.LIVE);
boolean expResult = false;
boolean result = instance.equals(obj);
assertEquals(expResult, result);
}
} |
78291176_7 | class TargetRange {
public static TargetRange from(@IntRange(from = 0) int start, @IntRange(from = 0) int end) {
if (end < start) {
throw new IllegalArgumentException("The end of the range shouldn't be before the start");
}
return new TargetRange(start, end);
}
private... | TargetRange targetRange = TargetRange.from(RANGE_ZERO, RANGE_TEN);
TargetRange expectedResult = TargetRange.from(RANGE_ZERO, RANGE_FIVE);
assertThat(targetRange).isNotEqualTo(expectedResult);
}
} |
78306233_0 | class FlagParser {
@NonNull
public List<AutoModFlag> parseFlags(@NonNull String rawFlags) {
final String[] splitFlags = rawFlags.split(",");
final List<AutoModFlag> flags = new ArrayList<>(splitFlags.length);
for (String rawFlag : splitFlags) {
String[] parts = rawFlag.spli... | assertTrue(parseFlags("").isEmpty());
}
} |
78359015_9 | class ValiFieldText extends ValiFieldBase<String> {
public ValiFieldText addMinLengthValidator(int minLength) {
return addMinLengthValidator(getErrorRes(ValiFi.Builder.ERROR_RES_LENGTH_MIN), minLength);
}
public ValiFieldText();
public ValiFieldText(@Nullable String defaultValue);
public ValiFieldText(@Null... | mField.set("1234");
mField.addMinLengthValidator("must be longer than 4 characters", 4);
assertThat(mField.isValid(), is(true));
}
} |
78391996_50 | class FileOperator {
public void read(long pos, Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) {
throw new IndexOutOfBoundsException();
}
while (byteCount > 0L) {
try {
// Read up to byteCount bytes.
byteBuffer.l... | FileOperator operator = new FileOperator(randomAccessFile.getChannel());
Buffer buffer = new Buffer();
try {
operator.read(0, buffer, -1L);
fail();
} catch (IndexOutOfBoundsException ignored) {
}
}
} |
78418280_0 | class RandomBookGenerator {
public List<Book> generate(int howMany) {
List<Book> books = new ArrayList<>();
for (int i = 0; i < howMany; i++) {
books.add(randomBook());
}
return books;
}
public Book randomBook();
private static String randomTitle();
pr... | List<Book> books = new RandomBookGenerator().generate(15);
assertEquals(15, books.size());
for (Book book : books) {
assertNotNull(book.getTitle());
assertNotNull(book.getAuthor());
assertNotEquals(0, book.getPublishDate().getTime());
}
}
} |
78420352_45 | class UIManagerModule extends ReactContextBaseJavaModule implements
OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter {
@ReactMethod
public void removeSubviewsFromContainerWithID(int containerTag) {
mUIImplementation.removeSubviewsFromContainerWithID(containerTag);
}
public UIManage... | UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView =
new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = uiManager.addMeasuredRootView(rootView);
final int containerTag = rootTag + 1;
final int containerSiblingTag = containerTag + 1... |
78444970_22 | class JarnikPrim {
public static <N> UndirectedGraph<N> compute(final UndirectedGraph<N> graph, final ToIntFunction<UndirectedGraph.Edge<N>> weighter) {
final MutableUndirectedGraph<N> result = new MutableUndirectedGraph<>();
if (!graph.nodes().isEmpty()) {
// chose arbitrary node to s... | final Map<UndirectedGraph.Edge<String>, Integer> w = new HashMap<>();
final MutableUndirectedGraph<String> g = new MutableUndirectedGraph<>();
g.addNode("a");
g.addNode("b");
w.put(g.addEdge("a", "b"), 10);
final UndirectedGraph<String> mst = JarnikPrim.compute(g, w::get... |
78556475_1 | class YamlConfiguration extends Configuration<YamlConfiguration> {
public final void loadAndSave() {
try {
load();
save();
} catch (ConfigurationStoreException e) {
if (e.getCause() instanceof NoSuchFileException) {
postLoad();
sav... | class A extends YamlConfiguration {
int i = 0;
protected A() { super(configPath, YamlProperties.DEFAULT); }
@Override
protected void postLoad() {
i++;
}
}
A a = new A();
a.loadAndSave();
assertThat(a.i... |
78566008_3 | class Result {
public static <T> Result<T> error(Throwable error) {
if (error == null) {
throw new NullPointerException("mError == null");
}
return new Result<>(null, error);
}
private Result(Response<T> response, Throwable error);
public static Result<T> response... | try {
Result.error(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("error == null");
}
}
} |
78622784_26 | class AxisRenderer {
ArrayList<Integer> calculateValues(int min, int max, int step) {
ArrayList<Integer> result = new ArrayList<>();
int pos = min;
while (pos <= max) {
result.add(pos);
pos += step;
}
// Set max Y axis label in case isn't already there
if (result.get(result.size() - 1) < max) resu... |
ArrayList<Integer> toAssert = new ArrayList<>();
toAssert.add(0);
toAssert.add(5);
toAssert.add(10);
assertEquals(toAssert, mXRndr.calculateValues(0, 8, 5));
}
} |
78735130_2 | class DatabaseService {
public List<String> getTopContextWordsInYear(final String corpusName,
final String table, final String word, final Integer year,
final int limit) {
final Corpus corpus = corpora.get(corpusName);
final List<String> words = new ArrayList<>();
if (!corpus.hasMappingFor(word) || (year ... | assertEquals(Arrays.asList(new String[] { "arr" }),
db.getTopContextWordsInYear(CORPUS,
DatabaseService.SIMILARITY_TABLE, "foo", 1910, 1));
assertEquals(Arrays.asList(new String[] { "arr", "boo" }),
db.getTopContextWordsInYear(CORPUS,
DatabaseService.SIMILARITY_TABLE, "foo", 1910, 2));
}
} |
78756665_3 | class XbelParser extends AbstractParser {
@Override
public Set<Link> parse(ParseContext context) throws IOException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(... | File path = new File(System.getProperty("user.dir"), "src");
path = new File(path, "test");
path = new File(path, "resources");
Set<Link> links = fixture.parse(new ParseContext(null, path.getAbsolutePath() + "/linksagogo.xbel", path.getAbsolutePath() + "/linksagogo.xbel"));
assertNotNull(links);
... |
78756993_29 | class History extends AbstractList<T> implements List<T> {
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return elements.addAll(index, c);
}
History();
History(List<T> elements);
@Nullable public K top();
@Nonnull public K fromTop(int offset);
@Nu... | TestKey testKey1 = new TestKey("Hello");
TestKey testKey2 = new TestKey("World");
TestKey testKey3 = new TestKey("Kappa");
History history = History.of(testKey1);
List<Object> objects = new ArrayList<>(2);
objects.add(testKey2);
objects.add(testKey3);
tr... |
78768320_0 | class TracingHandlerInterceptor extends HandlerInterceptorAdapter {
static boolean isTraced(HttpServletRequest httpServletRequest) {
// exclude pattern, span is not started in filter
return httpServletRequest.getAttribute(TracingFilter.SERVER_SPAN_CONTEXT) instanceof SpanContext;
}
public ... | HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getAttribute(TracingFilter.SERVER_SPAN_CONTEXT)).thenReturn(Mockito.mock(SpanContext.class));
assertTrue(TracingHandlerInterceptor.isTraced(request));
}
} |
78774547_9 | class MetricBlockFilter extends Filter<ILoggingEvent> {
@Override
public FilterReply decide(ILoggingEvent event) {
Marker eventMarker = event.getMarker();
if (isStarted() && eventMarker != null && eventMarker.contains(MetricPassFilter.METRIC_MARKER)) {
return FilterReply.DENY;
... | LoggingEvent event = new LoggingEvent();
MetricBlockFilter filter = new MetricBlockFilter();
filter.start();
assertEquals(FilterReply.NEUTRAL, filter.decide(event));
}
} |
78776301_3 | class ServletFilterHeaderSpanDecorator implements ServletFilterSpanDecorator {
@Override
public void onRequest(HttpServletRequest httpServletRequest, Span span) {
for (HeaderEntry headerEntry : allowedHeaders) {
String headerValue = httpServletRequest.getHeader(headerEntry.getHeader());
... | decorator = new ServletFilterHeaderSpanDecorator(headerEntries, "HEADER.");
Mockito.when(httpServletRequest.getHeader("If-Match")).thenReturn("10");
decorator.onRequest(httpServletRequest, span);
Mockito.verify(span).setTag("HEADER.if-match", "10");
}
} |
78808033_1 | class ButtonPresenter extends PrivvyPresenter<ButtonContract.View, ButtonContract.Interactor> implements ButtonContract.Presenter {
@Override
public void incrementNumber() {
Timber.d("Incrementing number");
int value = 1;
getInteractor().incrementNumberBy(value);
numberUpdateYok... | buttonPresenter.incrementNumber();
verify(mockYoke).changeNumber(eq(1));
}
} |
78842132_808 | class MessageService {
public List<Message> getFilteredMessages(MessageSearchCriteria searchCriteria) {
List<Message> messages = getMessages(searchCriteria);
if (searchCriteria.isModuleAbsent()) {
return messages.parallelStream()
.filter(e -> e.getLocale().equals(searchCriteria.getLocale())
&& e.ge... | String tenantId = "a.b.c";
final Tenant defaultTenant = new Tenant(Tenant.DEFAULT_TENANT);
final MessageIdentity messageIdentity1 = MessageIdentity.builder()
.code("code1")
.locale(ENGLISH_INDIA)
.module("module1")
.tenant(defaultTenant)
... |
78846472_0 | class MainPresenter extends ComponentPresenter<MainPresenter.View, MainComponent> {
@Override
public void onBindChange(@Nullable View view) {
super.onBindChange(view);
onView(v -> v.showBinderCounter(++bindCounter));
onView(v -> {
if (doInit) {
doInit = false... | MainPresenter mainPresenter = new MainPresenter(null);
verify(view, never()).showBinderCounter(anyInt());
mainPresenter.onBindChange(view);
verify(view).showBinderCounter(1);
mainPresenter.onBindChange(null);
mainPresenter.onBindChange(view);
verify(view).showBind... |
78859100_2 | class UserService {
public boolean login(String username, String password) {
List<String> permissions = apiClient.authenticate(username, password);
return permissions.contains("ADMIN");
}
@Inject public UserService(Application application);
@RealClass @Inject UserService userService;... | when(apiClient.authenticate(username, password)).thenReturn(Lists.newArrayList("ADMIN"));
assertTrue(userService.login(username, password));
}
} |
78957876_6 | class SwaggerConverterUtils {
public static String generateOAS3Definitions(String ballerinaSource, String serviceName)
throws IOException, SwaggerConverterException {
//Create empty swagger object.
Swagger swagger = new Swagger();
String swaggerSource;
BallerinaFile ball... | try {
String oasDef = SwaggerConverterUtils.generateOAS3Definitions(invalidEchoServiceBal, null);
Assert.fail("Error was not thrown for invalid ballerina service");
} catch (IOException e) {
Assert.fail("Error while converting ballerina echo service to swagger definit... |
78969853_5 | class MakeUpRepositoryImpl implements MakeUpRepository {
@Override
public Observable<List<MakeUp>> searchMakeUp(final String brandName, final String productName) {
return Observable.defer(() -> makeUpProductRestService.searchMakeUpProducts(brandName,
productName))
.retry... | // Given
when(makeUpProductRestService.searchMakeUpProducts(anyString(), anyString())).thenReturn
(get403ForbiddenError().toList());
// When
TestSubscriber<List<MakeUp>> subscriber = new TestSubscriber<>();
makeUpRepository.searchMakeUp(BRAND_COVERGIRL, PRODUCT_T... |
79060427_1213 | class ExtractSedaActionHandler extends ActionHandler {
@Override
public ItemStatus execute(WorkerParameters params, HandlerIO ioParam) {
checkMandatoryParameters(params);
handlerIO = ioParam;
final ItemStatus globalCompositeItemStatus = new ItemStatus(HANDLER_ID);
UnitType work... | VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID);
prepareResponseOKForAdminManagementClientFindIngestContracts(INGEST_CONTRACT_NO_CHECK);
final InputStream sedaLocal = new FileInputStream(PropertiesUtils.findFile(SIP_ADD_UNIT));
JsonNode parent = JsonHandler
.getFr... |
79065628_16 | class CouchbaseQueryUtil {
public static Observable<AsyncN1qlQueryRow> executeN1qlQuery(AsyncBucket bucket, N1qlQuery query) {
log.debug("Executing query: {}.", query.statement());
return bucket.query(query)
.map(result -> Tuple.create(query, result))
.flatMap(tuple... | AsyncN1qlQueryRow mockRow = mock(AsyncN1qlQueryRow.class);
when(mockResult.rows()).thenReturn(Observable.just(mockRow));
when(mockResult.finalSuccess()).thenReturn(Observable.just(true));
TestSubscriber<AsyncN1qlQueryRow> subscriber = new TestSubscriber<>();
executeN1qlQuery(m... |
79107120_1 | class PageSearch extends Search {
public PageSearch templates(String... resourceTypes) {
query().bool().filter().terms("cq:template", resourceTypes);
return this;
}
public PageSearch(ElasticSearchService elasticSearchService, String index);
public PageSearch path(String path);
public PageSearch ti... | underTest.templates("/apps/foo", "/apps/bar");
assertEquals("{\"query\":"
+ "{\"bool\":"
+ "{\"filter\":"
+ "["
+ "{\"terms\":"
+ "{\"cq:template\":"
+ "["
+ "\"/apps/foo\","
+ "\"/apps/bar\""
+ "]"
... |
79112912_0 | class AlfrescoCoreAdminHandler extends CoreAdminHandler {
NamedList<Object> actionFIX(SolrParams params) throws JSONException
{
String requestedCoreName = coreName(params);
var wrapper = new Object()
{
final NamedList<Object> response = new SimpleOrderedMap<>();
};
... | assertEquals(0, params.size());
NamedList<Object> actionResponse = admin.actionFIX(params);
assertEquals(0, actionResponse.size());
}
} |
79124323_22 | class LgoStreamingTradeService implements StreamingTradeService {
public Observable<OpenOrders> getOpenOrders(CurrencyPair currencyPair) {
return getOrderUpdates(currencyPair)
.map(
u ->
u.getAllOpenOrders().values().stream()
.filter(order -> order instance... | JsonNode snapshot = TestUtils.getJsonContent("/trade/orders-snapshot.json");
JsonNode update = TestUtils.getJsonContent("/trade/orders-update.json");
when(streamingService.subscribeChannel(anyString()))
.thenReturn(Observable.just(snapshot, update));
Observable<OpenOrders> openOrders = service.... |
79145090_11 | class JobScheduler {
@RestrictTo(RestrictTo.Scope.LIBRARY)
Scheduler getSchedulerForJob(Context context, JobInfo job) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return getSchedulerForTag(context, JobSchedulerSchedulerV28.TAG);
}
if (Build.VERSION.SDK_INT >= Bui... | public void testSchedulerInApi21() {
JobInfo api21Job = JobCreator.create(application).setRequiresCharging(true).build();
JobInfo api24Job = JobCreator.create(application).setPeriodic(15 * 60 * 1000L, 5 * 60 * 1000L).build();
JobInfo api26Job = JobCreator.create(application).setRequiresBatte... |
79209085_104 | class MediaStoreRequestHandler extends ContentStreamRequestHandler {
static PicassoKind getPicassoKind(int targetWidth, int targetHeight) {
if (targetWidth <= MICRO.width && targetHeight <= MICRO.height) {
return MICRO;
} else if (targetWidth <= MINI.width && targetHeight <= MINI.height) {
return... | assertThat(getPicassoKind(513, 385)).isEqualTo(FULL);
assertThat(getPicassoKind(1000, 1000)).isEqualTo(FULL);
assertThat(getPicassoKind(1000, 384)).isEqualTo(FULL);
assertThat(getPicassoKind(1000, 96)).isEqualTo(FULL);
assertThat(getPicassoKind(96, 1000)).isEqualTo(FULL);
}
} |
79226461_2 | class DecorationDelegate extends RecyclerView.ItemDecoration {
@Override public void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);... | when(recyclerView.getChildAt(anyInt())).thenReturn(child);
when(recyclerView.getChildCount()).thenReturn(3);
when(recyclerView.getChildAdapterPosition(child)).thenReturn(-1);
testAdapter.getItemDecoration().onDraw(canvas, recyclerView, state);
verify(testAdapter, never()).drawDecoration(canvas, rec... |
79246257_6 | class HighestValue implements Transform {
@Override
public List<List<Transmutation>> apply(List<List<Transmutation>> stageInput) {
final List<Transmutation> stageResult = new ArrayList<>();
// find highest value and if present, return, also setting the message code according to specified rules... | // ARRANGE
HighestValue transform = ImmutableHighestValue.of(null, HighestValue.Display.ORIGINAL_TIMESTAMP);
// ACT
List<List<Transmutation>> results = transform.apply(transformationResults);
// ASSERT
assertThat(results, not(empty()));
assertThat(results.get(0)... |
79266038_228 | class NativeProcessEnumeratorImpl implements NativeProcessEnumerator {
@Override
public List<NativeProcess> getProcesses() {
return pidEnumerator
.getPids()
.stream()
.map(processCollector::collect)
.collect(Collectors.toList());
}
public Native... | Map<Integer, String> pidDescriptions = new HashMap<>();
pidDescriptions.put(123, "toaster");
pidDescriptions.put(1, null);
pidDescriptions.put(3848, "ayy");
List<Integer> expectedPids = new ArrayList<>(pidDescriptions.keySet());
// pass `new` list so that `enumerator` ca... |
79304145_0 | class EsDailySnapshotStore extends EsStore implements DailySnapshotStore {
@Override
public EsDailySnapshotInstance getInstanceById(String instanceId) throws Exception {
SearchResponse
response =
this.retrieveByField("_id", instanceId, EsDailySnapshotInstance.class);
if (response.getHits().... | EsDailySnapshotStoreFactory factory = new EsDailySnapshotStoreFactory();
EsDailySnapshotStore
store =
(EsDailySnapshotStore) factory.getDailyStore(DateTime.parse("2016-07-14"));
EsDailySnapshotInstance inst = store.getInstanceById("i-9909451f");
Assert.assertEquals("i-9909451f", inst.get... |
79304189_29 | class InfluxDecoder {
public static List<Point> pointsFromString(String dbName, String payload) {
List<Point> dps = new ArrayList<>();
try {
Iterable<String> splits = lineFromPayLoad(payload);
for (String split : splits) {
Builder builder = pointFromLine(Point.newBuilder(), dbName, split);
if (build... | String testPoints = "cpu value=1i,value1=2i 1434055562000000000";
List<Point> dps = InfluxDecoder.pointsFromString("test", testPoints);
assertEquals(1, dps.size());
Point dp = dps.get(0);
assertEquals("cpu", dp.getMeasurementName());
assertEquals(0, dp.getTagsList().size());
assertEquals(1, dp.getValueL... |
79350243_60 | class Extensions {
@Nonnull
@CheckReturnValue
public static String append(@Nonnull String fileName, @Nonnull FileType fileType) {
final String extension = fileType.getDefaultExtension();
if (fileName.endsWith(DELIMITER + extension)) {
return fileName;
}
return fi... | // exercise
final String actual = Extensions.append("foo.java", JavaFileType.INSTANCE);
// verify
assertThat(actual)
.isEqualTo("foo.java");
}
} |
79360334_91 | class JTextPaneToolbox {
public static ArrayList<Integer> getLinesBetween(JTextPane pane, int start, int end) throws BadLocationException {
int startingline = transformToLineNumber(pane, start);
ArrayList<Integer> lines = new ArrayList<>();
lines.add(startingline);
String code = get... | JTextPane pane = new JTextPane();
pane.setText("12\n\n34\n5\n6");
ArrayList<Integer> linesBetween = JTextPaneToolbox.getLinesBetween(pane, 0, 5);
int lines[] = {0,1,2};
assertEquals(lines.length, linesBetween.size());
for (int i = 0; i < lines.length; i++) {
a... |
79403493_0 | class MultiValue {
public MultiValue(byte[]... values)
{
this(Arrays.asList(values));
}
public MultiValue(byte[]... values);
private MultiValue(List<byte[]> values);
public byte[] toByteArray();
private void writeTo(OutputStream output);
public static MultiValue from(byte[] ... | String sEntry1 = "Entry 1";
String sEntry2 = "Entry two";
MultiValue multiValue = new MultiValue(sEntry1.getBytes(), sEntry2.getBytes());
byte[] aBytes = multiValue.toByteArray();
int i = 0;
// count of number of entries
a... |
79467343_4 | class RxTuples {
public static <A, B, C, D, E> Function5<A, B, C, D, E, Quintet<A, B, C, D, E>> toQuintet() {
return new Function5<A, B, C, D, E, Quintet<A, B, C, D, E>>() {
@Override
public Quintet<A, B, C, D, E> apply(A a, B b, C c, D d, E e) {
return Quintet.with(... | Assert.assertEquals(true, RxTuples
.<Integer, Integer, Integer, Integer, Integer> toQuintet().apply(1, 2, 3, 4, 5)
.equals(RES_QUINTET));
Assert.assertEquals(
true,
RxTuples.<Integer, Integer, Integer, Integer, Integer> toQuintetFromQuartet... |
79483816_1 | class PublishRequestTracingHandler extends RequestHandler2 {
@Override
public void afterError(Request<?> request, Response<?> response, Exception e) {
if (request.getOriginalRequestObject() instanceof PublishRequest) {
Span span = tracing.tracer().nextSpan()
.remoteEndpoint(Endpoint.newBuilder()... | PublishRequest publishRequest = new PublishRequest("topic", "1234");
Request request = new DefaultRequest(publishRequest, "amazon-sns");
handler.afterError(request, null, new Exception("Aw, snap!"));
assertEquals( 1, spans.size() );
assertEquals(spans.getFirst().tags().get("error"), "Aw, snap!");
... |
79496898_9 | class NewVersionCheckerGitHubImpl implements NewVersionChecker {
@Override
public UpdatePackageInfo findNewUpdateIfAvailable() throws GenericException {
try {
String currentVersion = getCurrentVersion();
if (VERSION_UNRESOLVED.equals(currentVersion) || DEV_VERSION.equals(currentVersion)) {
// not spammin... | NewVersionCheckerGitHubImpl f = new NewVersionCheckerGitHubImpl();
f.setConfiguredVersion("0.0.0.1");
UpdatePackageInfo result = f.findNewUpdateIfAvailable();
assertNotNull(result);
}
} |
79514986_1 | class ConfigureReader {
public static Configure reader(String configueFileName) throws DocumentException {
logger.info("Begin read configure[{}]", configueFileName);
Configure configure = new Configure();
SAXReader reader = new SAXReader();
File file = new File(configueFileName);
... | try {
ConfigureReader.reader("src/test/resources/configure_miss_topic.xml");
Assert.fail();
} catch (Exception e) {
Assert.assertEquals(e.getMessage(), "mappings.mapping.datahubTopic is null");
}
}
} |
79539593_6 | class CompositeRepositoryImpl implements EventRepository {
@Override
public <P extends PublishedEvent> EventKey recordAndPublish(P publishedEvent) throws EventStoreException, ConcurrentEventException {
return recordAndPublishInternal(publishedEvent, Optional.empty(), entityEvent -> new DefaultConcurren... | mockCommon(intermediateEvent);
EventKey previousEntityEventKey = new EventKey();
ConcurrencyResolver concurrencyResolver = mock(ConcurrencyResolver.class);
Function<EntityEvent, ConcurrencyResolver<ConcurrentEventException>> factory = entityEvent -> concurrencyResolver;
EventKe... |
79564911_1340 | class SwiftObjectListService implements ListService {
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> children = new AttributedList<Path>();
final int limit = Pref... | final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path placeholder = new SwiftDirectoryFeature(session).mkdir(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.... |
79602914_10 | class PermissionRequestHandler extends RequestHandler {
@Nullable
public Location getLocation() {
if (isPermissionGranted()) {
return getRootRequest().device.location;
} else {
return null;
}
}
protected PermissionRequestHandler(RootRequest rootRequest)... | RootRequest rootRequest = TestObjects.permissionGrantedLocationRequest(true);
PermissionRequestHandler permissionRequestHandler = new PermissionRequestHandler(rootRequest) {
@Override
public RootResponse getResponse() {
return new RootResponse();
}
... |
79638652_6 | class OauthJdbcRepository extends AbstractJdbcRepository implements OauthRepository {
@Override
public ClientDetails findClientDetails(String clientId) {
final String sql = " select * from oauth_client_details where archived = 0 and client_id = ? ";
final List<ClientDetails> list = jdbcTemplate... | String clientId = "oaoedd";
final ClientDetails clientDetails = oauthJdbcRepository.findClientDetails(clientId);
assertNull(clientDetails);
ClientDetails clientDetails1 = new ClientDetails();
clientDetails1.clientId(clientId);
clientDetails1.clientSecret("Ole397dde2");
... |
79666748_1 | class RxCurryingConsumer {
public static <A, B> Function<A, Consumer<B>> curry(final BiConsumer<A, B> action) {
return new Function<A, Consumer<B>>() {
@Override
public Consumer<B> apply(final A a) throws Exception {
return new Consumer<B>() {
@Ov... | Function<Integer, Consumer<Integer>> variable = RxCurryingConsumer
.curry(new BiConsumer<Integer, Integer>() {
@Override
public void accept(Integer first, Integer second) {
Assert.assertEquals(5, first + second);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.