id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
68967191_6624 | class GcsPath implements Path, Serializable {
@Override
public Path resolveSibling(Path other) {
throw new UnsupportedOperationException();
}
public GcsPath(@Nullable FileSystem fs, @Nullable String bucket, @Nullable String object);
public static GcsPath fromUri(URI uri);
public static GcsPath fromU... | assertEquals(
"gs://bucket/bar/moo",
GcsPath.fromUri("gs://bucket/bar/foo").resolveSibling("moo").toString());
assertEquals(
"gs://bucket/moo", GcsPath.fromUri("gs://bucket/foo").resolveSibling("moo").toString());
thrown.expect(UnsupportedOperationException.class);
GcsPath.fromUr... |
69026532_22 | class User {
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
}
public User(int id, String username, String pa... | User user = new User(1, "homer", "**********");
Assert.assertFalse(user.equals(null));
}
} |
69044045_2 | class JaxRsUrlResolver implements UrlResolver {
@Override
public String compute(String url, WebContext context) {
if (context instanceof JaxRsContext && url != null) {
return ((JaxRsContext) context).getAbsolutePath(url, true);
}
return url;
}
}
class JaxRsUrlResolverT... | WebContext context = mock(WebContext.class);
JaxRsUrlResolver resolver = new JaxRsUrlResolver();
String resolvedUrl = resolver.compute("/a/relative/url", context);
assertThat(resolvedUrl, is("/a/relative/url"));
}
} |
69047858_9 | class ShowReposPresenter implements ShowReposContract.Presenter, ReposCallback {
@Override
public void restoreStateAndShowRepos(ReposByUsernameUI uiModel) {
if (isViewAttached()) {
if (uiModel != null) {
this.uiModel = uiModel;
view.showRepos(uiModel, false /... | // Given a stubbed uiModel
uiModel = new ReposByUsernameUI(REPOS_BY_USERNAME_UI_MAP, true /* is cached*/);
// When
presenter.restoreStateAndShowRepos(uiModel);
// Then
verify(view).showRepos(uiModel, false /*not going to top*/);
}
} |
69207015_4 | class FunctionHelper {
public static FunctionDetails parseFunctionString(String paramString) throws IllegalArgumentException
{
// trim any whitespace
String trimmedLine = paramString.trim();
// trimmed line is the data for the functions
FunctionDetails functionDetails = new FunctionDetails(trimmed... | FunctionDetails details = FunctionHelper.parseFunctionString(" dd/mm or next friday ");
assertThat(details, is(notNullValue()));
assertThat(details.getFunctionData(), is("dd/mm or next friday"));
assertThat(details.getFunctionParams(), is(nullValue()));
}
} |
69239703_0 | class AuthRepositoryImpl implements AuthRepository {
@Override
public Observable<Boolean> login(LoginDataParams params) {
if(params == null || isEmpty(params.getPhoneNumber()) || isEmpty(params.getPinNumber())) {
return Observable.error(new VoteException(MessageType.EMPTY_CREDENTIALS));
... | //when
Observable<Boolean> loginResult = authRepository.login(null);
//then
loginResult.test().assertError(VoteException.class);
}
} |
69273058_41 | class OrCondition implements Condition {
@Override
public boolean evaluate(Doc doc) {
return conditions.stream().anyMatch(condition -> condition.evaluate(doc));
}
public OrCondition(List<Condition> conditions);
}
class OrConditionTest {
@Test
public void testTwoConditionsFalse() {
| OrCondition andCondition = new OrCondition(Arrays.asList(c -> false, c -> false));
Doc doc = createDoc("field1", "value1");
assertThat(andCondition.evaluate(doc)).isFalse();
}
} |
69277020_0 | class KubernetesAccount extends ContainerAccount implements Cloneable {
@JsonProperty("oAuthScopes")
public List<String> getOAuthScopes() {
return oAuthScopes;
}
public boolean usesServiceAccount();
public String getKubeconfigFile();
@Override public void makeBootstrappingAccount(ArtifactSourcesConfig... | Yaml yamlParser = new Yaml();
Object parsedYaml =
yamlParser.load(
Joiner.on('\n')
.join(
"oauthScopes: [\"lowercase-a\"]", //
"oAuthScopes: [\"uppercase-a\"]"));
KubernetesAccount account =
new StrictObjectMapper().convertV... |
69284281_234 | class CommentConverter {
public static CommentDto convert(final Comment comment) {
return convert(comment, comment.getParentMessage() != null ? MessageConverter.convert(comment.getParentMessage()) : null);
}
private CommentConverter();
public static CommentDto convert(final Comment comment, ... | comment.setParentMessage(null);
CommentDto commentConverter = CommentConverter.convert(comment);
Assert.assertEquals(commentDto.getId(), commentConverter.getId());
Assert.assertEquals(commentDto.getText(), commentConverter.getText());
Assert.assertEquals(commentDto.getAuthor().getId(), commentConverter.getA... |
69289646_19 | class RecyclerViewProxy implements ScrollingViewProxy {
@Override
public void smoothScrollToPositionFromTop(int position, int i) {
mRecyclerView.getLinearLayoutManager().scrollToPositionWithOffset(position, i);
}
public RecyclerViewProxy(LinearRecyclerView recyclerView);
@Override public View getView(... | int position = 5;
int delta = 32;
mRecyclerViewProxy.smoothScrollToPositionFromTop(position, delta);
verify(mLayoutManager).scrollToPositionWithOffset(position, delta);
}
} |
69363264_27 | class Flow extends ModelElement {
Flow(String name, UseCase useCase) {
super(name, useCase.getModel());
this.useCase = useCase;
}
Flow(String name, UseCase useCase);
public UseCase getUseCase();
public List<FlowStep> getSteps();
public Optional<FlowStep> getFirstStep();
private boolean isStepInThisFlow(... | Model model = modelBuilder
.useCase(USE_CASE)
.basicFlow()
.step(CUSTOMER_ENTERS_TEXT).as(secondActor).user(EntersText.class).system(displaysEnteredText())
.step(CUSTOMER_ENTERS_TEXT_AGAIN).as(secondActor, customer).user(EntersText.class).system(displaysEnteredText())
.step(CUSTOMER_ENTERS_NU... |
69365079_0 | class MyAuthPlugin extends AuthPlugin.Adapter {
@Override
public void initialize( AuthProviderOperations authProviderOperations )
{
api = authProviderOperations;
api.log().info( "initialized!" );
loadConfig();
}
@Override public AuthInfo authenticateAndAuthorize( AuthToken... | // Given
MyAuthPlugin plugin = new MyAuthPlugin();
AuthProviderOperations api = mock( AuthProviderOperations.class );
AuthProviderOperations.Log log = mock( AuthProviderOperations.Log.class );
when( api.neo4jHome() ).thenReturn( Paths.get( "" ) );
when( api.log() ).thenR... |
69381318_1 | class AvroDeserializer implements Deserializer<T> {
@SuppressWarnings("unchecked")
@Override
public T deserialize(String topic, byte[] data) {
LOGGER.debug("data to deserialize='{}'", DatatypeConverter.printHexBinary(data));
try {
// get the schema
Schema schema = targetType.newInstance().get... | User user = User.newBuilder().setName("John Doe").setFavoriteColor("green")
.setFavoriteNumber(null).build();
byte[] data = DatatypeConverter.parseHexBinary("104A6F686E20446F6502000A677265656E");
AvroDeserializer<User> avroDeserializer = new AvroDeserializer<>(User.class);
assertThat(avroDeser... |
69400326_689 | class KsqlRestApplication implements Executable {
@VisibleForTesting
void startKsql(final KsqlConfig ksqlConfigWithPort) {
waitForPreconditions();
initialize(ksqlConfigWithPort);
}
@VisibleForTesting KsqlRestApplication(
// CHECKSTYLE_RULES.ON: ParameterNumberCheck
final ServiceContext se... | // When:
app.startKsql(ksqlConfig);
// Then:
final InOrder inOrder = Mockito.inOrder(ksqlResource, serverState);
verify(ksqlResource).handleKsqlStatements(
securityContextArgumentCaptor.capture(),
eq(new KsqlRequest(logCreateStatement, Collections.emptyMap(), Collections.emptyMap(),... |
69403823_0 | class MaterialActivityChooserBuilder {
public void show() {
if (mIntent == null || mIntent.getAction() == null) {
Log.e(TAG, "Cannot show the share screen - intent is missing or has no action.");
return;
}
Intent materialShareIntent = new Intent(mContext, mActivityCl... | //when
builder.show();
//then
verifyZeroInteractions(mockContext);
}
} |
69469299_29 | class WebSocketSubscriptionTransport implements SubscriptionTransport {
@Override
public void send(OperationClientMessage message) {
WebSocket socket = webSocket.get();
if (socket == null) {
callback.onFailure(new IllegalStateException("Send attempted on closed connection"));
return;
}
... | final AtomicReference<Throwable> callbackFailure = new AtomicReference<>();
subscriptionTransport = new WebSocketSubscriptionTransport(webSocketRequest, webSocketFactory, new SubscriptionTransport.Callback() {
@Override public void onConnected() {
}
@Override public void onFailure(Throwable ... |
69571507_52 | class UDPMessageEncoder {
static void writeJson(Span span, Buffer buffer) throws IOException {
JsonWriter writer = JsonWriter.of(buffer);
writer.beginObject();
writer.name("trace_id");
writer.value(new Buffer()
.writeByte('"')
.writeByte('1') // version
.writeByte('-')
... | Span span = serverSpan.toBuilder()
.kind(Span.Kind.CLIENT)
.name("get /")
.localEndpoint(Endpoint.newBuilder().serviceName("master").build())
.build();
String json = writeJson(span);
assertThat(readString(json, "name")).isEqualTo("get /");
}
} |
69595482_13 | class JdbcStorage implements IStorage {
@Override
public Collection<LinkedAccount> listLinkedAccounts(String userId) throws StorageException {
logger.debug("Getting a list of all Linked Accounts for {}.", userId);
try {
return this.jdbi.withHandle( handle -> {
String... | Collection<LinkedAccount> designs = storage.listLinkedAccounts("user");
Assert.assertNotNull(designs);
Assert.assertEquals(0, designs.size());
LinkedAccount account = new LinkedAccount();
Date now = new Date();
account.setType(LinkedAccountType.Bitbucket);
... |
69602447_2 | class WekaScoring extends BaseStep implements StepInterface {
private WekaScoringModel setModel( String modelFileName ) throws KettleException {
// Load the model
WekaScoringModel model = null;
try {
model = WekaScoringData.loadSerializedModel( modelFileName, getLogChannel(), this );
m_data.... | WekaScoringModel model = WekaScoringData.loadSerializedModel(
CLUSTERING_MODEL, null, new Variables());
assertTrue(model != null);
WekaScoringMeta meta = new WekaScoringMeta();
meta.setModel(model);
RowMetaInterface rmi = new RowMeta();
meta.getFields(rmi, null, null, null, new Varia... |
69678968_0 | class PredictG extends Predict<BaseInformationRecords.BaseInformation> {
public static String codeGT(Set<String> to, String from, SortedSet<String> altSet) {
IntArrayList codedAlleles = new IntArrayList();
String result = "";
for (String allele : to) {
if (from.equals(allele)) ... | SortedSet<String> alts = new ObjectAVLTreeSet<>();
alts.add("G");
Set<String> to = new ObjectArraySet<>();
to.add("G");
to.add("C");
//to = G/C
assertEquals("0/1", PredictG.codeGT(to, "C", alts));
to.remove("C");
//to = G/G
assertEquals("1"... |
69755813_0 | class OffersInteractorImpl implements OffersInteractor {
@Override
public Observable<OfferResponse> loadOffers(int page,
String format,
int applicationId,
String userI... | TestSubscriber<OfferResponse> testSubscriber = new TestSubscriber<>();
// call interactor with some random params
interactor.loadOffers(1, Constants.FORMAT_JSON, 2, "userId", "local", "osVersion", 3, "adId", true, "ip", "pub0", Constants.OFFER_TYPES, "device", "apiKey")
.subscri... |
69791298_0 | class MockApi {
public List<String> getPredictions(String query) {
if (query.length() > 0) {
int amountOfResults = 8;
return generatePredictions(amountOfResults, query);
}
return new ArrayList<>();
}
protected List<String> generatePredictions(int amountOfR... | MockApi api = new MockApi();
List<String> predictions = api.generatePredictions(5, "a");
assertEquals("abcde", predictions.get(0));
assertEquals("a", predictions.get(predictions.size() - 1));
}
} |
69807495_8 | class CartService {
public Single<Cart> addProduct(CartProduct cartProduct) {
return cartDataSource.addProduct(cartProduct)
.compose(cartPublisher());
}
public CartService(CartDataSource cartDataSource, CartStore cartStore);
public Observable<Cart> getCart();
public Singl... | CartProduct product = CartProductFactory.newCartProduct(ProductFakeCreator.createProduct(), 1);
when(cartDataSource.addProduct(any(CartProduct.class))).thenReturn(Single.just(Cart.EMPTY));
cartService.addProduct(product)
.test()
.assertComplete();
verify... |
69926042_13 | class ContentContainer implements Iterable<Content> {
public boolean hasSubContainers() {
return (mContentContainers.size() != 0);
}
public ContentContainer();
public ContentContainer(String name);
public static ContentContainer newInstance(String name);
public ContentContainer add... |
ContentContainer cc = new ContentContainer();
cc.addContentContainer(ContentContainer.newInstance("subTest"));
// Test if container has sub containers.
assertTrue(cc.hasSubContainers());
}
} |
70037033_23 | class AuxiliaryInfoUtil {
public static String getWordPart(String wordAndAux) {
int idx = getSeparatorIndex(wordAndAux);
return idx == 0 ? " " : wordAndAux.substring(0, idx);
}
public static int getSeparatorIndex(String wordAndAux);
public static String[] getWordParts(String[] wordAndAuxes);
public ... | Assert.assertEquals(" ", AuxiliaryInfoUtil.getWordPart("/POStag"));
Assert.assertEquals("1", AuxiliaryInfoUtil.getWordPart("1/POStag"));
Assert.assertEquals("word", AuxiliaryInfoUtil.getWordPart("word/POStag"));
Assert.assertEquals("word/stuff", AuxiliaryInfoUtil.getWordPart("word/stuff/POStag"));
}
... |
70037034_10 | class ContextFreeGrammar {
public String[] leftMostDerivation(String... words) {
ArrayList<String> expansion = new ArrayList<String>(words.length);
assert words.length > 0 && startSymbol.equals(words[0]);
for (String word : words) {
expansion.addAll(getTerminals(word));
}
return expansion... | ContextFreeGrammar contextFreeGrammar = new ContextFreeGrammar(nonTerminals, terminals, rules, startSymbol);
String[] expansion = contextFreeGrammar.leftMostDerivation("S", "CJ", "S");
assertArrayEquals(new String[]{"the", "man", "works", "and", "the", "man", "works"}, expansion);
checkExpansion(expansi... |
70038531_27 | class AlertTemplateValidator implements Validator<AlertTemplate> {
@Override
public void validate(AlertTemplate template) throws ValidationException {
if (template.getDestination() == null || template.getDestination().trim().isEmpty()) {
throw new ValidationException("Alert target can't be empty");
}
if (te... | AlertTemplateValidator validator = new AlertTemplateValidator();
AlertTemplate template = new AlertTemplate((short)2);
template.setMedia("slack");
template.setSubject("hello");
template.setBody("hello $x");
template.setTemplateName("Template");
template.setDestination("ABC@slack-channel");
try {
vali... |
70062587_21 | class ImageService {
public static boolean bufferedImagesEqualQuick(BufferedImage image1, BufferedImage image2) {
DataBuffer dataBuffer1 = image1.getRaster().getDataBuffer();
DataBuffer dataBuffer2 = image2.getRaster().getDataBuffer();
if (dataBuffer1 instanceof DataBufferByte && dataBuffer... | final BufferedImage image1 = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_INDEXED);
final BufferedImage image2 = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_INDEXED);
boolean result = ImageService.bufferedImagesEqualQuick(image1, image2);
assertThat(result, is(true));
... |
70140762_12 | class Order implements Serializable {
public BigDecimal getTotalSum() {
return getItemPriceSum();
}
public Order(long orderId, ObjectId userId, List<OrderItem> orderItems, DeliveryAddress deliveryAddress, String sessionId);
public Order();
public long getOrderId();
public void setOr... | //double globalDiscount = Double.parseDouble(Config.getProperty("GLOBAL_DISCOUNT"));
double globalDiscount = 0;
double total = 10.0 - (10.0 * (globalDiscount/100.0));
assertEquals(BigDecimal.valueOf(total).compareTo(order.getTotalSum()), 0);
}
} |
70146477_40 | class BootstrapReplicator {
public void run(AtomicBoolean bootstrapInProgress) {
if ((boolean) configuration.get(Augmenter.Configuration.BOOTSTRAP) == false) {
LOG.info("Skipping active schema bootstrapping");
bootstrapInProgress.set(false);
return;
}
LO... | HashMap<String, Object> configuration = new HashMap<>();
configuration.put(BinaryLogSupplier.Configuration.MYSQL_HOSTNAME, Collections.singletonList(BootstrapReplicatorTest.mysqlBinaryLog.getHost()));
configuration.put(BinaryLogSupplier.Configuration.MYSQL_PORT, String.valueOf(BootstrapReplicat... |
70147050_0 | class Property implements Serializable, KeyValuePair {
@JsonIgnore
public boolean equals(final Object o) {
// check if property attributes are equal.
if (o == null || !(o instanceof Property)) {
return false;
}
Property compare = (Property)o;
try {
System.out.pr... | Property p1 = new Property("test", "testString");
Property p2 = new Property("test", "testString");
Assert.assertFalse(p1 == p2);
Assert.assertFalse(p1.equals(null));
Assert.assertEquals(p1,p2);
}
} |
70162405_11 | class ExportHCatTable {
public static String generateSqlForExportSpec(ExaMetadata meta, ExaExportSpecification exportSpec) {
// Mandatory parameters
Map<String, String> params = exportSpec.getParameters();
String hcatDB = getMandatoryParameter(params, "HCAT_DB");
String hcatTable =... |
ExaExportSpecification exportSpec = mock(ExaExportSpecification.class);
ExaMetadata meta = mock(ExaMetadata.class);
when(meta.getScriptSchema()).thenReturn("hcat_schema");
Map<String, String> params = new HashMap<>();
addMandatoryParams(params);
params.put("COMPRESSION_... |
70189011_6 | class ConfigurationKeyProcessor extends AbstractProcessor {
static String calculateConfigurationBeanName(String className, String configurationBeanName) {
if (className == null) {
throw new IllegalArgumentException("Invalid class name");
}
if (configurationBeanName == null || !NAME_PATTERNS.matcher(configura... | softly.assertThat(calculateConfigurationBeanName(ENUM_CLASS, "*ConfBean")).isEqualTo(ENUM_CLASS + "ConfBean");
softly.assertThat(calculateConfigurationBeanName(ENUM_CLASS, "ConfBean*")).isEqualTo("ConfBean" + ENUM_CLASS);
softly.assertThat(calculateConfigurationBeanName(ENUM_CLASS, "Anno*Tation"))
.isEqualTo(... |
70198875_4 | class LottieCompositionFactory {
@WorkerThread
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName) {
String cacheKey = "asset_" + fileName;
return fromAssetSync(context, fileName, cacheKey);
}
private LottieCompositionFactory();
public static void setM... | LottieResult<LottieComposition> result = LottieCompositionFactory.fromAssetSync(RuntimeEnvironment.application, "square2.json");
assertEquals(FileNotFoundException.class, result.getException().getClass());
assertNull(result.getValue());
}
} |
70219747_191 | class MCRJPAAccessStore extends MCRAccessStore {
@Override
public void createAccessDefinition(MCRRuleMapping rulemapping) {
if (!existAccessDefinition(rulemapping.getPool(), rulemapping.getObjId())) {
Session session = MCRHIBConnection.instance().getSession();
MCRACCESSRULE acc... | final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
assertNotNull(
MCRHIBConnection.instance().getSession().get(MCRACCESS.class, new MCRACCESSPK(permission, objID)));
}
} |
70232982_0 | class MainPresenter {
public void getAwarenessData() {
subscription.add(
rxAwareness.snapshot().getHeadphoneState()
.map(headphoneState -> getHeadphoneStateString(headphoneState.getState()))
.subscribe(view::onHeadphoneStateLoaded, throwable -> Log.e(... | HeadphoneState headphoneState = Mockito.mock(HeadphoneState.class);
doReturn(HeadphoneState.PLUGGED_IN).when(headphoneState).getState();
doReturn(Single.just(headphoneState)).when(snapshot).getHeadphoneState();
Weather weather = Mockito.mock(Weather.class);
doReturn(new int[] {W... |
70371145_13 | class ObservableDispatcher extends Dispatcher<Observable<A>, Subscription> {
@Override
public Subscription dispatch(Observable<A> action) {
return action.subscribe(dispatchAction);
}
public ObservableDispatcher(final Dispatcher<A, ?> dispatcher);
}
class ObservableDispatcherTest {
@Tes... | Reducer<String, String> reducer = new Reducer<String, String>() {
@Override
public String reduce(String action, String state) {
return action;
}
};
SimpleStore<String> store = new SimpleStore<>("test1");
ObservableDispatcher<String> dis... |
70444046_0 | class Pagination extends HorizontalLayout {
public Pagination() {
}
public Pagination();
public Pagination(PaginationResource paginationResource);
protected void init(PaginationResource resource);
public void setItemsPerPage(int... perPage);
public void setTotalCount(long total);
pu... |
int totalCount = beans().size();
int currentPage = 6;
int limit = 20;
PaginationResource paginationResource = PaginationResource.newBuilder().setTotal(totalCount).setPage(currentPage).setLimit(limit).build();
init(paginationResource);
setItemsPerPage(10, 20, 50, 100);
... |
70470785_0 | class RecordDefineParser {
public Table parse(String RecordDefineStr){
//TODO Auto-generated method stub
return new Table();
}
}
class RecordDefineParserTest {
@Test
public void shouldTestRecordDefineParser() throws Exception{
| //Arrangement
String RecordDefineStr = "<Records>" +
"<Field1>" +
"<Name>NewTable</Name>" +
"<DataType>String</DataType>" +
"<Size>800</Size>" +
"<Precision>5</Precision>" +
... |
70515162_54 | class AuthenticationService {
protected Map<String, String> generateCommonIamPrincipalAuthMetadata(
final String iamPrincipalArn) {
Map<String, String> metadata = Maps.newHashMap();
metadata.put(CerberusPrincipal.METADATA_KEY_USERNAME, iamPrincipalArn);
metadata.put(CerberusPrincipal.METADATA_KEY_I... | authenticationService.adminRoleArns = "arn:aws:iam::0000000000:role/admin";
String principalArn = "arn:aws:sts::0000000000:assumed-role/admin/role-session";
String iamRoleArn = "arn:aws:iam::0000000000:role/admin";
when(awsIamRoleArnParser.convertPrincipalArnToRoleArn(principalArn)).thenReturn(iamRoleA... |
70629319_1 | class HotkeySettings extends Settings {
@Override
public Properties getDefaultProperties() {
Properties properties = new Properties();
properties.setProperty("newPlaylist", hotkeyToString(DEFAULT_NEWPLAYLIST));
properties.setProperty("importPlaylist", hotkeyToString(DEFAULT_IMPORTPLAYLIST));
properties... | HotkeySettings settings = new HotkeySettings();
Properties properties = settings.getDefaultProperties();
assertEquals(properties.get("newPlaylist"), "Ctrl+N");
assertEquals(properties.get("importPlaylist"), "Shift+Ctrl+N");
assertEquals(properties.get("undo"), "Ctrl+Z");
assertEquals(properties.get... |
70711909_35 | class HereAccount {
public static TokenEndpoint getTokenEndpoint(
HttpProvider httpProvider,
ClientCredentialsProvider clientCredentialsProvider) {
return new TokenEndpointImpl(reuseClock(clientCredentialsProvider), httpProvider, clientCredentialsProvider, new JacksonSerializer(), n... | HttpProvider mockHttpProvider = Mockito.mock(HttpProvider.class);
//HttpProvider spy = Mockito.spy(mockHttpProvider);
ClientCredentialsProvider credentials = new ClientCredentialsProvider() {
@Override
public String getTokenEndpointUrl() {
return "https:/... |
70738287_0 | class JavannaGson {
public <A extends Annotation> A parse( String json, Class<A> annotation ) {
Map<?, ?> map = gson.fromJson( json, Map.class );
return createAnnotation( annotation, map );
}
public JavannaGson( Gson gson );
public JavannaGson();
public A parse( Reader reader, C... | Server server = javannaGson.parse( testResource( "/server.json" ), Server.class );
assertEquals( "Super Server", server.name() );
assertEquals( 43, server.port() );
assertEquals( "/var/log/server.log", server.logFile() );
WhiteLists whiteLists = server.whiteLists();
as... |
70772509_1 | class CrawlerRunner {
public void run(final CrawlerSettings crawlerSettings, final List<Memo> memos) throws Exception {
CrawlConfig config = crawlerSettings.getCrawlConfig();
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
... | crawlerRunner.run(crawlerSettings, null);
Assert.assertEquals(0L, memos.get(0).getCounter().longValue());
}
} |
70780002_17 | class DmnJsonConverterUtil implements EditorJsonConstants, DmnStencilConstants {
public static boolean migrateModelV3(JsonNode decisionTableNode, ObjectMapper objectMapper) {
// migrate to v2
boolean wasMigrated = migrateModel(decisionTableNode, objectMapper);
// migrate to v3
if (... | JsonNode testJsonResource = parseJson(JSON_RESOURCE_2);
boolean wasMigrated = new DmnJsonConverterUtil().migrateModelV3(testJsonResource, OBJECT_MAPPER);
assertThat(wasMigrated).isTrue();
assertThat(testJsonResource.get("modelVersion").asText()).isEqualTo("3");
DmnDefinition d... |
70781239_1 | class MaskImpl implements Mask {
@Override
public boolean hasUserInput() {
if (slots.isEmpty()) {
return false;
}
return slots.getFirstSlot().anyInputToTheRight();
}
public MaskImpl(@NonNull Slot[] slots, boolean terminated);
public MaskImpl(@NonNull MaskImpl... | assertFalse(mask.hasUserInput());
mask.insertFront("1");
assertTrue(mask.hasUserInput());
mask.removeBackwards(0, 1);
assertFalse(mask.hasUserInput());
Mask nullMask = new MaskImpl(new Slot[]{}, true);
assertFalse(nullMask.hasUserInput());
}
} |
70809374_64 | class RestBotTriggerStore implements IRestBotTriggerStore {
@Override
public BotTriggerConfiguration readBotTrigger(String intent) {
try {
BotTriggerConfiguration botTriggerConfiguration = botTriggersCache.get(intent);
if (botTriggerConfiguration == null) {
botTr... | //setup
final BotTriggerConfiguration expected = createExpectedBotTriggerConfiguration();
when(botTriggersCache.get(eq(intent))).thenAnswer(invocation -> expected);
//test
BotTriggerConfiguration actual = restBotTriggerStore.readBotTrigger(intent);
//assert
Asse... |
70817233_5 | class TimeCalculation {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
static boolean isMinutesDiffMax(DateTime dateTime1, DateTime dateTime2, int maxMinutes) {
Period period = new Period(dateTime1, dateTime2);
Duration duration = period.toDurationFrom(dateTime1);
return Math... | DateTime dateTime1 = getDateTime(3016, 10, 26, 15, 20, 34);
Assert.assertFalse(TimeCalculation.isMinutesDiffMax(mReferenceDateTime, dateTime1, 5000));
DateTime dateTime2 = getDateTime(2017, 11, 16, 15, 20, 34);
Assert.assertFalse(TimeCalculation.isMinutesDiffMax(mReferenceDateTime, date... |
70868306_1 | class Repo implements Comparable<Repo>, Serializable {
public static int getCommitType(String[] splits) {
if (splits.length == 4)
return COMMIT_TYPE_REMOTE;
if (splits.length != 3)
return COMMIT_TYPE_TEMP;
String type = splits[1];
if ("tags".equals(type))
... | assertEquals("should be type head", Repo.COMMIT_TYPE_HEAD, Repo.getCommitType("refs/heads/foo"));
assertEquals("should be type head", Repo.COMMIT_TYPE_HEAD, Repo.getCommitType("refs/heads/foo/bar"));
assertEquals("should be type remote", Repo.COMMIT_TYPE_REMOTE, Repo.getCommitType("refs/remotes/... |
70905504_2 | class InstantRunBuildInfo {
public boolean hasNoChanges() {
return getArtifacts().isEmpty();
}
public InstantRunBuildInfo(@NonNull Element root);
@NonNull public String getTimeStamp();
public long getSecretToken();
@NonNull public String getVerifierStatus();
public boolean canHot... | InstantRunBuildInfo info = getBuildInfo("instantrun", "build-info-no-artifacts.xml");
assertTrue("If there are no artifacts, then it doesn't matter what the verifier said.", info.hasNoChanges());
info = getBuildInfo("instantrun", "build-info-res.xml");
assertFalse("If there is an artifa... |
70948568_133 | class Any {
@SafeVarargs
public static <T> CollectionCase<List<T>, T> nonemptyListOf(Case<T>... cases) {
return new CollectionCase.ListCase<T>()
.withSizeOf(Any.integer().inRange(1, 100))
.withElementsOf(new UnionCase<>(cases));
}
@SafeVarargs public static Case<T> of(Case<T>... cases);
@SafeVarargs publ... | Set<List<Integer>> actuals = Any.nonemptyListOf(Any::integer).generateAllOnce(random);
assertFalse(actuals.stream().anyMatch(List::isEmpty));
}
} |
71073678_31 | class Converter {
public static Calendar getCalendar(Object date, Calendar defaultValue) {
Calendar cal = new GregorianCalendar();
if (date instanceof java.util.Date) {
cal.setTime((java.util.Date) date);
return cal;
} else if (date != null) {
DateFormat ... | assertEquals(null, Converter.getCalendar("invalid date", null));
}
} |
71103781_3 | class FailbackRegistry extends AbstractRegistry {
@Override
public void register(URL url) {
if (destroyed.get()) {
return;
}
super.register(url);
failedRegistered.remove(url);
failedUnregistered.remove(url);
try {
// 向服务器端发送注册请求
doRegister(url);
} catch (Exception e) {
Throwable t = e;
... |
final CountDownLatch latch = new CountDownLatch(1);//全部共调用4次。成功才会减1. subscribe的失败尝试不会在做了
registry = new MockRegistry(registryUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.setBad(false);
for (int i = 0; i < trytimes; i++) {
Sys... |
71162914_1 | class CardValidator implements Validator {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 == 0) {
return true;
} else {
return false;
}
}
publi... |
CreditCard creditCard = new CreditCard("12341234", "10/10", 1234, "VISA");
CardValidator cardValidator = new CardValidator();
assertTrue("Credit card should be valid", cardValidator.validate(creditCard));
creditCard.setNumber("2");
assertTrue("Credit card should be valid", cardValidator.validate(c... |
71163137_1 | class I18NHelper {
public static String getHello(String lang){
return "Hello Time Hacker";
}
}
class I18NHelperTest {
@Test
public void runTest() throws Exception{
| Assert.assertNotNull(I18NHelper.getHello("en"));
}
} |
71171131_6 | class AuthorizationClient {
public static void openLoginInBrowser(Activity contextActivity, AuthorizationRequest request) {
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, request.toUri());
contextActivity.startActivity(launchBrowser);
}
public AuthorizationClient(Activity activity)... | AuthorizationRequest authorizationRequest = mock(AuthorizationRequest.class);
Activity activity = mock(Activity.class);
when(authorizationRequest.toUri()).thenReturn(Uri.parse("to://me"));
Mockito.doNothing().when(activity).startActivity(any(Intent.class));
ArgumentCaptor<Intent... |
71183878_8 | class ClaimImpl extends BaseClaim {
@Override
@Nullable
public Date asDate() {
if (!value.isJsonPrimitive()) {
return null;
}
long ms = Long.parseLong(value.getAsString()) * 1000;
return new Date(ms);
}
ClaimImpl(@NonNull JsonElement value);
@Over... | long seconds = Integer.MAX_VALUE + 10000L;
JsonElement value = gson.toJsonTree(seconds);
ClaimImpl claim = new ClaimImpl(value);
Date date = claim.asDate();
assertThat(date, is(notNullValue()));
assertThat(date.getTime(), is(seconds * 1000));
assertThat(date.getT... |
71197756_54 | class UnpackingJSBundleLoader extends JSBundleLoader {
void prepare() {
boolean unpacked = false;
final File lockFilePath = new File(mContext.getFilesDir(), LOCK_FILE);
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "UnpackingJSBundleLoader.prepare");
// Make sure we don't release the lock by l... | mBuilder.build().prepare();
final File aFile = new File(mDestinationPath, "a_file");
aFile.createNewFile();
when(mMockUnpackers[0].shouldReconstructDir(
same(mContext),
any(byte[].class)))
.thenReturn(true);
addUnpackers();
mBuilder.build().prepare();
assertFals... |
71227768_11 | class Property extends AbstractProperty {
public static Property extractProperty(String propertyDefinition) {
Property property = null;
if (propertyDefinition != null) {
String[] propertyAttributes = propertyDefinition.split(PIPE_REGEX, 2);
String name = propertyAttributes[... |
// #307 Annotation collée au texte
assertProperty(new Property("comment typo|@commentForgot space @required @password", "comment typo", true, null, "", "", true),
Property.extractProperty("comment typo|@commentForgot space @required @password"));
// #311
assertProperty(... |
71230327_0 | class MyService {
public String message() {
return this.serviceProperties.getMessage();
}
public MyService(ServiceProperties serviceProperties);
@Autowired
private MyService myService;
}
class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void c... | assertThat(myService.message()).isNotNull();
}
} |
71263775_2 | class IPFilterParser {
public int parseDAT(@NonNull InputStream is, @NonNull IPFilter filter)
{
int ruleCount = 0;
long lineNum = 0;
int parseErrorCount = 0;
LineIterator it;
try {
it = IOUtils.lineIterator(is, "UTF-8");
} catch (IOException e) {
... | FakeIPFilter filter = new FakeIPFilter();
try (InputStream is = IOUtils.toInputStream(dat_file, "UTF-8")) {
int ruleCount = new IPFilterParser(false).parseDAT(is, filter);
assertEquals(dat_expected_ranges.length, ruleCount);
List<Pair<String, String>> ranges = filter... |
71357459_1 | class SampleController extends AbstractGriffonController {
@MVCMember
public void setModel(@Nonnull SampleModel model) {
this.model = model;
}
@ControllerAction public void sayHello();
@Inject
private ArtifactManager artifactManager;
private SampleController controller;
@Rule
... | final SampleModel model = artifactManager.newInstance(SampleModel.class);
model.setInput("Griffon");
controller.setModel(model);
controller.invokeAction("sayHello");
await().atMost(2, SECONDS)
.until(() -> model.getOutput(), notNullValue());
assertEquals("He... |
71369123_8 | class MethodInvoker {
RestResponseEntity invoke(Object obj, LambdaProxyRequest request) {
MethodInvocationContext context = new MethodInvocationContext(lambdaLocalPath, methodPath, request);
try {
List<Object> args = paramRetrievers.stream()
.map(paramRetriever -> pa... | Method method = TestRestFunction10.class.getMethod("test2", String.class, LambdaProxyRequest.class);
MethodInvoker methodInvoker = new MethodInvoker(TestRestFunction10.class, method, "/testRestPath10");
LambdaProxyRequest req = new LambdaProxyRequest();
req.setHttpMethod("POST");
... |
71376921_7 | class RGson {
public <T> Observable<T> read(final String value, final Class<T> classInstance) {
return Observable.fromCallable(new Callable<T>() {
@Override
public T call() throws Exception {
return GsonFunctions.readValue(gson, value, classInstance);
}
... | final JsonElement jsonElement = null;
TestSubscriber<Entity> testSubscriber = new TestSubscriber<Entity>();
Observable<Entity> observable = rGson.read(jsonElement, Entity.class);
observable.subscribe(testSubscriber);
testSubscriber.assertNoErrors();
List<Entity> list =... |
71470246_3 | class GcsRepository extends AbstractArtifactRepository {
private boolean exists(final String sha1) {
final Blob blob = gcsStorage.get(gcsProperties.getBucketName(), sha1);
if (blob == null) {
return false;
}
return blob.exists();
}
public GcsRepository(final St... | final byte[] rndBytes = randomBytes();
final String knownContentType = "application/octet-stream";
when(gcsStorageMock.get(anyString(), anyString())).thenReturn(gcpObjectMock);
when(gcpObjectMock.exists()).thenReturn(true);
// test
storeRandomBytes(rndBytes, knownConten... |
71492242_3 | class TemplateId {
public String getRoot() {
return root;
}
public TemplateId(String root, Optional<String> extension);
public Optional<String> getExtension();
@Override public int hashCode();
@Override public boolean equals(Object obj);
public static TemplateId of(String root, O... | // Arrange
final String root = "root";
// Act
TemplateId templateId = new TemplateId(root, Optional.empty());
// Assert
assertEquals(root, templateId.getRoot());
}
} |
71499649_0 | class SpringCloudStreamAppGeneratorMojo extends AbstractMojo {
@Override
public void execute() throws MojoFailureException {
// Bom
AppBom appBom = new AppBom()
.withSpringBootVersion(this.bootVersion)
.withAppMetadataMavenPluginVersion(this.appMetadataMavenPluginVersion);
AppDefinition app = new AppD... |
// disable metadata in container image (Default)
SpringCloudStreamAppGeneratorMojo.ContainerImage containerImage = new SpringCloudStreamAppGeneratorMojo.ContainerImage();
containerImage.setEnableMetadata(false);
setMojoProperty("containerImage", containerImage);
this.springCloudStreamAppMojo.execute();
/... |
71517454_141 | class ConsentHelper {
public boolean isConsentTermOverlap(ConsentDto consentDto,
Date conStartDate, Date conEndDate) {
boolean isOverlap = false;
Date selStartDate = consentDto.getConsentStart();
Date selEndDate = consentDto.getConsentEnd();
isOverlap = isDatesOverlap(selStartDate, selEndDate, conStartDat... |
// Arrange
//selected date range
consentDto.setConsentStart((Date) dateFormat.parse("06/12/2013 00:00:00"));
consentDto.setConsentEnd((Date) dateFormat.parse("06/12/2013 22:59:59"));
//Act
boolean isOverlap = cst.isConsentTermOverlap(consentDto, conStartDate, conEndDate... |
71636870_6 | class PointCalculator {
public Point onSwipe() {
if (swipeDirection == SwipeDirection.LEFT_TO_RIGHT) {
return new Point(parentView.getWidth() - target.getWidth(), target.getY());
} else {
return new Point(target.getX(), parentView.getHeight() - target.getHeight());
}
}
public PointCalcu... | pointCalculatorUT = new PointCalculator(SwipeDirection.LEFT_TO_RIGHT, parentView, targetView,
progressCalculator);
Point point = pointCalculatorUT.onSwipe();
assertThat(point.x, is(900.0f));
assertThat(point.y, is(0f));
}
} |
71651118_6 | class Stash implements JSONAware, Cloneable {
public long parseLong(String k) {
return Long.parseLong((String) m.get(k));
}
public Stash(Map<String, ?> m);
public Stash();
public Stash(Stash m);
public static Stash stashFromPairs(Iterable<T> ts, Function<T, Map.Entry<String, Object... | Stash smap = stash("foo", "5", "bar", null);
assertEquals(5, smap.parseLong("foo"));
assertEquals(5, smap.parseLong("foo", 3));
assertEquals(3, smap.parseLong("bar", 3));
}
} |
71697731_3 | class SensorAnnotations {
public static void bind(@Nullable Context context) {
bind(context, context);
}
public static void bind(@Nullable Object target, @Nullable Context context);
public static void unbind(@Nullable Object target);
private static SensorBinder findSensorBinderToBind(@Null... | SensorAnnotations.bind(mContext);
assertThat(SensorAnnotations.BINDER_CACHE).isEmpty();
SensorAnnotations.bind(new Object(), mContext);
assertThat(SensorAnnotations.BINDER_CACHE).isEmpty();
}
} |
71725051_15 | class IotaAPI extends IotaAPICore {
@Document
public List<String> prepareTransfers(String seed, int security,
List<Transfer> transfers,
String remainder,
List<Input> inputs,
... | List<Transfer> transfers = new ArrayList<>();
transfers.add(new Transfer(TEST_ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2, 5, TEST_MESSAGE, TEST_TAG));
List<String> trytes = iotaAPI.prepareTransfers(TEST_SEED1, 2, transfers, null, null, null, false);
assertNotNull(trytes, "prepareTransfers ... |
71742185_44 | class WxMpServiceImpl implements WxMpService {
@Override
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken) {
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/auth?");
url.append("access_token=").append(oAuth2AccessToken.getAccessToken())... | Assert.fail("Not yet implemented");
}
} |
71791406_2 | class TokenCode {
public int getCurrentProgress() {
long cur = System.currentTimeMillis();
TokenCode active = getActive(cur);
if (active == null)
return 0;
long total = active.mUntil - active.mStart;
long state = total - (cur - active.mStart);
return (in... | int progress = totpToken.generateCodes().getCurrentProgress();
assertTrue(progress > 0);
assertTrue(progress < 1000);
}
} |
71833308_4 | class ProfileManager {
@GET
@Path("/{email: [\\w\\.]+@[\\w\\.]+}/subscriptions")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllSubscriptions(@PathParam("username") String username, @PathParam("email") String subscriberId) {
logger.debug("Fetch all subscriptions for subscriber {} b... | public void getAllSubscriptionsTest() {
final Response response = target(PATH + username + "/" + email + "/subscriptions")
.request()
.accept(MediaType.APPLICATION_JSON_TYPE)
.get();
assertEquals("Getting all subscriptions failed", 200, response.getSt... |
71840517_23 | class AuctionEntity extends PersistentEntity<AuctionCommand, AuctionEvent, AuctionState> {
private Persist<AuctionEvent> reply(CommandContext<PlaceBidResult> ctx, PlaceBidResult result) {
ctx.reply(result);
return ctx.done();
}
@Override public Behavior initialBehavior(Optional<AuctionStat... | driver.run(new StartAuction(auction), new PlaceBid(500, bidder1));
Outcome<AuctionEvent, AuctionState> outcome = driver.run(new PlaceBid(4000, bidder1));
assertThat(outcome.events(), allOf(
hasItem(bidPlaced(bidder1, 2000, 4000)),
hasSize(1)
));
... |
71849550_0 | class StringUtils {
public static String stripTrailingSlash(String stringWithPossibleTrailingSlash){
if (stringWithPossibleTrailingSlash.endsWith("/")){
return stringWithPossibleTrailingSlash.substring(0, stringWithPossibleTrailingSlash.length()-1);
}
return stringWithPossibleTrailingSlash;
... | assertEquals("https://some.thing/with/a/slash/on/the/end", StringUtils.stripTrailingSlash("https://some.thing/with/a/slash/on/the/end/"));
}
} |
71876131_7 | class NetworkMapper {
public List<com.nilhcem.devfestnantes.data.app.model.Session> toAppSessions(@Nullable List<Session> from, @NonNull Map<Integer, com.nilhcem.devfestnantes.data.app.model.Speaker> speakersMap) {
if (from == null) {
return null;
}
return stream(from).map(sess... | // Given
LocalDateTime startAt = LocalDateTime.now();
Session session = new Session(1, startAt, 20, Room.NONE.id, singletonList(10), "title", "description");
Map<Integer, com.nilhcem.devfestnantes.data.app.model.Speaker> speakersMap = new HashMap<>();
speakersMap.put(10, new com.... |
71912078_0 | class PhoneLocationEngine {
public PhoneType matchPhone(String number) {
// check the number is telephone or cellphone
Matcher cellphoneMatcher = cellphonePattern.matcher(number);
if(cellphoneMatcher.matches()) {
return PhoneType.CELL;
}
Matcher telephoneMatcher ... | PhoneLocationEngine engine = new PhoneLocationEngine();
PhoneType[] phones = new PhoneType[] {
new PhoneType("010-1234567", PhoneLocationEngine.PhoneType.TELE),
new PhoneType("0101234567", PhoneLocationEngine.PhoneType.TELE),
new PhoneType("17000000000", ... |
71924391_3 | class UserPresenter {
public void start() {
mDataSource.getUser(mLoadUserCallback);
}
public UserPresenter(UserRepository dataSource, UserView view);
public void stop();
public void updateUserName(final String userName);
private LoadUserCallback createLoadUserCallback();
private ... | //Given that start is called
mPresenter.start();
// Callback is captured
verify(mUserRepository).getUser(mLoadUserCallbackArgumentCaptor.capture());
// When the user is loaded
User user = new User("user name");
mLoadUserCallbackArgumentCaptor.getValue().onUserLoa... |
71975377_141 | class ComplexUtils {
public static double[] complex2Interleaved(Complex[] c) {
int index = 0;
final double[] i = new double[c.length * 2];
for (final Complex cc : c) {
final int real = index * 2;
final int imag = index * 2 + 1;
i[real] = cc.getReal();
... | Assertions.assertThrows(IllegalArgumentException.class,
() -> ComplexUtils.complex2Interleaved(c2d, -1)
);
}
} |
71982467_4 | class KerberosUtil {
static final String[] getPrincipalNames(String keytabFileName) throws IOException {
Keytab keytab = Keytab.read(new File(keytabFileName));
Set<String> principals = new HashSet<String>();
List<KeytabEntry> entries = keytab.getEntries();
for (KeytabEntry entry : e... | try {
KerberosUtil.getPrincipalNames(testKeytab);
Assert.fail("Exception should have been thrown");
} catch (IOException e) {
//expects exception
}
}
} |
72001417_0 | class CommonUtils {
public static boolean isPasswordValid(String password) {
if (isEmpty(password)) {
return false;
}
String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(password);
... | assertTrue(CommonUtils.isPasswordValid("12345678abc"));
assertFalse(CommonUtils.isPasswordValid("12345678"));
assertFalse(CommonUtils.isPasswordValid("123456789"));
assertFalse(CommonUtils.isPasswordValid("aa"));
assertFalse(CommonUtils.isPasswordValid("aaaaaaaa"));
asser... |
72017294_4 | class TextureStyleTranslator implements IStyleDecoder<Texture>, IStyleEncoder<Texture>, IStyleValidator<Texture> {
@Override
public Texture decode(String style)
{
if (!style.startsWith("url(") && !style.startsWith("assets("))
return Texture.EMPTY;
if (style.startsWith("url("))
... | Texture textureUVST = new Texture("brokkgui:textures/gui/container_background.png", 16, 16, 32, 32);
assertThat(adapter.decode("url(\"brokkgui:textures/gui/container_background.png\", 16, 16,32, 32 )"))
.isEqualTo(textureUVST);
}
} |
72129238_1 | class Json {
public static Object parse(String str) {
StringStream ss = new StringStream(str);
Object result = parseGeneral(ss);
if (result instanceof Symbol)
throw new IllegalArgumentException("Malformed JSON");
if (!isSymbol(parseGeneral(ss), -1))
throw new IllegalArgumentException("Malformed JSON");
... | String[] cases = {
"",
" ",
"a",
"false\"",
"trues",
"null1",
"*",
"00",
"01",
"08",
"+0",
"+2",
"+2.3",
"2.3.4",
"2e2e2",
"2e++0",
"2e+-0",
"2e--0",
"2f",
"0x10",
"0 0",
"0,0",
"0 //",
"\"",
"\"\\",
"\"\\\"",
"\"\"\"",
"\"\\a\"",
... |
72188443_6 | class SimpleAttributeProvider extends AbstractAttributeProvider {
@Override
protected HashBasedTable<Optional<String>, Optional<Locale>, String> getAttributeValue(final Collection<Locale> locales,
final ProductModel product, final MetaAttributeData metaAttribute)
{
final HashBasedTable<Optional<String>, Option... | final ProductModel product = new ProductModel();
product.setCode("productCode");
final ComposedTypeModel composedType = new ComposedTypeModel();
final MetaAttributeData metaAttribute = new MetaAttributeData();
metaAttribute.setBaseType(FhAttributeBaseType.FLOAT);
metaAttribute.setAttributeId("price");
me... |
72240906_14 | class IntValidator implements Validator<Integer> {
@Override
public boolean isSpecificationValid() {
return true;
}
@Override public String getInvalidSpecificationMessage();
}
class IntValidatorTest {
@Test
public void testLessThanOrEqualsToIsSpecificationValid() {
| IntValidator.LessThanOrEqualTo instance = new IntValidator.LessThanOrEqualTo(5);
assertTrue(instance.isSpecificationValid());
instance = new IntValidator.LessThanOrEqualTo(-999999999);
assertTrue(instance.isSpecificationValid());
}
} |
72241120_4 | class StopwatchImpl extends AbstractStopwatch {
@NonNull
@Override
public Observable<Long> start() {
if (timerObservable != null) {
LogUtil.d(TAG, "start(). Returning original Observable");
return timerObservable;
}
LogUtil.d(TAG, "start(). Returning new Obs... | // Setup
TestSubscriber<Long> testSubscriber = resetTest();
// Exercise
stopwatch.start().subscribe(testSubscriber);
advanceTimeBy(5L);
// Verify
testSubscriber.assertValues(1L, 2L, 3L, 4L, 5L);
}
} |
72283823_12 | class Palindrome {
public void init() {
final int MAX_LENGTH_OF_WORD = 5;
try (Scanner sc = new Scanner(System.in)) {
String line = sc.nextLine();
if (line.length() == MAX_LENGTH_OF_WORD) {
StringBuilder sbReverseWord = new StringBuilder();
fo... | String testWord = "Камок";
System.setIn(new ByteArrayInputStream(testWord.getBytes()));
new Palindrome().init();
assertThat(this.out.toString(), is(String.format("%s is NOT palindrome%s", testWord, sep)));
}
} |
72366767_64 | class ArticleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@VisibleForTesting
int getItemResourceFromType(int viewType) {
switch (viewType) {
case TYPE_HEADER_IMAGE: return R.layout.article_item_header;
case TYPE_TITLE: return R.layout.ar... | assertEquals(
R.layout.article_item_header_6,
adapter.getItemResourceFromType(ArticleAdapter.TYPE_HEADER_6));
}
} |
72403045_22 | class Database implements AutoCloseable {
public <T> Single<T> apply(Function<? super Connection, ? extends T> function) {
return member().map(member -> {
try {
return function.apply(member.value());
} finally {
member.checkin();
}
... | Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
CallableStatement st = con.prepareCall("call in1out0rs2(?)");
st.setInt(1, 0);
st.execute();
ResultSet... |
72428844_19 | class ChangesDetector {
public void newData(@Nonnull ChangesAdapter adapter,
@Nonnull List<? extends T> values,
boolean force) {
checkNotNull(adapter);
checkNotNull(values);
final H[] list = apply(values);
final ArrayList<H> objects ... | detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2), new Cat(3)), false);
reset(adapter);
detector.newData(adapter, ImmutableList.of(new Cat(1), new Cat(2).withName("two1"), new Cat(3).withName("tree1")), false);
verify(adapter).notifyItemRangeChanged(1, 2);
}
} |
72436214_29 | class ConstituencyAssociationService {
@Transactional
public Try<User> associateToUser(User permissible, UUID constituencyID, UUID userID) {
if (!permissible.isAdmin()) {
log.error("Non admin attempted to associate user={} to constituency={}. loggedInUser={}", userID, constituencyID, permis... | User admin = user().withRole(Role.ADMIN).build();
User user = user().withConstituencies(new HashSet<>()).build();
Constituency constituency = constituency().build();
given(constituencyRepository.findOne(constituency.getId())).willReturn(constituency);
given(userRepository.findOne... |
72462669_13 | class StackdriverSpanConsumer implements SpanConsumer {
@Override
public Call<Void> accept(List<Span> spans) {
if (spans.isEmpty()) return Call.create(null);
List<com.google.devtools.cloudtrace.v2.Span> stackdriverSpans =
SpanTranslator.translate(projectId, spans);
BatchWriteSpansRequest reques... | onClientCall(
observer -> {
observer.onNext(Empty.getDefaultInstance());
observer.onCompleted();
});
spanConsumer.accept(asList(TestObjects.CLIENT_SPAN)).execute();
ArgumentCaptor<BatchWriteSpansRequest> requestCaptor =
ArgumentCaptor.forClass(BatchWriteSpansReq... |
72479874_10 | class IntentTag extends ParameterizedTag {
static void parseAndSetExtra(Bundle target, String name, String value) {
Matcher m = EXTRAS_VALUE_CAST_PATTERN.matcher(value);
if (m.matches()) {
String type = m.group(2);
String rawValue = m.group(3);
String booleanValu... | IntentTag.parseAndSetExtra(mBundle, "zero", "int(0)");
verify(mBundle).putInt("zero", 0);
IntentTag.parseAndSetExtra(mBundle, "one", "int(1)");
verify(mBundle).putInt("one", 1);
IntentTag.parseAndSetExtra(mBundle, "neg_one", "int(-1)");
verify(mBundle).putInt("neg_one",... |
72495006_4 | class StackdriverMonitoringReporter extends ScheduledReporter {
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
String now = new DateTime(cloc... | reporter.report(map("gauge", gauge(1.1f)),
this.map(),
this.map(),
this.map(),
this.map());
assertTimeSeries(1, "gauge", GAUGE, T0, 1.1f );
}
} |
72517914_15 | class Geocoding {
public Maybe<Address> fromLocation(@NonNull Location location) {
return fromLocation(null, location, 1).flatMapMaybe(ADDRESS_MAYBE_FUNCTION);
}
Geocoding(Context context);
Geocoder getGeocoder(Locale locale);
public Maybe<Address> fromLocation(Locale locale, @NonNull ... | doReturn(addressList).when(geocoder).getFromLocation(latitude, longitude, 1);
geocoding.fromLocation(locale, latitude, longitude, 1).test()
.assertValue(addressList)
.assertComplete();
verifyGeocoderWithLocale();
}
} |
72586987_3 | class AES {
public static String unPackString(byte[] bytes) throws UnsupportedEncodingException {
return new String(unPackBytes(bytes), "UTF-8");
}
public static byte[] encrypt(byte[] bytes, byte[] encryptionKey);
public static byte[] decrypt(byte[] cipherText, byte[] encryptionKey);
publi... | assertThat(AES.unPackString(AES.pack(unpaddedtext)), is(unpaddedtext));
}
} |
72695594_90 | class TileInfo {
public Map<String, String> getSpriteFilenames() {
return spriteFilenames;
}
TileInfo(Tiles type);
public static Map<Tiles, TileInfo> getTileRegistry();
public static boolean hasLoaded();
public static void registerTiles();
private static void registerTile(TileInfo tile);
public static vo... | Map<String, String> fileNames = testGasTile.getSpriteFilenames();
assert (fileNames.keySet().size() == 1);
assert (fileNames.keySet().contains("DEFAULT"));
assert (fileNames.get("DEFAULT").equals("sprites/tiles/air.png"));
}
} |
72700804_0 | class DecimalUtils {
public static String toDecimal(long seconds, int nanoseconds)
{
StringBuilder sb = new StringBuilder(20)
.append(seconds)
.append('.');
// 14-Mar-2016, tatu: Although we do not yet (with 2.7) trim trailing zeroes,
// for general case,
... | String decimal = DecimalUtils.toDecimal(0, 0);
assertEquals("The returned decimal is not correct.", NO_NANOSECS_SER, decimal);
decimal = DecimalUtils.toDecimal(15, 72);
assertEquals("The returned decimal is not correct.", "15.000000072", decimal);
decimal = DecimalUtils.toDecim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.