id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
4189503_130 | class InProgramCalculation extends AbstractPatientCalculation {
@Override
public CalculationResultMap evaluate(Collection<Integer> cohort, Map<String, Object> params, PatientCalculationContext context) {
Program program = (params != null && params.containsKey("program")) ? (Program) params.get("program") : null;
... | Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
Program tbProgram = MetadataUtils.existing(Program.class, TbMetadata._Program.TB);
// Enroll patient #6 in TB program
TestUtils.enrollInProgram(TestUtils.getPatient(6), tbProgram, TestUtils.date(2012, 1, 1));
// Enroll pat... |
4193864_175 | class FeedRenderingPool {
void handleSubscriptions() {
Set<FeedProvider> requiredSubscriptions = buildRequiredSubscriptions();
List<FeedProvider> newSubscriptions = new ArrayList<FeedProvider>();
List<FeedProvider> removedSubscriptions = new ArrayList<FeedProvider>();
Set<FeedProvid... | pool.cancelTimer();
Field f = FeedView.class.getDeclaredField("feedPool");
f.setAccessible(true);
FeedRenderingPool rp = (FeedRenderingPool) f.get(fv1);
rp.cancelTimer();
final String feedId = "f1";
FeedView fv2 = Mockito.mock(FeedView.class);
FeedProvider... |
4195698_13 | class FileHelper {
protected static void copyDirectory(final File srcDir, final File destDir)
throws IOException {
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (srcDir.e... |
final File srcDir = buildOrnidroidHomeTest(TEST_DIRECTORY + "/srcDir");
final File destDir = new File(TEST_DIRECTORY + "/destDir");
// copy in an other directory
try {
FileHelper.copyDirectory(srcDir, destDir);
final File[] srcDirContent = srcDir.listFiles();
final File[] destDirContent = destDir.lis... |
4214268_3 | class Util {
public static long bin2long(byte[] array, int offset) {
return ((array[offset + 0] & 0xffL) << 56) + ((array[offset + 1] & 0xffL) << 48)
+ ((array[offset + 2] & 0xffL) << 40) + ((array[offset + 3] & 0xffL) << 32)
+ ((array[offset + 4] & 0xffL) << 24) + ((array[offset + 5] & 0xffL) <<... | assertEquals(1000L, Util.bin2long(thousandlong, 0));
}
} |
4233818_4 | class MyBean {
public DependencyA getDependencyA() {
return dependencyA;
}
public MyBean();
public MyBean(DependencyA dependencyA);
public void setDependencyA(DependencyA dependencyA);
@Autowired
@Qualifier(value="myBeanSetterInjection")
private MyBean myBeanSetterInjection;
@Autowired
@Qualifier(valu... | assertThat(myBeanConstructorInjection.getDependencyA(), notNullValue());
assertThat(myBeanSetterInjection.getDependencyA(), notNullValue());
}
} |
4237245_15 | class Vector extends AbstractList<E> implements List<E>, RandomAccess {
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= "
+ elementCount);
}
return (E) elementData[index];
}
public Vector(int initialCapacity);
public ... | fail("Not yet implemented");
}
} |
4238016_112 | class UnknownMacroMacroRunnable implements IMacroRunnable {
@Override
public String getHtml(IMacroContext macroContext) {
return "<span class=\"text-error\">{{" + macroContext.getMacroName() + "/}}</span>"; //$NON-NLS-1$ //$NON-NLS-2$
}
@Override public String cleanupHtml(String html);
private UnknownMacroMac... | when(context.getMacroName()).thenReturn("nonexistent"); //$NON-NLS-1$
assertEquals("<span class=\"text-error\">{{nonexistent/}}</span>", runnable.getHtml(context)); //$NON-NLS-1$
}
} |
4242485_127 | class BrowserOperatingSystemMapping implements Serializable {
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BrowserOperatingSystemMapping other = (BrowserOperati... | final BrowserOperatingSystemMapping m = new BrowserOperatingSystemMapping(1, 1);
final String otherClass = "";
assertThat(m.equals(otherClass)).isFalse();
}
} |
4265123_11 | class EnumGenerator {
public FieldDeclaration generateAttribute(Classifier clazz, AST ast,
Property property) {
Type type = property.getType();
logger.log(Level.FINE, "Class: " + clazz.getName() + " - "
+ "Property: " + property.getName() + " - "
+ "Property Upper: " + property.getUpper() + " - "
+... | AST ast = AST.newAST(AST.JLS3);
CompilationUnit cu = ast.newCompilationUnit();
EnumDeclaration ed = enumGenerator.generateEnum(clazz, ast, cu);
EList<Property> properties = mock(EList.class);
Iterator<Property> propertyIter = mock(Iterator.class);
Property property = mock(Property.class);
Type type = moc... |
4265955_13 | class CSVDataStore extends ContentDataStore implements FileDataStore {
@Override
public FeatureReader<SimpleFeatureType, SimpleFeature> getFeatureReader() throws IOException {
return new CSVFeatureSource(this).getReader();
}
public CSVDataStore(File file);
public CSVDataStore(File file, ... | FeatureReader<SimpleFeatureType, SimpleFeature> reader = csvDataStore.getFeatureReader();
List<Coordinate> geometries = new ArrayList<Coordinate>();
List<String> cities = new ArrayList<String>();
List<String> numbers = new ArrayList<String>();
while (reader.hasNext()) {
... |
4276349_2 | class GalaxyAnnouncementModule extends AbstractModule {
@Provides
@Singleton
AnnouncementConfig getAnnouncementConfig(final Config config)
{
final AnnouncementConfig baseConfig = config.getBean(AnnouncementConfig.class);
return new AnnouncementConfig(baseConfig) {
@Override... | final GalaxyAnnouncementModule module = new GalaxyAnnouncementModule();
final AnnouncementConfig cfg = module.getAnnouncementConfig(config);
Assert.assertEquals("configured-service", cfg.getServiceName());
Assert.assertEquals("configured-type", cfg.getServiceType());
Assert.ass... |
4288215_27 | class PLCLoginModule implements LoginModule {
@Override
public boolean logout() throws LoginException {
LOG.debug("logout");
subject.getPrincipals().clear();
return true;
}
@Override public boolean abort();
@Override public boolean commit();
@Override public void initia... | when(userDao.getByUsername(eq(TEST_USERNAME))).thenReturn(testUser);
PLCLoginModule testLoginModule = invokeLogin(TEST_USERNAME, TEST_PASSWORD);
assertTrue(subject.getPrincipals().contains(new UserRole("plcuser")));
assertTrue(subject.getPrincipals().contains(new UserPrincipal(testUser))... |
4291387_17 | class DynamicPropertyUpdater {
void addOrChangeProperty(final String name, final Object newValue, final Configuration config) {
// We do not want to abort the operation due to failed validation on one property
try {
if (!config.containsKey(name)) {
logger.debug("adding p... | AbstractConfiguration.setDefaultListDelimiter(':');
AbstractConfiguration config = new ConcurrentCompositeConfiguration();
config.addConfigurationListener(new ExpandedConfigurationListenerAdapter(new MyListener()));
MyListener.resetCount();
config.setProperty("test.host", "test:... |
4298283_0 | class KakaduUtilities {
public static void initializeRGBChannels(Jp2_channels channels) throws KduException {
final int numColours = 3;
channels.Init(numColours);
// channels.Set_colour_mapping(0, 0, 0);
// channels.Set_colour_mapping(1, 0, 1);
// channels.Set_colour_mapping... | assumeTrue(format("JNI version=%d, expected < 7, ignoring", JNI_VERSION), JNI_VERSION < 7);
KakaduUtilities.initializeRGBChannels(channels);
verify(channels).Init(eq(3));
List<List<Object>> args = colorMappingCapturer.invocationArguments;
assertEquals(3, args.size());
... |
4298401_4 | class ClouderaManagerClientBuilder {
public static void clearCachedResources() {
clientStaticResources.invalidateAll();
}
public ClouderaManagerClientBuilder withAcceptLanguage(
String acceptLaunguage);
public ClouderaManagerClientBuilder withBaseURL(URL baseUrl);
public ClouderaManagerClientBuild... | ClouderaManagerClientBuilder builder = new ClouderaManagerClientBuilder();
ApiRootResource a = newProxy(builder);
assertNotNull(a);
ApiRootResource b = newProxy(builder);
assertNotNull(b);
ClouderaManagerClientBuilder.clearCachedResources();
// test after clear
assertNotNull(newProxy(bu... |
4298676_0 | class QueryDslCustomerRepository implements CustomerRepository {
@Override
@Transactional(readOnly = true)
public List<Customer> findAll() {
SQLQuery allCustomersQuery = qdslTemplate.newSqlQuery().from(qCustomer)
.leftJoin(qCustomer._addressCustomerRef, qAddress);
return qdslTemplate.query(allCustomersQuery... | List<Customer> results = repository.findAll();
assertThat(results, is(notNullValue()));
assertThat(results, hasSize(3));
assertThat(results.get(0), notNullValue());
assertThat(results.get(1), notNullValue());
assertThat(results.get(2), notNullValue());
}
} |
4298816_47 | class FileTools {
public static void listFilesRecursive(File path, List<File> filesArray) {
if (path.exists()) {
File[] files = path.listFiles();
if (files == null) {
Log.fatal("Could not list file " + path.toString() + " you may not have read permissions, skipping i... | // test on SymLinkNullPointer
try {
File sudoersFile = new File("/etc/sudoers");
if (!sudoersFile.exists()) {
Log.fatal("Could not test FileTools on file where we have no read rights");
}
ArrayList<File> files = new ArrayList<>();
... |
4300205_7 | class TicketSeedFileParser {
public List<SessionTicketKey> parse(File file) throws IOException {
return parseBytes(Files.toByteArray(file));
}
public TicketSeedFileParser();
public TicketSeedFileParser(String hexSalt);
public TicketSeedFileParser(byte[] salt);
public List<SessionTi... | List<SessionTicketKey> keys = new TicketSeedFileParser().parse(
new File(TicketSeedFileParserTest.class.getResource("/seeds_with_only_current.json").getFile()));
Assert.assertEquals(2, keys.size());
}
} |
4315362_26 | class Try implements Iterable<T>, Serializable {
@SuppressWarnings("unchecked")
public <U> Try<U> flatMap(CheckedFunction<? super T, ? extends Try<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
if (isSuccess()) {
try {
return (Try<U>) mappe... | assertSame(FAILURE, SUCCESS.flatMap(ignored -> FAILURE));
}
} |
4335519_191 | class ExpressionStack {
public ExpressionStack execute(ExpressionTree expression, ProgramStateConstraints constraints) {
Deque<SymbolicValue> newStack = copy();
Kind kind = ((JavaScriptTree) expression).getKind();
switch (kind) {
case LOGICAL_COMPLEMENT:
SymbolicValue negatedValue = newStac... | execute("a == null");
assertSingleValueInStack(RelationalSymbolicValue.create(Kind.EQUAL_TO, simple1, SpecialSymbolicValue.NULL));
}
} |
4336113_33 | class NATBehavior implements Attribute {
@Override
public AttributeType getType() {
return NATSTUNAttributeType.NAT_BEHAVIOR;
}
public NATBehavior();
public NATBehavior(final NATFeatureRealization mapping, final NATFeatureRealization filtering);
public NATFeatureRealization getFeatu... | assertEquals("Type must be correct.", this.behavior.getType(), NATSTUNAttributeType.NAT_BEHAVIOR);
}
} |
4340532_4 | class AcceptHeader {
public List<Accept> getAccepts() {
return accepts;
}
public AcceptHeader(final String headerValue);
}
class AcceptHeaderTest {
@Test
public void multipleMediaRanges_withWhiteSpace() {
| final String appXml = APPLICATION_XML.getMediaType();
final String appXhtml = APPLICATION_XHTML_XML.getMediaType();
final String appPdf = APPLICATION_PDF.getMediaType();
final AcceptHeader acceptHeader = new AcceptHeader(appXml + ", " + appXhtml + ", " + appPdf);
assertE... |
4349381_5 | class Segment {
public static List<Segment> parseSegments(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Gson gson = new Gson();
return gson.fromJson(reader, new TypeToken<List<Segment>>() {}... | //given
InputStream is = this.getClass().getResourceAsStream(
"/segments.json");
//when
List<Segment> segs = Segment.parseSegments(is);
//then
assertNotNull(segs);
assertEquals(3, segs.size());
assertEquals(5, segs.get(2).coords.size());
... |
4353723_0 | class Select2MultiChoice extends AbstractSelect2Choice<T, Collection<T>> {
static List<String> splitInput(String input) {
if (input.startsWith("{") && input.endsWith("}")) {
// Assume we're using JSON IDs
List<String> result = new ArrayList<String>();
int openBracket =... | List<String> strings = Select2MultiChoice.splitInput("A");
assertEquals(1, strings.size());
assertEquals("A", strings.get(0));
}
} |
4368712_128 | class CombinedFeedController {
@POST
@Template(name = "/index.ftl")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Viewable create(@Valid @BeanParam FeedRequestBean request) {
String[] urlArray = createUrls(request.getUrls()).stream().toArray(String[]::new);
CombinedFeed feed =... | Form form = new Form();
form.param("title", params[0]);
form.param("description", params[1]);
form.param("urls", new StringJoiner(",").add(params[2]).add(params[3]).toString());
form.param("refreshPeriod", params[4]);
Response response = target().request().post(Entity.en... |
4368907_40 | class XBELValidatorServiceImpl implements XBELValidatorService {
@Override
public void validate(String s) throws ValidationError {
try {
xv.validate(s);
} catch (SAXParseException e) {
final String name = e.getSystemId();
final String msg = e.getMessage();
... | final String testxml =
ROOT + "examples/invalid/beldocument_invalid.xbel";
final File testFile = new File(testxml);
if (!testFile.canRead())
fail("can't read " + testxml);
xvs.validate(testFile);
}
} |
4376619_1 | class DecompressTasklet implements Tasklet {
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream()));
File targetDirectoryAsFile = new File(targetDirectory);
i... | DecompressTasklet tasklet = new DecompressTasklet();
tasklet.setInputResource(new ClassPathResource("/input/products.zip"));
File outputDir = new File("./target/decompresstasklet");
if(outputDir.exists()) {
FileUtils.deleteDirectory(outputDir);
}
tasklet.setTargetDirectory(outputDir.getAbsolutePath());
... |
4387088_1 | class BackupManager {
public static List<File> getBackupList(String bookUID) {
File[] backupFiles = new File(getBackupFolderPath(bookUID)).listFiles();
Arrays.sort(backupFiles);
List<File> backupFilesList = Arrays.asList(backupFiles);
Collections.reverse(backupFilesList);
re... | String bookUID = createNewBookWithDefaultAccounts();
BookUtils.activateBook(bookUID);
BackupManager.backupActiveBook();
Thread.sleep(1000); // FIXME: Use Mockito to get a different date in Exporter.buildExportFilename
BackupManager.backupActiveBook();
assertThat(BackupM... |
4389698_31 | class JavaCCReader extends Reader {
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
try {
return reader.read(cbuf, off, len);
} catch (IOException e) {
return handleIOException(e);
}
}
public JavaCCReader(Reader reader);
... | final StringReader stringReader = new StringReader("hello");
final JavaCCReader javaccReader = new JavaCCReader(stringReader);
final BufferedReader reader = new BufferedReader(javaccReader);
assertEquals("hello", reader.readLine());
}
} |
4390160_3 | class OoaBFilter {
public int getSize() {
return array.length;
}
public OoaBFilter(int size, int bufSize);
public boolean containsAndAdd(Element element);
}
class OoaBFilterTest {
@Test
public void testSizeRounding() {
| OoaBFilter filter = new OoaBFilter(3, 0);
assertEquals("3 should round to 4", 4, filter.getSize());
filter = new OoaBFilter(4, 0);
assertEquals("4 should round to 4", 4, filter.getSize());
filter = new OoaBFilter(129, 0);
assertEquals("129 should round to 256", 256, filter.getSize());
}
} |
4398263_37 | class BasicRequestFactory implements RequestFactory {
public <RequestType extends ConversationsRequest> Request create(RequestType request) {
if (request instanceof ReviewsRequest) {
return createFromReviewRequest((ReviewsRequest) request);
} else if (request instanceof QuestionAndAnswe... | final ReviewSubmissionRequest request = new ReviewSubmissionRequest.Builder(Action.Submit, "prod1")
.authenticationProvider(new BVHostedAuthenticationProvider("red@email.com", "https://red.com/auth"))
.hostedAuthenticationEmail("blue@email.com")
.hostedAuthenticationCallback("https://blue.co... |
4408504_1 | class StdInChIGenerator extends StdInChITool {
public InChI generateInchi(IAtomContainer atc)
throws IOException, CDKException {
String workingDir=System.getProperty("user.dir")+
System.getProperty("file.separator");
return generateInchi(atc,workingDir);
}
public InC... | IAtomContainer ac = new AtomContainer();
IAtom a1 = new Atom("C");
IAtom a2 = new Atom("C");
a1.setImplicitHydrogenCount(3);
a2.setImplicitHydrogenCount(3);
ac.addAtom(a1);
ac.addAtom(a2);
ac.addBond(new Bond(a1, a2, IBond.Order.SINGLE));
InChI inc... |
4416959_338 | class MutableComponentModelImpl implements MutableComponentModel {
public boolean isRootClass()
{
return parentModel == null;
}
public MutableComponentModelImpl(String componentClassName, Logger logger, Resource baseResource,
ComponentModel parentModel, bo... | Resource r = mockResource();
Logger logger = mockLogger();
replay();
MutableComponentModel model = new MutableComponentModelImpl(CLASS_NAME, logger, r, null, false, null);
assertTrue(model.isRootClass());
MutableComponentModel subModel = new MutableComponentModelImpl(... |
4421246_0 | class BasicIndexRuleEvaluator extends QueryEvaluator<Node> {
@Override
public QueryResult getResult() throws Exception {
return this.getResult(false);
}
public BasicIndexRuleEvaluator(final CommonCoreQueryEvaluator<Node> evaluator);
public BasicIndexRuleEvaluator();
public BasicIndexRuleEvaluator(final boo... | {
QueryResult selectResult = evaluator.getResult(
"SELECT ?s ?p ?o " +
"WHERE {?s ?p ?o.}");
assertEquals(700, selectResult.size());
}
insertTriple();
{
QueryResult selectResult = evaluator.getResult(
"SELECT ?s ?p ?o " +
"WHERE {?s ?p ?o.}");
assertEquals(701, selectResult.s... |
4437408_1 | class GeoCoordinate implements Comparable<GeoCoordinate> {
@Override
public String toString() {
return "latitude: " + this.latitude + ", longitude: " + this.longitude;
}
public GeoCoordinate(double latitude, double longitude);
public GeoCoordinate(int latitudeE6, int longitudeE6);
public GeoCoordinate(Stri... | GeoCoordinate invalidCoordinate = new GeoCoordinate(91d, 0d);
fail("invalid coordinate must throw exception: " + invalidCoordinate.toString());
}
} |
4449830_4 | class VlcjDevice implements WebcamDevice, BufferFormatCallback, RenderCallback, FPSSource {
@Override
public String toString() {
return String.format("%s[%s (%s)]", getClass().getSimpleName(), getName(), getMRL());
}
protected VlcjDevice(MediaListItem item);
public String getCaptureDevice();
public MediaLis... | VlcjDriver driver = getDriverMock();
Assert.assertNotNull(driver.toString());
}
} |
4494450_40 | class NestedNode {
public IParserNode getLastChild()
{
final IParserNode lastChild = getChild( numChildren() - 1 );
return lastChild != null
&& lastChild.numChildren() > 0 ? lastChild.getLastChild()
: lastChild;
}
protected NestedNode( fi... | assertEquals( NodeKind.RETURN,
function.getLastChild().getId() );
assertNull( function.getChild( Integer.MAX_VALUE ) );
}
} |
4514536_390 | class NamedClusterLoadSaveUtil {
public void saveNamedClusterRep( NamedCluster namedCluster, NamedClusterService namedClusterService, Repository rep,
IMetaStore metaStore, ObjectId id_job, ObjectId objectId, LogChannelInterface logChannelInterface )
throws KettleException {
if ( namedCluster != nul... | String hdfsHost = "hdfsHost";
String hdfsPort = "hdfsPort";
String jobTrackerHost = "jobTrackerHost";
String jobTrackerPort = "jobTrackerPort";
when( namedCluster.getHdfsHost() ).thenReturn( hdfsHost );
when( namedCluster.getHdfsPort() ).thenReturn( hdfsPort );
when( namedCluster.getJobTrac... |
4522462_26 | class IntrospectionModeller {
public static AbstractResource createResource(Class<?> resourceClass) {
final Class<?> annotatedResourceClass = getAnnotatedResourceClass(resourceClass);
final Path rPathAnnotation = annotatedResourceClass.getAnnotation(Path.class);
final boolean isRootResource... | AbstractResource subResource = IntrospectionModeller.createResource(TestSubResourceOne.class);
assertEquals(null, subResource.getPath());
assertEquals(2, subResource.getResourceMethods().size());
assertEquals(0, subResource.getSubResourceLocators().size());
assertEquals(0, subRes... |
4536629_11 | class LocalResourceOwnerAuthenticator implements ResourceOwnerAuthenticator {
@Override
public AuthenticatedPrincipal authenticate(String username, String password) {
ResourceOwner user = resourceOwnerRepository.findByUsername(username);
if (user == null) {
return null;
}
// Validate pas... | AuthenticatedPrincipal principal =
this.authenticator.authenticate(this.resourceOwner.getUsername(), "bad");
assertNull(principal);
}
} |
4541580_83 | class Humanize {
public static String wordWrap(final String value, final int len)
{
if (len < 0 || value.length() <= len)
return value;
BreakIterator bi = BreakIterator.getWordInstance(currentLocale());
bi.setText(value);
return value.substring(0, bi.following(len)... | int df = rand.nextInt(9);
String phrase = "Lorem ipsum dolorem si amet, lorem ipsum. Dolorem sic et nunc." + df;
assertEquals(wordWrap(phrase, 2), "Lorem");
assertEquals(wordWrap(phrase, 30), "Lorem ipsum dolorem si amet, lorem");
assertEquals(wordWrap(phrase, phrase.length()), ... |
4544259_1 | class RepositoryServiceImpl implements RepositoryService {
@Override
public void updateBundleRepositoryDescriptor(String name) throws Exception {
if (repositories.get(name) == null) {
throw new IllegalArgumentException("Repository " + name + " doesn't exist");
}
if (reposito... | repositoryService.create("test");
repositoryService.addArtifact("mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.elasticsearch/7.3.2_1", "test");
repositoryService.updateBundleRepositoryDescriptor("test");
Assert.assertTrue(Files.exists(Paths.get("target/repositories/test... |
4544982_100 | class Scope {
@Nullable
public Symbol getSymbol(String name, Kind... kinds) {
List<Kind> kindList = Arrays.asList(kinds);
List<Symbol> result = new ArrayList<>();
for (Symbol s : symbols) {
if (s.called(name)) {
if (kindList.isEmpty() || kindList.contains(s.kind())) {
result.add... | Scope methodScope = getScopeFor(Kind.METHOD_DECLARATION);
assertThat(methodScope.getSymbol("$g")).isNotNull();
}
} |
4546290_35 | class IndexRecordFilterHook implements RecordUpdateHook {
@Override
public void beforeUpdate(Record record, Record originalRecord, Repository repository, FieldTypes fieldTypes,
RecordEvent recordEvent) throws RepositoryException, InterruptedException {
Collection<IndexInfo> indexInfos = ind... | IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.UPDATE);
recordEvent.setTableName(Table.RECORD.name);
indexFilt... |
4546424_51 | class AdminService extends DbService implements ServiceConstants {
@GET
@Path (REST_API_VIDEOS)
@Produces (MediaType.APPLICATION_JSON)
public Response findVideos() {
if (isDebugEnabled) {
S_LOGGER.debug("Entered into AdminService.findVideos()");
}
try {
List<VideoInfo> videoList = mongoO... | List<VideoInfo> videolist = mongoOperation.getCollection(VIDEOS_COLLECTION_NAME , VideoInfo.class);
assertNotNull(videolist);
}
} |
4570530_3 | class ContextAnalyzer {
public boolean areThereImportsWithoutExports() {
boolean allImportsHaveExports = false;
for (String importedBeanName : imports.keySet()) {
if (!exports.containsKey(importedBeanName)) {
allImportsHaveExports = true;
String ... | ContextAnalyzer analyzer = new ContextAnalyzer();
String beanName = "firstObject";
BeanReferenceInfo importRef1 = new BeanReferenceInfo();
importRef1.setBeanName(beanName);
analyzer.putInImports(importRef1);
assertTrue(analyzer.areThereImportsWi... |
4576305_28 | class RabbitMQCollector extends CollectorComponent {
@Override
public CheckResult check() {
try {
start();
CheckResult failure = connection.failure.get();
if (failure != null) return failure;
return CheckResult.OK;
} catch (Throwable e) {
Call.propagateIfFatal(e);
return... | CheckResult check = collector.check();
assertThat(check.ok()).isFalse();
assertThat(check.error()).isInstanceOf(UncheckedIOException.class);
}
} |
4581618_0 | class TypeUtil {
public static IType removeQualifiers(IType type) {
while (type instanceof IQualifierType) {
type = ((IQualifierType) type).getType();
}
return type;
}
public static IType getPointerToType(IType type);
public static boolean isIBasicType(IType type, I... | IASTFunctionDefinition mainFunctionDefinition =
(IASTFunctionDefinition) declarationsInFile.get(0);
IASTCompoundStatement body = (IASTCompoundStatement) mainFunctionDefinition.getBody();
IASTStatement[] statements = body.getStatements();
assertTrue(statements[2] instanceof I... |
4586516_11 | class NotAuthorizedExceptionMapper extends CandlepinExceptionMapper implements ExceptionMapper<NotAuthorizedException> {
@Override
public Response toResponse(NotAuthorizedException exception) {
return getDefaultBuilder(exception, Response.Status.UNAUTHORIZED, determineBestMediaType()).build();
}
}... | NotAuthorizedException nae = new NotAuthorizedException(
"Not Authorized", "Negotiate", "Basic realm=candlepin");
NotAuthorizedExceptionMapper naem =
injector.getInstance(NotAuthorizedExceptionMapper.class);
Response r = naem.toResponse(nae);
assertEquals(401, r.g... |
4597760_91 | class MondrianFileObject extends DecoratedFileObject {
@Override
public FileContent getContent() throws FileSystemException {
return new DecoratedFileContent( super.getContent() ) {
@Override public InputStream getInputStream() throws FileSystemException {
return annotator.getInputStream( super.g... | FileObject schemaFile = FileObjectTestHelper.mockFile( "schemaFile", true );
FileObject annotationsFile = FileObjectTestHelper.mockFile( "annotationsFile", true );
MondrianSchemaAnnotator mondrianSchemaAnnotator = new MondrianSchemaAnnotator() {
@Override
public InputStream getInputStream(
... |
4603135_103 | class EmbeddedEPNManager extends AbstractEPNManager {
public void publish(String subject, java.util.List<? extends java.io.Serializable> events) throws Exception {
publish(subject, new EventList(events));
}
protected EPNContainer getContainer();
protected java.util.Map<String,java.util.List<Em... | Network net=new Network();
net.setName(TEST_NETWORK);
net.setVersion(VER1);
Subscription sub=new Subscription();
sub.setSubject(TEST_SUBJECT);
sub.setNodeName(N1);
net.getSubscriptions().add(sub);
Node n1=new Node();
n1.setName(N1... |
4605969_0 | class ProjectionSupport {
public static Point2D.Double convertToLatLon(double x, double y) {
return convertToLatLon(x, y, new Point2D.Double());
}
public static Point2D.Double convertToLatLon(double x, double y,
Point2D.Double result);
public static Point2D.Double convertFromLatLon(double lat, doubl... | Point2D.Double p = ProjectionSupport.convertToLatLon(547300.0, 179000.0);
assertEquals(0.12031431734872115, p.x, 1e-7);
assertEquals(51.49076555222841, p.y, 1e-7);
}
} |
4606342_196 | class VcVmUtil {
public static boolean runSPOnSingleVM(NodeEntity node, Callable<Void> call) {
if (node.getMoId() == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
return false;
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
... | NodeEntity node = new NodeEntity();
node.setMoId("vm-001");
MockVcCache.setGetFlag(true);
MockTmScheduler.setResultIsNull(false);
MockTmScheduler.setFlag(VmOperation.START_VM, true);
Callable<Void> callable = getCallable();
boolean result = VcVmUtil.runSPOnSingleVM(node, callab... |
4610430_20 | class RouterImpl implements Router {
@Override
public String getReverseRoute(
Class<?> controllerClass,
String controllerMethodName) {
Optional<Map<String, Object>> parameterMap = Optional.empty();
return getReverseRoute(controllerClass, controllerMethodName, parameter... | String contextPath = "";
when(ninjaProperties.getContextPath()).thenReturn(contextPath);
String route = router.getReverseRoute(TestController.class, "ref");
String route2 = router.getReverseRoute(new MethodReference(TestController.class, "ref"));
assertThat(route, is("... |
4614129_29 | class TinySAL implements SAL {
@Override
public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) {
CardApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandle... | System.out.println("cardApplicationDisconnect");
// test normal case
// get esign path
CardApplicationPath cardApplicationPath = new CardApplicationPath();
CardApplicationPathType cardApplicationPathType = new CardApplicationPathType();
cardApplicationPathType.setCardApplication(appIdentifier_ESIGN);
cardApplica... |
4643211_0 | class CountTimestampSamplesWritable implements Writable {
public CountTimestampSamplesWritable(long count, long epochMilliseconds, List<Long> samples) {
this.countTimestampWritable = new CountTimestampWritable(count, epochMilliseconds);
this.samples = samples;
}
public CountTimestampSamplesWritable(lon... | CountTimestampSamplesWritable orig =
new CountTimestampSamplesWritable(7L, 123L, Arrays.asList(18L, 19L, 20L));
assertEquals(orig.getCount(), 7L);
assertEquals(orig.getEpochMilliseconds(), 123L);
assertEquals(Arrays.asList(18L, 19L, 20L), orig.getSamples());
ByteArrayOutputStream bytesOut = ... |
4646950_7 | class SauceSession {
public MutableCapabilities getCapabilities() {
sauceOptions = getSauceOptions();
setBrowserOptions(browserName);
capabilities.setCapability(sauceOptionsTag, sauceOptions);
capabilities.setCapability(CapabilityType.BROWSER_NAME, browserName);
capabilitie... | String actualBrowser = sauceSession.getCapabilities().getBrowserName();
assertThat(actualBrowser, IsEqualIgnoringCase.equalToIgnoringCase("Chrome"));
}
} |
4653065_0 | class UdhUtil {
public static byte[] getMessageWithUdhInBytes(String s, byte dataCoding) {
final int udhLength = ((byte)s.charAt(0))+1;
final byte[] udh = s.substring(0, udhLength).getBytes();
final byte[] content = DataCodingSpecification.getMessageInBytes(s.substring(udhLength), dataCodin... | String message = "This is the message";
byte dataCoding = 0;
String messageWithUdh = new String(udh).concat(message);
byte[] result = UdhUtil.getMessageWithUdhInBytes(messageWithUdh, dataCoding);
Assert.assertEquals(udh[0], result[0]);
Assert.assertEquals(udh[1], result[1... |
4664478_9 | class DeployLifecycleParticipant extends AbstractMavenLifecycleParticipant implements LogEnabled {
public void afterProjectsRead(final MavenSession session)
throws MavenExecutionException
{
try {
final int totalModules = session.getProjects().size();
logger.info("Inspecting build with total o... | final Model model = createModel("org.foo", "simple");
// deploy defined as "usual"
model.getBuild().getPlugins().add(
createPlugin(DeployLifecycleParticipant.MAVEN_DEPLOY_PLUGIN_GROUP_ID,
DeployLifecycleParticipant.MAVEN_DEPLOY_PLUGIN_ARTIFACT_ID, "deploy"));
// out plugin just decla... |
4665987_17 | class DataSourceConfigManager implements ManagedServiceFactory {
@Override
public void updated(final String pid, final Dictionary config) throws ConfigurationException {
deleted(pid);
if (config == null) {
return;
}
Dictionary<String, Object> loadedConfig = external... | final DataSourceFactory dsf = expectTracked(c, context, DataSourceFactory.class, H2_DSF_FILTER);
DataSource ds = expectDataSourceCreated(dsf);
expectRegistration(ds);
StringEncryptor encryptor = expectTracked(c, context, StringEncryptor.class, "(objectClass=org.jasypt.encryption.StringEn... |
4668183_0 | class IdRegistry {
@Nonnull
public T get(String id) throws IllegalArgumentException {
T t = map.get(id);
if (t == null) {
throw new IllegalArgumentException("Unknown id <" + id + ">");
}
return t;
}
protected IdRegistry(Set<T> instances);
}
class IdRegist... | Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(FooRegistry.class);
Multibinder.newSetBinder(binder(), Foo.class);
}
});
FooRegistry registry = injector.getInstance(Foo... |
4673630_6 | class LdapSettingsManager {
public Map<String, LdapUserMapping> getUserMappings() {
if (userMappings == null) {
// Use linked hash map to preserve order
userMappings = new LinkedHashMap<>();
String[] serverKeys = settings.getStringArray(LDAP_SERVERS_PROPERTY);
if (serverKeys.length > 0) {... | LdapSettingsManager settingsManager = new LdapSettingsManager(
generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery());
assertThat(settingsManager.getUserMappings().size()).isEqualTo(2);
// We do it twice to make sure the settings keep the same.
assertThat(settingsManager.g... |
4678495_8 | class IsGoodQuality extends FilterFunc {
@Override
public Boolean exec(Tuple tuple) throws IOException {
if (tuple == null || tuple.size() == 0) {
return false;
}
try {
Object object = tuple.get(0);
if (object == null) {
return false;
}
int i = (Integer) object;
... | Tuple tuple = TupleFactory.getInstance().newTuple(new Integer(1));
assertThat(func.exec(tuple), is(true));
}
} |
4694994_16 | class WebOpacNet extends OkHttpBaseApi implements OpacApi {
static String[] getTitleAndSubtitle(String title) {
Matcher titleMatcher = Pattern.compile("<\u00ac1>([^<]*)</\u00ac1>").matcher(title);
Matcher subtitleMatcher = Pattern.compile("<\u00ac2>([^<]*)</\u00ac2>").matcher(title);
if (ti... | String[] titleAndSubtitle = WebOpacNet.getTitleAndSubtitle(
"<¬1>Letzte Dinge regeln</¬1><¬2>fürs Lebensende vorsorgen - mit " +
"Todesfällen umgehen</¬2>");
assertEquals("Letzte Dinge regeln", titleAndSubtitle[0]);
assertEquals("fürs Lebensende ... |
4695543_1 | class Util {
public static String camelCaseToLowerUnderscore(String s) {
if (s.toUpperCase().equals(s) && isLettersAndDigits(s)) {
return s.toLowerCase();
}
StringBuilder b = new StringBuilder();
b.append(s.charAt(0));
boolean underscoreAdded = false;
bo... | assertEquals("hello_there", camelCaseToLowerUnderscore("HelloTHERE"));
}
} |
4695732_1 | class MapFileWriter {
static int writeHeaderBuffer(final MapWriterConfiguration configuration,
final TileBasedDataProcessor dataProcessor, final ByteBuffer containerHeaderBuffer) {
LOGGER.fine("writing header");
LOGGER.fine("Bounding box for file: " + dataProcessor.getBoundingBox().maxLatitudeE6 + ", "
+ ... | ByteBuffer headerBuffer = ByteBuffer.allocate(MapFileWriter.HEADER_BUFFER_SIZE);
int headerLength = MapFileWriter.writeHeaderBuffer(this.configuration, this.dataProcessor, headerBuffer);
// expected header length
// 20 + 4 + 4 + 8 + 8 + 16 + 2
// + 9 ("Mercator")
// + 1 + 8 + 1
// + 3 ("de")
// + 17 ("... |
4713292_14 | class RepetitionChecker extends AbstractTypedChecker {
public List<Mistake> check(Sentence sentence) {
List<Mistake> mistakes = new LinkedList<Mistake>();
int offset = sentence.getSpan().getStart();
List<Token> tokens = sentence.getTokens();
String token = tokens.get(0).getLexeme().toLowerCase();
for (i... |
Sentence sentence = createSentence("Se se morre de amor .",
Class.SUBORDINATING_CONJUNCTION, Class.PERSONAL_PRONOUN,
Class.FINITIVE_VERB, Class.PREPOSITION, Class.NOUN,
Class.PUNCTUATION_MARK);
RepetitionChecker checker = new RepetitionChecker();
List<Mistake> errors = checker.check(sentence);
ass... |
4726303_127 | class Operator extends AbstractSopremoType implements
ISerializableSopremoType, JsonStream, Cloneable, BeanInfo {
public List<JsonStream> getOutputs() {
final ArrayList<JsonStream> outputs = new ArrayList<JsonStream>(this.maxOutputs);
for (int index = 0; index < this.maxOutputs; index++)
outputs.add(this.get... | final Operator<?> fixture = new OpImpl(0);
final List<JsonStream> result = fixture.getOutputs();
assertNotNull(result);
assertEquals(1, result.size());
final List<JsonStream> expectedResults = new ArrayList<JsonStream>();
expectedResults.add(fixture.getOutput(0));
assertEquals(expectedResults, result);... |
4726428_33 | class MigrationProperties extends Properties {
public int getRequiredInt(String property) {
String prop = getRequiredString(property);
try {
return Integer.parseInt(prop);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Property " + property + " expected type: int");
... | assertEquals(VALID_INT_VALUE, sut.getRequiredInt(VALID_INT));
}
} |
4737996_7 | class SignatureManagerImpl implements SignatureManager {
@Override
public Map<SignatureType, SortedMap<String, SignatureFileInfo>> getAvailableSignatureFiles() {
final Path binSigFileDir = config.getSignatureFileDir();
final Path containerSigFileDir = config.getContainerSignatureDir();... |
deleteSigDirs();
createSigDirs();
final Path containerSigFile1 = containerSigFileDir.resolve("container_sigs-20100927.xml");
final Path containerSigFile2 = containerSigFileDir.resolve("container_sigs-20100827.xml");
Files.createFile(containerSigFile1);
... |
4738719_1 | class JacORBConfiguration implements Configuration {
@Override
public void setAttributes(Properties properties)
{
// Some lunatics illegally put non String objects into System props
// as keys / values - we ignore them.
for ( String key : properties.stringPropertyNames() )
{... | Properties orbProps = new Properties();
orbProps.setProperty("org.omg.CORBA.ORBClass", "org.jacorb.orb.ORB");
orbProps.setProperty("org.omg.CORBA.ORBSingletonClass", "org.jacorb.orb.ORBSingleton");
ORB orb = ORB.init( new String[] {}, orbProps);
Properties props = new Properties(... |
4741942_80 | class LoadBalancingSinkProcessor extends AbstractSinkProcessor {
@Override
public Status process() throws EventDeliveryException {
Status status = null;
Iterator<Sink> sinkIterator = selector.createSinkIterator();
while (sinkIterator.hasNext()) {
Sink sink = sinkIterator.next();
try {
... | Channel ch = new MockChannel();
int n = 100;
int numEvents = 3*n;
for (int i = 0; i < numEvents; i++) {
ch.put(new MockEvent("test" + i));
}
MockSink s1 = new MockSink(1);
s1.setChannel(ch);
MockSink s2 = new MockSink(2);
s2.setChannel(ch);
// s2 always fails
s2.setF... |
4741958_389 | class ClusterClassifier extends AbstractVectorClassifier implements OnlineLearner, Writable {
@Override
public Vector classify(Vector instance) {
if (models.get(0) instanceof SoftCluster) {
Collection<SoftCluster> clusters = Lists.newArrayList();
List<Double> distances = Lists.newArrayList();
... | ClusterClassifier classifier = newGaussianClassifier();
Vector pdf = classifier.classify(new DenseVector(2));
assertEquals("[0,0]", "[0.212, 0.576, 0.212]",
AbstractCluster.formatVector(pdf, null));
pdf = classifier.classify(new DenseVector(2).assign(2));
assertEquals("[2,2]", "[0.952, 0.047... |
4744588_1 | class LuaContainerLaunchParameters implements ContainerLaunchParameters {
public String toCommand(LuaWrapper table) {
StringBuilder sb = new StringBuilder(table.getString(LuaFields.COMMAND_BASE));
if (!table.isNil(LuaFields.ARGS)) {
LuaWrapper a = table.getTable(LuaFields.ARGS);
Iterator<LuaPair>... | env.setString(LuaFields.COMMAND_BASE, "${JAVA_HOME}/bin/java -Xmx512M com.cloudera.kitten.test.Main");
LuaWrapper args = env.createTable(LuaFields.ARGS);
args.setString("-Dmapred.jobtracker.url", "http://foo:50030");
args.setBoolean("-Dmapred.compress.output", false);
args.addString("bar");
asse... |
4750298_0 | class DisplayLayerHandler implements MessageHandler {
Pair<URL, Map<String, Serializable>> createParams(BufferedReader reader)
throws Exception {
String line = reader.readLine();
URL resourceId = null;
Map<String, Serializable> params = new HashMap<String, Serializable>();
while (line != null) {
line ... | DisplayLayerHandler handler = new DisplayLayerHandler();
String resourceId = "file://home/user/data/myshp.shp#myshp";
String shpId ="file://home/user/data/myshp.shp";
StringBuilder builder = new StringBuilder("geoResourceId;"+resourceId );
builder.append("\nurl;java.net.URL;"+shpId );
String message = build... |
4757131_6 | class UserForm extends BasePage {
public String save() {
// For some reason, WebTest + Tomcat causes version to be 0. Works fine on Jetty.
if (user.getId() != null && user.getId() == 0) {
user.setId(null);
}
if (user.getId() == null) {
user.setVersion(null);... | bean.setId("-1");
bean.edit();
assertNotNull(bean.getUser());
bean.getUser().setFirstName("Jack");
assertEquals(bean.save(), "success");
assertNotNull(bean.getUser());
}
} |
4759439_0 | class ShadowMaker {
public static void processImage(String in, String out) throws IOException {
File imageFile = new File(in);
BufferedImage bufferedImage= ImageIO.read(imageFile);
int width = bufferedImage.getWidth(null);
int height = bufferedImage.getHeight(null);
Buffered... | URL in = ShadowMakerTest.class.getResource("test.png");
URL out = ShadowMakerTest.class.getResource("out.png");
assertNotNull(in);
assertNotNull(out);
System.out.println(in.getFile());
System.out.println(out.getFile());
ShadowMaker.processImage(
in... |
4782751_9 | class Reference implements InvocationHandler {
public void setMethodName(String methodName) {
this.methodName = methodName;
}
protected Reference(Bridge client, String dT, String dI, String oI,
String mN, List<String> operations);
protected Reference(Reference other);
public Reference(Bridge bridge, List... | // Set method name on 4 part
reference.setMethodName("foobar");
assertEquals(reference.getMethodName(), "foobar");
// Set method name on 3 part
ref3.setMethodName("foobar");
assertEquals(ref3.getMethodName(), "foobar");
}
} |
4805389_0 | class Person {
public String getName() {
return name;
}
public Person(String name);
}
class PersonTest {
@Test
public void canConstructAPersonWithAName() {
| Person person = new Person("Larry");
assertEquals("Larry", person.getName());
}
} |
4810329_146 | class CallExpressionImpl extends PyTree implements CallExpression, HasTypeDependencies {
@Override
public InferredType type() {
Symbol calleeSymbol = calleeSymbol();
if (calleeSymbol != null) {
InferredType type = getType(calleeSymbol);
if (type.equals(InferredTypes.anyType()) && callee.is(Kind... | assertThat(lastExpression("len()").type()).isEqualTo(InferredTypes.INT);
}
} |
4812472_36 | class MatrixUtils {
public static double minAbsDiag(Matrix matrix) {
double min = Double.MAX_VALUE;
for (int i = 0; i < matrix.getColumnDimension(); i++) {
double curr = Math.abs(matrix.get(i, i));
if (min > curr) {
min = curr;
}
}
return min;
}
public static boolean anyNaNorInf(Matrix matrix... | Matrix X = new Matrix( new double[][] {
{ 5, -4},
{-4, 6},
});
assertEquals(5, MatrixUtils.minAbsDiag(X), 0.000001);
X = new Matrix( new double[][] {
{ 5, -1},
{-4, -2},
});
assertEquals(2, MatrixUtils.minAbsDiag(X), 0.000001);
}
} |
4820146_5 | class PHPass {
public boolean CheckPassword(String password, String storedHash) {
String hash = cryptPrivate(password, storedHash);
MessageDigest md = null;
if (hash.startsWith("*")) { // If not phpass, try some algorythms from unix crypt()
if (storedHash.startsWith("$6$")) {
... | boolean check = phpass.CheckPassword(wrongpl, hashpl);
assertFalse(check);
}
} |
4823750_0 | class LoginController {
@RequestMapping(method = RequestMethod.POST)
public String handleLogin(@RequestParam String username, @RequestParam String password, HttpSession session)
throws AuthenticationException {
Account account = this.accountService.login(username, password);
session... |
MockHttpSession mockHttpSession = new MockHttpSession();
mockHttpSession.setAttribute(LoginController.REQUESTED_URL, "someUrl");
String view = this.loginController.handleLogin("john", "secret", mockHttpSession);
Account account = (Account) mockHttpSession.getAttribute(LoginController.... |
4835576_9 | class DefaultMockSelectionStrategy implements MockSelectionStrategy {
@SuppressWarnings("unchecked")
public <T> OrderedSet<T> selectMocks(OrderedSet<Object> mocks, Class<T> mockClass) {
OrderedSet<T> matchingMocks = new OrderedSet<T>();
for (Object object : mocks) {
if (mockClass.isAssignableFrom(object.getCl... | // Given
Object mock1 = mock(InputStream.class);
Object mock2 = mock(OutputStream.class);
OrderedSet<Object> mocks = new OrderedSet<Object>(Arrays.asList(mock1, mock2));
// When
OrderedSet<FileOutputStream> actualMocks = strategy.selectMocks(mocks, FileOutputStream.class);
// Then
assertTrue(actualMoc... |
4889322_32 | class ClientActionClassesResolver {
public Map<String, ClientActionClassInformation> resolve() {
Map<String, ClientActionClassInformation> actionClasses = new HashMap<String, ClientActionClassInformation>();
Map<String, Object> foundActions = springIntegration.getActualContext().getBeansWithAnnotation(Clien... | //given
//when
Map<String, ClientActionClassInformation> actionClasses = clientActionClassesResolver.resolve();
//then
assertTrue(actionClasses.containsKey(NonStandardClientActionClass.NAME));
ClientActionClassInformation namedFromClassName = actionClasses.get(NonStandardClientActionClass.NAME... |
4889980_4 | class ValidatorMandatory extends AbstractValueValidator<Object> {
public static ValidatorMandatory getInstance() {
return INSTANCE;
}
public ValidatorMandatory();
@Override protected String getCode();
@Override protected NlsMessage validateNull();
private NlsMessage getFailureMessage();
@Override... |
verifyPositiveValidation(ValidatorMandatory.getInstance(), BigDecimal.ZERO);
}
} |
4898786_11 | class ProcessManagerContext {
synchronized void tryAcceptTask(TaskHandle taskHandle) throws IllegalStateException {
tryCheckLoad();
TaskExclusivity prevExclusivity = currentExclusivity;
String prevExclusiveId = currentExclusiveId;
boolean canAccept = tryChangeExclusivity(taskHandle);
if (canAccept) {
... |
RuntimeInfo runtimeInfo = createRuntimeInfo();
ProcessManagerContext managerContext = new ProcessManagerContext(clusterContext, runtimeInfo);
setUpTaskHandle(taskHandle1, CONTEXT_EXCLUSIVE, taskId1, contextId1);
setUpTaskHandle(taskHandle2, CONTEXT_EXCLUSIVE, taskId2, contextId2);
try {
managerContext.... |
4908338_0 | class Detail extends BaseHstComponent {
@Override
public void doBeforeRender(final HstRequest request, final HstResponse response) throws HstComponentException {
HippoBean doc = getContentBean(request);
if (doc == null) {
log.warn("Did not find a content bean for relative content ... | HippoBean detailBean = new MockHippoBean();
ServletContext servletContext = createMock(ServletContext.class);
ComponentConfiguration componentConfiguration = new MockComponentConfiguration();
ObjectConverter objectConverter = createMock(ObjectConverter.class);
HstRequest reques... |
4910671_5 | class Searcher {
private List<Result> search(Query query, Optional<Sort> sort) {
IndexSearcher searcher = null;
try {
searcher = new IndexSearcher(DirectoryReader.open(directory));
List<Result> result = new ArrayList<>();
TopDocs topDocs = searcher.search(query, ... | Talk talk1 = newAuthorTalk("Florian Hopf");
Talk talk2 = newAuthorTalk("Florian");
indexer.index(talk1, talk2);
List<Result> documents = searcher.search("speaker:Florian");
assertEquals(2, documents.size());
documents = searcher.search("speaker:\"Florian Hopf\"");
... |
4925395_67 | class ThreadedInstaller implements Installer {
@Override
public void install(final Version version) {
new Thread(new Runnable() {
@Override
public void run() {
wrapped.install(version);
}
}).start();
}
public ThreadedInstaller(Installer wrapped);
public static Installer P... | installer.install(version);
Thread.sleep(10);
verify(wrappedSpy).install(version);
}
} |
4941867_5 | class AnnotationFinder extends ClassVisitor {
public Set<Class<?>> getAnnotatedClasses() {
return annotatedClasses;
}
public AnnotationFinder(ClassLoader classLoader, Collection<Class<? extends Annotation>> annotations);
private Class<?> selfClass();
private Class<?> classFromInternalNam... | Collection<String> compile = cp.compile(
"package governator.test;" +
"public class Foo {" +
" @A class Inner {}" +
" @A static class StaticInner {}" +
"}"
);
assertThat(scan("governator.test.Foo$Inner", a).getAnnotatedClasses(),
... |
4946769_202 | class HttpUtils {
public static String completeUrlWithHttpIfProtocolIsNotHttpOrHttpsOrPropertyExpansion(String endpoint) {
if (StringUtils.isNullOrEmpty(endpoint)) {
return endpoint;
}
endpoint = endpoint.trim();
String lowerCaseEndpoint = endpoint.toLowerCase();
... | assertEquals("HTTP://LOCALHOST:9001/TEST/A001", HttpUtils.completeUrlWithHttpIfProtocolIsNotHttpOrHttpsOrPropertyExpansion(uppercaseURLHTTP));
}
} |
4955633_3 | class AliasMessage implements Message {
public static Builder builder(String previousId) {
return new Builder(previousId);
}
public abstract String previousId();
public Builder toBuilder();
}
class AliasMessageTest {
@Test
public void invalidPreviousIdThrows() {
| try {
AliasMessage.builder(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("previousId cannot be null or empty.");
}
}
} |
4959580_16 | class RepeaterUtil implements IRepeaterUtil {
@Override
public String isComponentScrollBarAtBottom(MarkupContainer component) {
return String.format("QuickView.isComponentScrollBarAtBottom('%s');", component.getMarkupId());
}
public RepeaterUtil(Application application);
public static Re... | public void isComponentScrollBarAtBottom() {
WebMarkupContainer c = new WebMarkupContainer("parent");
c.setMarkupId("parent");
String actual = RepeaterUtil.get().isComponentScrollBarAtBottom(c);
String expected = "QuickView.isComponentScrollBarAtBottom('parent');";
Assert.ass... |
4992906_267 | class SaxonXPathRuleQuery extends AbstractXPathRuleQuery {
@Override
public List<String> getRuleChainVisits() {
initializeXPathExpression();
return super.getRuleChainVisits();
}
@Deprecated public SaxonXPathRuleQuery();
public SaxonXPathRuleQuery(DeprecatedAttrLogger attrCtx);
... | SaxonXPathRuleQuery query = createQuery("//dummyNode[@Test1 = false()][@Test2 = true()]");
List<String> ruleChainVisits = query.getRuleChainVisits();
Assert.assertEquals(1, ruleChainVisits.size());
Assert.assertTrue(ruleChainVisits.contains("dummyNode"));
Assert.assertEquals(2, q... |
5002457_14 | class ComputeRays {
public static double splitLineStringIntoPoints(LineString geom, double segmentSizeConstraint,
List<Coordinate> pts) {
// If the linear sound source length is inferior than half the distance between the nearest point of the sound
// so... | GeometryFactory factory = new GeometryFactory();
List<Coordinate> sourcePoints = new ArrayList<>();
// source line is split in 3 parts of 2.5 meters
// This is because minimal receiver-source distance is equal to 5 meters
// The constrain is distance / 2.0 so 2.5 meters
/... |
5003951_0 | class ClojureModelWriter extends ModelWriterSupport {
public void write(Writer writer, Map<String, Object> stringObjectMap, Model model) throws IOException {
try {
final Var REQUIRE = Var.intern(RT.CLOJURE_NS, Symbol.create("require"));
final Symbol REFLECTOR = Symbol.create("org.so... | Model model = readClojureModel("test1.clj");
assertNotNull(model);
ClojureModelWriter writer = new ClojureModelWriter();
StringWriter sw = new StringWriter();
writer.write(sw, new HashMap(), model);
System.out.println(sw.getBuffer().toString());
}
} |
5017081_2 | class Slugify {
@Deprecated
public Slugify(boolean lowerCase) {
this();
withLowerCase(lowerCase);
}
@Deprecated public Slugify(boolean lowerCase);
public Slugify();
public Slugify withCustomReplacement(final String from, final String to);
public Slugify withCustomReplacements(final Map<String, String> ... | // given
String string = "\tHello \tworld \r\t";
// when
String result = new Slugify().slugify(string);
// then
assertEquals("hello-world", result);
}
} |
5022064_10 | class StringDistanceBuilderExample {
public static float example03() {
String a = "A quirky thing it is. This is a sentence.";
String b = "This sentence is similar; a quirky thing it is.";
StringDistance metric =
with(new EuclideanDistance<String>())
.tokenize(Tokenizers.whitespace())
.build();
... | assertEquals(2.0000f, StringDistanceBuilderExample.example03(), DELTA);
}
} |
5054231_2 | class MessageUtils {
static public List<BodyPart> extractMessageAttachments(Log logger, Object content) throws MessagingException, IOException {
ArrayList<BodyPart> ret = new ArrayList<BodyPart>();
if (content instanceof Multipart) {
Multipart part = (Multipart) content;
for... | Message message = TestUtils.createMockMimeMessage(session, 2);
List<BodyPart> parts = MessageUtils.extractMessageAttachments(logger, message.getContent());
assertEquals(2, parts.size());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.