id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
100716846_10 | class SpringCloudFunctionInvoker implements FunctionInvoker, Closeable {
@Override
public Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt) {
SpringCloudMethod method = loader.getFunction();
Object[] userFunctionParams = coerceParameters(ctx, method, evt);
Object r... | SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, new SimpleFunctionInspector());
Object result = invoker.tryInvoke(fnWrapper, new Object[]{ Arrays.asList("hello", "world") });
assertThat(result).isInstanceOf(List.class);
assertThat((List) result).containsSequence("hello"... |
100758796_3 | class MainViewModel extends AndroidViewModel {
void sendColorMsg(MeshId targetMeshId, Colour msgColor) {
try {
if (targetMeshId != null) {
String payload = targetMeshId.toString() + ":" + msgColor.toString();
rmConnector.sendDataReliable(targetMeshId, payload);
... | MeshId targetId = mockMeshId;
Colour msgColor = Colour.RED;
String payload = String.valueOf(targetId) + ":" + msgColor;
//Trigger
spyViewModel.sendColorMsg(targetId, msgColor);
//verify
verify(rightMeshConnector).sendDataReliable(targetId, payload);
veri... |
100808500_35 | class PutInvariantSpanOp extends Op {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
PutInvariantSpanOp other = (PutInvariantSpanOp) obj;
if (ripIndex != other.ripIndex)
return fal... | PutInvariantSpanOp op1 = new PutInvariantSpanOp(100, 50, 1, 0);
PutInvariantSpanOp op2 = new PutInvariantSpanOp(101, 50, 1, 0);
assertFalse(op1.equals(op2));
assertFalse(op2.equals(op1));
}
} |
100928537_1 | class StateMachine {
public void nextMicrophoneState() {
switch (getMicrophoneState()) {
case BLOCKED:
microphoneState = MicrophoneState.NO_SOUND;
jsonParser.setMicrophoneState("softEmptyNoise");
break;
case NO_SOUND:
m... | assertEquals(MicrophoneState.BLOCKED, stateMachine.getMicrophoneState());
stateMachine.nextMicrophoneState();
assertEquals(MicrophoneState.NO_SOUND, stateMachine.getMicrophoneState());
stateMachine.nextMicrophoneState();
assertEquals(MicrophoneState.NEUTRAL_SOUND, stateMachine.ge... |
100955538_0 | class Cookie {
public static Cookie parse(String setCookie) {
return parse(System.currentTimeMillis(), setCookie);
}
private Cookie(String name, String value, long expiresAt, String domain, String path,
boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent);
... | assertThat(Cookie.parse("foo")).isNull();
assertThat(Cookie.parse("foo; Path=/")).isNull();
}
} |
101047757_15 | class FromConfigurationOperation extends GraphOperation {
@Override
public void callPreProcessing(SimulationState simulationState) {
Integer graphId = this.properties.getIntegerProperty(graphIdName);
Double precisionSeed = this.properties.getDoubleProperty(precisionSeedName);
Boolean insideAreaSeed = this.p... |
public void fromConfiguration_loadsSingleVertexWithPrecision_WithSuccess(String configurationFile) throws Exception {
// Arrange
createConfiguration(configurationFile);
// Arrange
createConfiguration(configurationFile);
SimulationState state = mock(SimulationState.class);
// Act
graphOperation.ca... |
101179084_0 | class RxDownloader {
public Single<List<FileContainer>> asList() {
this.subject.subscribe(this.itemsObserver);
this.size = this.files.size();
this.remains = this.size;
Observable<FileContainer> observable = Observable
.fromIterable(this.files)
.observ... | rxDownloader = builder
.strategy(DownloadStrategy.MAX)
.addFile("http://fakeURL.com/error-file.jpg")
.build();
List<FileContainer> res = rxDownloader.asList().blockingGet();
res.forEach(fileContainer -> {
Log.i("RxDownloader", "key" + ... |
101231823_11 | class IEXPrice implements Comparable<IEXPrice>, Serializable {
@Override
public int compareTo(final IEXPrice iexPrice) {
return compare(this.getNumber(), iexPrice.getNumber());
}
public IEXPrice(final long number);
public long getNumber();
public BigDecimal toBigDecimal();
@Overr... | final long biggerNumber = 12345678L;
final long smallerNumber = 1234567L;
final IEXPrice iexPrice_1 = new IEXPrice(biggerNumber);
final IEXPrice iexPrice_2 = new IEXPrice(smallerNumber);
assertThat(iexPrice_1.compareTo(iexPrice_2)).isEqualTo(1);
}
} |
101264180_0 | class BookServiceImpl implements BookService {
@Override
@Transactional
public Book saveBook(@NotNull @Valid final Book book) {
LOGGER.debug("Creating {}", book);
Book existing = repository.findOne(book.getId());
if (existing != null) {
throw new BookAlreadyExistsExcepti... | final Book savedBook = stubRepositoryToReturnUserOnSave();
final Book book = UserUtil.createBook();
final Book returnedBook = bookService.saveBook(book);
// verify repository was called with book
verify(bookRepository, times(1)).save(book);
assertEquals("Returned book sho... |
101380382_1 | class MockableClient extends OkHttpClient {
@Override
public Call newCall(Request request) {
if (shouldMockRequest(request)) {
return mockedClient.newCall(request);
} else {
return realClient.newCall(request);
}
}
MockableClient(Registry registry,
... | // Given
givenWhenFunctionReturns(true);
givenEndpointInRegistry(true);
// When
testee.newCall(REQUEST);
// Then
verify(mockClient).newCall(REQUEST);
verify(realClient, never()).newCall(any(Request.class));
}
} |
101408117_12 | class IMemoryImageInputStream extends ImageInputStreamImpl {
@Override
public int read(byte[] buffer, int offset, int length) throws IOException
{
int read = 0;
try {
read = memory.getBytesAt(address, buffer,offset,length);
} catch (MemoryFault f) {
if (f.getAddress() == address) {
/* Couldn't re... | AbstractMemory memory = new MockMemory(ByteOrder.BIG_ENDIAN);
memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF}, 0, 0x10000,
0x10000));
memory.addMemorySource(new UnbackedMemorySource(0x20000, 0x10000, "Deliberately not backed"));
IMemoryImageInp... |
101422199_3 | class PgCopyEscaper {
public String escapeForStdIn(String text) {
if (text == null) {
return null;
}
int firstEscapableChar = findFirstEscapableChar(text);
if (firstEscapableChar == -1) {
return text;
}
StringBuilder sb = new StringBuilder(t... | String text = "1234\tvalue\t5678\t";
String escaped = escaper.escapeForStdIn(text);
assertEquals("1234" + ESCAPED_BY_CHAR + FIELD_TERMINATED_CHAR + "value" + ESCAPED_BY_CHAR
+ FIELD_TERMINATED_CHAR + "5678" + ESCAPED_BY_CHAR + FIELD_TERMINATED_CHAR, escaped);
logger.info(... |
101436299_2 | class UriUtils {
public static URI getParent(final URI uri) {
if (isRoot(uri)) {
return null;
} else {
//get the parent path (with a slash on the end)
final URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
final String ... | final URI uri = URI.create(INTERNAL_URI_PREFIX + "/child/grandchild");
assertEquals("incorrect parent", URI.create(INTERNAL_URI_PREFIX + "/child"), UriUtils.getParent(uri));
}
} |
101477481_4 | class TsvParser {
private static Optional<Node> parseNode(String nodeString) {
try {
return Optional.of(NodeFactoryExtra.parseNode(nodeString));
} catch (RiotException e) {
log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage());
return Optional... | Node parseNode = NodeFactoryExtra.parseNode("\"Hallo \\\"Echo\\\"!\"@de");
assertEquals("de", parseNode.getLiteralLanguage());
assertEquals("Hallo \"Echo\"!", parseNode.getLiteralValue());
}
} |
101495687_0 | class FeaturePluginToMavenDependencyConverter {
static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) {
return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet());
}
private static Dependency convert(IFeaturePlugin featurePlugin);
... |
IFeaturePlugin featurePlugin = Mockito.mock(IFeaturePlugin.class);
Mockito.when(featurePlugin.getId()).thenReturn(FEATURE_PLUGIN_ID_FX);
Mockito.when(featurePlugin.getVersion()).thenReturn(FEATURE_PLUGIN_VERSION_FX);
Set<Dependency> dependencies = FeaturePluginToMavenDependencyConverter.convert(new HashSe... |
101559429_7 | class ActivityResult {
@Override
public String toString() {
return "ActivityResult { ResultCode = " +
resultCode + ", Data = " + data + " }";
}
public ActivityResult(int okResultCode, int resultCode, Intent data);
public Intent getData();
public int getResultCode();
... | String testResult = "ActivityResult { ResultCode" +
" = " + resultCode + ", Data = " + intent + " }";
assertEquals(activityResult.toString(), testResult);
}
} |
101634406_18 | class ChannelConfigurator {
void sync(@NonNull PolicyConfiguration config) {
if (!config.getChannels().isPresent()) {
LOG.info("No alerts channels for policy {} - skipping...", config.getPolicyName());
return;
}
LOG.info("Synchronizing alerts channels for policy {}..... | // given
AlertsChannel emailChannelInPolicy = channelInPolicy(savedEmailChannel, POLICY_ID, POLICY_ID + 1);
when(alertsChannelsApiMock.list()).thenReturn(ImmutableList.of(
savedUserChannel,
emailChannelInPolicy,
channelInPolicy(savedSlackChannel, P... |
101637037_0 | class EmbeddedJMSBrokerHolder implements AutoCloseable, ConnectionFactoryAccessor, ActiveMQConnectionFactoryAccessor, BrokerURIAccessor {
public static EmbeddedJMSBrokerHolder create(final String name, boolean marshal, boolean persistent) {
final File tempDir = Files.createTempDir();
LOGGER.debug("... | try (final EmbeddedJMSBrokerHolder embeddedJmsBrokerHolder = EmbeddedJMSBrokerHolder
.create("name", false, false)) {
assertNotNull(embeddedJmsBrokerHolder.getBrokerService());
assertFalse(embeddedJmsBrokerHolder.getBrokerService().isStarted());
}
}
} |
101650961_1 | class ZeebeExpressionResolver implements BeanFactoryAware {
@SuppressWarnings("unchecked")
public <T> T resolve(final String value) {
final String resolvedValue = resolve.apply(value);
if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) {
return (T) resolvedValue;
}
return (T) thi... | final String normalString = resolver.resolve("normalString");
assertThat(normalString).isEqualTo("normalString");
}
} |
101732174_16 | class WatchTimeout {
public static long availableTimeout(long expectedTimeoutMillis) {
return availableTimeout(expectedTimeoutMillis, 0);
}
private WatchTimeout();
public static long availableTimeout(long expectedTimeoutMillis, long currentTimeoutMillis);
}
class WatchTimeoutTest {
@T... | assertThat(availableTimeout(1_000, 0)).isEqualTo(1_000);
assertThat(availableTimeout(1_000, 1_000)).isEqualTo(1_000);
assertThat(availableTimeout(MAX_MILLIS, 1_000)).isEqualTo(MAX_MILLIS - 1_000);
assertThat(availableTimeout(MAX_MILLIS + 1_000, 0)).isEqualTo(MAX_MILLIS);
assertTh... |
101735230_1 | class CommunicationsMediatorImpl implements CommunicationsMediator {
@Override
public void transmitData(String data, Direction direction) {
for (DataReceiver dataReceiver : this.subscribers.get(direction)) {
dataReceiver.dataReceived(data);
}
}
public CommunicationsMediato... | final int[] called = new int[1];
called[0] = 0;
DataReceiver receiver1 = new DataReceiver() {
int[] call = called;
@Override
public void dataReceived(String data) {
call[0]++;
}
};
DataReceiver receiver2 = new Data... |
101884957_6 | class NotHerePresenter implements NotHereFragmentContract.Presenter {
@Override
public void onItemClicked(int i) {
ArrayList<OsmObject> intentList = new ArrayList<>();
intentList.add(0, this.alternateList.get(i));
PoiList.getInstance().setPoiList(intentList);
view.startActivity();
}
NotHerePresenter(Not... | notHerePresenter.onItemClicked(0);
verify(view).startActivity();
}
} |
101970978_0 | class AbstractClient {
protected static void init() {
keywordSet.add("-" + HOST_ARGS);
keywordSet.add("-" + HELP_ARGS);
keywordSet.add("-" + PORT_ARGS);
keywordSet.add("-" + PASSWORD_ARGS);
keywordSet.add("-" + USERNAME_ARGS);
keywordSet.add("-" + ISO8601_ARGS);
keywordSet.add("-" + MAX_P... | AbstractClient.init();
String[] keywords = {AbstractClient.HOST_ARGS, AbstractClient.HELP_ARGS,
AbstractClient.PORT_ARGS,
AbstractClient.PASSWORD_ARGS, AbstractClient.USERNAME_ARGS, AbstractClient.ISO8601_ARGS,
AbstractClient.MAX_PRINT_ROW_COUNT_ARGS,};
for (String keyword : keywords... |
101989943_11 | class IconHelper {
public static BufferedImage fillBackground(BufferedImage img, Color color) {
BufferedImage nImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
Graphics2D g = nImg.createGraphics();
g.setColor(color);
g.fillRect(0, 0, nImg.getWidth(), nImg.getHeight());
g.drawImage(im... | assertTrue(IconHelper.fillBackground(IconHelper.createColoredFrame(Color.GREEN).image, Color.GREEN) instanceof BufferedImage);
}
} |
102026692_2 | class EtcdHeartbeatLease implements AutoCloseable {
public Long getLeaseId() {
initLease();
return leaseId;
}
public EtcdHeartbeatLease(Client etcdClient, HeartbeatProperties properties);
public void initLease();
public void revoke();
@Override public void close();
priva... | Client client = Client.builder()
.endpoints(container.clientEndpoint())
.build();
HeartbeatProperties heartbeatProperties = new HeartbeatProperties();
heartbeatProperties.setInterval(5);
EtcdHeartbeatLease heartbeatLease = new EtcdHeartbeatLease(client, he... |
102047648_0 | class Counter extends Applet {
private void getBalance(APDU apdu, byte[] buffer) {
Util.setShort(buffer, (byte) 0, balance);
apdu.setOutgoingAndSend((byte) 0, (byte) 2);
}
private Counter();
public static void install(byte[] buffer, short offset, byte length);
public void process... | assertArrayEquals(new byte[]{0x00, 0x00}, getBalance().getData());
}
} |
102083574_26 | class BrowserBuilder {
static URL findLocalizedResourceURL(String resource, Locale l, IOException[] mal, Class<?> relativeTo) {
URL url = null;
if (l != null) {
url = findResourceURL(resource, "_" + l.getLanguage() + "_" + l.getCountry(), mal, relativeTo);
if (url != null) {... | File zh = new File(dir, "index_zh.html"); zh.createNewFile();
File zhCN = new File(dir, "index_zh_CN.html"); zhCN.createNewFile();
IOException[] mal = { null };
URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class);... |
102093756_64 | class EvoSQLRunner implements QueryRunner {
Result convertResult(nl.tudelft.serg.evosql.Result evoSqlResult) {
return new Result(
evoSqlResult.getInputQuery(),
evoSqlResult.getPathResults().stream()
.filter(pr -> pr.getFixture() != null)
... | Result result = new Result("Select * From table", 0);
result.getPathResults().add(buildPathResult(1));
result.getPathResults().add(buildPathResult(2));
EvoSQLRunner evoSQLRunner = new EvoSQLRunner();
nl.tudelft.serg.evosql.brew.data.Result brewResult = evoSQLRunner.convertResult... |
102096357_1 | class Vector3D {
public static float scalarMultiply(float[] lhs, float[] rhs) {
return lhs[x]*rhs[x] + lhs[y]*rhs[y] + lhs[z]*rhs[z];
}
public static float[] vectorMultiply(float[] lhs, float[] rhs);
public static float distanceVertices(float[] left, float[] right);
public static float vec... | float vec1[] = {1, 0, 0};
float vec2[] = {0, 1, 0};
float res = Vector3D.scalarMultiply(vec1, vec2);
assertTrue(equal(res, 0));
float v3[] = {5, 0, 0};
float v4[] = {3, -1, 0};
res = Vector3D.scalarMultiply(v3, v4);
assertTrue(equal(res, 15));
}
} |
102143456_2 | class ProductEventConsumer extends AbstractKafkaConsumer {
@KafkaListener(topics = "${eventing.topic_name}")
public void listen(final ConsumerRecord<String, String> consumerRecord, final Acknowledgment ack) {
super.handleConsumerRecord(consumerRecord, ack);
}
@Inject protected ProductEventCon... | final ProductEventProcessor processor = mockedProcessor(TEMPORARY_ERROR);
productEventConsumer = new ProductEventConsumer(processor, unprocessableEventService);
productEventConsumer.listen(CONSUMER_RECORD,ack);
verify(ack, never()).acknowledge();
verify(processor).processEvent(a... |
102170678_7 | class ApiVerticle extends AbstractVerticle {
private void getProduct(RoutingContext rc) {
String itemId = rc.request().getParam("itemid");
catalogService.getProduct(itemId, ar -> {
if (ar.succeeded()) {
Product product = ar.result();
if (product != null) ... | doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation){
Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(1);
handler.handle(Future.failedFuture("error"));
return null;
}
}).when(catalogSe... |
102229956_2 | class InboxModel implements InteractionContextSink {
public abstract Map<Identifier, InboxTask> getTasks()public abstract Map<Identifier, InboxTask> getTasks();
}
class InboxModelTest {
@Test
public void givenEmptyModelWhenCreatedTaskThenModelHasTask() {
| // Given
InboxModel model = new InMemoryInboxModel();
// When
List<Event> events = new ArrayList<>();
Identifier id = new Identifier(0);
events.add(new CreatedEvent());
InteractionContext context = new InteractionContext("task", -1, new Date(), Collections.<String, String>emptyMap(), new In... |
102268868_0 | class Version {
public String toString() {
return mMajor + "." + mMinor + "." + mBuild;
}
public Version(String versionString);
public boolean isEqualTo(Version compareVersion);
public boolean isLowerThan(Version compareVersion);
public boolean ishIGHERThan(Version compareVersion);
... | String testVersion = "7.0.0";
Version version = new Version(testVersion);
assertEquals(version.toString(), testVersion);
}
} |
102274375_9 | class JsonBindingExample extends JsonData {
public String annotationPropertiesMapping() {
return JsonbBuilder.create().toJson(magazine);
}
public String serializeBook();
public Book deserializeBook();
public String serializeListOfBooks();
public List<Book> deserializeListOfBooks();
... | JsonBindingExample jsonBindingExample = new JsonBindingExample();
String result = jsonBindingExample.annotationPropertiesMapping();
assertThat(result).isEqualToIgnoringCase(expectedMagazine);
}
} |
102328857_0 | class BaseActionImpl {
public BaseActionImpl() {
}
public BaseActionImpl();
public BaseActionImpl(InferenceConfigDefinition kpiDefinition);
protected abstract void execute();
protected String getEsQueryWithDates(JobSchedule schedule, String esQuery);
protected void executeNeo4jGraphQuery();
protected Map<... | assertEquals("AVERAGE",ExecutionActions.AVERAGE.toString());
}
} |
102341886_2 | class Reader {
public static void read(Swagger swagger, Set<Class<?>> classes) {
final Reader reader = new Reader(swagger);
for (Class<?> cls : classes) {
final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false,
new ArrayList<String>(), new ArrayList<String>(), new ArrayList<Str... | @Test
public void testApplyParameters(){
Swagger swagger = new Swagger();
Reader.read(swagger, new HashMap<Class<?>, Object>(){{
put(InterfaceServiceTest.class, new InterfaceServiceImplTest());
}}, "/h");
// System.out.println(Json.pretty(swagger));
Map<String, Path> paths = swagger.getPaths();
Asser... |
102415104_0 | class HomePresenter extends BasePresenter<HomeContract.View> implements HomeContract.Presenter {
@Override
public void fetchUsers() {
if (this.getView() != null) {
this.getView().onLoading(true);
this.addDisposable(mRepository.fetchUsers(this.getView().getPage()).
... | mPresenter.fetchUsers();
verify(mRepository, times(1)).fetchUsers(2);
}
} |
102444259_0 | class WsProducer extends DefaultProducer {
public static void sendMessage(WebSocket webSocket, String msg, boolean streaming) {
if (streaming && msg.length() > STREAM_BUFFER_SIZE) {
int p = 0;
while (p < msg.length()) {
if (msg.length() - p < STREAM_BUFFER_SIZE) {
webSocket.sendCont... | var wsMockHelper = new WebSocketMockHelper();
// var producerMockDefault = getProducerMock(wsMockHelper, false);
// var producerMockStreaming = getProducerMock(wsMockHelper, true);
getTestByteArrayStream().forEach(bytes -> {
try {
WsProducer.sendMessage(wsMockHe... |
102452115_247 | class Tileable implements Entity {
public boolean isReleasable(Direction direction, Marble marble) {
if (tile == null) {
throw new IllegalStateException(TILEABLE_UNPLACED);
}
Tile neighbour = tile.get(direction);
return neighbour != null && neighbour.getTileable().accep... | Tileable tileable = grid.get(0, 1).getTileable();
assertThat(tileable.isReleasable(Direction.RIGHT, marble)).isFalse();
}
} |
102471968_31 | class CreditDraftMapper implements Function<CreditDraftRaw, CreditDraft> {
@Override
@SuppressWarnings("ConstantConditions")
public CreditDraft apply(@NonNull final CreditDraftRaw raw) throws Exception {
assertEssentialParams(raw);
return CreditDraft.builder()
.id... | CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder()
.status("UNEXPECTED")
.build();
CreditDraft draft = mapper.apply(raw);
assertThat(draft.status()).isEqualTo(CreditDraftStatus.UNE... |
102596286_136 | class PsbAppServiceIdGenerator {
public static Map<String, String> generatePsbAppServiceIdsByAppSvcName(
final String appInstanceName,
final Set<String> appServiceNames,
int psbMaxAppIdLength) {
Map<String, String> psbAppServiceIds =
new HashMap<>(appServ... | Map<String, String> ret = PsbAppServiceIdGenerator.generatePsbAppServiceIdsByAppSvcName(
"cool app",
new HashSet<>(
Arrays.asList("svc a", "svc b", "svc c")),
12 + 11
);
ret.values().forEach(s -> Assert.assertTrue(s + " too... |
102608940_2 | class PortfolioServiceImpl implements PortfolioService {
@Override
public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) {
if (amount <= 0) {
resultHandler.handle(Future.failedFuture("Cannot buy " + quote.getString("name") + " - the amount must be " +
... | Async async = tc.async();
service.buy(100, quote("A", 10, 20, 10), ar -> {
tc.assertTrue(ar.failed());
tc.assertTrue(ar.cause().getMessage().contains("not enough stocks"));
async.complete();
});
}
} |
102874275_21 | class ShaclSailFactory implements SailFactory {
@Override
public Sail getSail(SailImplConfig config) throws SailConfigException {
if (!SAIL_TYPE.equals(config.getType())) {
throw new SailConfigException("Invalid Sail type: " + config.getType());
}
ShaclSail sail = new ShaclSail();
if (config instanceof ... | ShaclSailConfig config = new ShaclSailConfig();
ShaclSail sail = (ShaclSail) subject.getSail(config);
assertMatchesConfig(sail, config);
}
} |
102874374_19 | class Federate extends ConsoleCommand {
@Override
public void execute(String... parameters) throws IOException {
if (parameters.length < 4) {
consoleIO.writeln(getHelpLong());
} else {
LinkedList<String> plist = new LinkedList<>(Arrays.asList(parameters));
plist.remove(); // "federate"
boolean distin... | execute(MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID2);
verifyFailure(MEMORY_MEMBER_ID1 + " already exists.");
}
} |
102955709_23 | class AsperaFaspManagerWrapper {
public long startTransfer(final String xferId, final String transferSpecStr) {
log.info("Starting transfer with xferId [" + xferId + "]");
if (log.isDebugEnabled()) {
log.debug("Transfer Spec for Session with xferId [" + xferId + "]");
log.debug(AsperaTransferManagerUti... |
PowerMockito
.when(
TransferListener.getInstance(null, null)
).thenReturn(mockTransferListener);
PowerMockito
.when(
faspmanager2.startTransfer(anyString(), isNull(String.class), anyString(), any(TransferListener.class))
).thenReturn(3L);
when(mockLog.isDebugEnabled()).thenReturn(false)... |
102960162_2 | class RouteSimilarity {
public String getRouteString() {
return routeString;
}
public RouteSimilarity(RouteData routeData, String currentRoute);
public RouteSimilarity(String url, String currentRouteParts);
private int calculateSimilarity(String url, String currentRoute);
public Rou... | String[] urls = new String[]{
"navigation/view2",
"navigation2/view1",
"navigation/view1",
"navigation/view4",
"navigation/view5",
"navigation/view6",
"navigation/view7",
"navigation/v... |
103009179_4 | class SmartOpenIdController extends DelegateController implements Serializable {
@Override
public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) {
final String openIdMode = request.getParameter(OpenIdConstants.OPENID_MODE);
if (StringUtils.equals(openIdM... | request.addParameter("openid.mode", "associate");
final boolean canHandle = smartOpenIdController.canHandle(request, response);
request.removeParameter("openid.mode");
assertEquals(true, canHandle);
}
} |
103023961_0 | class CompositionBundle implements Bundle {
private static Function composition(Context context) {
return args -> {
final Composition composition;
switch (args.length) {
case 0:
composition = new Composition();
break;
... | final var context = new Context();
BundleLoader.loadSingle(context, CompositionBundle.class);
assertThat(context.functions(), hasKey("composition"));
assertThat(context.composition(), nullValue());
assertThat(context.variables(), allOf(
not(hasKey("Width")),
... |
103027757_19 | class ShadowResources {
public String getPackageName() {
if (!TextUtils.isEmpty(mPackageName)) {
return mPackageName;
}
String manifestPath = null;
// AndroidManifest.xml 可能目录(不同gradle版本,不同目录,蛋疼)
List<String> manifestPaths = Arrays.asList(
"buil... | Assert.assertEquals("net.yui", resources.getPackageName());
}
} |
103109633_0 | class SpansToDependencyLinks implements Function<Iterable<Span>, Iterable<Dependency>> {
protected Optional<Dependency> sharedSpanDependency(Set<Span> sharedSpans) {
String clientService = null;
String serverService = null;
for (Span span: sharedSpans) {
for (KeyValue tag: span.... | SpansToDependencyLinks spansToDependencyLinks = new SpansToDependencyLinks("");
Set<Span> sharedSpans = new HashSet<>();
sharedSpans.add(createSpan("clientName", Tags.SPAN_KIND_CLIENT));
sharedSpans.add(createSpan("serverName", Tags.SPAN_KIND_SERVER));
Optional<Dependency> result... |
103139287_0 | class HelloWorldController {
@RequestMapping("/")
public String sayHello() {
return "Hello,World!";
}
@PostMapping(value = "/request_param") public String requestParam(@RequestParam(value = "name") String name);
@PostMapping(value = "/request_body") public UserInfo requestBody(@RequestPara... | assertEquals("Hello,World!",new HelloWorldController().sayHello());
}
} |
103151406_0 | class OpenhabSseConnection extends SseConnection implements SseConnection.ISseDataListener {
@Override
protected String buildUrl() {
return mUrl + "/rest/events?topics=" + buildTopic();
}
OpenhabSseConnection();
void addItemValueListener(IStateUpdateListener l);
public void removeI... | OpenhabSseConnection c = new OpenhabSseConnection();
c.setServerUrl("URL");
c.setItemNames("cmdName");
assertEquals("URL/rest/events?topics=smarthome/items/cmdName/command", c.buildUrl());
c.setItemNames("cmdName","item1", "item2");
assertEquals("URL/rest/events?topics=s... |
103155862_90 | class JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse {
public List<JSON2DSources> getSources() {
return sources;
}
JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request);
private Double[][] constructMetric(float[] table, MatrixResult result);
pu... | Assert.assertEquals(3, durationsMatrixResponse.getSources().size());
Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, durationsMatrixResponse.getSources().get(0).getLocation());
}
} |
103232734_56 | class BundleHelper {
static void putNumberParam(Bundle bundle, String key, String number) {
String[] types = {"int", "long", "double", "float"};
boolean found = false;
for (String type : types) {
try {
if (type.equals("int") && !number.toLowerCase().endsWith("l")... | // Given
Bundle bundle = new Bundle();
String intKey = "int";
String intValue = "3";
String longKey = "long";
String longValue = "8L";
String longKey2 = "long2";
String longValue2 = "" + Long.MAX_VALUE;
String doubleKey = "double";
String d... |
103259097_1 | class LoginPresenter extends BasePresenter<Contract.View> implements Contract.Presenter {
@Override
public boolean isLogined() {
return KeyManager.getToken() != null;
}
public LoginPresenter(Contract.View view);
@Override public void attachView();
private void init();
@Override p... | KeyManager.clear();
Assert.assertEquals(
false,
presenter.isLogined()
);
}
} |
103286363_0 | class ResourceBundleService extends TranslationService {
@Override
public String translate(String key) {
return rb.getString(key);
}
public ResourceBundleService(ResourceBundle rb);
public void changeLocale(ResourceBundle newValue);
private final ResourceBundle rbEN;
private fin... | ResourceBundleService rbs = new ResourceBundleService(rbEN);
Assert.assertEquals("Test Form", rbs.translate("form_title"));
try {
rbs.translate("non_existing");
fail();
} catch (MissingResourceException ignored) {}
}
} |
103328683_2 | class MessageDecryptVerifier {
public static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts) {
if (isPartEncryptedOrSigned(part)) {
return part;
}
Part foundPart;
foundPart = findPrimaryPartInAlternative(part);
if (foundPart != nul... | List<Part> outputExtraParts = new ArrayList<>();
BodyPart pgpInlinePart = bodypart("text/plain", PGP_INLINE_DATA);
Message message = messageFromBody(
multipart("mixed",
pgpInlinePart,
bodypart("application/octet-stream")
... |
103377081_14 | class StringCalculator {
public int add(String input) {
if ("".equals(input))
return 0;
String delimiter = extractDelimiter(input);
String[] numberArray = extractNumbers(input, delimiter);
return sumNumberArray(numberArray);
}
private String[] extractNumbers(String input, String delimi... |
Assert.assertEquals(3, this.calculator.add("1,2,1001"));
}
} |
103384901_13 | class DataUtils implements Serializable {
public static List<String> parseStringList(Object object) {
if (object == null) {
return null;
}
return Splitter.onPattern("(?:\r?\n)+")
.splitToList(object.toString())
.stream()
.map(Strin... | assertEquals(Lists.newArrayList("\\?.*$-->>", "a-->>b"),
DataUtils.parseStringList("\\?.*$-->>\na-->>b\r\r\n\n"));
}
} |
103464837_5 | class JsonUtil {
public static Map<String, String> getJsonPathsForTemplating(Set<Map.Entry<String, JsonElement>> root) {
Map<String, String> paths = new HashMap<>();
searchJsonForTemplate(root, paths, "$");
return paths;
}
private JsonUtil(/* empty */);
public static boolean ... | String template = "{ \"a\" : { \"b\": \"{{value}}\", \"c\": { \"b\": \"{{value}}\"}}, \"c\": { \"b\": \"{{value}}\"}, \"num\": 343, \"bool\": true}";
JsonObject document = (JsonObject) new JsonParser().parse(template);
Map<String, String> paths = JsonUtil.getJsonPathsForTemplating(document);
... |
103522601_0 | class ByteCode {
public static void printOpCode(InstructionHandle insHandle, ConstantPoolGen cpg) {
System.out.print("[" + String.format("%02d", insHandle.getPosition()) + "] ");
printOpCode(insHandle.getInstruction(),cpg);
}
public static void printOpCode(Instruction ins, ConstantPoolGen ... | PrintStream sysOut = mock(PrintStream.class);
System.out.println("Sysout hijack!");
PrintStream oldPrintStream = System.out;
try {
System.setOut(sysOut);
InvokeInstruction ins = mock(InvokeInstruction.class);
ConstantPoolGen cpg = mock(ConstantPoolG... |
103558693_18 | class CategorySpecifications {
public Specification<Category> byUser(User user) {
return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get(Category_.masterCategory).get(MasterCategory_.user), user);
}
@Autowired
private CategorySpecifications testSubject;
@Autowired
priv... | User user = userRepository.save(new User("Bob", "€"));
MasterCategory mcMonthly = masterCategoryRepository.save(new MasterCategory().setName("Monthly").setUser(user));
MasterCategory mcSavings = masterCategoryRepository.save(new MasterCategory().setName("Savings").setUser(user));
catego... |
103560333_112 | class RewardRiskRatioCriterion extends AbstractAnalysisCriterion {
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
}
@Override public Num calculate(BarSeries series, TradingRecord tradingRecord);
@Overri... | AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(3.5), numOf(2.2)));
assertFalse(criterion.betterThan(numOf(1.5), numOf(2.7)));
}
} |
103613782_3 | class RootController {
@RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String rootRedirect() {
return "index";
}
@Autowired
private TestRestTemplate restTemplate;
@Value("${custom.baseurl}")
private String baseurl;
private static final Logger logger;
}
class... | ResponseEntity<String> result = restTemplate.exchange("/",
HttpMethod.GET, new HttpEntity(null), String.class);
logger.info(result.toString());
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}
} |
103630840_15 | class TeamService {
public List<UserTeam> listUserTeamsAgree(Team team) throws ShepherException {
if (team == null) {
throw ShepherException.createIllegalParameterException();
}
return userTeamBiz.listByTeam(team.getId(), Status.AGREE);
}
@Transactional public boolean c... | long teamId = 1;
Team team = teamService.get(teamId);
List<UserTeam> applies = teamService.listUserTeamsAgree(team);
Assert.assertNotNull(applies);
Assert.assertEquals(3, applies.size());
}
} |
103653841_10 | class FsMountPoint implements Serializable, Comparable<FsMountPoint> {
public URI toHierarchicalUri() {
final URI hierarchical = this.hierarchical;
return null != hierarchical
? hierarchical
: (this.hierarchical = uri.isOpaque()
? path.toHierarchi... | for (final String[] params : new String[][] {
{ "foo:bar:baz:/x/bö%20m?plö%20k!/bä%20g?zö%20k!/", "baz:/x/bö%20m/bä%20g?zö%20k" },
{ "foo:bar:baz:/x/bööm?plönk!/bäng?zönk!/", "baz:/x/bööm/bäng?zönk" },
{ "foo:bar:baz:/boom?plonk!/bang?zonk!/", "baz:/boom/bang?zonk" },
... |
103700346_53 | class EventRestController {
@ApiOperation(value = "This API returns Latest Events per Scenario present in Elastic Search for given App Name", response = ResponseEntity.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Returned Latest Events per Scenario for given App Name"),
@ApiResponse(code = 4... | setSecuirtyContext(TEAMNAME, USERNAME);
EventRecorder eventRecorder = createEvent(TEAMNAME);
EventRecorder eventSecondRecorder = createEvent(TEAMNAME);
TeamUser teamUser = createTeamUserObject(USERNAME, TEAMNAME);
List<EventRecorder> events = new ArrayList<>();
events.add(eventRecorder);
events.add(event... |
103764705_39 | class Primality {
public static boolean isPrime(int x) {
if (x <= 1) {
return false;
}
int i = 2;
while (i <= x && x % i != 0) {
i++;
}
return i == x;
}
}
class PrimalityTest {
@Test
public void checkSomePrimeNumbers() {
| int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109,
113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191,
193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269,
271, 277, 281, 283,... |
104092353_0 | class TomcatVersionValidator extends ValidatorBase implements IConstants, IConfigKeys {
public static String getTomcatVersion(String serverInfo) {
String result = null;
if (serverInfo != null && !serverInfo.isEmpty()) {
Debug.log("TomcatVersionValidator.getTomcatVersion() - validating... |
Assert.assertEquals(IConstants.TOMCAT_VER_60, TomcatVersionValidator.getTomcatVersion(VMWARE_TOMCAT6_SERVERINFO));
Assert.assertEquals(IConstants.TOMCAT_VER_60, TomcatVersionValidator.getTomcatVersion(WINDOWS_TOMCAT6_SERVERINFO));
Assert.assertEquals(IConstants.TOMCAT_VER_60, TomcatVersionValid... |
104094274_11 | class RdfObjectLoader {
public static <T> Set<T>
load(
Function<Model, Set<Resource>> resourceSelector,
Class<T> clazz,
Model model
) {
return load(resourceSelector, clazz, model, m -> m, c -> {}, m -> {});
}
private RdfObjectLoader();
public static Set<T> load(
Function<Model, Set<Resourc... |
Set<Person> people = RdfObjectLoader.load(selectAllResources, Person.class, model);
assertThat("", people, hasSize(8));
}
} |
104249541_2 | class CheckInfo {
@CheckingMethodType
public int getTypeCheck() {
return mTypeCheck;
}
public CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck);
@Nullable public Boolean getState();
public void setState(@Nullable Boolean state);
public void setTypeCheck(int typ... | checkInfo.setTypeCheck(CH_TYPE_HOOKS);
assertEquals(checkInfo.getTypeCheck(), CH_TYPE_HOOKS);
}
} |
104262301_52 | class JWTService {
public long getRTokenExpirationTime() {
// expiration time should come in seconds, that's why the * 1000 and extra-zeros for 2592000 seconds
return sc.getRTokenExpirationTime() > 0
? (sc.getRTokenExpirationTime() * THOUSAND)
: DEFAULT_REFRESH_TOKEN... | long prev = Long.parseLong(String.valueOf(ReflectionTestUtils.getField(sc, "rTokenExpirationTime")));
final long expTime = -10;
ReflectionTestUtils.setField(sc, "rTokenExpirationTime", expTime);
assertTrue("Expiration time for refresh token must be greater than zero",
jwt... |
104490112_1 | class ECKeyStore {
public void changePassword(char[] password) throws KeyStoreException {
try {
for (String alias : Collections.list(ks.aliases())) {
Entry entry = ks.getEntry(alias, new PasswordProtection(this.password)); // read
ks.setEntry(alias, entry, new Pa... | ECKeyStore ks = new ECKeyStore();
PrivateKey k1 = PrivateKey.fresh(NetworkType.TESTNET);
// add a key
String alias1 = ks.addKey(k1);
// change password
ks.changePassword("test".toCharArray());
// retrieve the key
PrivateKey k2 = ks.getKey(ECKeyStore.get... |
104512497_44 | class DeviceBatteryMetricsCollector extends SystemMetricsCollector<DeviceBatteryMetrics> {
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(DeviceBatteryMetrics snapshot) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
snapshot.batteryLevelPct = getBatteryLevel(getBat... | ShadowSystemClock.setElapsedRealtime(5000);
when(mContext.registerReceiver(
Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
.thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 20, 100));
DeviceBatteryMetrics metrics = new DeviceBatteryMetr... |
104516152_0 | class PomHelper {
public static boolean updatePomVersions(List<PomUpdateStatus> pomsToChange, List<DependencyVersionChange> changes) throws IOException {
Map<String, String> propertyChanges = new TreeMap<>();
for (PomUpdateStatus status : pomsToChange) {
status.updateVersions(changes, p... | File outDir = Tests.copyPackageSources(getClass());
LOG.info("Updating poms in " + outDir);
File[] files = outDir.listFiles();
assertNotNull("No output files!", files);
assertTrue("No output files!", files.length > 0);
List<PomUpdateStatus> pomsToChange = new ArrayList... |
104670115_42 | class CamelSinkFactory implements SinkFactory {
@Override public String name() {
return "camel";
}
@Override public Single<Sink<T>> create(Vertx vertx, String name, Config config);
private Vertx vertx;
}
class CamelSinkFactoryTest {
private Vertx vertx;
@Test
public void testName() {
| CamelSinkFactory factory = new CamelSinkFactory();
assertThat(factory.name()).isEqualTo("camel");
}
} |
104705553_29 | class ObjectMapperJsonSerializer implements JsonSerializer {
@Override
public <T> T clone(T object) {
if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializable)) {
... | List<NonSerializableObject> original = new ArrayList<>();
original.add(new NonSerializableObject("value"));
List<NonSerializableObject> cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
}
} |
104718236_8 | class DBAuthenticator implements IAuthenticator {
@Override
public synchronized boolean checkValid(String clientId, String username, byte[] password) {
// Check Username / Password in DB using sqlQuery
if (username == null || password == null) {
LOG.info("username or password was nu... | final DBAuthenticator dbAuthenticator = new DBAuthenticator(
ORG_H2_DRIVER,
JDBC_H2_MEM_TEST,
"SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
SHA_256);
assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes()));
}
} |
104718330_8 | class SmartOpenIdController extends DelegateController implements Serializable {
@Override
public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) {
String openIdMode = request.getParameter("openid.mode");
if (openIdMode != null && openIdMode.equals("assoc... | request.addParameter("openid.mode", "anythingElse");
boolean canHandle = smartOpenIdController.canHandle(request, response);
request.removeParameter("openid.mode");
assertEquals(false, canHandle);
}
} |
104770714_18 | class Properties {
public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) {
whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue()));
}
private Properties();
public static P newPropertyWithCallback(Supplier<P> propertyFactory... | final Property<Object> valuedProp = new SimpleObjectProperty<>(new Object());
final Property<Object> listener = new SimpleObjectProperty<>();
whenPropertyIsSet(valuedProp, listener::setValue);
assertThat(listener.getValue()).isEqualTo(valuedProp.getValue());
}
} |
104872758_8 | class SystemPropertyListBuilder {
public String build(String type, String key, String value){
StringBuilder sb = new StringBuilder();
sb.append("-D");
sb.append(type);
sb.append('.');
sb.append(key);
sb.append('=');
sb.append(value);
return sb.toString();
}
private SystemPropertyListBuilder builder... | assertEquals("-Dprefix.key=null",builderToTest.build("prefix", "key",null));
}
} |
104883492_14 | class SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao {
@Override
public List<SeasonData> fetchAllByYear(Integer year) {
List<SeasonData> ret = null;
String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?";
Object[] args = { year };
// Run the query
ret = get... | log.info("*** BEGIN Test ***");
Integer year = 2017;
List<SeasonData> results = classUnderTest.fetchAllByYear(year);
assertEquals(68, results.size());
log.info("*** END Test ***");
}
} |
104889165_120 | class GbifJsonConverter {
public static String toStringPartialJson(SpecificRecordBase... records) {
return toPartialJson(records).toString();
}
public static ObjectNode toJson(SpecificRecordBase... records);
public static ObjectNode toPartialJson(SpecificRecordBase... records);
public static String toSt... |
// Expected
String expected = "{\"id\":\"777\"}";
// State
MultimediaRecord record = MultimediaRecord.newBuilder().setId("777").build();
// When
String result = GbifJsonConverter.toStringPartialJson(record);
// Should
assertEquals(expected, result);
assertTrue(JsonValidationUtils... |
104974693_54 | class SessionService implements IService, IInputTranslator {
public Session open(IOFSwitch sw) {
return open(new MessageContext(), sw);
}
public Session open(MessageContext context, IOFSwitch sw);
@Override public void setup(FloodlightModuleContext moduleContext);
@Override public Command ... | IOFSwitch sw = createMock(IOFSwitch.class);
setupSwitchMock(sw, dpId);
swWriteSecondFail(sw);
doneWithSetUp(sw);
CompletableFuture<Optional<OFMessage>> future = null;
try (Session session = subject.open(context, sw)) {
future = session.write(makePacketOut(sw.... |
104984928_109 | class ConnectorsResource {
@POST
@Path("/{connector}/restart")
public void restartConnector(final @PathParam("connector") String connector,
final @QueryParam("forward") Boolean forward) throws Throwable {
FutureCallback<Void> cb = new FutureCallback<>();
her... | final Capture<Callback<Void>> cb = Capture.newInstance();
herder.restartConnector(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb));
String ownerUrl = "http://owner:8083";
expectAndCallbackException(cb, new NotAssignedException("not owner test", ownerUrl));
EasyMock.expect(Rest... |
104999768_0 | class CarManufacturer {
public Car manufactureCar(Specification spec) {
Car car = carFactory.createCar(spec);
entityManager.merge(car);
return car;
}
@InjectMocks
private CarManufacturer testObject;
@Mock
private CarFactory carFactory;
@Mock
private EntityManage... | Specification spec = new Specification();
Car car = new Car(spec);
when(entityManager.merge(any())).then(a -> a.getArgument(0));
when(carFactory.createCar(any())).thenReturn(car);
assertThat(testObject.manufactureCar(spec)).isEqualTo(car);
verify(carFactory).createCar(... |
105010160_279 | class Entities {
static String unescape(String string) {
return unescape(string, false);
}
private Entities();
public static boolean isNamedEntity(final String name);
public static boolean isBaseNamedEntity(final String name);
public static Character getCharacterByName(String name);
... | String text = "⨔ 𝔮";
String un = "⨔ \uD835\uDD2E"; // 𝔮
assertEquals(un, Entities.unescape(text));
}
} |
105032211_6 | class DefaultProviderDataAccessor implements ProviderDataAccessor {
@Override
@Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
public List<ProviderUserModel> getUsersByProviderConfigId(Long providerConfigId) {
if (null == providerConfigId) {
return List.of();
... | ProviderUserEntity providerUserEntity = new ProviderUserEntity(projectOwnerEmail, true, 1L);
ProviderProjectRepository providerProjectRepository = Mockito.mock(ProviderProjectRepository.class);
ProviderUserRepository providerUserRepository = Mockito.mock(ProviderUserRepository.class);
... |
105079548_0 | class linkedList {
public linkedList()
{
start = null;
end = null;
size = 0;
}
public linkedList();
public boolean isEmpty();
public int getSize();
public void insertAtStart(int val);
public void insertAtEnd(int val);
public void insertAtPos(int val , int ... | LinkedList<Integer> intList = new LinkedList<Integer>();
assertTrue(intList.add(1));
assertTrue(intList.add(2));
assertEquals(new Integer(1), intList.head());
assertEquals(new Integer(2), intList.tail());
assertTrue(intList.add(3));
assertEquals(new Integer(3), intList.tail());
assertEquals(3, intList.s... |
105089121_1005 | class Utils {
public static String resolvePassword( VariableSpace variables, String password ) {
String resolvedPassword = variables.environmentSubstitute( password );
if ( resolvedPassword != null ) {
// returns resolved decrypted password
return Encr.decryptPasswordOptionallyEncrypted( resolved... | String password = "password";
// is supposed the password stays the same
assertSame( password, Utils.resolvePassword(
Variables.getADefaultVariableSpace(), password ).intern() );
}
} |
105094044_21 | class ChainContainer implements Cloneable {
public boolean rollback(Block block) {
int length = chain.getAllBlockList().size();
if (block == null || length == 0) {
return false;
}
Block bestBlock = chain.getBestBlock();
if (!block.getHeader().getHash().equals(bes... | testAddAgent();
assertEquals(chainContainer.getCurrentRound().getMemberCount(), 2);
for (int i = 3; i > 0; i--) {
Block bestBlock = chainContainer.getBestBlock();
boolean success = chainContainer.rollback(bestBlock);
assert (success);
}
assert... |
105104598_8 | class HumidityNotification implements BluetoothNotification<byte[]> {
@Override
public void run(byte[] bytes) {
float temperature = decodeTemperature(bytes[1], bytes[0]);
float humidity = decodeHumidity(bytes[3], bytes[2]);
SensorLog sensorLog = new SensorLog(config.getId(), ImmutableM... | Faker faker = new Faker();
// Really this should be between 0 and 100... but yet again, I don't get Java bytes
double humidity = faker.number().randomDouble(4, 0, 50);
int humidityNorm = (int)(humidity * 65536 / 100);
// -40 + (165 * ((msb << 8) | (lsb & 0xff)) / 65536.0f)
... |
105110479_3 | class JavaBeanBinder extends BeanBinder {
@Override
public <T> T bind(final PropertyName name, final BindData<T> target, final Binder.Env env, final PropertyBinder propertyBinder) {
boolean hasKnownBindableProperties = env.getSource().containsDescendantOf(name);
Bean<T> bean = Bean.get(target, ... | String name = "hmily.yml";
Map<String, Object> map = new HashMap<>();
map.put("hmily.stringTest", 123);
map.put("hmily.integerTest", "123");
map.put("hmily.doubleTest", "123");
map.put("hmily.longTest", "123");
map.put("hmily.chartTest", "A");
map.put("hmi... |
105195850_1 | class GenericWindowing implements Windowing {
@Override
public long getFirstContainingTime(long Tl, long Tr, long T) {
assert 0 <= Tl && Tl <= Tr && Tr < T;
long l = T-1 - Tr, r = T-1 - Tl, length = Tr - Tl + 1;
if (!addWindowsUntilLength(length)) {
return -1;
}
... | GenericWindowing exp = new GenericWindowing(new ExponentialWindowLengths(2));
assertEquals(101, exp.getFirstContainingTime(98, 99, 100));
assertEquals(103, exp.getFirstContainingTime(96, 99, 100));
assertEquals(107, exp.getFirstContainingTime(92, 99, 100));
assertEquals(115, exp.... |
105200994_7 | class WorldLoader {
@Nullable
public static Location worldlessBlockLocationFromConfig(@NotNull ConfigurationSection conf) {
try {
int x = Integer.parseInt(conf.getString(X));
int y = Integer.parseInt(conf.getString(Y));
int z = Integer.parseInt(conf.getString(Z));
... |
YamlConfiguration conf = new YamlConfiguration();
conf.set(WorldLoader.X, 4);
conf.set(WorldLoader.Y, 0);
conf.set(WorldLoader.Z, -4);
Location loc = WorldLoader.worldlessBlockLocationFromConfig(conf);
Assert.assertNotNull(loc);
}
} |
105203803_1 | class MainPresenter extends BaseTypedPresenter<String, Throwable> {
@Override
public void onViewResumed() {
getView().showData("This is some awesome data");
getView().showError(new RuntimeException("Exceptional Error"));
}
MainPresenter(ITypedView<String, Throwable> view);
@Mock... | mPresenter.onViewResumed();
verify(mView).showError(any(Throwable.class));
}
} |
105218129_201 | class JDKImperativeDeckOfCardsAsSortedSet {
public SortedSet<Card> spades()
{
return this.cardsBySuit.get(Suit.SPADES);
}
public JDKImperativeDeckOfCardsAsSortedSet();
private SortedSet<Card> buildCardsAsSortedSet();
private Map<Suit, SortedSet<Card>> buildCardsAsMapBySuit();
pub... | Assert.assertEquals(13, this.jdkDeck.spades().size());
Assert.assertTrue(Iterate.allSatisfy(this.jdkDeck.spades(), Card::isSpades));
}
} |
105238970_124 | class UpdateRequestLastModifiedDateOnFundedHandler {
@EventListener
public void handle(final RequestFundedEvent event) {
final Request request = requestRepository.findOne(event.getRequestId())
.orElseThrow(() -> new RuntimeException("Unable to find reque... | final long requestId = 6578L;
final RequestFundedEvent event = RequestFundedEvent.builder().requestId(requestId).build();
final Request request = RequestMother.fundRequestArea51()
.withLastModifiedDate(LocalDateTime.now().minusWeeks(3))
... |
105269391_1 | class KafkaMetricsSet implements MetricSet {
public Boolean connectionToKafkaTopicsIsSuccess() {
if (nonNull(metricTopics) && nonNull(connectionTimeoutTopic)) {
StopWatch executionTime = StopWatch.createStarted();
DescribeTopicsOptions describeTopicsOptions = new DescribeTopicsOptio... | KafkaMetricsSet kafkaMetricsSet = initKafkaMetricSet();
kafkaEmbedded.destroy();
assertFalse(kafkaMetricsSet.connectionToKafkaTopicsIsSuccess());
}
} |
105288171_6 | class LazyModuleLoader {
public synchronized Class loadModule(String moduleName, String className)
throws LazyLoadingException {
try {
return mLoaderAlgorithm.loadModule(moduleName, className);
} catch (Throwable t) {
throw new LazyLoadingException(t);
}
}
public LazyModuleLoader(... | // given
Mockito.when(mModulePathsNo1Mock.containsNativeLib()).thenReturn(true);
Mockito.when(mModulePathsNo1Mock.getNativeLibsDirectory()).thenReturn(mNativeLibsDirectoryMock);
// when
Class returnedClass = mObjectUnderTest.loadModule(MODULE_NAME_NO1, LazyModule.class.getName());
// then
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.