id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
32634272_14 | class OptimizerUtil {
public static boolean isWithinBounds (int[] rgParams, int[] rgLowerBound, int[] rgUpperBound)
{
// sanity checks...
OptimizerUtil.checkBoundVars (rgLowerBound, rgUpperBound);
if (rgParams == null)
throw new NullPointerException ("The argument rgParams must not be null.");
if (rgPara... | Assert.assertTrue (OptimizerUtil.isWithinBounds (new int[] { 8, 16, 8 }, m_rgLowerBounds, m_rgUpperBounds, m_listConstraints));
}
} |
32648170_0 | class Messages {
public String getString(String key) {
try {
return res_bund.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public Messages(String countryTag);
public void setBUNDLE_NAME(String bn);
}
class Message... | Messages m = new Messages("en");
assertNotNull(m);
assertFalse(m.getString("Report.Distribution").startsWith("!"));
assertTrue(m.getString("NONEXISTENT.KEY.SHOULD.BE.SOURROUNDED.BY.EXCLAMATION.MARKS").startsWith("!"));
}
} |
32677360_2 | class DownloadXmlTask extends AsyncTask<String, Void, List<Project>> {
@Override
protected void onPostExecute(List<Project> result) {
listViewController.updateListView(result);
}
public DownloadXmlTask(ProjectParser projectParser, ListViewController listViewController, ProjectStorageControlle... | Project project1 = new Project();
Project project2 = new Project();
List<Project> projects = asList(project1, project2);
downloadXmlTask.onPostExecute(projects);
verify(listViewController).updateListView(projects);
}
} |
32693202_87 | class SettingsRepositoryImpl implements SettingsRepository {
@Override public Set<String> unset(String data) {
Set<String> errors = new HashSet<>();
Map<String, Set<String>> values = TextUtils.parseAssignment(data);
values.keySet().forEach(
k -> {
String ... | assertThat(settingsRepository.unset("missing_key"), hasSize(1));
}
} |
32714807_6 | class StringUtils {
public static String addTrailingIfNeeded(String s, String trailing) {
String value = s;
if ((null != s) && (null != trailing)) {
if (isTruthy(s) && !s.endsWith(trailing)) {
value = s + trailing;
}
}
return value;
}
... | Assert.assertEquals("hello", StringUtils.addTrailingIfNeeded("hello", null));
}
} |
32731947_1 | class PostsPresenter {
public void loadPostsFromAPI() {
postsAPI.getPostsObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers
.mainThread())
.subscribe(new Subscriber<List<Post>>() {
... |
//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... |
32753016_28 | class Version {
@Override
public String toString() {
return osType.label + "-" + versionSingleNumber;
}
public Version(OsType osType, int version);
public Version(String osString, String versionString);
private static int parseToSingleInt(String version);
private static int pars... | Version version = new Version("iOS", "1.2.4");
assertEquals("iOS-10204", version.toString());
version = new Version("iOS", "1.1.1");
assertEquals("iOS-10101", version.toString());
version = Version.UNKNOWN_VERSION;
assertEquals("unknown-0", version.toString());
}
} |
32771134_7 | class ActionCreator {
public final void createEditTodoAction(long todoId, String newDescription) {
DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>();
bundle.put(TodoAction.DataKeys.ID, todoId);
bundle.put(TodoAction.DataKeys.DESCRIPTION, newDescription);
actionBus.post(new... | final AtomicBoolean testDone = new AtomicBoolean(false);
actionBus.register(new Object() {
@Subscribe
public void addTodo(TodoAction action) {
assertThat(action.getData().get(TodoAction.DataKeys.ID, -1)).isEqualTo(10);
assertThat(action.getData().... |
32777313_11 | class BDXR2IdentifierFactory implements IIdentifierFactory {
@Nullable
public BDXR2ProcessIdentifier createProcessIdentifier (@Nullable final String sScheme, @Nullable final String sValue)
{
final String sRealScheme = nullNotEmpty (sScheme);
final String sRealValue = nullNotEmpty (isProcessIdentifierCase... | final BDXR2IdentifierFactory aIF = BDXR2IdentifierFactory.INSTANCE;
assertNotNull (aIF.createProcessIdentifier (null, null));
assertNotNull (aIF.createProcessIdentifier (null, "any"));
assertNotNull (aIF.createProcessIdentifier (null, ""));
assertNotNull (aIF.createProcessIdentifier ("", ""));
a... |
32784502_8 | class CryptTool {
public static byte[] derivePublicKey(byte[] privateKey) {
return NaCl.derivePublicKey(privateKey);
}
public static EncryptResult encryptTextMessage(String text, byte[] senderPrivateKey, byte[] recipientPublicKey);
public static EncryptResult encryptImageMessage(EncryptResult encryptResult, Upl... | Key privateKey = Key.decodeKey(Common.myPrivateKey);
Key publicKey = Key.decodeKey(Common.myPublicKey);
byte[] derivedPublicKey = CryptTool.derivePublicKey(privateKey.key);
Assert.assertNotNull("derived public key", derivedPublicKey);
Assert.assertEquals(derivedPublicKey, publicKey.key);
}
} |
32790574_2 | class MyOlciPixelOp extends PixelOperator {
static String findWaveBand(Product product, boolean fail, double centralWavelength, double maxDeltaWavelength, String... bandNames) {
Band[] bands = product.getBands();
String bestBand = null;
double minDelta = Double.MAX_VALUE;
for (Band ... | Product product = new Product("dummy", "dummy", 10, 10);
addBand(product, "a");
addBand(product, "b");
addBand(product, "c");
addBand(product, "d");
addBand(product, "e");
addBand(product, "f");
addBand(product, "g");
addBand(product, "h");
... |
32790911_1 | class SMPSettings implements ISMPSettings {
public boolean isDirectoryIntegrationRequired ()
{
return m_aSettings.getAsBoolean (SMPServerConfiguration.KEY_SMP_DIRECTORY_INTEGRATION_REQUIRED,
SMPServerConfiguration.DEFAULT_SMP_DIRECTORY_INTEGRATION_REQUIRED);
}
public ... | final SMPSettings aSettings = new SMPSettings ();
assertTrue (aSettings.isDirectoryIntegrationRequired ());
}
} |
32794630_1 | class UtilBase {
static String mangleIndexPage(String data, String mainJS, String mainClass) {
Pattern loadClass = Pattern.compile("loadClass *\\( *[\"']" + mainClass);
Matcher loadClassMatcher = loadClass.matcher(data);
if (loadClassMatcher.find()) {
return data;
}
... | String data = "\n"
+ "<html>\n" +
" <head>\n" +
" </head>\n" +
" <body>\n" +
" <h1>H1</h1>\n" +
"<!-- ${browser.bootstrap} -->\n" +
" </body>\n" +
"</html>";
String res = UtilBase.mangleIn... |
32802417_0 | class ReflectionUtils {
public static boolean hasSuperClass(Class<?> classA, Class<?> classB) {
// end recursion
if (classA.equals(classB))
return true;
boolean superclass = false;
// check superclass
Class<?> superClass = classA.getSuperclass();
if (superClass != null) {
if (superClass.equals(cla... | assertTrue(ReflectionUtils.hasSuperClass(URI.class, Object.class));
assertFalse(ReflectionUtils.hasSuperClass(Object.class, URI.class));
assertTrue(ReflectionUtils.hasSuperClass(Object.class, Object.class));
assertTrue(ReflectionUtils.hasSuperClass(URI.class, URI.class));
assertTrue(ReflectionUtils.hasSuperC... |
32823958_24 | class ExecutorEnvironmentalVariables {
public List<Protos.Environment.Variable> getList() {
return envList;
}
public ExecutorEnvironmentalVariables(Configuration configuration);
public ExecutorEnvironmentalVariables(Configuration configuration, long lNodeId);
private void populateEnvMap... | int ram = 2048;
Mockito.when(configuration.getMem()).thenReturn((double) ram);
ExecutorEnvironmentalVariables env = new ExecutorEnvironmentalVariables(configuration);
for (Protos.Environment.Variable var : env.getList()) {
if (var.getName().equals(ExecutorEnvironmentalVariab... |
32834215_0 | class MvpBasePresenter implements MvpPresenter<V> {
@UiThread @Override public void attachView(V view) {
viewRef = new WeakReference<V>(view);
presenterDestroyed = false;
}
@Deprecated @UiThread public V getView();
@Deprecated @UiThread public boolean isViewAttached();
@Deprecated @UiThread @Overrid... | MvpBasePresenter<MvpView> presenter = new MvpBasePresenter<>();
MvpView mvpView = new MvpView() {
};
Assert.assertFalse(presenter.isViewAttached());
presenter.attachView(mvpView);
Assert.assertTrue(presenter.isViewAttached());
}
} |
32848140_150 | class UniverseUtil {
public UniverseQuery convertQuery(String text, UniverseClient client, String token)
throws UniverseException {
StringBuilder select = new StringBuilder();
StringBuilder universe = new StringBuilder();
StringBuilder buf = new StringBuilder();
StringBuilder resultObj = new St... | String request1 = "universe [testUniverse];\n" +
"select [Measure].[name5]\n" +
"where [Filter].[name3];";
String request2 = "universe [testUniverse];\n" +
"select [Measure].[name5]\n" +
"where [Measure].[name5] > 2 and [Filter].[name3];";
String request3 = "universe [testUni... |
32870652_2 | class Window {
private void processSample() {
lastProcessedSpectrum = pushedSamples;
FFTSignalProcessing.ProcessingResult result = signalProcessing.processSample(window,
aWeighting, true);
// Move result by 1 backward
if(windowResults.length > 1) {
System... | final int sampleRate = 44100;
double p0 = 32767.;
double dbFsReference = -20 * Math.log10(p0);
// Reference spectrum
double[] refSpl = {-66, -68.04, -67.52, -45.97, -31.96, -37.13, -49.21, -35.29, -43.01,
-42.95, -48.65, -49.04, -53.27, -52.15, -52.65, -52.8, -52.... |
32895424_36 | class ListGcsBuckets {
public static void listGcsBuckets(String googleAccessKeyId, String googleAccessKeySecret) {
// String googleAccessKeyId = "your-google-access-key-id";
// String googleAccessKeySecret = "your-google-access-key-secret";
// Create a BasicAWSCredentials using Cloud Storage HMAC crede... | ListGcsBuckets.listGcsBuckets(KEY_ID, SECRET_KEY);
String output = bout.toString();
assertThat(output, CoreMatchers.containsString("Buckets:"));
}
} |
32935706_259 | class NotificationManagerImpl extends BasePresenter implements NotificationManager,
NotificationItem.ActionDelegate,
Notification.NotificationObserver,
... | Notification notification = new Notification("test message", PROGRESS);
manager.showNotification(notification);
reset(view);
manager.onValueChanged();
verify(view).setNotificationCount(eq(1));
reset(view);
notification.setStatus(FINISHED);
reset(view);... |
32935729_404 | class DockerFileFactory {
@NotNull
public VirtualFile newInstance(@NotNull String href) {
return newInstance(href, NAME, PATH);
}
@Inject public DockerFileFactory(ProjectServiceClient projectServiceClient,
DtoFactory dtoFactory,
AppCon... | VirtualFile fileNode = factory.newInstance(SOME_TEXT);
verify(dtoFactory).createDto(Link.class);
verify(link).withHref(SOME_TEXT);
verify(link).withRel(GET_CONTENT);
verify(dtoFactory).createDto(ItemReference.class);
verify(itemReference).withName(NAME);
verify... |
32954678_11 | class Access {
public boolean isControlled() {
return CONTROLLED.equalsIgnoreCase(value);
}
public Access(String accessType);
public boolean isOpen();
public boolean isOther();
}
class AccessTest {
@Test
public void test_missing_access_type() {
| val sut = new Access("");
assertThat(sut.isControlled()).isTrue();
}
} |
32957224_43 | class ConfigurationAlgorithm {
public static void configure(final Definitions definitions) {
// Identify configured gateways
final Set<Gateway> reconfiguredGatewaySet = findConfiguredGateways(definitions);
// Find and remove absent sequence flows
prune(definitions, (Set) findAbsen... |
// Obtain the test document
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(IDResolver.class.getName(), new DefinitionsIDResolver());
Definitions definitions = (Definitions) unmarshaller.unmarshal(trivialGatewayFile);
// Exercise the method
... |
32975439_411 | class DistCpUtils {
public static void preserve(FileSystem targetFS, Path path,
CopyListingFileStatus srcFileStatus,
EnumSet<FileAttribute> attributes,
boolean preserveRawXattrs) throws IOException {
// If not preserving a... | FileSystem fs = FileSystem.get(config);
EnumSet<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class);
Path dst = new Path("/tmp/dest2");
Path src = new Path("/tmp/src2");
createFile(fs, src);
createFile(fs, dst);
fs.setPermission(src, fullPerm);
fs.setOwner(src, "somebody",... |
32976823_59 | class RobotsFactory {
@Beta
@Nonnull
public Client createClient() {
Client client = ClientBuilder.newClient()
.register(new FollowRedirectsFilter(config.getMaxRedirectHops()))
.register(new HttpStatusHandler())
.register(new LoggingClientFilter(this.g... | Client client = factory.createClient();
assertThat(client, notNullValue());
}
} |
33024207_3 | class SequencingConcern extends ConcernOf<ShippingService> implements ShippingService {
@Override
public int makeBooking( Cargo cargo, Voyage voyage )
{
int ok = next.makeBooking( cargo, voyage );
if( ok < 0 )
{
return ok;
}
Property<Integer> gen = genera... | SingletonAssembler assembler = new SingletonAssembler(
module -> module.transients( ShippingServiceTestComposite.class )
);
ShippingService shippingService = createMock( ShippingService.class );
Cargo cargo = createMock( Cargo.class );
Voyage voyage = createMock( Voya... |
33030494_0 | class Queue {
public boolean isEmpty() {
return head == tail;
}
public Queue();
public Queue(int queueSize);
public void enqueue(Object element);
public Object dequeue();
public boolean isFull();
}
class QueueTest {
@Test
public void testIsEmpty() throws QueueOverflow... | Queue queue = new Queue();
Assert.assertTrue(queue.isEmpty());
queue.enqueue(1);
Assert.assertFalse(queue.isEmpty());
}
} |
33046639_32 | class WiktionaryResource extends AbstractResource {
public boolean containsEntity(Entity entity) {
Set<WordEntry> entries = WiktionaryUtils.entityToWords(wkt, entity);
if (entries.size() == 0) {
return false;
}
else {
return true;
}
}
public ... | wiktionaryGerman.setIsCaseSensitive(true);
assertTrue("Auto", wiktionaryGerman.containsEntity(new Entity("Baum", Entity.PoS.n)));
assertTrue("Auto", wiktionaryGerman.containsEntity(new Entity("Auto", Entity.PoS.n)));
assertFalse("auto", wiktionaryGerman.containsEntity(new Entity("auto", Entity.PoS.n)));
asser... |
33052737_2 | class Page {
public static Page allPages() {
return new Page(ALL_PAGES, ALL_PAGES);
}
private Page(int start, int end);
public static Page singlePage(int page);
public static Page pageRange(int start, int end);
}
class PageTest {
@Test
public void testAllPages() throws Excepti... | Page page = Page.allPages();
assertTrue(page.start < 0);
assertTrue(page.end < 0);
assertEquals(page.start, page.end);
}
} |
33053071_10 | class LocalDBSessionFactory implements DBSessionFactory {
@Override
public DBSession createSession() throws JasDBException {
if(StringUtils.stringNotEmpty(instance)) {
return new LocalDBSession(instance);
} else {
return new LocalDBSession();
}
}
@Overri... | LocalDBSessionFactory localDBSessionFactory = new LocalDBSessionFactory();
localDBSessionFactory.createSession().addInstance("testInstance");
DBSession session = localDBSessionFactory.createSession("testInstance");
assertThat(session.getInstanceId(), is("testInstance"));
}
} |
33053133_7 | class MapperInfoHandler extends AnnotationHandlerBase {
@SuppressWarnings("rawtypes")
public void configureOutputKeyValue(Job job, Class<? extends Mapper> mapperClass,
MapperInfo map, boolean isMapOnly) {
MaraAnnotationUtil util = MaraAnnotationUtil.INSTANCE;
// Try and work it out from the generics
Type[]... | handler.configureOutputKeyValue(job, TestMapperSubclassTest.class, null, true);
verify(job).setMapOutputKeyClass(Text.class);
verify(job).setMapOutputValueClass(NullWritable.class);
verify(job).setOutputKeyClass(Text.class);
verify(job).setOutputValueClass(NullWritable.class);
}
} |
33075946_8 | class PathLengthComparator extends PathBasedComparator {
@Override
public double getSimilarity(Entity e1, Entity e2)
throws SimilarityException, LexicalSemanticResourceException
{
// entity overrides the equals method with a usable variant
if (e1.equals(e2)) {
return 0.0;
... | LexSemResourceComparator comparator = new PathLengthComparator(germanet);
Set<Entity> entitiesAuto = germanet.getEntity("Auto", PoS.n);
Set<Entity> entitiesBagger = germanet.getEntity("Bagger", PoS.n);
Set<Entity> entitiesSchnell = germanet.getEntity("schnell", PoS.adj);
assert... |
33082868_6 | class RecipientServiceImpl implements RecipientService {
@Override
public List<Recipient> findReadyToNotify(NotificationType type) {
switch (type) {
case BACKUP:
return repository.findReadyForBackup();
case REMIND:
return repository.findReadyForRemind();
default:
throw new IllegalArgumentExcep... | final List<Recipient> recipients = ImmutableList.of(new Recipient());
when(repository.findReadyForRemind()).thenReturn(recipients);
List<Recipient> found = recipientService.findReadyToNotify(NotificationType.REMIND);
assertEquals(recipients, found);
}
} |
33100783_0 | class JarTransformer {
public void transform(@Nonnull ClassPath inputPath) throws IOException {
SCAN:
{
for (ClassPathArchive inputArchive : inputPath) {
LOG.debug("Scanning archive {}", inputArchive);
for (ClassPathResource inputResource : inputArchive)... | processor.setSkipManifest(true);
// processor.add(new PathFilterJarProcessor(Collections.singleton("META-INF/jarjar-testdata.properties")));
transformer.transform(classPath);
Method m = getMethod(outputFile, "org.anarres.jarjar.testdata.pkg0.Main", "main", String[].class);
m.inv... |
33119850_1 | class AlternateFreeRegexFileMatcher implements AlternateFileMatcher {
public boolean matches(@NotNull String filename) {
return names.contains(filename);
}
public AlternateFreeRegexFileMatcher(String currentFilename, AlternateConfiguration configuration);
public boolean canProcess();
@No... | // prepare test
AlternateConfiguration configuration = new AlternateConfiguration();
configuration.freeRegexActive = true;
configuration.genericRegexActive = false;
configuration.freeRegexItems.clear();
// java file finds Test and properties
configuration.freeRege... |
33125888_3 | class BigIntegers {
public static BigInteger[] random(BigInteger from, BigInteger to, Random rnd, int size, int bits) {
InputValidation.begin()
.when(from == null, "from is null")
.when(to == null, "to is null")
.when(from != null && to != null && from.compareTo(to) >= 0, "from not less than to")
.when(... | BigInteger[] bigs = BigIntegers.random(
BigInteger.ZERO,
BigInteger.TEN,
new Random(),
1000,
4);
Set<BigInteger> numerals = new HashSet<BigInteger>(Arrays.asList(bigs));
Set<BigInteger> expected = new HashSet<BigInteger>(Arrays.asList(
BigInteger.valueOf(0),
BigInteger.valueOf(1),
... |
33135232_0 | class CollectionSizer {
public static int getCollectionSize( String range, int collectionSize )
{
int min = Integer.parseInt( range.split( "-" )[0] );
int max = Integer.parseInt( range.split( "-" )[1] );
if ( min == 0 && max == 0 )
{
return 0;
}
if ( ... | assertThat( CollectionSizer.getCollectionSize( "1-10", 20 ) ).isBetween( 0, 9 );
assertThat( CollectionSizer.getCollectionSize( "1-10", 5 ) ).isBetween( 0, 4 );
assertThat( CollectionSizer.getCollectionSize( "0-0", 5 ) ).isEqualTo( 0 );
assertThat( CollectionSizer.getCollectionSize( "10-... |
33147632_256 | class LoggingCallback extends Callback<T> {
@Override
public void failure(TwitterException exception) {
logger.e(TweetUi.LOGTAG, exception.getMessage(), exception);
if (cb != null) {
cb.failure(exception);
}
}
LoggingCallback(Callback cb, Logger logger);
stat... | final Callback<Tweet> developerCallback = mock(Callback.class);
final Logger logger = mock(Logger.class);
final LoggingCallback<Tweet> cb = new TestLoggingCallback<>(developerCallback, logger);
cb.failure(new TwitterException(TEST_MESSAGE));
verify(logger).e(any(String.class), an... |
33194850_3 | class RestClient {
public ApiVersion getApiVersion()
throws IOException, ServerIOException {
return cloudApi.getApiVersion();
}
public RestClient(final Credentials credentials);
public RestClient(final Credentials credentials, final OkHttpClient client);
public RestClient(fi... | ApiVersion apiVersion = client.getApiVersion();
logger.info("apiVersion: " + apiVersion);
assertThat(apiVersion.getBuild(), not(isEmptyOrNullString()));
assertTrue("2.12.22".equalsIgnoreCase(apiVersion.getBuild()));
assertTrue("v1".equalsIgnoreCase(apiVersion.getApiVersion()));
... |
33263136_2 | class MetricCollectorResource {
@POST
@Consumes({MediaType.APPLICATION_JSON})
public Response doPost(
List<Map<String, Object>> events,
@QueryParam(_CLUSTER) final String cluster
) throws IOException
{
if (Strings.isNullOrEmpty(cluster)) {
return Response.status(Response.Status.BAD_REQ... | List<Map<String, Object>> in = buildTestEvent("xxx");
Response resp = resource.doPost(in, TEST_CLUSTER);
Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
}
} |
33272606_2 | class Graph implements GraphInterface {
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != this.getClass())
return false;
Graph b = (Graph) obj;
return nodeSet.equals(b.getAllNodes()) && getAllEdges().equals(b.getAllE... | Graph testGraphCopy = copyGraph();
AB.setAttribute("label", "BA");
assertFalse(testGraph.equals(testGraphCopy));
}
} |
33314734_92 | class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
Map<String, StoredException> getStoredExceptions(){
if(exceptionPersister != null) {
return exceptionPersister.loadAll();
} else {
return null;
}
}
CustomExceptionHandler(Context con... | ExceptionPersister mockExceptionPersister = mock(ExceptionPersister.class);
CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(null, null, false);
customExceptionHandler.exceptionPersister = mockExceptionPersister;
customExceptionHandler.getStoredExceptions();
... |
33324205_6 | class PlainOntologyIdStoreConfiguration extends ResourceLoader implements
OntologyIdStoreConfiguration {
@Override
public Map<String, OntologyIdInfo> getInfos() {
return Collections.unmodifiableMap(infos);
}
@Inject PlainOntologyIdStoreConfiguration(@Named("PlainOntologyIdStoreConfigurationResource") String ... | String longPattern = "long:00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
String storeConfig = "testOntologyName \t foo:000000 \t 41 \t 48 ... |
33360686_25 | class AnnotationHelper {
public ReturnType extractReturnType(final Method annotatedMethod) {
EdmFunctionImport functionImport = annotatedMethod.getAnnotation(EdmFunctionImport.class);
ReturnType returnType = new ReturnType();
if (functionImport.returnType().isCollection()) {
returnType.setMultiplic... | Method method = FunctionExecutor.class.getMethod("findNames", String.class);
ReturnType returnType = annotationHelper.extractReturnType(method);
Assert.assertEquals("Names", returnType.getTypeName().getName());
}
} |
33374862_1 | class SomeClass {
public String saySomething()
{
return "Hello World!";
}
}
class SomeClassTest {
@Test
public void testDoSomething()
{
| SomeClass sc = new SomeClass();
Assert.assertEquals("Hello World!", sc.saySomething());
}
} |
33383826_25 | class InMemoryPermissionsImpl implements PermissionsInterface {
@Override
public boolean isSharing(User user) {
final String userKey = userKey(user);
return user.getEntries().stream().anyMatch(e -> {
if (e instanceof Workflow) {
final Map<String, Role> map = resource... | // Nothing shared at all
Assert.assertFalse(inMemoryPermissions.isSharing(johnDoeUser));
// Share with Jane
final Permission permission = new Permission("jane", Role.OWNER);
inMemoryPermissions.setPermission(johnDoeUser, fooWorkflow, permission);
Assert.assertTrue(inMemo... |
33397227_35 | class NMHeartBeatHandler extends BaseInterceptor {
@Override
public void beforeRMNodeEventHandled(RMNodeEvent event, RMContext context) {
switch (event.getType()) {
case STARTED:
// Since the RMNode was just started, it should not have a non-zero capacity
RMNode rmNode = context.getRMNode... | resetNodeTotalCapability(nodeOne, 0, 0);
resetNodeTotalCapability(nodeTwo, 2, 512);
Offer offerOne = TestObjectFactory.getOffer("localhost-one", "slave-one", "mock", "offer-one", 1.0, 512.0);
Offer offerTwo = TestObjectFactory.getOffer("localhost-two", "slave-two", "mock", "offer-two", 3.0, 1024.0);
... |
33401991_77 | class RestoCardViewHolder extends CardViewHolder {
@Override
public void populate(Card card) {
super.populate(card);
RestoMenuCard menuCard = card.checkCard(Card.Type.RESTO);
RestoMenu menu = menuCard.getRestoMenu();
RestoChoice choice = menuCard.getRestoChoice();
Strin... | View view = inflate(activityContext, R.layout.home_card_resto);
RestoCardViewHolder viewHolder = new RestoCardViewHolder(view, adapter);
RestoMenuCard card = generate(RestoMenuCard.class);
viewHolder.populate(card);
MenuTable table = view.findViewById(R.id.menu_table);
R... |
33453737_3 | class DocumentOutputUtil {
public static String getIframeAdminContentWrapperTemplate() throws IOException {
try (InputStream templateStream =
DocumentOutputUtil.class.getClassLoader().getResourceAsStream(IFRAME_CONTENT_WRAPPER_TEMPLATE_PATH)) {
return IOUtils.toString(templ... |
String iframeTemplate = DocumentOutputUtil.getIframeAdminContentWrapperTemplate();
Document document = Jsoup.parse(iframeTemplate, "testBase");
// assert that there is iframeElement and that it uses the expeted context variables
Elements wrapperElement = document.select("div");
... |
33492382_4 | class App implements Parcelable, Comparable<App> {
public boolean matches(String filter) {
return filter != null && title.contains(filter);
}
public App(String title);
private App(Parcel in);
@Override public int compareTo(App app);
@Override public boolean equals(Object o);
@Ov... | // Given
App app = new App("MyTitle");
// When
boolean result = app.matches("");
// Then
assertThat(result).isTrue();
}
} |
33500369_8 | class Person {
public String getName() {
return name;
}
public Person(String name);
}
class PersonTest {
@Test
public void canConstructAPersonWithAName() {
| Person person = new Person("Harry");
assertEquals("Harry", person.getName());
}
} |
33547254_5 | class ExceptionProcessorImpl implements ExceptionProcessor {
@Override
public <T extends Exception> InternalResponse<Object> process(final T ex,
final InternalRequest<Object> req,
... | ApplicationContextImpl context = getApplicationContextWithBody();
ResponseStub response = new ResponseStub();
response.setOutputStream(new ByteArrayOutputStream());
RequestStub request = new RequestStub();
request.setAccept(singletonList(PLAIN_TEXT));
Map<HeaderName, St... |
33547660_1 | class Naming {
public static boolean isQname(String s) {
int len = s.length();
if (len == 0)
return false;
if (!isNameStartCharNs(s.charAt(0)))
return false;
for (int i = 1; i < len; i++) {
char c = s.charAt(i);
if (!isNameCharNs(c)) {
if (c == ':' && ++i < len && isNa... | Assert.assertFalse(Naming.isQname("foo::"));
}
} |
33559545_59 | class CompositeDelayFunction implements DelayFunction<R, X> {
@Override
public Duration computeDelay(final R result, final X failure, final ExecutionContext context) {
return functions.stream()
.map(function -> function.computeDelay(result, failure, context))
.filter(Obj... | when(second.computeDelay(eq("2"), any(), any())).thenReturn(Duration.ofSeconds(2));
assertEquals(Duration.ofSeconds(2), unit.computeDelay("2", null, null));
}
} |
33591418_10 | class NewRelocatorMethodAdapter extends AnalyzingMethodNode {
@Override
public void visitEnd() {
AbstractInsnNode next = instructions.getFirst();
boolean removeFrame = false;
int stackSize = 0;
while (next != null) {
AbstractInsnNode node = next;
next = ... | adapter.visitCode();
adapter.visitFrame(F_NEW, 0, EMPTY_OBJECTS, 0, EMPTY_OBJECTS);
adapter.visitInsn(NOP);
adapter.visitFrame(F_NEW, 0, EMPTY_OBJECTS, 0, EMPTY_OBJECTS);
adapter.visitInsn(RETURN);
adapter.visitMaxs(0, 0);
adapter.visitEnd();
InOrder inOr... |
33645738_0 | class WordsApiDataProvider implements DataProvider {
@Override
public Observable<Pair<String, Response<RhymesResponse>>> rhymes(final String word) {
return apiService.rhymes(word)
.map(new Func1<Response<RhymesResponse>, Pair<String, Response<RhymesResponse>>>() {
@O... | Response<RhymesResponse> response = Response.success(new RhymesResponse(new Rhymes(
Arrays.asList("hi", "bye", "sigh"))));
String word = "high";
when(apiService.rhymes(word)).thenReturn(Observable.just(response));
Pair<String, Response<RhymesResponse>> pair =
... |
33670015_1 | class FileBasedLexicon implements Lexicon {
public Sentiment get(String key) {
final String value = properties.getProperty(key);
return value == null ? Sentiment.NEUTRAL : Sentiment.valueOf(value);
}
public FileBasedLexicon(String fileName);
@Override public String toString();
}
class FileBasedLexiconTest... | final FileBasedLexicon lexicon = new FileBasedLexicon("lexicon.properties");
assertEquals(Sentiment.HAPPY, lexicon.get("devoxx"));
assertEquals(Sentiment.SAD, lexicon.get("framework"));
}
} |
33675294_8 | class FirmwareService {
public UpdateFirmwareResponseDto updateFirmware(final DlmsConnectionHolder conn, final DlmsDevice device,
final String firmwareIdentification) throws OsgpException {
LOGGER.info("Updating firmware of device {} to firmware with identification {}", device,
... | // Arrange
final String firmwareIdentification = "fw";
when(this.firmwareFileCachingRepository.retrieve(firmwareIdentification)).thenReturn(null);
// Act
try {
this.firmwareService.updateFirmware(this.dlmsConnectionHolderMock, this.dlmsDeviceMock,
... |
33766200_0 | class Policy extends PolicyDef {
@Override
public EvaluationResult evaluate(EvaluationContext evaluationContext) throws EvaluationException {
/*
* First check to see if we are valid. If not, return an error status immediately
*/
if (!this.validate()) {
return new E... | PolicyDef policy = createPolicy();
EvaluationResult evaluationResult = policy.evaluate(evaluationContext);
Collection<IdReference> policyIdentifiers = getPolicyIdentifiers(evaluationResult);
assertEquals(1, policyIdentifiers.size());
assertEquals(Decision.INDETERMINATE, evalua... |
33769933_17 | class JkPathTree implements Closeable {
public JkPathTree importTree(JkPathTree tree, CopyOption... copyOptions) {
createIfNotExist();
if (tree.exists()) {
tree.stream().filter(excludeRootFilter()).forEach(path -> {
Path target = this.getRoot().resolve(tree.getRoot().rel... | Path dirSample = Files.createTempDirectory("sample");
JkPathTree tree = JkPathTree.of(dirSample);
tree.importTree(JkPathTree.ofZip(createSampleZip()));
assertTrue(Files.isDirectory(tree.get("subfolder")));
assertTrue(Files.isRegularFile(tree.get("subfolder").resolve("sample.txt")... |
33776978_8 | class SplayTree {
public boolean find(int key) {
splay(key);
return root.key == key;
}
private void splay(int key);
public void add(int key, Object elem);
public void delete(int elem);
private void print(SplayNode node);
static SplayTree tree;
static Random rand;
s... | for (int n = 0; n < 10; n++) {
for (int i = 0; i < inserted.length; i++) {
assertTrue(tree.find(inserted[i]));
}
}
for (int i = 0; i < 1000; i++) {
assertFalse(tree.find(rand.nextInt(inserted.length) + inserted.length + 1));
}
}
} |
33782165_29 | class AbstractDogecoinParams extends NetworkParameters implements AuxPoWNetworkParameters {
protected long calculateNewDifficultyTargetInner(int previousHeight, final Block prev,
final Block nextBlock, final Block blockIntervalAgo) {
return this.calculateNewDifficultyTargetInner(previousHeight,... | int previousHeight = 239;
long previousBlockTime = 1386475638; // Block 239
long lastRetargetDifficulty = 0x1e0ffff0;
long lastRetargetTime = 1386474927; // Block 1
long nextDifficulty = 0x1e00ffff;
long newDifficulty =
params.calculateNewDifficultyTargetInner... |
33813213_4 | class AttrsDecorator implements Decorator {
@Override
public void apply(View view, View parent, String name, Context context, AttributeSet attributeSet) {
if (!clazz().isAssignableFrom(view.getClass())) {
return;
}
values = obtainAttributes(context, attributeSet);
i... | TypedArray typedArray = mockTypedArray(1, false);// we suppose we dont have custom attr here
spyWithTypedArray(typedArray);
String name = "android.widget.TextView";
attrsDecorator.apply(textView, parent, name, context, attributeSet);
assertThat(attrsDecorator.values).isNotNull();... |
33816473_0 | class RedmineClient {
public int getIssueCount() throws IOException {
Request request = new Request.Builder()
.url(url + "/issues.json")
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().s... | RedmineClient redmineClient = new RedmineClient(
redmineContainer.getRedmineUrl());
assertEquals(
"The issue count can be retrieved.",
0,
redmineClient.getIssueCount());
}
} |
33829862_43 | class Version {
@Override
public String toString() {
if (StringUtils.isBlank(customName)) {
if (lowNumber == 0) {
return String.format("%s.%s", bigNumber, intermediateNumber);
}
return String.format("%s.%s.%s", bigNumber, intermediateNumber, lowNumber... | Version version1 = new Version("4-dev");
assertEquals("4.0-dev", version1.toString());
}
} |
33854851_43 | class WootricCustomMessage implements Parcelable {
public String getPlaceholderForScore(int scoreValue, String surveyType, int surveyTypeScale) {
final Score score = new Score(scoreValue, surveyType, surveyTypeScale);
if(score.isDetractor() && getDetractorPlaceholder() != null) {
retur... | assertThat(customMessage.getPlaceholderForScore(4, "CES", 0)).isEqualTo("passive_prompt_text");
assertThat(customMessage.getPlaceholderForScore(5, "CES", 0)).isEqualTo("passive_prompt_text");
}
} |
33856324_2 | class MsgObject {
@Override
public String toString() {
StringBuilder str = new StringBuilder();
getGroupValueHandler(getClass()).appendToString(this, str);
return str.toString();
}
private static GroupHandler getGroupValueHandler(Class<?> javaClass);
@SuppressWarnings("rawt... | assertEquals("ArrayMsg [strings=null, ints=null, basics=null]", new ArrayMsg(null, null, null).toString());
assertEquals("ArrayMsg [strings=[], ints=[], basics=[]]",
new ArrayMsg(new String[0], new int[0], new Basic[0]).toString());
assertEquals("ArrayMsg [strings=[a], ints=[1],... |
33861662_2 | class ModuleClass2 {
int neg(final int stuff) {
return -stuff;
}
public int negDoubleStuff(final int stuff);
ModuleClass2 testTarget;
}
class ModuleClass2Test {
ModuleClass2 testTarget;
@Test
public void neg() throws Exception {
| int any = anyInt();
assertEquals(-any, testTarget.neg(any));
}
} |
33926359_0 | class Debouncer {
public static boolean debounce(final String identifier, final Runnable r, final int millis) {
if(getInstance().runnables.containsKey(identifier)) {
// debounce
Log.d(TAG, String.format("Debouncing runnable with identifier \"%s\"", identifier));
Runnable... | final String identifier = "test";
final Counter counter = new Counter();
final Runnable r1 = new Runnable() {
@Override
public void run() {
Log.i(TAG, String.format("Runnable with identifier \"%s\" ran", identifier));
counter.increment();... |
33955440_0 | class BoxBookmark extends BoxItem {
public static BoxBookmark createFromId(String bookmarkId) {
JsonObject object = new JsonObject();
object.add(FIELD_ID, bookmarkId);
object.add(FIELD_TYPE, TYPE);
return new BoxBookmark(object);
}
public BoxBookmark();
public BoxBook... | // given
String expectedId = "5";
String expectedType = BoxBookmark.TYPE;
// when
BoxBookmark bookmark = BoxBookmark.createFromId(expectedId);
String id = bookmark.getId();
String type = bookmark.getType();
// then
Assert.assertEquals(expectedId,... |
33957901_11 | class ServiceSettings {
static long getNextNextStartTimeFor(long start, long end) {
DateTime now = DateTime.now();
Interval interval = SyncthingUtils.getIntervalForRange(now, start, end);
if (interval.isAfter(now)) {
//Interval hasnt started yet
return interval.getSt... | long now = DateTime.parse("2015-03-21T14:12:00").getMillis();//2:12pm
DateTimeUtils.setCurrentMillisFixed(now);
//before interval is interval start when start < end
long start = parseTime("15:12"); //3:12pm
long end = parseTime("16:12");//4:12pm
assertThat(getNextNextS... |
33978966_38 | class Lazy {
public List<Thing> getList() {
return this.list;
}
public Lazy(List<Thing> list);
}
class LazyTest {
@Test
public void shouldRespectWithNull() {
| Lazy item = new LazyBuilder().withList((List<Thing>)null).build();
assertNull(item.getList());
}
} |
33989963_26 | class HighlighterVisitor extends SubscriptionVisitor {
private void highlight(SyntaxToken token, TypeOfText type) {
highlighting.highlight(token.line(), token.column(), token.endLine(), token.endColumn(), type);
}
public HighlighterVisitor(SensorContext sensorContext);
@Override public Set<Kind> nodesToVisit(... | highlight(" /**Comment*/ ");
assertHighlighting(2, 12, TypeOfText.STRUCTURED_COMMENT);
}
} |
34034770_5 | class JWTFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String ... | MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
as... |
34039690_3 | class DateUtilExtensions {
public static Calendar previous(Calendar self) {
Calendar result = (Calendar) self.clone();
result.add(Calendar.DATE, -1);
return result;
}
public static int getAt(Date self, int field);
public static Calendar toCalendar(Date self);
public static ... | SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("20180101"));
assertEquals("20171231", sdf.format(DateUtilExtensions.previous(calendar).getTime()));
}
} |
34044841_37 | class ComplaintTypeService {
@Transactional
public ComplaintType createComplaintType(ComplaintType complaintType) {
return complaintTypeRepository.save(complaintType);
}
@Autowired public ComplaintTypeService(ComplaintTypeRepository complaintTypeRepository);
public ComplaintType findBy(L... | ComplaintType complaintType = new ComplaintTypeBuilder().withDefaults().withName("Roads").build();
complaintTypeService.createComplaintType(complaintType);
verify(complaintTypeRepository).save(complaintType);
}
} |
34112580_0 | class CustomIssueRegistry extends IssueRegistry {
@Override public List<Issue> getIssues() {
return Arrays.asList(
HelloWorldDetector.ISSUE,
IdPrefixDetector.ISSUE,
StringReferencesDetector.ISSUE,
ClassNamesDetector.ISSUE,
LayoutNamesDetector.ISSUE
);
}
}
class Cus... | CustomIssueRegistry customIssueRegistry = new CustomIssueRegistry();
List<Issue> actual = customIssueRegistry.getIssues();
assertThat(actual).containsExactly(
HelloWorldDetector.ISSUE,
IdPrefixDetector.ISSUE,
StringReferencesDetector.ISSUE,
ClassNamesDetector.ISSUE,
... |
34138670_0 | class SegmentedIdGenerator implements IdGenerator {
@Override // IdGenerator
public synchronized long nextValue() {
if (offset == 0) {
newSegment();
}
if (++offset == SEGMENT_SIZE){
offset = 0;
}
return ++value;
}
public SegmentedIdGenerator(long initialValue,
... | final long initialValue = 1000;
final long serviceInitialValue = -1;
final long maxValue = 10000000;
IdGeneratorService service = new LocalIdService(serviceInitialValue);
SegmentedIdGenerator id = new SegmentedIdGenerator(initialValue, service);
for (long i = initialValue + 1; i <= maxValue; i+... |
34202547_6 | class MapBuilder {
public MapBuilder<K, V> put(final K key, final V value) {
this.internalMap.put(key, value);
return this;
}
public static MapBuilder<K, V> newHashMap();
public static MapBuilder<K, V> newLinkedHashMap();
public static MapBuilder<K, V> newUnmodifableMap(final Provi... | final MapBuilder<String, String> mapBuilder = MapBuilder.newHashMap();
Assertions.assertNotNull(mapBuilder);
mapBuilder.put("Hello", "World");
Assertions.assertTrue(mapBuilder.get().containsKey("Hello"));
Assertions.assertTrue(mapBuilder.get().get("Hello").equals("World"));
}... |
34206566_4 | class NewsSerializer implements Serializer<News> {
@Override
public byte[] serialize(String topic, News data) {
try {
return mapper.writeValueAsBytes(data);
} catch (JsonProcessingException ex) {
throw new SerializationException("Could not transform Object to JSON: " + e... | NewsSerializer serializer = new NewsSerializer();
UUID uuid = UUID.randomUUID();
News news = new News(uuid, "Test Author", "Test TitleÄÖÜ", "Test test test");
byte[] bytes = serializer.serialize("", news);
News reparsedNews = mapper.readValue(bytes, News.class);
assertTha... |
34212608_2 | class Routing {
public static <T extends Route> T build(Class<T> routeType, Consumer<String> consumer) {
PathImplementor implementor = RoutingImpl.getImplementorByClass(routeType);
if (implementor == null) {
throw new IllegalArgumentException("Invalid route type: " + routeType);
... | new StringRouteImpl().parse();
SavingConsumer consumer = new SavingConsumer();
StringRoute route = Routing.build(StringRoute.class, consumer);
route.path("baz");
assertEquals("foo/baz/bar", consumer.consumed);
route.nondeterminatePath("bazz");
assertEquals("foo... |
34216921_28 | class PlayerCreator {
Hero createPlayer(ShipConfig shipConfig, boolean shouldSpawnOnGalaxySpawnPosition, RespawnState respawnState, SolGame game, boolean isMouseControl, boolean isNewShip) {
Vector2 position = findPlayerSpawnPosition(shipConfig, shouldSpawnOnGalaxySpawnPosition, game);
game.getCam(... | int shipConfigMoney = 42;
when(shipConfig.getMoney()).thenReturn(shipConfigMoney);
respawnState.setRespawnMoney(0);
playerCreator.createPlayer(shipConfig, false, respawnState, solGame, false, false);
verifyBuildNewFar(shipConfiguration().withMoney(shipConfigMoney));
}
} |
34217961_0 | class SketchInteractionListener implements RainbowInputController.RainbowInteractionListener {
@Override
public void onSketchTouched(MotionEvent event) {
if (hasPaintListener()) {
paintListener.onPaintingStart();
}
inkPerformer.reset();
}
SketchInteractionListener... | sketchInteractionListener.onSketchTouched(motionEvent);
verify(inkPerformer).reset();
}
} |
34336359_71 | class CamelExchangeBus implements ExchangeBus {
@Override
public void init(ServiceDomain domain) {
if (_logger.isDebugEnabled()) {
_logger.debug("Initialization of CamelExchangeBus for domain " + domain.getName());
}
SimpleRegistry registry = _camelContext.getWritebleRegist... | RuntimeErrorInterceptor interceptor = new RuntimeErrorInterceptor(
false, ExchangeInterceptor.PROVIDER);
_camelContext.getWritebleRegistry().put("interceptor", interceptor);
_provider.init(_domain);
ServiceReference ref = registerInOutService("inOut");
Exchange ex... |
34374370_4 | class HTraceConfiguration {
public abstract String get(String key)public abstract String get(String key);
public abstract String get(String key)public static HTraceConfiguration fromMap(Map<String, String> conf);
public abstract String get(String key)public static HTraceConfiguration fromKeyValuePairs(String... pairs... | System.setProperty("supercalifragilistic.property", "1");
System.setProperty("htrace.supercalifragilistic.property", "2");
System.setProperty("foo.htrace.supercalifragilistic.property", "3");
JavaPropertyConfiguration conf =
new JavaPropertyConfiguration.Builder().
addPrefix("foo.htrace.")... |
34382546_8 | class WeightedMovingAverage {
public List<DataPoint> learn() {
List<DataPoint> result = new ArrayList<>(dataPoints.size());
EvictingQueue<Double> window = EvictingQueue.create(weights.length);
int endHalf = weights.length / 2;
// add zeros to the beginning
for (int i = 0;... | List<DataPoint> points = Arrays.asList(new DataPoint(1D, 0L), new DataPoint(1D, 5L),
new DataPoint(1D, 10L), new DataPoint(1D, 15L), new DataPoint(1D, 20L), new DataPoint(1D, 25L),
new DataPoint(1D, 30L));
WeightedMovingAverage weightedMovingAverage = new WeightedMovingA... |
34383946_7 | class ReleaseDetails {
@Override
public String toString() {
return "ReleaseDetails [id=" + this.id + ", version=" + this.version + ", buildDate=" + this.buildDate + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
private ReleaseDetails();
private ReleaseDetails(final String id, final String ve... | ReleaseDetails instance = ReleaseDetails.byId(NAME);
String dateFormat = "yyyy-MM-dd";
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Date date = formatter.parse("2011-07-31");
assertEquals("ReleaseDetails [id=" + NAME + ", version=0.0.0-TEST, buildDate=" + date.toString() + "]",
instance.... |
34387413_4 | class CrawlingStrategy {
public boolean isCrawable(URL url, int depth) {
if (url != null && !visitedUrls.contains(url) && isCrawlingAllowed(url) && depth < crawlerMaxDepth) {
visitedUrls.add(url);
if(url.getPath().endsWith("/")){
try {
visitedUrls... | try {
URL url = new URL("http://jcertif.com/lab/2014/05/04/il-etait-une-fois-le-lab.html");
assertFalse(strategy.isCrawable(url, 11));
} catch (MalformedURLException ex) {
Logger.getLogger(CrawlingStrategyTest.class.getName()).log(Level.SEVERE, null, ex);
... |
34409518_236 | class AbstractRsJs {
String getJsFilename(String classname, String fwk) {
String path = classname.replaceAll("\\.", File.separator);
if (null != fwk) {
return File.separator + path + "." + fwk + Constants.JS;
}
return File.separator + path + Constants.JS;
}
abstract List<InputStream> getStreams();
@GET... | System.out.println("getJsFilename");
String classname = "p1.p2.p3.Cls1";
String expResult = "/p1/p2/p3/Cls1.fwk.js";
String result = instance.getJsFilename(classname, "fwk");
assertThat(result).isEqualTo(expResult);
}
} |
34430212_3 | class EncryCredentialAuthenticationHandler extends
AbstractPreAndPostProcessingAuthenticationHandler {
@Override
protected boolean doAuthentication(KnightCredential credential) throws AuthenticationException {
//不支持的凭据直接返回false.
if(!this.supports(credential)){
return false;
... |
/**
* 测试异常输入情况。
*/
Assert.assertFalse(handler.authenticate(null));
Credential credential = Mockito.mock(Credential.class);
Assert.assertFalse(handler.authenticate(credential));
/**
* 测试解密失败抛出异常的情况。
*/
EncryCredential encryCredential = new EncryCredential("sssddaf");
EncryCredentialManage... |
34430581_0 | class SampleBlazegraphCustomFunctionRemote {
public static void loadDataFromResource(final RemoteRepositoryManager repo,
final String namespace, final String resource) throws Exception {
final InputStream is = SampleBlazegraphCustomFunctionRemote.class
.getResourceAsStream(resource);
if (is == null) {
t... |
final String namespace = "test";
final Properties journalProperties = new Properties();
{
journalProperties.setProperty(Journal.Options.BUFFER_MODE,
BufferMode.MemStore.name());
}
Journal m_indexManager = new Journal(journalProperti... |
34446334_72 | class EndpointUtil {
public static String decodeClientURI(String clientUri) {
return clientUri.startsWith(Constants.URI_CLIENT_PREFIX)
? clientUri.substring(Constants.URI_CLIENT_PREFIX.length()): clientUri;
}
public static String encodeEndpoint(String uri, String operation);
pu... | assertEquals(URI, EndpointUtil.decodeClientURI(Constants.URI_CLIENT_PREFIX + URI));
}
} |
34456739_2 | class Form {
public boolean save() {
return save(null);
}
protected Form(Builder<S, D> builder);
public void display(Bundle bundle);
public void display();
public void forceSave();
public boolean save(Bundle bundle);
public void forceSave(Bundle bundle);
private static f... | AuthModelSource source = new AuthModelSource(null);
AuthModelDrain drain = new AuthModelDrain(null);
Form form = new Form.Builder<>(source, drain, mapper).build();
assertNull(drain.getDrain());
form.display();
assertFalse(form.save());
source.getSource().email... |
34482253_0 | class RoomManager {
public Set<String> getRooms() {
return new HashSet<String>(rooms.keySet());
}
public RoomManager(RoomHandler roomHandler, KurentoClientProvider kcProvider);
public Set<UserParticipant> joinRoom(String userName, String roomName, boolean dataChannels,
boolean webParticipant, Kure... | assertThat(manager.getRooms(), not(hasItem(roomx)));
exception.expect(RoomException.class);
exception.expectMessage(containsString("must be created before"));
userJoinRoom(roomx, userx, pidx, false);
assertThat(manager.getRooms(), not(hasItem(roomx)));
}
} |
34520372_0 | class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws ServiceBrokerApiVersionException {
if (version != null && !anyVersionAllowed()) {
String apiVersion = request.getHeader(version.getBro... | BrokerApiVersionInterceptor interceptor = new BrokerApiVersionInterceptor(null);
assertTrue(interceptor.preHandle(request, response, null));
}
} |
34537449_0 | class CvsMapper {
public String map(Observation observation) {
return observation.getId() + SEPARATOR + observation.getName() + SEPARATOR + observation.getTime();
//TODO: Add escaping logic if name contains double quotes or commas
}
}
class CvsMapperTest {
@Test
public void testBadData() {
| assertThat(new CvsMapper().map(new Observation(1, "name\"with\"quotes", "1", null)), nullValue());
}
} |
34568856_0 | class StorageAccess {
public String safeFilename(String filename) {
// Remove bad characters from filenames
filename = filename.replaceAll("[*?/<>&!#$+\"'{}:@\\\\]",""); // Removes bad characters
filename = filename.replaceAll("\\s{2,}", " "); // Removes double spaces
return filena... | String input = "This is a <*bad*> /Filename\\ & who knows what it wull do!! # $ + \" ' { } : @ ";
String output;
String expected = "This is a bad Filename who knows what it wull do";
StorageAccess storageAccess = new StorageAccess();
output = storageAccess.safeFilename(input);
... |
34579789_4 | class RetrofitServiceMethod {
public List<MethodSpec> generateCodeWithRetryStaleIfRequired() {
MethodSpec methodSpec = generateCode(false);
if (!canAppendStaleHeader()) {
return singletonList(methodSpec);
}
return asList(methodSpec, generateCode(true));
}
public RetrofitServiceMethod(Exe... | List<MethodSpec> methodSpecs = singleMethodInfo(Foo5.class).generateCodeWithRetryStaleIfRequired();
assertEquals("@retrofit.http.GET(\"/hoge\")\n"
+ "@retrofit.http.Headers(\"Cache-Control: max-stale=86400\")\n"
+ "public abstract rx.Observable<java.lang.String> bar$$RetryStale(java.util... |
34582928_61 | class NetworkUtils {
public static String getAbsoluteUrl(String url) {
String absoluteUrl = url;
if (!TextUtils.isEmpty(absoluteUrl) && !absoluteUrl.startsWith("http")) {
absoluteUrl = StringUtils.appendOptional(BuildConfig.WS_ENDPOINT, absoluteUrl);
}
return absoluteUr... | // Given
String url = "/imgs/nilhcem.jpg";
// When
String result = NetworkUtils.getAbsoluteUrl(url);
// Then
assertThat(result).isEqualTo(BuildConfig.WS_ENDPOINT + url);
}
} |
34623357_10 | class FavoriteSurface {
public boolean isEmpty() {
return surface == null && surfaceGroup == null && !allRounder && !none;
}
public FavoriteSurface(PlayerPerformance performance);
private static int getMaxWonPctGapIndex(List<SurfaceWonPct> surfaces);
private void setSurface(Surface surface);
private void se... | FavoriteSurface favoriteSurface = new FavoriteSurface(performance(
new WonLost(0, 1),
new WonLost(1, 1),
new WonLost(1, 1),
new WonLost(0, 0)
));
assertThat(favoriteSurface.isEmpty()).isTrue();
assertThat(favoriteSurface).hasToString("");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.