id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
43356615_97 | class Tracker {
Tracker setParam(String key, Closure value) {
return processSetParam(key, value);
}
public Tracker();
Tracker(boolean registerNeeded);
public Tracker(android.content.Context context);
Tracker(android.content.Context context, boolean registerNeeded);
public Tr... | ParamOption options = new ParamOption().setPersistent(true).setAppend(true);
tracker.setParam(key, 1)
.setParam(key, "test");
tracker.setParam(key, 1, options)
.setParam(key, 67, options);
assertEquals(1, buffer.getVolatileParams().size());
assert... |
43357646_0 | class RoboVMWebService {
public void getProducts(Action<List<Product>> completion) {
Objects.requireNonNull(completion);
if (products != null) {
ActionWrapper.WRAPPER.invoke(completion, products);
} else {
api.products().enqueue(new Callback<ProductsResponse>() {
... | Call<ProductsResponse> call = api.products();
ProductsResponse response = call.execute().body();
assertTrue(response.isSuccess());
List<Product> products = response.getProducts();
assertNotNull(products);
assertEquals(products.size(), 2);
Product menJavaTShirt ... |
43367865_1 | class LRS {
public String LRS(String query)
{
String[] suffixes = new String[query.length()];
for(int i = 0; i < query.length(); i++)
{
suffixes[i] = query.substring(i);
}
Arrays.sort(suffixes);
Pair answer = new Pair();
answer.count = 0;
for(int i = 0; i < suffixes.length - 1; i++)
{
Pair... | String test = "bananabanana";
String answer = lrs.LRS(test);
String expected = "banana";
assertTrue(answer.equals(expected));
}
} |
43368910_4 | class Types {
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
// Type is a normal class.
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
... | try {
Types.getRawType(null);
fail("An IllegalArgumentException must have occurred as we passed a null object to this method");
} catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().startsWith("Expected a Class, ParameterizedType, or GenericArrayType"));
... |
43388015_0 | class NaturalOrder implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return compareStrings(o1, o2);
}
public static final int compareStrings(String s1, String s2);
}
class NaturalOrderTest {
@Test
public void testCompare() {
| System.out.println("compare");
String s1 = "i";
String s2 = "I";
int expResult = 0;
int result = NaturalOrder.compareStrings(s1, s2);
assertEquals(expResult, result);
s1 = "ISAAC metadata (ISAAC)";
s2 = "health concept";
result = NaturalOrder.compareStrings(s1, s2)... |
43398044_198 | class ProjectRestApi extends ApiBase implements ProjectApi {
@Override
public void getTasksForProjectAsync(final String projectId, final FutureCallback<ResourceList<Task>>
responseCallback)
throws
IOException {
final String path = String.format("%s/%s/tasks", getBasePath(), projectId);
R... | Task task1 = new Task();
task1.setId("task1");
Task task2 = new Task();
task2.setId("task2");
Task task3 = new Task();
task3.setId("task3");
String nextPageLink = "nextPageLink";
ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2), nextPageLink, null)... |
43430328_1 | class PermissionPresenter {
public void requestReadContactsPermission() {
checkAndRequestPermission(Action.READ_CONTACTS);
}
public PermissionPresenter(PermissionAction permissionAction, PermissionCallbacks permissionCallbacks);
public void requestReadContactsPermissionAfterRationale();
... | when(permissionAction.hasSelfPermission(READ_CONTACTS)).thenReturn(false);
when(permissionAction.shouldShowRequestPermissionRationale(READ_CONTACTS)).thenReturn(true);
permissionPresenter.requestReadContactsPermission();
verify(permissionCallbacks).showRationale(Action.ACTION_CODE_READ_... |
43502922_10 | class Translator {
public Task translate(InternalTask in) {
Task out = null;
if (in != null) {
out = new Task();
out.uuid = in.uuid;
out.description = in.description;
out.done = in.status == InternalTask.Status.Completed;
out.urgency = in.... | assertTrue(mTranslator.translate(null) == null);
}
} |
43504026_27 | class WebXmlParameters {
public String getAjaxProcessingTextOnRequest() {
return ajaxProcessingTextOnRequest;
}
public WebXmlParameters(final ExternalContext externalContext);
private boolean readBooleanParameter(final String parameter, final ExternalContext context);
private String read... | assertEquals(WebXmlParameters.DEFAULT_AJAX_PROCESSING_TEXT, new WebXmlParameters(defaultValueExternalContext).getAjaxProcessingTextOnRequest());
assertEquals(OVERRIDDEN_AJAX_PROCESSING_TEXT, new WebXmlParameters(overriddenValueExternalContext).getAjaxProcessingTextOnRequest());
}
} |
43563629_9 | class AmazonAppStoreRule implements IEnvironmentBasedRule {
@Override
public boolean shouldAllowFeedbackPrompt(@NonNull final IEnvironment environment) {
return environment.isAmazonAppStoreInstalled();
}
@NonNull @Override public String getDescription();
private AmazonAppStoreRule amazonA... | // Arrange
when(environment.isAmazonAppStoreInstalled()).thenReturn(true);
// Act
final boolean isEnvironmentRuleSatisfied = amazonAppStoreRule.shouldAllowFeedbackPrompt(environment);
// Assert
assertTrue("Environment based rule should be satisfied", isEnvironmentRuleSa... |
43568553_0 | class SchemaVersion implements Comparable<SchemaVersion> {
public int compareTo(SchemaVersion other) {
if(this.version.equalsIgnoreCase(other.version)
|| this.version == V_ANY.version
|| other.version == V_ANY.version) {
return 0;
}
String[] v1Splits = this.version.split("\\.")... | SchemaVersion schemaVersion1 = new SchemaVersion();
SchemaVersion schemaVersion2 = new SchemaVersion();
schemaVersion1.version = "1.0";
schemaVersion2.version = "1.0";
assertEquals(0, schemaVersion1.compareTo(schemaVersion2));
schemaVersion1.version = "1.0";
schemaVersion2.version ... |
43569889_0 | class CryptoUtil {
static long getLong(final byte[] bytes) {
return new BigInteger(bytes).longValue();
}
public static byte[] convertDEREncodedSignatureToJWSConcatenated(final byte[] derEncodedSignatureValue);
public static byte[] convertJWSConcatenatedToDEREncodedSignature(final byte[] concatenatedSigna... |
Assert.assertEquals(CryptoUtil.getLong(bytes), expected);
}
} |
43591538_6 | class PlacesViewModel implements IPlacesViewModel {
@Override
public Observable<Boolean> fetchAllPlaces() {
return mPlacesApi.placesResult()
.map(googleSearchResult -> {
allPlaces = googleSearchResult.results;
mPlaces.onNext(googleSearchResult.res... | AtomicInteger atomicInteger = new AtomicInteger(0);
when(placesApi.placesResult()).thenReturn(
Observable.create(subscriber -> {
if (atomicInteger.getAndIncrement() < 3) {
subscriber.onError(new Exception());
} else {
... |
43645816_99 | class LogFormatter {
public <Message extends PMessage<Message, Field>, Field extends PField>
String format(Message message) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
formatTo(out, message);
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
public ... | OptionalFields credentials = OptionalFields
.builder()
.setStringValue("username")
.setBinaryValue(Binary.fromBase64("password"))
.build();
LogFormatter formatter = new LogFormatter(true, (writer, field, value) -> {
if (field.g... |
43682339_3 | class TargetFactory {
@VisibleForTesting
protected File findImageFile(String imageFile) {
File foundImageFile = findImageFile(folderToScan, imageFile);
// creating non existing file to avoid NPE
return foundImageFile == null ? new File(imageFile) : foundImageFile;
}
public void... | // user mistakenly added "/" in front of relative file name
File f1 = targetFactory.findImageFile("/" + FILE_PATH);
assertTrue(f1.exists());
File f2 = targetFactory.findImageFile("\\" + FILE_PATH_BACKSLASHED);
assertTrue(f2.exists());
}
} |
43688721_56 | class AutosleepServiceInstanceService implements ServiceInstanceService {
@Override
public UpdateServiceInstanceResponse updateServiceInstance(
UpdateServiceInstanceRequest request) throws
ServiceInstanceUpdateNotSupportedException, ServiceBrokerException, ServiceInstanceDoesNotExistExc... | // given transient service with secret exists
transient_service_with_secret_exist_in_database();
// when user gives auto enrollment without secret
UpdateServiceInstanceRequest updateRequest = getUpdateRequestWithArbitraryParams(
singletonMap(Config.ServiceInstanceParamet... |
43734923_111 | class ConstructConsequentVisitor extends AbstractQueryModelVisitor<RuntimeException> {
public Set<StatementPattern> getConsequents() {
return consequentStatementPatterns;
}
public Set<StatementPattern> getBnodes();
@Override public void meet(Projection projection);
@Override public void me... | Extension extension = new Extension(new SingletonSet(),
new ExtensionElem(new ValueConstant(FOAF.PERSON), "x"),
new ExtensionElem(new ValueConstant(RDF.TYPE), "y"),
new ExtensionElem(new ValueConstant(OWL.CLASS), "z"));
Projection projection = new Projecti... |
43792695_1 | class MamircConnector {
static byte[] makePongIfPing(byte[] line) {
// Skip prefix, if any
int i = 0;
if (line.length >= 1 && line[i] == ':') {
i++;
while (i < line.length && line[i] != ' ')
i++;
while (i < line.length && line[i] == ' ')
i++;
}
// Check that next 4 characters are "PING" ... | String[][] cases = {
{null, ""},
{null, "PONG"},
{null, "PINGU"},
{null, " PING"},
{null, " :abc PING"},
{null, "PING:def"},
{null, "abc WHAT PING"},
{null, "STOPPING"},
{null, ":nick!user@host PRIVMSG #chan :PING"},
{"PONG", "PING"},
{"PONG", ":prefix PING"},
{"PONG ", ":pre PIN... |
43826822_0 | class RiverService {
public boolean embarkTourists(int n) throws RiverServiceException {
processInstance = ksession.startProcess("com.yahoo.sorelmitra.EmbarkTourists");
int state = processInstance.getState();
LOG.info("Process state is " + state);
if (state != ProcessInstance.STATE_... | Assert.assertEquals(10, cutter.getEmptySeats());
boolean result;
result = rs.embarkTourists(6);
Assert.assertTrue(result);
Assert.assertEquals(4, cutter.getEmptySeats());
result = rs.embarkTourists(6);
Assert.assertFalse(result);
Assert.assertEquals(4, ... |
43829671_3 | class CoordinatesDao extends BaseDao {
public List<DNCWorkCoordinate> getCoordinates() {
SessionWrapper session = getCurrentSourceSession();
try {
Query getCoordinates = session.getNamedQuery("getCoordinates");
List<DNCWorkCoordinate> coordinateList = getCoordinates
... | dao.executeSQLQueryForSource("create table vwTestCoordinates(patientId int, sourceTable varchar(100), sourceColumn varchar(100), idInSourceTable int, pkColumnName varchar(100), type varchar(100), updateTime varchar(100))");
dao.executeSQLQueryForSource("insert into vwTestCoordinates values(5, 'patientDo... |
43832779_133 | class ParkController {
@SuppressWarnings("unchecked")
@RequestMapping("/{token}*")
public String userFront(@PathVariable String token,
@RequestParam(required = false) String tag,
@RequestParam(required = false) String q,
@RequestParam(required = false) Integer page,
... | ParkController controller = new ParkController();
Map<String, Object>[] filteredStbs = new HashMap[1];
Map<String, Object>[] allStbs = new HashMap[2];
Map<String, Object> stb1 = new HashMap<String, Object>();
stb1.put(MetaStb.ID, "sample");
stb1.put(MetaStb.TAGS, Arrays.a... |
43901081_9 | class TaskModel {
public Task get(int index) {
return taskManager.get(index);
}
public TaskModel(ClientModel clientModel, TaskManager taskManager);
@Handler public void selectedClientChanged(SelectedClientChangedEvent event);
public void subscribe(Object listener);
public void unsubs... | assertEquals(task1, model.get(0));
assertEquals(task2, model.get(1));
}
} |
43913943_40 | class LoginPresenter extends AbstractPresenter<ILoginView> {
public void onLoginClick() {
logger.debug("onLoginClick() called");
getView().showProgress();
call = loginModule.login(login, password);
call.enqueue(
data -> getView().advance(),
error -> {... | initPresenter();
when(loginModule.login(anyString(), anyString())).thenReturn(Call.error(new PasswordException()));
presenter.onLoginClick();
verify(view).setPasswordErrorVisible(true);
}
} |
43923787_43 | class PropertiesLoader {
public static Properties load(final String path) {
try {
InputStream input = null;
try {
final Resource resource = new ClassPathResource(path);
input = resource.getInputStream();
} catch (final IOException e) {
... | final String path = "/context.properties";
final String notFoundPath = "/context_notfound.properties";
final String classPath = "classpath:context.properties";
try {
PropertiesLoader.load(notFoundPath);
} catch (final Throwable e) {
Assert.assertEquals(e i... |
43952556_16 | class DefaultDatabaseAccessor implements DatabaseAccessor {
public void createDatabase() throws StorageExistsException {
this.fileStructure.initializeStorage(storage, attributes, ATTRIBUTE_VERSION);
}
DefaultDatabaseAccessor(String version, String databaseName, Storage storage);
DefaultDat... |
DefaultDatabaseAccessor accessor = new DefaultDatabaseAccessor("x.y", "myDb", storage, extraAttributes("custom", "myValue"), fileStructure, recordStructure);
accessor.createDatabase();
ArgumentCaptor<Map<String, String>> actualAtts = ArgumentCaptor.forClass(Map.class);
verify(fileStr... |
44007584_141 | class UrlUtils {
public static Map<String, String> convertSubscribe(Map<String, String> subscribe) {
Map<String, String> newSubscribe = new HashMap<String, String>();
for (Map.Entry<String, String> entry : subscribe.entrySet()) {
String serviceName = entry.getKey();
String s... | String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe);
assertEquals(subscribe, newSubscribe);
}
} |
44013219_19 | class ProcessEnginePluginEvent extends Event<T> {
public static PreInitEvent preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
return new PreInitEvent(processEngineConfiguration);
}
protected ProcessEnginePluginEvent(T data, Class<S> type);
public static PostInitEvent postInit(Process... | camundaEventBus.register(new AbstractProcessEnginePlugin() {
@Override
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
processEngineConfiguration.getBeans();
}
});
camundaEventBus.notify(ProcessEnginePluginEvent.preInit(processEngineConfiguration))... |
44013289_4 | class TypeUtils {
public static boolean equals(@Nullable Object left, @Nullable Object right) {
if (left == right) { return true; }
if (left == null || right == null) { return false; }
// handle arrays on both sides as special case for efficiency
Class<?> leftClass = left.getClass(... | Integer[] integers1 = new Integer[]{Integer.valueOf(1), Integer.valueOf(2)};
Integer[] integers2 = new Integer[]{Integer.valueOf(1), Integer.valueOf(2), new Integer(3)};
int[] ints1 = {1, 2};
int[] ints2 = {1, 2, 3};
List<Integer> lintegers = asList(Integer.valueOf(1), Integer.va... |
44064037_42 | class Load8BitRegisterAIntoHLAddress extends Instruction {
@Override public void execute() {
byte registerValue = z80.get8BitRegisterValue(Register.A);
int address = z80.get16BitRegisterValue(Register.HL);
mmu.writeByte(address, registerValue);
z80.setLastInstructionExecutionTime(2);
}
Load8Bi... | Instruction instruction = new Load8BitRegisterAIntoHLAddress(z80, mmu);
instruction.execute();
assertEquals(2, z80.getLastInstructionExecutionTime());
}
} |
44124366_61 | class DefaultFilterDialect implements JoinFilterDialect, SubqueryFilterDialect {
@Override
public Map<String, FilterExpression> parseTypedExpression(String path, MultivaluedMap<String, String> filterParams)
throws ParseException {
Map<String, FilterExpression> expressionMap = new HashMap<>(... | MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add(
"filter[book.awards][hasnomember]",
"awards1"
);
assertEquals(
"{book=book.awards HASNOMEMBER [awards1]}",
dialect.parseTypedExpressi... |
44130574_4 | class EtcdClient implements InitializingBean, DisposableBean {
public EtcdResponse put(final String key, final String value) throws EtcdException {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
builder.pathSegment(key);
MultiValueMap<String, String> payload = new LinkedMultiValue... | server.expect(MockRestRequestMatchers.requestTo("http://localhost:2379/v2/keys/sample?ttl=60"))
.andExpect(MockRestRequestMatchers.method(HttpMethod.PUT))
.andExpect(MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_FORM_URLENCODED))
.andExpect(MockRestRequestMatchers.content().string("v... |
44133514_1 | class BundleUtils {
public static boolean equals(Bundle left, Bundle right) {
if (left == right) {
return true;
}
if (left == null
|| right == null) {
return false;
}
final Set<String> leftSet = left.keySet();
final Set<St... | final Bundle left = new Bundle();
left.putInt("int", 9);
left.putDouble("double", 1.D);
final Bundle right = new Bundle();
right.putInt("int2", 9);
right.putDouble("double", 1.D);
assertFalse(BundleUtils.equals(left, right));
}
} |
44167878_7 | class Utils {
public static String trimPreffix(String s, String preffix) {
if (Strings.isNullOrEmpty(preffix))
return s;
return s.startsWith(preffix) ? s.substring(preffix.length()) : s;
}
public static boolean isNull(Object object);
public static boolean atLeastOneIsNull(Object... objects);
public static... | assertEquals("toto", Utils.trimPreffix("toto", "titi"));
assertEquals("toto", Utils.trimPreffix("tititoto", "titi"));
assertEquals("tototiti", Utils.trimPreffix("tototiti", "titi"));
assertEquals("toto", Utils.trimPreffix("toto", ""));
assertEquals("", Utils.trimPreffix("titi", "titi"));
assertEquals("", Ut... |
44190749_14 | class UserManagementController extends AbstractUserAndContractsController {
@RequestMapping(value = TgolKeyStore.EDIT_USER_URL, method = RequestMethod.POST)
@Secured(TgolKeyStore.ROLE_ADMIN_KEY)
protected String submitEditUserForm(
@ModelAttribute(TgolKeyStore.CREATE_USER_COMMAND_KEY) CreateUse... | setUpMockRoleDataService();
setUpMockUserDataService(false, false, false);
setUpMockAuthenticationContext();
// Finally the form is conform and the admin page is returned
CreateUserCommand createUserCommand = createUserCommandFactory.getNewCreateUserCommand();
createUser... |
44196774_1 | class PostsPresenter {
public void loadPostsFromAPI() {
/* postsAPI.getPostsObservable().retryWhen(new Function<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> apply(Observable<? extends Throwable> errorNotification) {
return erro... |
//create mocks
Observable<List<Post>> postsObservable = (Observable<List<Post>>) mock(Observable.class);
//define return values
when(postsPresenter.postsAPI.getPostsObservable()).thenReturn(postsObservable);
when(postsObservable.subscribeOn(Schedulers.io())).thenReturn(postsObs... |
44250608_23 | class FlowFilter implements HttpFilter {
@Override
public void doFilter(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException {
flow.readFrom(request::getHeader);
if (isLegacyRequest(request)) {
... | assertThrows(IllegalArgumentException.class, () ->
filter.doFilter(mock(ServletRequest.class), mock(HttpServletResponse.class), null));
}
} |
44253742_143 | class NomadEndpoint implements NomadServer<T> {
@Override
public AcceptRejectResponse rollback(RollbackMessage message) throws NomadException {
return server.rollback(message);
}
public NomadEndpoint(InetSocketAddress address, NomadServer<T> server);
public InetSocketAddress getAddress();
@Override ... | when(server.rollback(rollbackMessage)).thenReturn(acceptRejectResponse);
NomadEndpoint<String> namedServer = new NomadEndpoint<>(name, server);
assertEquals(acceptRejectResponse, namedServer.rollback(rollbackMessage));
verify(server).rollback(rollbackMessage);
}
} |
44253783_1032 | class MetadataTotalsInterceptor extends MetadataMetricsInterceptorImpl {
private int getValue(String key, AdaptrisMessage msg) {
if (!msg.headersContainsKey(key)) {
return 0;
}
return Integer.parseInt(msg.getMetadataValue(key));
}
public MetadataTotalsInterceptor();
public MetadataTotalsIn... | LifecycleHelper.init(metricsInterceptor);
LifecycleHelper.start(metricsInterceptor);
AdaptrisMessage message = createMessage();
assertEquals(0, metricsInterceptor.getStats().size());
submitMessage(message);
// Make sure there is 1 message in the cache
assertEquals(1, metricsInterceptor.getS... |
44263579_1 | class InventoryService {
public InventoryCategory getCategory(String name) {
if (name == null) {
return null;
}
return inventoryRepository.findByName(name);
}
public List<InventoryCategory> getAllCategories();
public void addCategory(InventoryCategory category);
@Inject
private Inven... | InventoryCategory category = inventoryService.getCategory("default_category");
Assert.assertEquals("default description", category.getCategoryDescription());
category = inventoryService.getCategory("extra_category");
Assert.assertEquals(1002, category.getId());
Assert.assertEqual... |
44293742_1 | class WXBizMsgCrypt {
String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] corpi... | try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, corpId);
assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2));
} catch (AesException e) {
e.printStackTrace();
fail("no异常");
}
}
} |
44308560_186 | class Events {
static Map<String, String> ensureOrderedMapOfStringsToStrings(final Map<?, ?> map) {
final Map<String, String> result = new LinkedHashMap<>();
map.forEach((key, value) -> result.put((String) key, (String) value));
return result;
}
static URI toFileUri(final String so... | final Map<?, ?> map = ImmutableMap.of("x", "a", "y", new Object());
assertThatExceptionOfType(ClassCastException.class)
.isThrownBy(() -> Events.ensureOrderedMapOfStringsToStrings(map));
}
} |
44336879_2 | class ReLinkerInstance {
protected File getWorkaroundLibFile(final Context context,
final String library,
final String version) {
final String libName = libraryLoader.mapLibraryName(library);
if (TextUtils.isEmpty(vers... | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller);
final String libName = testLoader.mapLibraryName(TEST_LIB);
final File libFile = new File(libDir, libName);
assertThat(instance.getWorkaroundLibFile(context, TEST_LIB, null), is(libFile));
final F... |
44343498_11 | class TranslatorFactory extends BaseComponentFactory<Translator, TranslatorConfiguration> {
public static Translator buildTranslator() throws ToolkitException {
return buildTranslator(null, null);
}
public TranslatorFactory();
public TranslatorFactory(Properties properties);
public Tr... | Properties properties = new Properties();
properties.setProperty(TranslatorConfiguration.TRANSLATOR_CLASS_NAME_KEY, FakeTranslator.class.getName());
Translator translator = TranslatorFactory.buildTranslator(null, properties);
assertNotNull("Translator was not built.", translator);
}
... |
44431868_10 | class AuthObservable {
@Deprecated
public Observable<AuthToken> getToken(final Context context, final String email, final String scope) {
return Observable.create(new Observable.OnSubscribe<AuthToken>() {
@Override
public void call(Subscriber<? super AuthToken> observer) {
... | Exception e = new Exception();
when(GoogleAuthUtil.getToken(context, "email", scope)).thenThrow(e);
sut.getToken(context, "email", scope).subscribe(testSubscriber);
testSubscriber.assertError(e);
}
} |
44431891_7 | class PreferencesHelper {
public int getAutoRefreshInterval() {
return Integer.valueOf(mSettingsPref.getString(mResources.getString(R.string.preferences_settings_key_auto_refresh_interval), "3"));
}
@Inject public PreferencesHelper(Context context);
public void clear();
public void saveS... | assertThat(mPreferencesHelper.getAutoRefreshInterval()).isEqualTo(3);
}
} |
44437701_4 | class Singleton {
@SuppressWarnings("unchecked")
public static <T extends Singleton> T getInstance(Class<T> clazz) {
Singleton singleton;
Lock lock;
(lock = GLOBAL_LOCK.readLock()).lock(); //1st locking
try {
singleton = CACHE.get(clazz); //1st reading
... | D d = D.getInstance();
byte[] buffer;
try (ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout)) {
oout.writeObject(new DWrapper(d));
oout.flush();
buffer = bout.toByteArray();
... |
44453405_2 | class ArgsToVote {
public static Vote parse(String[] arguments) {
return parse(arguments, null);
}
public static Vote parse(String[] arguments, Map<String, String> additionalArgs);
}
class ArgsToVoteTest {
@Test
void handlesInvalidRequest() {
| assertThrows(IllegalArgumentException.class, () -> {
ArgsToVote.parse(new String[0]);
});
}
} |
44465166_89 | class CorelexFeatureExtractor extends WordFeatureExtractor {
@Override
public Set<Feature> getWordFeatures(TextAnnotation ta, int wordPosition) throws EdisonException {
if (data.size() == 0)
loadDataFromClassPath();
String lemma = WordHelpers.getLemma(ta, wordPosition);
S... | TextAnnotation ta = DummyTextAnnotationGenerator.generateAnnotatedTextAnnotation(false, 3);
assertEquals(CorelexFeatureExtractor.instance.getWordFeatures(ta, 1).toString(), "[cae]"); // construction
assertEquals(CorelexFeatureExtractor.instance.getWordFeatures(ta, 20).toString(), "[avt]"); // p... |
44519815_18 | class Slice extends AbstractSlice {
@Override
public void reset()
{
super.reset();
m_lastValues.clear();
}
protected Slice();
public Slice(/*@ non_null @*/ Function func, /*@ non_null @*/ Processor proc,
Function clean_func);
public Slice(/*@ non_null @*/ Function func, /*@ non_null @*/... | Slice sli = new Slice(Numbers.isEven, new Sum());
QueueSource source = new QueueSource().setEvents(1, 1, 6, 2, 3);
Connector.connect(source, sli);
Pullable p = sli.getPullableOutput();
Map<Object,Object> map;
for (int k = 0; k < 2; k++)
{
assertEquals(0, sli.getActiveSliceCount());
map = (Map<Object... |
44525387_28 | class ModelNodeResult extends ModelNode {
public final ModelNode value() {
return get(Constants.RESULT);
}
@Deprecated public ModelNodeResult();
public ModelNodeResult(ModelNode original);
private String adjustAssertMessage(String message);
public final boolean isSuccess();
publ... | ModelNodeResult result = new ModelNodeResult(DEFINED_RESULT_BOOLEAN);
assertTrue(result.booleanValue());
assertTrue(result.booleanValue(false));
result = new ModelNodeResult(DEFINED_RESULT_NUMBER);
assertEquals(13, result.intValue());
assertEquals(13L, result.longValue()... |
44565647_8 | class ControlledPwmServlet extends AbstractPwmServlet implements PwmServlet {
public abstract Class<? extends ProcessAction> getProcessActionsClass( )public abstract Class<? extends ProcessAction> getProcessActionsClass( );
public abstract Class<? extends ProcessAction> getProcessActionsClass( )public String servletU... | final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
{
final Class<? extends AbstractPwmServlet.ProcessAction> processActionsClass = controlle... |
44586882_134 | class PebbleTemplateService implements TemplateService {
@Override
public
@NonNull
String mergeTemplateIntoString(final @NonNull String templateReference,
final @NonNull Map<String, Object> model)
throws IOException, TemplateException {
final Strin... | //Arrange
final Map<String, Object> modelObject = new ImmutableMap.Builder<String, Object>().build();
assertions.assertThat(modelObject).isNotNull();
expectedException.expect(NullPointerException.class);
//Act
templateService.mergeTemplateIntoString(null, modelObject);
... |
44603117_13 | class DataSourceService {
@PreAuthorize("hasAuthority(#datasourceName+'_MANAGE') or hasAuthority('SYS_MANAGE_DATASOURCE')")
public int deleteDataSource(String datasourceName) {
checkNotNull(datasourceName);
if(isStaticDataSource(datasourceName)) return 0;
DBDataSource datasourceCondition = new DBDataSource();... | final DBDataSource datasourceCondition = new DBDataSource();
datasourceCondition.setOwner(uttestuser);
datasourceCondition.setName(uttestdatasource1);
datasourceCondition.setType("druid");
datasourceCondition.setEndpoint("http://endpoint.test.com");
datasourceCondition.setCreateTime(new Date()); ... |
44646140_1 | class Checks {
public static void checkNotNull(@Nullable Object object, @NonNull String message) {
if (object == null) {
throw new NullPointerException(message);
}
}
private Checks();
}
class ChecksTest {
@Test
public void checkNotNullNegative() {
| try {
checkNotNull(null, "Throw me!");
failBecauseExceptionWasNotThrown(NullPointerException.class);
} catch (NullPointerException expected) {
assertThat(expected).hasMessage("Throw me!");
}
}
} |
44676582_3 | class ClassUtils {
public static <T, R> Method getReferencedMethod(Class<T> clazz, ReadMethodRef<T, R> methodRef) {
return findReferencedMethod(clazz, methodRef::call);
}
@SuppressWarnings("unchecked") public static Method getReferencedMethod(Class<T> clazz, WriteMethodRef<T, A1> methodRef);
@... | Method getter = ClassUtils.getReferencedMethod(Sample.class, Sample::getProperty);
assertThat(getter.getDeclaringClass()).isEqualTo(Sample.class);
assertThat(getter.getName()).isEqualTo("getProperty");
Method setter = ClassUtils.getReferencedMethod(Sample.class, Sample::setProperty);
... |
44723874_1 | class Request implements Comparable<Request<T>> {
public int getTrafficStatsTag() {
return mDefaultTrafficStatsTag;
}
@Deprecated public Request(String url, Response.ErrorListener listener);
public Request(int method, String url, Response.ErrorListener listener);
public void setParams(M... | UrlParseRequest nullUrl = new UrlParseRequest(null);
assertEquals(0, nullUrl.getTrafficStatsTag());
UrlParseRequest emptyUrl = new UrlParseRequest("");
assertEquals(0, emptyUrl.getTrafficStatsTag());
UrlParseRequest noHost = new UrlParseRequest("http:///");
assertEquals(0... |
44750616_34 | class TimeStampRecorder implements RecordedTimeStamps {
public void responseBodyCompleted() {
responseBodyCompleted = timeProvider.currentTimeInMillis();
}
public TimeStampRecorder(TimeProvider timeProvider);
public void recordCreatedRequest();
public void startWriteHeaders();
public void completedWriteHead... | timeStampRecorder.responseBodyCompleted();
assertEquals(5005, timeStampRecorder.getResponseBodyCompleted());
}
} |
44764619_1 | class ShmackUtils {
public static ExecuteResult runOnMaster(String executable, String... arguments)
throws ExecuteException, IOException {
return runOnMaster(ExecExceptionHandling.THROW_EXCEPTION_IF_EXIT_CODE_NOT_0, executable, arguments);
}
public static String determineScriptDir();
public static void syncF... | ExecuteResult result = ShmackUtils.runOnMaster("hostname");
// example hostname: ip-10-0-7-102.us-west-1.compute.internal
assertTrue("Hostname of aws-node: " + result, result.getStandardOutput().contains("compute.internal"));
}
} |
44804216_0 | class TermuxActivity extends Activity implements ServiceConnection {
static LinkedHashSet<CharSequence> extractUrls(String text) {
StringBuilder regex_sb = new StringBuilder();
regex_sb.append("("); // Begin first matching group.
regex_sb.append("(?:"); ... | assertUrlsAre("hello http://example.com world", "http://example.com");
assertUrlsAre("http://example.com\nhttp://another.com", "http://example.com", "http://another.com");
assertUrlsAre("hello http://example.com world and http://more.example.com with secure https://more.example.com",
... |
44820217_1 | class Lists {
public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<>(fromList, function)
: new TransformingSequentialList<>(fromList, function);
... | List<String> fromList = new LinkedList<>();
fromList.add("1");
fromList.add("2");
fromList.add("3");
fromList.add("4");
List<Integer> toList = Lists.transform(fromList, Integer::parseInt);
assertEquals(toList.size(), fromList.size());
System.out.println(... |
44829848_4 | class InstanceController implements RouterNanoHTTPD.UriResponder {
@Override
public Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> map, NanoHTTPD.IHTTPSession ihttpSession)
{
return ResponseGenerator.generateMethodNotAllowedResponse();
}
@Override public Response... | InstanceController instanceController = new InstanceController();
NanoHTTPD.Response response = instanceController.get(null,null,null);
String body = IOUtils.toString(response.getData());
assertEquals("Error, method not allowed", body);
assertEquals(NanoHTTPD.Response.Status.ME... |
44838366_3 | class RxPalette {
@CheckResult @NonNull
public static Single<Palette> generate(@NonNull final Bitmap bitmap) {
return Single.fromCallable(new Callable<Palette>() {
@Override
public Palette call() throws Exception {
return Palette.from(bitmap).generate();
... | TestSubscriber<Palette> testSubscriber = new TestSubscriber<>();
Palette.Builder nullBuilder = null;
//noinspection ConstantConditions
RxPalette.generate(nullBuilder)
.test()
.assertError(NullPointerException.class);
}
} |
44871316_100 | class Automation extends BaseOpenMessage {
protected static void checkRangeType(String where, Type type, String bus) {
checkNotNull(where, "invalid null value: [where]");
checkNotNull(type, "invalid null value: [type]");
checkNotNull(bus, "invalid null value: [bus]");
checkArgument(... | assertThat(captureThrowable(() -> checkRangeType("10", Type.POINT_TO_POINT, NO_BUS)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("value must be between 11 and 99");
assertThat(captureThrowable(() -> checkRangeType("100", Type.POINT_TO_POINT, NO_BUS)))
... |
44872273_23 | class SnackbarBuilder {
@SuppressWarnings("WeakerAccess")
public SnackbarBuilder appendMessage(CharSequence message) {
initialiseAppendMessages();
appendMessages.append(message);
return this;
}
public SnackbarBuilder(View view);
public SnackbarBuilder(Activity activity);
public SnackbarBuil... | SnackbarBuilder builder = createBuilder();
builder.appendMessage("message", Color.RED);
assertThatMessagesWithColorsAppended(builder, "message", Color.RED);
}
} |
44934002_1 | class Pointer implements AutoCloseable {
protected Deallocator deallocator() {
return deallocator;
}
public Pointer();
public Pointer(final Pointer p);
public Pointer(final Buffer b);
private native void allocate(Buffer b);
void init(long allocatedAddress, long allocatedCapaci... | System.out.println("Deallocator");
final boolean[] failed = { false };
ExecutorService pool = Executors.newFixedThreadPool(24);
for (int i = 0; i < 24; i++) {
pool.execute(new Runnable() {
@Override public void run() {
try {
... |
44944683_0 | class EntityResultBean {
String getKey() {
if (contentInputBean != null) {
return contentInputBean.getKey();
}
return null;
}
EntityResultBean(ContentInputBean contentInputBean);
Object getResult();
}
class EntityResultBeanTest {
@Test
public void testGetEntityLogInputBean() throw... | ContentInputBean contentInputBean = new ContentInputBean("", "auditKey", new DateTime(), null);
EntityResultBean entityResultBean = new EntityResultBean(contentInputBean);
Assert.assertEquals(entityResultBean.getKey(), "auditKey");
}
} |
44976376_0 | class RxActivityLauncher {
Observable<ActivityResult> startActivityForResult(
final Action3<Intent, Integer, Bundle> launchActivityAction,
final Intent intent, final int requestCode, final Bundle options) {
final PublishSubject<ActivityResult> subject = createSubjectIfNotExist(requ... | doThrow(ActivityNotFoundException.class).when(launchAction)
.call(any(Intent.class), anyInt(), any(Bundle.class));
final RxActivityLauncher launcher = new RxActivityLauncher();
final TestSubscriber<ActivityResult> testSubscriber = TestSubscriber.create();
launcher.startA... |
45028592_110 | class Tokenizer {
void train(final InstanceList instList, final Pipe myPipe) {
final long s1 = System.currentTimeMillis();
// set up model
model = new CRF(myPipe, null);
model.addStatesForLabelsConnectedAsIn(instList);
// get trainer
final CRFTrainerByLabelLikelihood crfTrainer = new CRFTrainerByLabelLi... |
final Tokenizer tokenizer = new Tokenizer();
final List<String> trainDataORG = readLinesFromFile(FILENAME_TRAIN_DATA_ORG);
final List<String> trainDataTOK = readLinesFromFile(FILENAME_TRAIN_DATA_TOK);
final InstanceList trainData = tokenizer.makeTrainingData(trainDataORG, trainDataTOK);
final Pipe trainPipe ... |
45078096_2 | class ManifestExportPageController {
public void setSaveManifestPath(String pPath) {
if (isSaveManifestPathEnabled()) {
mSaveManifestPath = pPath;
}
}
public ManifestExportPageController();
public void setGenerateManifest(boolean pGenerate);
public void setSaveManifes... | mTested.setGenerateManifest(true);
mTested.setSaveManifest(true);
mTested.setSaveManifestPath(PATH_VALUE);
assertEquals("the save path should have been set", PATH_VALUE, mTested.getSaveManifestPath());
}
} |
45120221_14 | class AccountController extends BusinessController implements
Accountblservice {
@Override
public ResultMessage delete(String ID) {
try {
return account.delete(ID);
} catch (RemoteException e) {
if (ExceptionHandler.myExceptionHandler(myType, this)) {
return delete(ID);
}
}
return ResultMessag... | fail("Not yet implemented");
}
} |
45165644_119 | class VideoResource {
public String getDetails(Integer id, String... fields) throws Exception {
if (fields.length == 0) {
return videos.get(id).toString();
}
return fieldJsonMapper.toJson(videos.get(id), fields);
}
public VideoResource(FieldJsonMapper fieldJsonMapper, ... | String actualDetails = resource.getDetails(1);
String expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": "
+ "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\",}";
assertEquals(expectedDetails, actualDetails... |
45222397_6 | class AssertParcelable {
public static <T extends Parcelable> void assertThatObjectParcelable(T object) {
if (object == null) {
throw new NullPointerException("object == null");
}
final Parcel parcel = Parcel.obtain();
try {
object.writeToParcel(parcel, 0);... | ClassWithOkParcelableImplButNoEquals object = new ClassWithOkParcelableImplButNoEquals("yo");
try {
AssertParcelable.assertThatObjectParcelable(object);
failBecauseExceptionWasNotThrown(AssertionError.class);
} catch (AssertionError expected) {
assertThat(exp... |
45225736_44 | class ScrapConsumerLoader {
public static <K> ScrapConsumerLoader<K> byConveyorName(String name) {
return Conveyor.byName(name).scrapConsumer();
}
public ScrapConsumerLoader(Consumer<ScrapConsumer<K, ?>> globalPlacer, ScrapConsumer<K, ?> consumer);
public ScrapConsumerLoader<K> first(ScrapConsumer<K, ?> consu... | AssemblingConveyor<Integer,String,String> ac = new AssemblingConveyor<>();
ac.setName("test");
ScrapConsumerLoader<Integer> scl = ScrapConsumerLoader.byConveyorName("test",new IgnoreScrap<>());
assertNotNull(scl);
}
} |
45239946_67 | class QueryEngine extends TemplateMetaData {
public List<Record> perform(String query, boolean explain) throws SQLException {
// QueryProcessor queryProcessor = new QueryProcessor(context);
QueryProcessor queryProcessor = new QueryProcessor(context, knowledgeCache, introspectCache);
QueryPa... | String query = "select \n" +
" o_bp/data[at0001]/events[at0006]/data[at0003]/items[at0005]/value/magnitude as max_systolic,\n" +
" o_bp/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/magnitude as max_diastolic,\n" +
" o_bp/data[at0001]/even... |
45257264_47 | class RemoteGitHelper {
public void installGit(SshConnection connection, SystemSpecification os) throws IOException {
if (isGitInstalled(connection)) {
return;
}
if (!SystemSpecification.UBUNTU.equals(os.getDistributionName())) {
throw new UnsupportedOperationException(
"Only ubuntu is supported for... | when(connection.tryExecute("which", "git")).thenReturn(
new ExecutionResult(0, "", ""));
remoteGitHelper.installGit(connection, SystemSpecification.UBUNTU_1404);
verify(connection, never()).execute("sudo", "apt-get", "-y", "install", "git");
}
} |
45304947_10 | class VideoUploadedEventCodec implements MessageCodec<VideoUploadedEvent, VideoUploadedEvent> {
@Override
public String name() {
return "VideoUploadedEvent Codec";
}
@Override public void encodeToWire(Buffer buffer, VideoUploadedEvent s);
@Override public VideoUploadedEvent decodeFromWire(... | VideoUploadedEventCodec codec = new VideoUploadedEventCodec();
assertThat(codec.name()).isEqualTo("VideoUploadedEvent Codec");
}
} |
45334811_21 | class DomaEventEntityListener extends NullEntityListener<T> implements
ApplicationEventPublisherAware {
@Override
public void postDelete(T t, PostDeleteContext<T> context) {
this.eventPublisher.publishEvent(new PostDeleteEvent<>(t, context));
}
@Override public void preInsert(T t, PreInsertContext<T> context)... | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(DomaEventEntityListener.class);
context.register(DomaEventListenerFactory.class);
context.register(PostDeleteHandler.class);
context.refresh();
DomaEventEntityListener<Entity> entityListener = context
... |
45340108_21 | class Ipv4FieldFactory extends AbstractFieldFactory<String> {
@Override
public String newInstance(int uniqueId) {
return AddressUtils.longToIpv4(longFactory.newInstance(uniqueId));
}
public Ipv4FieldFactory(String address);
@Override public String toString();
private LongFieldFactory cidrToLongFactory(Strin... | Ipv4FieldFactory factory = new Ipv4FieldFactory("127.0.0.0/30");
assertEquals(factory.newInstance(0), "127.0.0.0");
assertEquals(factory.newInstance(1), "127.0.0.1");
assertEquals(factory.newInstance(2), "127.0.0.2");
assertEquals(factory.newInstance(3), "127.0.0.3");
assertEquals(factory.newInstance(4), "1... |
45384078_1 | class NumberConverter {
public static void serialize(final double value, final JsonWriter sw) {
sw.writeDouble(value);
}
static void write4(final int value, final byte[] buf, final int pos);
static void write3(final int number, final byte[] buf, int pos);
static void write2(final int value, final byte[] buf, f... | final Random rnd = new Random(1337);
final List<Long> collection = new ArrayList<Long>();
for (long i = 1L; i <= 1000000000000000000L; i *= 10) {
collection.add(i); // 1000000
collection.add(-i); // -1000000
for (int r = 0; r < 100; r+... |
45396840_8 | class Repository {
public synchronized boolean updateList(UUID uuid, GroceryList updatedList) {
updatedList.setId(uuid);
groceryLists.replaceAll(list -> uuid.equals(list.getId()) ? updatedList : list);
save();
return groceryLists.contains(updatedList);
}
public Repository(... | emptyRepository.createList(groceryList);
groceryList.setSettled(true);
groceryList.setShoppingItems(new Item[] { ITEM_SOY_MILK });
assertTrue(emptyRepository.updateList(groceryList.getId(), groceryList));
Optional<GroceryList> updatedList = emptyRepository.getList(groceryList.ge... |
45433519_67 | class OntologyHierarchiesPresenterImpl implements OntologyHierarchiesView.Presenter,
OntologyHierarchySelectionChangedEvent.OntologyHierarchySelectionChangedEventHandler,
AppRatingSelected.AppRatingSelected... | AppRatingSelected eventMock = mock(AppRatingSelected.class);
App appMock = mock(App.class);
when(eventMock.getApp()).thenReturn(appMock);
int mockScore = 3;
when(eventMock.getScore()).thenReturn(mockScore);
/*** CALL METHOD UNDER TEST ***/
uut.onAppRatingSelected... |
45471150_4 | class CalendarDataFactoryImpl extends CalendarDataFactory {
@Override
public VisibleMonths create(Date month, int rows) {
Calendar calendar = setToFirstDayOf(month);
List<Day> lastMonth = calculateLastMonth(calendar);
List<Day> currentMonth = calculateCurrentMonth(calendar);
Lis... | Calendar calendar = Calendar.getInstance();
calendar.set(2015, 10, 2); // oct 2015, has 31 days, jan has 31, first day was sun
VisibleMonths months = CalendarDataFactory.getInstance(Locale.GERMANY).create(calendar.getTime(), SIX_ROWS);
assertThat(months.getLastMonth().size()).isEqualTo... |
45477569_4 | class AccountApiController {
@RequestMapping(value = "account/testLogin", method = {RequestMethod.POST})
public Result<Void> testLogin(ExampleAccount account) throws Exception {
return Result.createSuccess();
}
@RequestMapping(value = "account/login", method = RequestMethod.POST) @Account(fals... | /**
* 未登陆
*/
httpClientAdapter.setAccountToken(null);
apiManager.accountApi.testNotLoginData();
Result<Void> result = apiManager.accountApi.testLogin();
Assert.assertEquals(result.getStatus(), Result.ACCOUNT_ERROR);
}
} |
45489191_6 | class DockerProvisioningStrategy extends NodeProvisioner.Strategy {
@VisibleForTesting
protected static boolean notAllowedStrategy(DockerSlaveTemplate template) {
if (isNull(template)) {
LOG.debug("Skipping DockerProvisioningStrategy because: template is null");
return true;
... | final DockerSlaveTemplate template = new DockerSlaveTemplate("id");
template.setRetentionStrategy(null);
assertThat(notAllowedStrategy(template), is(true));
}
} |
45489240_10 | class CoordinatesParser {
@NonNull
public static GeoPoint parse(@NonNull String input) throws IllegalArgumentException {
Result result = parseWithResult(input);
return result.coordinates;
}
@NonNull static List<Token> lex(@NonNull String input);
private static void lexUtmOrGprs(Lis... | double testLatitude = 39.095973;
double testLongitude = -94.573414;
GeoPoint actual = CoordinatesParser.parse("15N 363936 4328605");
assertEquals("Failed to parse 15N 363936 4328605", testLatitude, actual.getLatitude(), 0.000005);
assertEquals("Failed to parse 15N 363936 4328605"... |
45502729_34 | class Strings {
public static boolean empty( String value ) {
return value == null || "".equals(value);
}
public static String diff( String original, String revised );
public static int count( String source, String regex );
public static boolean nonEmpty(String value);
public static ... |
Assert.assertEquals( true, Strings.empty( null ) );
assertEquals( true, Strings.empty( "" ) );
assertEquals( false, Strings.empty( "asdf" ) );
}
} |
45510398_66 | class Config {
private void mergeConfigsFromClasspath() throws IOException {
List<String> dirs = Arrays.asList(
"META-INF/flexovm/" + os + "/" + sliceArch,
"META-INF/flexovm/" + os);
// The algorithm below preserves the order of config data from the
// class... | File tmpDir = createTempDir();
File cacheDir = new File(tmpDir, "cache");
File p1 = createMergeConfig(tmpDir, "p1", "Foo", OS.macosx, Arch.x86, false);
File p2 = createMergeConfig(tmpDir, "p2", "Wooz", OS.linux, Arch.x86, false);
// Create a jar file with both x86 and x86_64 by f... |
45519303_4 | class MainViewModel extends ViewModel {
public void onClickButtonRecyclerView() {
attachedActivity.startActivity(AndroidVersionsActivity.class);
}
MainViewModel(@NonNull ActivityComponent activityComponent,
@Nullable State savedInstanceState);
public void onClickButtonClic... | viewModel.onClickButtonRecyclerView();
verify(attachedActivity).startActivity(AndroidVersionsActivity.class);
}
} |
45526710_11 | class ImageUtil {
public static BufferedImage loadEmbeddedBase64Image(String imageDataUri) {
try {
byte[] buffer = getEmbeddedBase64Image(imageDataUri);
if (buffer != null) {
return ImageIO.read(new ByteArrayInputStream(buffer));
}
} catch (IOExce... | String onePixel = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAC4jAAAuIwF4pT92AAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC";
BufferedImage result = ImageUtil.loadEmbeddedBase64Image(onePixel);
Assert.assertThat(result.getHeight(), is(1));
Assert.ass... |
45527579_10 | class FederatedUserApprovalHandler implements UserApprovalHandler {
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
//by default, we don't show the consent screen as EB just did this
return true;
}
@Override public AuthorizationReques... | assertTrue(subject.isApproved(request, authentication));
}
} |
45610821_3 | class PasswordHash {
public static boolean verify(byte[] password, String argon2Hash) throws IOException {
Argon2Hash input = Argon2Hash.parse(argon2Hash);
// Convert algorithm name to algorithm ID
int algorithmId = Argon2Parameters.ARGON2_i;
for (Map.Entry<Integer, String> entry: A... | System.out.println("Testing Argon2 hash verification using various algorithm parameters.");
PasswordHash.verify("password".getBytes(StandardCharsets.UTF_8),
"$argon2i$v=19$m=65536,t=2,p=1$c29tZXNhbHQ$wWKIMhR9lyDFvRz9YTZweHKfbftvj+qf+YFY4NeBbtA");
PasswordHash.verify("password".ge... |
45615254_2 | class KeyAllocationStrategy {
public byte[] getKey(int messageNum) {
return keys.get(messageNum % uniqueKeys);
}
public KeyAllocationStrategy(KeyAllocationStrategyDefinition strategyDefinition);
@Override public String toString();
private byte[] asByteArray(int i);
}
class KeyAllocatio... | KeyAllocationStrategy s0 = getStrategy(KeyAllocationType.fair, 2);
assertThat(s0.getKey(0), equalTo(s0.getKey(0))); // consistency
assertThat(s0.getKey(0), equalTo(s0.getKey(2))); // modulo around uniqueKeys
assertThat(s0.getKey(0), not(equalTo(s0.getKey(1))));
KeyAllocationStra... |
45644056_5 | class MetricsTrackingOngoingRequest extends ForwardingOngoingRequest implements TrackedOngoingRequest {
@Override
public void drop() {
metrics.drop();
super.drop();
}
MetricsTrackingOngoingRequest(
RequestMetrics metrics,
OngoingRequest ongoingRequest);
@Override public void reply(Res... | request.drop();
verify(delegate).drop();
}
} |
45681674_2 | class SwiftAstScanner {
public static SourceFile scanSingleFile(File file, SquidAstVisitor<SwiftGrammar>... visitors) {
if (!file.isFile()) {
throw new IllegalArgumentException("File '" + file + "' not found.");
}
AstScanner<SwiftGrammar> scanner = create(new SwiftConfiguration(... | SourceFile file = SwiftAstScanner.scanSingleFile(new File("src/test/resources/Test.swift"));
assertThat(file.getInt(SwiftMetric.COMMENT_LINES), is(3));
}
} |
45682878_0 | class GameController implements IModelChangedListener, Parcelable {
public void deleteNote(int row, int col, int value) {
GameCell c = gameBoard.getCell(row,col);
c.deleteNote(value);
//notifyListeners();
}
public GameController();
public GameController(SharedPreferences pref... | controller.setNote(1, 2, 5);
controller.setNote(1, 2, 9);
controller.deleteNote(1, 2, 5);
boolean[] result = {false, false, false, false, false, false, false, false, true};
assertArrayEquals(result, controller.getNotes(1, 2));
}
} |
45692123_0 | class StrFormatUtil {
public static String parseCharset(String target){
Matcher matcher = charsetPattern.matcher(target);
if (matcher.find()){
return matcher.group(1);
}
return "";
}
public static String info(String pattern,Object... params);
public static S... | String t = "text/html; charset=utf-16;text/html; charset=utf-8";
String r = StrFormatUtil.parseCharset(t);
System.out.println(r);
Assert.assertTrue("utf-8".equals(r));
}
} |
45700808_1 | class UserProfileBridge implements LockReactBridge {
private void put(String key, Map<String, Object> map, WritableMap into) {
if (map == null || map.isEmpty()) {
return;
}
final WritableMap writableMap = Arguments.createMap();
for (Map.Entry<String, Object> entry: map.... | final HashMap<String, Object> user = Maps.newHashMap();
user.put("first_name", "John");
user.put("last_name", "Doe");
user.put("friend_count", 14);
final HashMap<String, Object> app = Maps.newHashMap();
app.put("subscription", "bronze");
final UserProfile profil... |
45705189_1 | class GeoLocationUtils {
public static GeoLocation centralLocation(List<GeoLocation> geoLocations) {
Objects.requireNonNull(geoLocations);
if (geoLocations.isEmpty()) {
return null;
}
int locationCount = geoLocations.size();
if (locationCount == 1) {
return geoLocations.iterator().next();
}
doub... | List<GeoLocation> locations = new ArrayList<>();
locations.add(new GeoLocation(121.612016711363d, 32));
locations.add(new GeoLocation(121.849004871905, 31));
GeoLocation centralLocation = GeoLocationUtils.centralLocation(locations);
assertEquals(121.73, centralLocation.getLatitude(), 0.001);
assertEquals(31... |
45721011_231 | class NacosCoordinator implements ClusterRegister, ClusterNodesQuery {
@Override
public List<RemoteInstance> queryRemoteNodes() {
List<RemoteInstance> result = new ArrayList<>();
try {
List<Instance> instances = namingService.selectInstances(config.getServiceName(), true);
... | List<Instance> instances = mockInstance();
when(namingService.selectInstances(anyString(), anyBoolean())).thenReturn(instances);
List<RemoteInstance> remoteInstances = coordinator.queryRemoteNodes();
assertEquals(remoteInstances.size(), instances.size());
}
} |
45732211_6 | class EmbeddingsPipeline {
public static void main(String[] args)
throws IOException, UIMAException
{
String inputDir = args.length > 0 ? args[0] : DEFAULT_SOURCE;
CollectionReaderDescription reader = createReaderDescription(TextReader.class,
TextReader.PARAM_SOURCE... | int expectedSize = 28;
int dimensionality = 50;
EmbeddingsPipeline.TARGET_FILE.delete();
EmbeddingsPipeline.main(new String[] {});
List<String> output = Files.readAllLines(EmbeddingsPipeline.TARGET_FILE.toPath());
assertEquals(expectedSize, output.size());
asser... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.