id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
123788136_10 | class Interval {
public boolean isEmpty() {
return this.start >= this.end;
}
private Interval(int start, boolean startInclusive, int end, boolean endInclusive);
public static Interval ofOpenOpen(int start, int end);
public static Interval ofOpenClosed(int start, int end);
public static Interval ofCl... | assertTrue(Interval.ofOpenOpen(0, 0).isEmpty());
assertFalse(Interval.ofClosedClosed(0, 0).isEmpty());
assertFalse(Interval.ofClosedOpen(0, 1).isEmpty());
assertTrue(Interval.ofOpenClosed(1, 0).isEmpty());
}
} |
123808995_14 | class MergeBasicProcessorOptions extends ProcessorOptions {
public MergeBasicProcessorOptions() {
}
public MergeBasicProcessorOptions();
public MergeBasicProcessorOptions(MergeBasicProcessorOptions other);
public MergeBasicProcessorOptions(ProcessorOptions other);
public MergeBasicProcess... | new MergeBasicProcessorOptionsConverter();
String badStr = "{\"name\": 10, \"type\": 20, \"fields\": false}";
String optStr = "{\"instances\":1,\"name\":\"name\",\"type\":\"type\",\"defaultCapacity\":100,\"onFlush\":{},\"operations\":{}}";
ProcessorOptions optPump = new ProcessorOption... |
123822761_2 | class VertxVaadinContext implements VaadinContext {
@Override
public <T> T getAttribute(Class<T> type, Supplier<T> defaultValueSupplier) {
T result = context.get(type.getName());
if (result == null && defaultValueSupplier != null) {
result = defaultValueSupplier.get();
c... | String value = context.getAttribute(String.class);
Assert.assertNull(value);
}
} |
123949037_0 | class CloudProvider {
public String getName() {
return this.name;
}
public CloudProvider(String providerName, Integer limitOfVMs, String runtimeConnectorClass, String connectorJarPath,
String connectorMainClass, Map<String, String> connectorProperties);
public void addCloudImage(Clou... | Map<String, String> properties = new HashMap<>();
CloudProvider cp = null;
try {
cp = new CloudProvider(PROVIDER_NAME, 0, RUNTIME_CONNECTOR, null, null, properties);
} catch (Exception e) {
fail("Could not create the Cloud Provider");
return;
}... |
123960848_6 | class AllowListMetricFilter extends SimpleRegexMetricFilter {
@Override
public boolean isAllowed(Metric metric) {
return allowList.stream()
.anyMatch(filter -> super.filterMatches(filter, metric));
}
public AllowListMetricFilter(List<String> allowList);
@Override public S... | List<String> allowList = Lists.newArrayList();
allowList.add("*pcs*");
AllowListMetricFilter filter = new AllowListMetricFilter(allowList);
Assert.assertTrue(filter.isAllowed(metric("some.pcs.metric")));
Assert.assertTrue(filter.isAllowed(metric("pcs.metric")));
Assert.assertTrue(filter.isAllowed(metric("me... |
123970806_41 | class CryptoCompareClientService {
public CryptoCompareResponseDTO getHistorical(CryptoCompareCurrency fromCurrency, List<CryptoCompareCurrency> toCurrency, long timeInSecond) throws Exception {
CryptoCompareResponseDTO cryptoCompareResponseDTO = restTemplate.getForObject(
getPriceHistorica... | CryptoCompareConversionRateResponse rateResponseUSD = new CryptoCompareConversionRateResponse(CryptoCompareCurrency.USD, new BigDecimal(401.25));
CryptoCompareConversionRateResponse rateResponseBTC = new CryptoCompareConversionRateResponse(CryptoCompareCurrency.BTC, new BigDecimal(0.0056));
Cryp... |
124004218_29 | class FileSystemUtil {
public static List<FileStatus> listAll(FileSystem fs, Path path, boolean recursive, PathFilter... filters) throws IOException {
List<FileStatus> statuses = new ArrayList<>();
listAll(fs, path, recursive, statuses, mergeFilters(filters));
return statuses;
}
public static List<F... | List<FileStatus> statuses = FileSystemUtil.listAll(fs, new Path(base, "a"), true, new PathFilter() {
@Override
public boolean accept(Path path) {
return path.getName().endsWith("a") || path.getName().endsWith(".txt");
}
});
assertEquals("Directory and file count should match", 7, s... |
124063585_3 | class ReplayController {
@PostMapping("/replay")
public String replay() {
replayer.replay("nl.fourscouts.blog.replays.projections");
return "Replay started...";
}
@GetMapping("/replay") public String progress();
@Autowired
private MockMvc mvc;
@MockBean
private Replayer replayer;
}
class ReplayControl... | mvc
.perform(post("/replay"))
.andExpect(status().isOk());
verify(replayer).replay(any());
}
} |
124093107_0 | class BufferedLiveEvent extends SingleLiveEvent<T> {
@Override public void setValue(@Nullable T t) {
if (hasActiveObservers() && mBuffer.isEmpty()) { // See onActive
super.setValue(t);
} else {
mBuffer.add(t);
}
}
@Override public void postValue(@Nullable f... | ble.setValue("a");
assertObserved();
lifecycle.handleLifecycleEvent(ON_START);
assertObserved("a");
ble.setValue("b");
assertObserved("b");
ble.setValue("c");
lifecycle.handleLifecycleEvent(ON_STOP);
ble.setValue("d");
ble.setValue("e");
... |
124140585_0 | class MinimumDistanceCalculator extends Attribute {
public static int calculateDistance(Object[] entities, int start, int end) {
boolean[] visited = new boolean[entities.length];
int[] distance = new int[entities.length];
for (int i = 0; i < entities.length; i++) {
distance[i] =... | List<Entity> entityList = testModel.entityList();
int result = MinimumDistanceCalculator
.calculateDistance(entityList.toArray(), 0, 2);
Assert.assertEquals(1, result);
result = MinimumDistanceCalculator
.calculateDistance(entityList.toArray(), 0, 0);
... |
124201472_2 | class DataType {
public static @Nullable String nameForOid(int oid) { return dataTypes.get(oid); public static @Nullable String nameForOid(int oid) { return dataTypes.get(oid); }
public static @Nullable String nameForOid(int oid) { return dataTypes.get(oid); private DataType();
public static @Nullable String nameFo... | for (Field oidField : oidFields)
Assert.assertEquals(oidField.getName(), DataType.nameForOid((int) oidField.get(null)));
}
} |
124230133_6 | class PwnedPasswordClient {
CompletableFuture<List<Hex>> fetchHashesAsync(Hex hashedPassword) {
Call call = httpClient.newCall(buildRequest(hashedPassword));
CompletableFuture<List<Hex>> future = new CompletableFuture<>();
call.enqueue(new Callback() {
@Override
pu... | PwnedPasswordClient pwnedPasswordClient = new PwnedPasswordClient(new OkHttpClient(), "http://localhost:8089", "unit-test");
try {
pwnedPasswordClient.fetchHashesAsync(Hex.from("password")).get();
fail();
} catch (ExecutionException e) {
assertTrue(e.getCause... |
124364226_0 | class ClusterConfig {
protected ClusterProperties getClusterProperties() {
String keyPrefix = "yfs.gateway.";
ClusterProperties clusterProperties = new ClusterProperties();
Map<String, String> map = PropertiesUtil.getProperty("cluster.properties");
Set<Integer> nodeIds = new HashSet... | ClusterProperties clusterProperties = new ClusterConfig().getClusterProperties();
Assert.assertEquals("server1", clusterProperties.getLocal());
Assert.assertEquals("yfs-gateway/data/metadata", clusterProperties.getMetadataDir());
Assert.assertEquals(6003, clusterProperties.getNode().get(... |
124397000_25 | class OAuth2AccessTokenService {
public OAuth2AccessTokenResponse getAccessToken(ClientProperties clientProperties) {
if (clientProperties == null) {
throw new OAuth2ClientException("ClientProperties cannot be null");
}
log.debug("getting access_token for grant={}", clientProper... | assertThatExceptionOfType(OAuth2ClientException.class)
.isThrownBy(() -> oAuth2AccessTokenService.getAccessToken(onBehalfOfProperties()))
.withMessageContaining("no authenticated jwt token found in validation context, cannot do on-behalf-of");
}
} |
124447570_0 | class TranslationService {
Maybe<TranslationResult> getOnlineTranslation(String question, String langFrom, String langTo) {
if (appState.isOfflineMode) {
return Maybe.empty();
}
return seznamRetrofit.create(SeznamRestInterface.class)
.doTranslate(langFrom + "_" +... | TranslationResult translationResult = translationService.getOnlineTranslation("pas", "cz", "ru")
.blockingGet();
assertEquals(3, translationResult.getTranslations().size());
assertEquals("pas", translationResult.getWord());
}
} |
124503196_5 | class MainPagerPresenter extends BasePresenter<MainPagerContract.View> implements MainPagerContract.Presenter {
@Override
public void addCollectArticle(int position, FeedArticleData feedArticleData) {
addSubscribe(mDataManager.addCollectArticle(feedArticleData.getId())
.compose(RxUtils.... | login();
FeedArticleData feedArticleData = getFeedArticleData();
mMainPagerPresenter.addCollectArticle(0, feedArticleData);
Mockito.verify(mView).showCollectArticleData(ArgumentMatchers.eq(0),
ArgumentMatchers.eq(feedArticleData),
ArgumentMatchers.any(Feed... |
124518729_11 | class QuoteRule implements Rule {
@Override
public boolean conforms(final List<String> pMarkdownLines) {
return QUOTE_PATTERN.matcher(pMarkdownLines.get(0)).matches();
}
@Override public int getLinesConsumed();
@Override public MarkdownItem toMarkdownItem(final List<String> pMarkdownLines);
private QuoteRule... | List<String> strings = new ArrayList<>();
strings.add("< Quote");
assertFalse(mQuoteRule.conforms(strings));
}
} |
124578706_11 | class TypePostProcessorResultHandler implements ResultHandler<Object> {
@Override
public void handleResult(Object result) {
if (result == null) {
return;
}
if (result instanceof Throwable) {
THREAD_CONTEXT.set((Throwable) result);
}
Object obj = r... | IllegalArgumentException ex = new IllegalArgumentException("[TEST]");
rh.handleResult(ex);
assertEquals(1, captor.getAllValues().size());
assertEquals(ex, captor.getAllValues().get(0));
}
} |
124743561_1 | class HttpHeaders {
public void set(String name, String value) {
List<String> values = headers.get(name);
if (values == null) {
values = new ArrayList<>(1);
headers.put(name, values);
} else {
values.clear();
}
values.add(value);
}
... | HttpHeaders headers = new HttpHeaders(2);
headers.set("Connection", "close");
headers.set("Connection", "Keep-Alive");
headers.set("Accept-Encoding", "gzip, deflate");
Assert.assertEquals("Keep-Alive", headers.get("Connection"));
Assert.assertEquals("gzip, deflate", head... |
124775013_2 | class NestedRadioGroupManager {
public void check(@IdRes int id) {
// don't even bother
if (id != -1 && (id == checkedId)) {
return;
}
if (checkedId != -1) {
setCheckedStateForView(checkedId, false);
}
if (id != -1) {
setCheckedS... | //given
int initialCheckId = 12345;
int newCheckId = 54321;
nestedRadioGroupManager.initCheckedId(initialCheckId);
//when
nestedRadioGroupManager.check(newCheckId);
//then
verify(nestedRadioGroupManager).setCheckedStateForView(initialCheckId, false);
... |
124862112_29 | class BizCommandProvider implements CommandProvider {
@Override
public String handleCommand(String command) {
return new BizCommand(command).process();
}
@Override public String getHelp();
@Override public boolean validate(String command);
private BizManagerService bizManagerService;
... | Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1"))
.setBizState(BizState.ACTIVATED);
Biz bizA2 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V2"))
.setBizState(BizState.DEACTIVATED);
Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")... |
124863824_5 | class TimeWaitRunner {
public void doWithRunnable(Runnable runnable) {
long currentTimeMillis = System.currentTimeMillis();
if (runImmediately) {
runnable.run();
} else if (currentTimeMillis > lastLogTime + waitTime) {
synchronized (this) {
if (curren... | TimeWaitRunner timeWaitLogger = new TimeWaitRunner(1000);
AtomicLong atomicLong = new AtomicLong();
new Thread(()->{
while (true){
timeWaitLogger.doWithRunnable(atomicLong::incrementAndGet);
}
}).start();
Thread.sleep(1500);
Assert.... |
124869132_4 | class App {
public List<ChangedFile> getChangedFilesForCommit(RevCommit commit) throws IOException, GitAPIException {
List<ChangedFile> changedFiles = new ArrayList<>();
int rangeSize = 6;
int lowerIntervall = (-1) * (rangeSize / 2);
int upperIntervall = (rangeSize / 2) + 1;
... | //arrange
App app = appToBeTested;
RevCommit commit = revCommitsToBeTested.get(0);
//act
List<ChangedFile> changedFiles = app.getChangedFilesForCommit(commit);
//assert
assertEquals(changedFiles.size(),31);
}
} |
124882400_142 | class Element extends Node {
@Override
public Element wrap(String html) {
return (Element) super.wrap(html);
}
public Element(String tag);
public Element(Tag tag, String baseUri, Attributes attributes);
public Element(Tag tag, String baseUri);
protected List<Node> ensureChildNo... | Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>");
Element p = doc.select("p").first();
p.wrap("<div class='head'></div>");
assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html()));
Element ret = p.w... |
124900009_15 | class CustomerRepository {
public Customer getFallbackCustomer(Long id, Throwable e) {
log.warn("Failed to obtain Customer, " + e.getMessage() + " for customer with id " + id);
Customer c = new Customer();
c.setId(id);
c.setUsername("Unknown");
c.setName("Unknown");
c.setSurname("Unknown");
c.setAddress... | Customer c = new Customer();
c.setId(new Long(1));
c.setUsername("Unknown");
c.setName("Unknown");
c.setSurname("Unknown");
c.setAddress("Unknown");
c.setCity("Unknown");
c.setCountry("Unknown");
c.setZipCode("Unknown");
Customer found = repository.getFallbackCustomer(new Long(1), new Exception()... |
124923731_1 | class CustomMetricsExample implements Predictor<Integer, Float> {
@Override
public CompletionStage<List<Prediction<Integer, Float>>> predict(
final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input) {
return predictorBuilder.predictor().predict(scheduler, timeout, input);... | // #SemanticMetricRegistry
final SemanticMetricRegistry registry = new SemanticMetricRegistry();
final MetricId metricId = MetricId.build().tagged("service", "my-application");
// #SemanticMetricRegistry
final CustomMetricsExample example = new CustomMetricsExample(registry, metricId);
example... |
125110164_1 | class WireSafeEnum {
@Nonnull
@SuppressWarnings("unchecked")
public static <T extends Enum<T>> WireSafeEnum<T> of(@Nonnull T value) {
checkNotNull(value, "value");
Class<T> enumType = (Class<T>) value.getClass();
ensureEnumCacheInitialized(enumType);
return (WireSafeEnum<T>) ENUM_LOOKUP_CACHE.ge... | Throwable t = catchThrowable(() -> WireSafeEnum.of(NumericJsonEnum.ABC));
assertThat(t)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("NumericJsonEnum");
}
} |
125157861_34 | class Promise implements HasPromise<DATA>, HasResult<DATA>, Pipeable<HasPromise<DATA>> {
@SuppressWarnings("unchecked")
public final <TARGET> Promise<TARGET> mapResult(Function<Result<? super DATA>, Result<? extends TARGET>> mapper) {
requireNonNull(mapper);
return (Promise<TARGET>)newSubPromis... | val promise = Promise.ofException(new IOException());
assertEquals (PromiseStatus.COMPLETED, promise.getStatus());
assertStrings("Result:{ Exception: java.io.IOException }", promise.getCurrentResult());
val promise2 = promise.mapResult(result -> result.whenEx... |
125371981_24 | class DateRange implements Serializable, Comparable<DateRange> {
@Nonnull
public Optional<DateRange> getOverlap(@Nonnull DateRange otherRange) {
if (this.getGueltigAb().isAfter(otherRange.getGueltigBis()) || this.getGueltigBis().isBefore(otherRange.getGueltigAb())) {
return Optional.empty();
}
LocalDate ab... | LocalDate schnittpunkt = LocalDate.of(1976, 11, 19);
DateRange schnittpunktRange = new DateRange(schnittpunkt, schnittpunkt);
DateRange a = new DateRange(schnittpunkt.minusYears(1), schnittpunkt);
DateRange b = new DateRange(schnittpunkt, schnittpunkt.plusYears(1));
Optional<DateRange> overlap = a.getOverla... |
125381655_0 | class User implements Serializable {
public void setName(String name) {
this.name = name;
}
public User();
public User(String name, String email);
public Integer getId();
public void setId(Integer id);
public String getName();
public String getEmail();
public void setEma... | User user = new User("User", "user@test.com");
user = userBean.add(user);
user.setName("User1");
userBean.update(user);
Assert.assertNotNull(userBean.findByName("User1"));
}
} |
125417291_49 | class EnableState extends BinaryState {
void setDrawable(@NonNull StateDraweeView view) {
FrescoImageController.create()
.load(getDrawable(view.isEnabled() ? STATE_ON : STATE_OFF))
.into(view);
}
@Override public void attach(@NonNull final StateDraweeView view);
@Overri... | StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application));
EnableState state = new EnableState();
state.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear);
state.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear);
state.setDrawable(view);
Mo... |
125471878_1 | class AddNewItemViewModel extends ViewModel {
public void addNewStock(String symbolName, BigDecimal shareCount) {
Date date = new Date();
symbolName = symbolName.trim();
StockPortfolioItem item = new StockPortfolioItem(
symbolName,
shareCount,
... | viewModel.addNewStock("GOOG", BigDecimal.ONE);
verify(portfolioRepository, atLeast(1))
.save(any(StockPortfolioItem.class));
}
} |
125498620_7 | class CryptoCavaWrapper {
public static byte[] base64Decode(byte[] base64Decoded) {
return ((SodiumDecoder)
(in, out, reference) ->
Sodium.sodium_base642bin(out, in.length, in, in.length, null, reference, null, VARIANT_URLSAFE_NO_PADDING)
).decode(base64Decod... | byte[] base64Encoded = getUrlEncoder().withoutPadding().encode("test".getBytes());
assertArrayEquals("test".getBytes(StandardCharsets.UTF_8), CryptoCavaWrapper.base64Decode(base64Encoded));
}
} |
125508132_80 | class SyncCheck {
private SyncCheck(final int syncRateFactor, final int minThresholdSeconds, final int syncRateInSeconds) {
this.syncRateInSeconds = syncRateInSeconds;
this.lastSyncThresholdSeconds = Math.max(minThresholdSeconds, syncRateFactor * syncRateInSeconds);
LOG.info("lastSyncThres... | int syncRateFactor = 1;
int syncRateInSeconds = 1;
SyncCheck syncCheck = SyncCheck.createForTests(syncRateFactor, 1, syncRateInSeconds);
CheckResult notStartedCheck = syncCheck.syncCheck(scheduler);
assertFalse(notStartedCheck.isUp());
assertEquals(Status.DOWN, notStarted... |
125578728_2 | class StreamContext implements Context {
@Override
public final Collection<String> deleteState(final Collection<String> addresses)
throws InternalError, InvalidTransactionException {
TpStateDeleteRequest delRequest = TpStateDeleteRequest.newBuilder().addAllAddresses(addresses)
.setContextId(this.... | Stream stream = mock(Stream.class);
Context ctx = new StreamContext(stream, "test-context-id");
List<String> deleteList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
deleteList.add(RandomString.make(70));
}
FutureByteString okResponse = new FutureByteString("test-correlation-id");... |
125602657_0 | class Sample3Controller {
@PostMapping("/sample3")
public String save(@RequestBody PointDto requestDto){
messagingTemplate.convertAndSend("sample3", requestDto);
return "success";
}
@MockBean PointRepository pointRepository;
@Autowired ObjectMapper objectMapper;
@Autowired Samp... | // given:
PointDto requestDto = PointDto.builder()
.userId(1L)
.savePoint(1000L)
.description("buy laptop")
.build();
given(pointRepository.save(any()))
.willThrow(new IllegalArgumentException("fail"));
poi... |
125627767_0 | class FunctionApp {
public static JsonObject main(JsonObject args) {
JsonObject response = new JsonObject();
response.addProperty("greetings", "Hello! Welcome to OpenWhisk on OpenShift");
return response;
}
}
class FunctionAppTest {
@Test
public void testFunction() {
| JsonObject args = new JsonObject();
JsonObject response = FunctionApp.main(args);
assertNotNull(response);
String greetings = response.getAsJsonPrimitive("greetings").getAsString();
assertNotNull(greetings);
assertEquals("Hello! Welcome to OpenWhisk on OpenShift", greetin... |
125691541_55 | class Solver {
public int moves() {
return solution.size() - 1;
}
public Solver(WorldState initial);
public Iterable<WorldState> solution();
}
class TestSolver {
@Test
public void test4x4BoardPuzzles() {
| for (int i = 0; i <= 30; i += 1) {
String pnum = String.format("%02d", i);
String puzzleName = "input/puzzle4x4-" + pnum + ".txt";
Board b = readBoard(puzzleName);
int numMoves = i;
BoardPuzzleSolution bps = new BoardPuzzleSolution(puzzleName, b, numMo... |
125705175_1 | class CurrentPlayerSwitch extends AbstractGameRules {
public void switchCurrentPlayer(Game game) {
if (game.isFinished()) {
return;
}
int iterations = 0;
Player player = game.getCurrentPlayer();
boolean isMoveFeasible;
do {
player = getNextPlayer(game, player.getId());
is... | game.setFinished(true);
currentPlayerSwitch.switchCurrentPlayer(game);
assertThat(game.getCurrentPlayer().getId()).isEqualTo(FIRST_PLAYER_ID);
}
} |
125752732_452 | class OfflineQueryController extends AbstractQueryController {
@Override
public <T extends ParseObject> Task<Integer> countAsync(
ParseQuery.State<T> state,
ParseUser user,
Task<Void> cancellationToken) {
if (state.isFromLocalDatastore()) {
return offlineStore.countFromPinAsync(state.pi... | TestNetworkQueryController networkController = new TestNetworkQueryController();
OfflineQueryController controller = new OfflineQueryController(null, networkController);
ParseQuery.State<ParseObject> state = new ParseQuery.State.Builder<>("TestObject")
.build();
controller.countAsync(state, nul... |
125770258_0 | class HelloWorldView extends Composite {
@UiHandler("showButton")
void handleShowButtonClick(ClickEvent e) {
if (bananaCount != 0) {
foodMultipleSelect.getSelectedItems()
.forEach(item -> Notify.notify(item.toString()));
} else {
notify("No banana, no food.");
}
eventBus.fireEvent(new ChangeViewE... | // CUT
view.handleShowButtonClick(null);
// Asserts
verify(foodMultipleSelect, times(1)).getSelectedItems();
}
} |
125843963_15 | class RESTService {
@GET
@Context
@Path("/questionsold")
@Produces(MediaType.APPLICATION_JSON)
public RESTQuestions getQuestionsJSON(@Context ServletContext context, @QueryParam("domain") String domain, @QueryParam("type") List<String> questionTypes, @QueryParam("limit") int maxNrOfQuestions) {
logger.info("RES... | fail("Not yet implemented");
}
} |
125942409_0 | class OnlineShopping {
public void switchStore(Store storeToSwitchTo) {
Cart cart = (Cart) session.get("CART");
DeliveryInformation deliveryInformation = (DeliveryInformation) session.get("DELIVERY_INFO");
if (storeToSwitchTo == null) {
if (cart != null) {
for (I... | DeliveryInformation deliveryInfo = new DeliveryInformation("HOME_DELIVERY", nordstan, 60);
deliveryInfo.setDeliveryAddress("NEARBY");
Cart cart = new Cart();
cart.addItem(cherryBloom);
cart.addItem(blusherBrush);
cart.addItem(masterclass);
cart.addItem(makeoverNo... |
125985734_86 | class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer {
@Override
public void customize(WebServerFactory server) {
setMimeMappings(server);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStati... | props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customi... |
126022604_1 | class Util {
public static Calendar getCalendarForLocale(Calendar oldCalendar, Locale locale) {
if (locale == null)
throw new IllegalArgumentException("You must specify the Locate value");
if (oldCalendar == null)
return Calendar.getInstance(locale);
long currentTi... | Locale locale = new Locale("en", "US");
Calendar calendar = Calendar.getInstance(locale);
Calendar result = Util.getCalendarForLocale(calendar, locale);
assertEquals(result.getTime(), result.getTime());
}
} |
126149876_50 | class FallbackJSBundleLoader extends JSBundleLoader {
@Override
public String loadScript(CatalystInstanceImpl instance) {
while (true) {
try {
return getDelegateLoader().loadScript(instance);
} catch (Exception e) {
if (e.getMessage() == null || !e.getMessage().startsWith(RECOVERABL... | JSBundleLoader delegates[] = new JSBundleLoader[] {
recoverableLoader("url1", "error1"),
recoverableLoader("url2", "error2")
};
FallbackJSBundleLoader fallbackLoader =
new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates)));
try {
fallbackLoader.loadScript(null);
... |
126250036_0 | class SQLLookupService extends AbstractSQLLookupService<String> {
@Override
public Class<?> getValueType() {
return String.class;
}
public SQLLookupService();
@Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors();
@Override Optional<String> databaseLookup(Map... | assertEquals(sqlLookupService.getValueType(), String.class);
}
} |
126275473_1175 | class ResourceTypesResource extends RealmAwareResource {
@Override
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request) {
String principalName = "unknown";
try {
final Subject subject = getSubject(context);
principalN... | //given
CreateRequest mockCreateRequest = mock(CreateRequest.class);
JsonValue content = mock(JsonValue.class);
given(mockCreateRequest.getContent()).willReturn(content);
given(mockCreateRequest.getNewResourceId()).willReturn(null);
given(content.toString()).willReturn(... |
126316912_98 | class FieldAgent implements IOFogModule {
public String deProvision(boolean isTokenExpired) {
logInfo("Start Deprovisioning");
if (!provisioningLock.tryLock()) {
String msg = "Provisioning in progress";
logInfo(msg);
return msg;
}
try {
... | try {
initiateMockStart();
when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK);
when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenThrow(new SSLHandshakeException("Invalid operation"));
String response = field... |
126590345_3 | class ActivityLifebus extends BaseLifebus<Activity, ActivityEvent> {
@NonNull
public static Lifebus<ActivityEvent> create(@NonNull Activity activity) {
final Application application = activity.getApplication();
if (application == null) {
throw new IllegalStateException("Provided act... | // when created lifebus immediately registers callbacks
final Activity activity = mock(Activity.class);
final Application application = mock(Application.class);
ActivityLifebus.create(application, activity);
verify(application, times(1))
.registerActivityLifecy... |
126705523_2 | class MyServiceImpl implements MyService {
@Override
@ServiceValidation
public DTO getDto (final DTO dto){
return dto;
}
@Autowired
private MyService myService;
}
class MyServiceImplTest {
@Autowired
private MyService myService;
@Test
public void everythingFine(){
|
final DTO dto = new DTO();
dto.setNumber(1);
dto.setText("test");
final DTO result = myService.getDto(dto);
Assert.assertEquals(result.getNumber(), dto.getNumber());
Assert.assertEquals(result.getText(), dto.getText());
}
} |
126711206_181 | class Ed25519DsaSigner implements DsaSigner {
@Override
@SuppressWarnings("squid:S00117")
public Signature sign(final byte[] data) {
if (!this.getKeyPair().hasPrivateKey()) {
throw new CryptoException("cannot sign without private key");
}
Hasher hasher32 = Hashes::sha512;
Hasher hasher64 =... | // Arrange:
final CryptoEngine engine = this.getCryptoEngine();
final KeyPair keyPair = KeyPair.random(engine);
final Ed25519DsaSigner dsaSigner =
new Ed25519DsaSigner(keyPair) {
@Override
public boolean isCanonicalSignature(Signature signature) {
return false;
... |
126785618_6 | class CoconutValidator {
public static boolean areFieldsValid(CoconutView... views) {
boolean ret = true;
for (CoconutView view : views) {
CoconutInput inputView = view.getCoconutView();
if (inputView == null || inputView.isOptional()) {
continue;
... | when(coconutView.getCoconutView()).thenReturn(coconutInput);
when(coconutInput.getInput()).thenReturn("1234");
when(coconutInput.getValidationRegex()).thenReturn("[0-9]+");
when(coconutInput.getErrorMessages()).thenReturn("only numbers");
boolean condition = CoconutValidator.areF... |
126825296_298 | class CommandRunner implements Runnable, Closeable {
void fetchAndRunCommands() {
ConsumerRecords<CommandId, Command> records = commandStore.getNewCommands();
log.trace("Found {} new writes to command topic", records.count());
for (ConsumerRecord<CommandId, Command> record : records) {
CommandId co... | StatementExecutor statementExecutor = mock(StatementExecutor.class);
statementExecutor.handleStatement(anyObject(), anyObject());
expectLastCall().times(4);
replay(statementExecutor);
CommandStore commandStore = mock(CommandStore.class);
expect(commandStore.getNewCommands()).andReturn(new Consu... |
126844782_4 | class DefaultEventStoreService implements EventStoreService {
@Override
public Optional<ContractEventDetails> getLatestContractEvent(
String eventSignature, String contractAddress) {
int page = eventStore.isPagingZeroIndexed() ? 0 : 1;
final PageRequest pagination = new PageRequest... | when(mockPage.getContent()).thenReturn(null);
when(mockEventStore.getContractEventsForSignature(
eq(EVENT_SIGNATURE), eq(CONTRACT_ADDRESS), any(PageRequest.class))).thenReturn(mockPage);
assertEquals(false, underTest.getLatestContractEvent(EVENT_SIGNATURE, CONTRACT_ADDRESS).isPre... |
126886615_2 | class DefaultDiffUtilComparator implements DiffUtilComparator<MODEL> {
@Override
public boolean areContentsTheSame(MODEL oldModel, MODEL newModel) {
return oldModel == newModel;
}
@Override public boolean areItemsTheSame(MODEL oldModel, MODEL newModel);
@Override public Object getChangePayload(MODEL old... | //funny but we can't actually mock equals with any mock lib !
//SOF: https://stackoverflow.com/q/3007532/693752
//GIVEN
DefaultDiffUtilComparator<String> itemComparatorUnderTest = new DefaultDiffUtilComparator<>();
//WHEN
final boolean areContentsTheSame = itemComparatorUnderTest.areContentsThe... |
126941683_6 | class FileNasStorage implements RdfFileStorageSpi {
private List<String> listFilesWithRegexs(String folderName, boolean all, String[] regexs) {
List<String> paths = listFilesHandler(folderName, all);
if (regexs == null || regexs.length == 0) {
return paths;
}
List<String... | List<String> paths = storage.listFiles(File.class.getResource("/storage").getPath(),
new String[] { "folder1*" });
Assert.assertEquals(1, paths.size());
}
} |
127004420_52 | class DL4JSequenceRecommender extends RecommendationEngine {
@Override
public EvaluationResult evaluate(List<CAS> aCas, DataSplitter aDataSplitter)
{
// Prepare a map where we store the mapping from labels to numeric label IDs - i.e.
// which index in the label vector represents which label... | IncrementalSplitter splitStrategy = new IncrementalSplitter(0.8, 50, 10);
DL4JSequenceRecommender sut = new DL4JSequenceRecommender(buildNerRecommender(), traits,
cache);
JCas cas = loadNerDevelopmentData("thatIncrementalNerEvaluationWorks");
int i = 0;
while (sp... |
127047174_1 | class StoreByMetroAreaQueryController {
@GetMapping("/stores-by-metro-area")
public Collection<StoreByMetroAreaProjection> listStoresByLocation(@RequestParam String metroArea) {
return repository.findAllProjectedByLocation(metroArea);
}
public StoreByMetroAreaQueryController(StoreByMetroAreaR... | StoreByMetroAreaProjection storeProjection = makeStoreByMetroAreaProjection();
doReturn(singletonList(storeProjection))
.when(mockRepository)
.findAllProjectedByLocation(any());
mockMvc
.perform(
get("/stores-by-metro-area"... |
127063666_2 | class ButtplugWSClient extends ButtplugClient {
public void connect(URI url) throws Exception {
connect(url, false);
}
public ButtplugWSClient(String clientName);
public void connect(String url, boolean trustAll);
public void connect(URI url, boolean trustAll);
@Override public void ... | ButtplugWSClient client = new ButtplugWSClient("Java Test");
client.connect(new URI("wss://localhost:12345/buttplug"), true);
Assert.assertTrue(client.startScanning());
Thread.sleep(5000);
client.requestDeviceList();
for (DeviceMessageInfo deviceInfo : client.getDevices(... |
127102257_1 | class CertificateCoder2 {
public static String sign(byte[] sign, String keyStorePath, String alias,
String password) throws Exception {
// 获得证书
X509Certificate x509Certificate = (X509Certificate) getCertificate(
keyStorePath, alias, password);
/... | System.err.println("私钥加密——公钥解密");
String inputStr = "sign";
byte[] data = inputStr.getBytes();
byte[] encodedData = CertificateCoder2.encryptByPrivateKey(data,
keyStorePath, alias, password);
byte[] decodedData = CertificateCoder2.decryptByPublicKey(encodedData... |
127160868_1 | class Money {
public Money add(Money money) {
BigDecimal total = this.getAmount().add(money.getAmount());
return new Money(total);
}
public Money();
public Money(BigDecimal amount);
public Money(int amount);
public boolean isGreaterThan(Money comparison);
public BigDecimal getAmount();
@Override publ... | Money base = new Money();
assertEquals(BigDecimal.ZERO, base.getAmount());
Money moneyToAdd = new Money(100);
assertEquals(new Money(100), base.add(moneyToAdd));
}
} |
127163887_0 | class RocketLander {
static Point2D thrustVector(final float rotation, final float thurstAcceleration) {
return new Point2D.Float(-thurstAcceleration*(float)Math.sin(rotation), thurstAcceleration*(float)Math.cos(rotation));
}
public RocketLander();
public RocketLander(final RocketLander toCopy);
public void... | final float delta = 0.0001f;
Point2D vec;
vec = RocketLander.thrustVector(0, 5);
assertEquals(vec.getX(), 0f, delta);
assertEquals(vec.getY(), 5f, delta);
vec = RocketLander.thrustVector((float)Math.toRadians(180), 5);
assertEquals(vec.getX(), 0f, delta);
assertEquals(vec.getY(), -5f, delta);
vec... |
127330859_9 | class FeatureFlagsService {
public boolean shouldApplyFeatureWithFlag(long flagId) {
final Optional<FlagDTO> flag = featureFlagsRepo.getFlag(flagId);
return flag.map(FlagDTO::getPortionIn).map(this::randomWithinPortion)
.orElse(false);
}
@Autowired public FeatureFlagsServi... | when(featureFlagsRepo.getFlag(anyLong())).thenReturn(Optional.of(new FlagDTO(randomLong(), randomString(), 50)));
when(random.nextInt(100)).thenReturn(20);
assertTrue(featureFlagsService.shouldApplyFeatureWithFlag(randomLong()));
}
} |
127346527_5 | class PropertiesResolver implements Verifications<T> {
public Resolved<Set<T>> resolve(List<T> props, DefaultProperties defProps) {
if (props == null) {
return resolvedEmptyProps();
}
DefaultProperties defaultProperties = createDefaultProperties(defProps);
List<Resolved<T>> allResults = resolve... | T props = copy(mockProps);
props.setResponders(null);
Resolved<Set<T>> resolved = propertiesResolver
.resolve(Collections.singletonList(props), mockDefProps);
assertThat(resolved.isErr()).isFalse();
assertThat(resolved.succ()).hasSize(1);
}
} |
127468887_24 | class CassandraCQLClient extends DB {
@Override
public Status read(String table, String key, Set<String> fields,
HashMap<String, ByteIterator> result) {
try {
Statement stmt;
Select.Builder selectBuilder;
if (fields == null) {
selectBuilder = QueryBuilder.select().all();
... | insertRow();
final HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();
final Status status = client.read(CoreWorkload.table, DEFAULT_ROW_KEY, null, result);
assertThat(status, is(Status.OK));
assertThat(result.entrySet(), hasSize(11));
assertThat(result, hasEntry("field2... |
127471055_64 | class MovieController {
@GetMapping("/movie/delete/{id}")
public String deleteMovie(
@PathVariable("id") final UUID id,
@RequestParam(value = "returnUrl", defaultValue = "") final String returnUrl,
final RedirectAttributes redirectAttributes,
final Authentication authentication,... | final UUID movieId = UUID.randomUUID();
when(movieService.isAuthorizedOnMovie(TEST_AUTHENTICATED_USER, movieId)).thenReturn(true);
mockMvc.perform(post("/movie/delete")
.with(csrf())
.with(user(TEST_AUTHENTICATED_USER))
.param("id", movieId.toString())
... |
127518477_1 | class ExecutorEngine implements AutoCloseable {
@SuppressWarnings("unchecked")
public <I, O> List<O> execute(final I input, final Collection<ExecuteUnit<I, O>> executeUnits, Long timeout,
TimeUnit timeUnit) {
if (executeUnits.size() == 1) {
try {
... | ExecutorService delegate = Executors.newFixedThreadPool(3);
ExecutorEngine executorEngine = new ExecutorEngine(delegate);
List<Integer> inputs = Lists.newArrayList(1, 2, 3);
thrown.expect(ExecuteException.class);
thrown.expectMessage("execute task throw exception");
try {... |
127565224_36 | class ArrayListMultimap implements Multimap<K, V> {
@Override
public Multiset<K> keys() {
return new ArrayListMultiset<>(map.entrySet()
.stream()
.flatMap(this::toKeys)
.collect(Collectors.toList()));
}
private ArrayListMultimap();
public s... | final var given = ArrayListMultimap.create();
given.put("key1", "item1");
given.put("key1", "item1");
given.put("key2", "item2");
final var values = List.of("key1", "key1", "key2");
final var expected = new ArrayListMultiset<>(values);
final var actual = given.... |
127623072_6 | class TypeLiteral {
public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<? extends K> keyType, Class<? extends V> valueType) {
return new TypeLiteral<>(Map.class, keyType, valueType);
}
@SuppressWarnings("unchecked") protected TypeLiteral();
@SuppressWarnings("unchecked") private TypeLite... | TypeLiteral<Map<String, List<? extends Number>>> typeLiteral1 = new TypeLiteral<Map<String, List<? extends Number>>>(){};
TypeLiteral<Map<String, List<? extends Number>>> typeLiteral2 = TypeLiteral.mapOf(new TypeLiteral<String>(){}, new TypeLiteral<List<? extends Number>>(){});
TypeLiteral<Map... |
127727728_0 | class SofaBootVersionEndpoint {
@ReadOperation
public List<Object> versions() {
if (endpointResult.isEmpty()) {
try {
endpointResult = Stream
.of(resourcePatternResolver.getResources(SOFA_BOOT_VERSION_PROPERTIES))
.map(this::lo... | SofaBootVersionEndpoint sofaBootVersionEndpoint = new SofaBootVersionEndpoint();
List<Object> list = sofaBootVersionEndpoint.versions();
Assert.assertTrue(list.size() > 0);
}
} |
127777820_0 | class InMemoryCache {
public synchronized ImmutableSet<Feature> getFeatures() {
return ImmutableSet.copyOf(features.values());
}
@Inject public InMemoryCache();
public synchronized void putFeature(Feature feature);
public void removeFeature(String id);
public void clear();
public Optional<Feature>... | assertThat(inMemoryCache.getFeatures()).isEmpty();
}
} |
127906050_0 | class CipherStorageFactory {
public static CipherStorage newInstance(Context context, Storage storage) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return new CipherStorageAndroidKeystore(context, storage);
}
return new CipherStorageSharedPreferencesKeystore(context, ... | assertThat(CipherStorageFactory.newInstance(null))
.isSameAs(InMemoryCipherStorage.INSTANCE);
}
} |
127906883_15 | class DateUtil {
public static long getMillSecond(String data){
long time = Long.parseLong(data);
if(data.length() == LENGTH_SECOND){
time = Long.parseLong(data) * 1000;
} else if(data.length() == LENGTH_MILLISECOND){
time = Long.parseLong(data);
} else if(d... | long result = DateUtil.getMillSecond("1584500160000");
Assert.assertEquals(result, 1584500160000L);
result = DateUtil.getMillSecond("1584500160000000");
Assert.assertEquals(result, 1584500160000L);
result = DateUtil.getMillSecond("1584500160000000000");
Assert.assertEqu... |
127918464_1 | class DatabaseOLAPService implements OLAPService<PhysicalTable, Field> {
@Override
public DataSet<Field> fetchData(Connector connector, Cube cube) {
SelectJoinStep<Record> fact = using((DataSource) null, null).select(cube.getFields().stream().map((c) -> {
return field(c.asField()).as(c.getColumnNameAlias());
... | assertEquals(2, olapService.fetchData(connector, cube).getDatas().size());
}
} |
128018428_130 | class TokenCacheNodeManager {
public static void putTokenCacheNode(long tokenId, TokenCacheNode cacheNode) {
TOKEN_CACHE_NODE_MAP.put(tokenId, cacheNode);
}
public static void prepare(int concurrencyLevel, int maximumWeightedCapacity);
public static TokenCacheNode getTokenCacheNode(long tokenI... | setCurrentMillis(System.currentTimeMillis());
for (long i = 0; i < 100; i++) {
final TokenCacheNode node = new TokenCacheNode();
node.setTokenId(i);
node.setFlowId(111L);
node.setResourceTimeout(10000L);
node.setClientTimeout(10000L);
... |
128022542_2 | class Tesseract1 extends TessAPI1 implements ITesseract {
@Override
public String doOCR(File imageFile) throws TesseractException {
return doOCR(imageFile, null);
}
protected TessBaseAPI getHandle();
@Override public void setDatapath(String datapath);
@Override public void setLanguage(... | logger.info("doOCR on a BMP image with bounding rectangle");
File imageFile = new File(this.testResourcesDataPath, "eurotext.bmp");
Rectangle rect = new Rectangle(0, 0, 1024, 800); // define an equal or smaller region of interest on the image
String expResult = "The (quick) [brown] {fox}... |
128056094_15 | class MultisourceBeanLocator implements ConfiguredBeanLocator {
@Override
public boolean hasBeanOfName(String name) {
return locators.stream()
.map(locator -> locator.hasBeanOfName(name))
.filter(Boolean::booleanValue)
.findFirst().orElse(false);
}
... | when(source1.hasBeanOfName(eq("test"))).thenReturn(false);
when(source2.hasBeanOfName(eq("test"))).thenReturn(false);
Assert.assertFalse(multisourceBeanLocator.hasBeanOfName("test"));
}
} |
128169626_1 | class TimeZoneEngine {
public Optional<ZoneId> query(double latitude, double longitude) {
final List<ZoneId> result = index.query(latitude, longitude);
return result.size() > 0 ? Optional.of(result.get(0)) : Optional.empty();
}
private TimeZoneEngine(Index index);
private static void... | assertEquals(Optional.of(ZoneId.of("Europe/Amsterdam")), engine.query(51.4457, 4.9248));
assertEquals(Optional.of(ZoneId.of("Europe/Brussels")), engine.query(51.4457, 4.9250));
assertEquals(Optional.of(ZoneId.of("Europe/Brussels")), engine.query(51.4437,4.9186));
assertEquals(Optional.of... |
128191219_0 | class StyleBuilders {
public FontBuilder fontArial() {
return Styles.fontArial();
}
public FontBuilder font();
public FontBuilder font(String fontName, boolean bold, boolean italic, int fontSize);
public FontBuilder fontArialBold();
public FontBuilder fontTimesNewRoman();
public Fo... | FontBuilder fontBuilder = cut.fontArial();
Assert.assertEquals(ARIAL, fontBuilder.getFont().getFontName());
Assert.assertFalse(fontBuilder.getFont().getBold());
Assert.assertFalse(fontBuilder.getFont().getItalic());
}
} |
128219123_103 | class RdsLookupService {
public Optional<GatekeeperRDSInstance> getOneInstance(AWSEnvironment environment, String dbInstanceIdentifier, String instanceName) {
logger.info(dbInstanceIdentifier);
Long startTime = System.currentTimeMillis();
List<String> securityGroupIds = sgLookupService.fetc... | Mockito.when(amazonRDSClient.describeDBInstances(Mockito.any())).thenReturn(
new DescribeDBInstancesResult().withDBInstances(
initializeInstance("instance1", RDS_ENGINE_PG, "gk-A-instance", "db-gk1", STATUS_AVAILABLE, SG_ONE, null)));
Optional<GatekeeperRDSInstanc... |
128272183_81 | class CatalogFactory {
public static CatalogService getCatalogService(HttpClient httpClient) throws ConnectorSDKException {
ConnectorSDKUtil adobeResourceUtil = ConnectorSDKUtil.getInstance();
String catalogEndpoint = adobeResourceUtil.getEndPoint(ResourceName.CATALOG);
return new CatalogSe... | setUp();
assertTrue(CatalogFactory.getCatalogService()!=null);
CatalogService cat = CatalogFactory.getCatalogService(null);
assertTrue(cat != null);
}
} |
128309964_0 | class CartesianChromosome extends Chromosome<T> implements LinearChromosome<Integer>, Cloneable {
public String getExpression() {
Map<Integer, List<Integer>> nodes = getPhenome();
String[] expressions = new String[genome.size() + getOutputs().size()];
Set<Integer> keysSet = nodes.keySet();
... | CartesianChromosome<Double> chrome = new CartesianChromosome<>(Arrays.asList(
new Addition(), new Subtraction(), new Multiplication(), new Division(),
new Power(), new Root(), new Sin(), new Cos(), new Tan()
),0,0,0,0, Arrays.asList(0), null, null);
String expecte... |
128403104_0 | class NibbleArray {
public int get(int index) {
int bitStartIndex = index * bitsPreEntry;
int arrayStartIndex = bitStartIndex >>> 6; // bitStartIndex / 64
int arrayEndIndex = (bitStartIndex + bitsPreEntry - 1) >>> 6;
Validate.inclusiveBetween(0, array.length - 1, arrayEndIndex);
... | assertArrayEquals(bit8RawArray, bit8Array.toArray());
assertArrayEquals(bit24RawArray, bit24Array.toArray());
assertArrayEquals(bit31RawArray, bit31Array.toArray());
}
} |
128535513_29 | class StreamUtil {
public static String toString(final InputStream in, final String encoding) throws IOException {
return new String(streamToByteArray(in), encoding);
}
public static byte[] streamToByteArray(final InputStream in);
public static InputStream copyStream(final InputStream in);
... | final InputStream is = new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8));
assertThat("foo").isEqualTo(StreamUtil.toString(is, "UTF-8"));
}
} |
128639728_0 | class ChaincodeRepositoryConfigurationExtension extends RepositoryConfigurationExtensionSupport {
@Override
protected Collection<Class<? extends Annotation>> getIdentifyingAnnotations() {
logger.debug("getIdentifyingAnnotations return {" + Chaincode.class.getName() + "}");
return Collections.si... | Assert.assertTrue("Not contain correct annotation", extension.getIdentifyingAnnotations().contains(Chaincode.class));
}
} |
128753992_42 | class CountDown {
public int countDown(int n) {
if (0 <= n) { // bug here
n--;
}
return n;
}
public int doNothing(int n);
}
class CountDownTest {
@Test
public void test03() {
| assertEquals(0, new CountDown().countDown(0));
}
} |
129100096_33 | class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (O... | env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))... |
129118555_5 | class FormEditorValidator extends ContentTypeValidatorBase {
@Override
public void validate(Content content, Issues issues) {
Struct formData = content.getStruct(formDataProperty);
String action = content.getString(formActionProperty);
// Validate form fields
if (formData != null && formData.get(... | Content testContent = contentRepository.getContent("8");
IssuesImpl<Content> issues = new IssuesImpl<>(testContent, testContent.getProperties().keySet());
formEditorValidator.validate(testContent, issues);
// Ensure, all expected validation errors occurred.
String key = "formData.formElements.TextFi... |
129126757_5 | class DateUtils {
public String getPeriodUIString(PeriodType periodType, Date date, Locale locale) {
String formattedDate;
Date initDate = getNextPeriod(periodType, date, 0);
Calendar cal = getCalendar();
cal.setTime(getNextPeriod(periodType, date, 1));
cal.add(Calendar.DA... | Date testDate = DateUtils.oldUiDateFormat().parse("2019-01-11");
assertEquals("11/1/2019", DateUtils.getInstance().getPeriodUIString(null, testDate, Locale.ENGLISH));
assertEquals("11/1/2019", DateUtils.getInstance().getPeriodUIString(PeriodType.Daily, testDate, Locale.ENGLISH));
assert... |
129169685_0 | class PassiveAdminClient extends AdminClient {
public static PassiveAdminClient getInstance() { return INSTANCE; public static PassiveAdminClient getInstance() { return INSTANCE; }
public static PassiveAdminClient getInstance() { return INSTANCE; private PassiveAdminClient();
public static PassiveAdminClient getIns... | assertSame(adminClient, PassiveAdminClient.getInstance());
}
} |
129194897_0 | class LrcUtil {
public static String getArtist(String lrcString) {
String pattern = "\\[ar:(.*)\\]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(lrcString);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
... | assertEquals("中文", LrcUtil.getArtist("[ar:中文]"));
assertEquals("1125", LrcUtil.getArtist("[ar:1125]"));
assertEquals("[1125]", LrcUtil.getArtist("[ar:[1125]]"));
assertEquals(null, LrcUtil.getArtist("[ar1235]"));
}
} |
129196583_5 | class ServiceMethodInvoker {
public Flux<ServiceMessage> invokeMany(
ServiceMessage message, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) {
return Flux.from(invoke(toRequest(message, dataDecoder))).map(this::toResponse);
}
public ServiceMethodInvoker(Method method, Object service... | final String methodName = "throwException2";
final Class<? extends StubService> serviceClass = stubService.getClass();
final Method method = serviceClass.getMethod(methodName);
final MethodInfo methodInfo =
new MethodInfo(
serviceClass.getName(),
methodName,
... |
129207304_0 | class RpcBindingConverter implements BindingConverter<RpcBindingParam, RpcBinding> {
protected List<RpcBindingMethodInfo> parseSofaMethods(SofaMethod[] sofaMethods) {
List<RpcBindingMethodInfo> rpcBindingMethodInfos = new ArrayList<RpcBindingMethodInfo>();
for (SofaMethod sofaMethod : sofaMethods)... |
RpcBindingConverter rpcBindingConverter = new BoltBindingConverter();
SofaReference reference = null;
try {
reference = RpcBindingConverterTest.class.getDeclaredField("testAnnotation").getAnnotation(
SofaReference.class);
} catch (NoSuchFieldException e) {
... |
129428289_6 | class WebFormHandler {
public BaseConsent login(String appId, String sessionId, String sessionData, String username, String password, BaseClient.CookieStorage cookieStorage) throws UserLoginFailedException {
String result = this.client.login(appId, sessionId, sessionData, username, password, cookieStorage)... | Mockito.when(client.login(anyString(), anyString(), anyString(), anyString(), anyString(), any(BaseClient.CookieStorage.class))).thenReturn(consentFormHTML);
assertThat(webFormHandler.login("app-id", "session-id", "session-data", "user", "password", cookieStorage))
.isInstanceOf(BaseCons... |
129498280_9 | class AccountController {
@RequestMapping(path = "/account", method = RequestMethod.POST)
public ResponseEntity<Account> addAccount(@RequestBody Account account) {
return ResponseEntity.status(HttpStatus.CREATED).body(service.addAccount(account));
}
@RequestMapping(path = "/account/{id}", method = RequestMethod... | Account mockAccount = mock(Account.class);
Long id = new Long(1);
when(mockAccount.getId()).thenReturn(id);
when(mockAccount.getName()).thenReturn("Sagar Jadhav");
when(service.addAccount(mockAccount)).thenReturn(mockAccount);
ResponseEntity<Account> responseEntity = controller.addAccount(mockAccount);
... |
129501565_13 | class Octree {
public List<T> flatten() {
List<T> list = new ArrayList<T>();
Deque<Octree<T>> queue = new ArrayDeque<>();
queue.push(this);
while (queue.size() > 0) {
Octree<T> tree = queue.pop();
if (tree.item != null) {
list.add(tree.item)... | Octree<String> o = new Octree<>();
o.insert(0, 0, 0, 8, "Foo");
o.insert(32, 16, 8, 4, "Bar");
List<String> f = o.flatten();
assertEquals(2, f.size());
assertTrue(f.contains("Foo"));
assertTrue(f.contains("Bar"));
}
} |
129508952_16 | class Utils {
public static synchronized String getCountryName(Context context) {
String countryName = "";
try {
Locale locale =
context.getApplicationContext().getResources().getConfiguration().locale;
countryName = locale.getDisplayCountry();
} ... | String countryName = Utils.getCountryName(context);
assertThat(countryName, is(notNullValue()));
}
} |
129699491_18 | class Classes {
public static <T> T getValueFromProtectedField(Object object, String fieldName) {
Class<?> clazz = object.getClass();
try {
Field field = clazz.getDeclaredField(fieldName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
... | Object object = new Instanciable();
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> Classes.getValueFromProtectedField(object, "missingField"))
.withMessage("Cannot find field missingField in class com.github.fridujo.automocker.utils.ClassesTest$Instancia... |
129712230_1 | class FieldUtils {
public static Object getPrivateField(Class<?> clazz, Object target, String fieldName) {
Field field = ReflectionUtils.findField(clazz, fieldName);
if (field != null) {
ReflectionUtils.makeAccessible(field);
return ReflectionUtils.getField(field, target);
... | Feign.Builder builder = Feign.builder();
Request.Options options = (Request.Options) FieldUtils.getPrivateField(Feign.Builder.class, builder, "options");
Assert.assertNotNull(options);
System.out.println(options.connectTimeoutMillis() + ":" + options.readTimeoutMillis());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.