id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
24634425_374 | class Converter {
public static String getProviderXML(Provider provider) {
return toXML(Provider.class, provider);
}
public static Provider getProviderObject(String xml);
public static String getRootCollectionJSON(List<Provider> providers);
private static Collection prepareCollection(List<Provider> provide... | Provider provider = new Provider();
provider.setHref("/11");
provider.setId(11);
provider.setName("Nome");
provider.setVmmUrl("Punto final");
Link linkParent = new Link();
linkParent.setRel("parent");
linkParent.setHref("/");
linkParent.setType(PROVIDER_REGISTRY_NAMESPACE);
Link linkSelf = new Link(... |
24635052_3 | class EventMatchCondition extends Condition {
public boolean isSatisfied(Event event) {
String fieldVal = null;
// some information are in the decrypted event (like type)
if (event.isEncrypted() && (null != event.getClearEvent())) {
JsonObject eventJson = event.getClearEvent().... | condition.key = "content.other_field";
condition.pattern = "other_value";
Assert.assertTrue(condition.isSatisfied(event));
condition.pattern = "*value";
Assert.assertTrue(condition.isSatisfied(event));
condition.pattern = "value";
Assert.assertFalse(condition.is... |
24641218_11 | class LatticeGUIMustache {
public static Stream<String> getKnownTemplates() throws IOException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL knownDirURL = cl.getResource(TEMPLATE_DIR);
if( knownDirURL == null) {
throw new IllegalStateException("Unable to find mustache templates. Erro... | List<String> knownTemplates = LatticeGUIMustache.getKnownTemplates().collect(Collectors.toList());
assertTrue(knownTemplates.size()>0);
assertTrue(knownTemplates.stream().anyMatch(
t -> t.endsWith(LatticeGUIMustache.TEMPLATE_3DMOL))
);
assertTrue(knownTemplates.stream().anyMatch(
t -> t.endsWith(Lat... |
24650339_37 | class Utils {
public static String getGroupId(PwsResult pwsResult) {
// The PWS does not always give us a group id yet.
if (pwsResult.getGroupId() == null || pwsResult.getGroupId().equals("")) {
try {
return new URI(pwsResult.getSiteUrl()).getHost() + pwsResult.getTitle();
} catch (URISyn... | String groupId = "group";
PwsResult mockResult = Mockito.mock(PwsResult.class);
Mockito.when(mockResult.getGroupId()).thenReturn(groupId);
Assert.assertEquals(groupId, Utils.getGroupId(mockResult));
}
} |
24653868_21 | class ACLFileParser {
public static AuthorizationsCollector parse(File file) throws ParseException {
if (file == null) {
LOG.warn("parsing NULL file, so fallback on default configuration!");
return AuthorizationsCollector.emptyImmutableCollector();
}
if (!file.exists... | Reader conf = new StringReader("topic /weather/italy/anemometer");
AuthorizationsCollector authorizations = ACLFileParser.parse(conf);
// Verify
assertTrue(authorizations.canRead(new Topic("/weather/italy/anemometer"), "", ""));
assertTrue(authorizations.canWrite(new Topic("/wea... |
24676715_0 | class ItemsetTree {
public ItemsetTree(final Multiset<Integer> singletons) {
items = singletons;
}
public ItemsetTree(final Multiset<Integer> singletons);
public Itemset randomWalk();
public void traverse(final ItemsetTreeNode node, final Itemset itemset);
public void buildTree(final File inputFile);
publi... |
final File input = getTestFile("contextItemsetTree.txt"); // database
// Get frequency of single items
final Multiset<Integer> singletons = ItemsetMining
.scanDatabaseToDetermineFrequencyOfSingleItems(input);
// Applying the algorithm to build the itemset tree
final ItemsetTree itemsetTree = new Itemset... |
24691184_68 | class NotificationSettingsInteractor extends ValueInteractor<ArrayList<NotificationSetting>> {
public Observable<VoidResponse> disableAll() {
return latest().map(this::disableAll)
.flatMap(this::updateNotificationSettings);
}
@Override protected boolean isDataDisposable();
... | final ArrayList<NotificationSetting> list = new ArrayList<>(1);
list.add(create(true));
list.add(create(true));
list.add(create(true));
notificationSettingsInteractor.notificationSettings.onNext(list);
Sync.last(notificationSettingsInteractor.disableAll());
for... |
24713325_1 | class PropertyInterpolator extends AbstractPropertyLoader {
@Override
public Optional<String> lookupOptional(String name) {
return delegate.lookupOptional(name).map(this::replace);
}
public PropertyInterpolator(PropertyLoader delegate);
private String replace(String value);
}
class Pro... | PropertyLoader loader = mock(PropertyLoader.class);
when(loader.lookupOptional("prop")).thenReturn(Optional.of("{first}-second-{third}"));
when(loader.lookupOptional("first")).thenReturn(Optional.empty());
when(loader.lookupOptional("third")).thenReturn(Optional.empty());
String... |
24748638_22 | class JooqBundle implements ConfiguredBundle<C>, JooqConfiguration<C> {
@Override
public void run(C configuration, Environment environment) throws Exception {
// configure primary data source factory
configureDataSourceFactory(
configuration,
environment,
... | jooqBundle.run(new DropwizardConfig(), environment);
ArgumentCaptor<JooqHealthCheck> captor = ArgumentCaptor.forClass(JooqHealthCheck.class);
verify(healthChecks).register(eq(DEFAULT_NAME), captor.capture());
assertThat(captor.getValue().getValidationQuery()).isEqualTo(validationQueryP... |
24765223_2 | class RESTUserGroupServiceImpl extends BaseRESTServiceImpl implements RESTUserGroupService {
@Override
public Response insert(RESTInputGroup userGroup) throws NotFoundRestEx, InternalErrorRestEx, ConflictRestEx {
// check that no group with same name exists
boolean exists;
try {
... |
{
RESTInputGroup group1 = new RESTInputGroup();
group1.setName("g1");
restUserGroupService.insert(group1);
}
LOGGER.info("Inserting dup");
try {
RESTInputGroup group2 = new RESTInputGroup();
group2.setName("g1");
r... |
24771298_8 | class SegmentTemplate extends AbstractStravaOperations implements SegmentOperations {
public StravaSegment getSegmentById(String id) {
return restTemplate.getForObject(buildUri("/segments/" + id), StravaSegment.class);
}
public SegmentTemplate(RestTemplate restTemplate, boolean isAuthorizedForUse... | mockServer.expect(requestTo("https://www.strava.com/api/v3/segments/1234")).andExpect(method(GET))
.andExpect(header("Authorization", "Bearer ACCESS_TOKEN"))
.andRespond(withSuccess(new ClassPathResource("segment.json", getClass()), MediaType.APPLICATION_JSON));
StravaSegment segment = strava.segment... |
24787461_0 | class WebPWriter extends ImageWriter {
@Override
public void write( IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param ) throws IOException {
if ( param == null ) {
param = getDefaultWriteParam();
}
WebPWriteParam writeParam = (WebPWriteParam) param;
ImageOutputStream output ... | final ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
ImageIO.write(im, "webp", baoStream);
assertTrue(baoStream.size() > 0);
final String testName = "ImageIo";
final File file = createOutputFile(testName, outputName);
final FileOutputStream foStream = new FileOutputSt... |
24834448_0 | class Information {
@Override
public int hashCode() {
int result = localName != null ? localName.hashCode() : 0;
result = 31 * result + (localDescription != null ? localDescription.hashCode() : 0);
result = 31 * result + (localPricing != null ? localPricing.hashCode() : 0);
retu... | Information first = new Information("Full edition", "Access to all themes", "€ 1.00");
Information second = new Information("Full edition", "Access to all themes", "€ 1.00");
assertEquals(first, second);
assertEquals(first.hashCode(), second.hashCode());
}
} |
24855056_82 | class TopologyResource {
@GET
@Path("/{topologyId}")
@Produces(MediaType.APPLICATION_JSON)
public Topology getTopology(@PathParam("topologyId") String topologyId) {
String userId = (String) SecurityUtils.getSubject().getPrincipal();
return topologyService.getTopology(topologyId, userId)... | final Topology mockedTopology = RandomGenerator.randomObject(Topology.class);
doReturn(mockedTopology)
.when(topologyServiceMock)
.getTopology(mockedTopology.getId(), TEST_SUBJECT_ID);
mockAuthenticatedSubject();
TopologyCo... |
24892974_1 | class CodingUtil {
public static long readLong(byte[] buffer) {
return ((((long) buffer[7] & 0xffL)) |
(((long) buffer[6] & 0xffL) << 8) |
(((long) buffer[5] & 0xffL) << 16) |
(((long) buffer[4] & 0xffL) << 24) |
(((long) buffer[3] & 0xffL) << 32) |
... | // Zero
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.asLongBuffer().put(0);
assertEquals(0, CodingUtil.readLong(buffer.array()));
// Max value
buffer.position(0);
buffer.asLongBuffer().put(Long.MAX_VALUE);
assertEquals(Long.MAX_VALUE, CodingUtil.read... |
24920193_0 | class ALU {
public static Object plus(Object o1, Object o2) throws IllegalStateException {
Class<?> c1 = o1.getClass();
Class<?> c2 = o2.getClass();
if (c1 == String.class || c2 == String.class) {
return String.valueOf(o1).concat(String.valueOf(o2));
}
if (Number... | Assert.assertEquals(Integer.class, ALU.plus(b, b).getClass());
Assert.assertEquals(Integer.class, ALU.plus(b, s).getClass());
Assert.assertEquals(Integer.class, ALU.plus(b, i).getClass());
Assert.assertEquals(Long.class, ALU.plus(b, l).getClass());
Assert.assertEquals(Float.class... |
24968217_0 | class DependencyMediatorMojo extends AbstractMojo {
public void execute() throws MojoExecutionException, MojoFailureException {
if (isSkip()) {
getLog().info(project.getArtifactId() + " skipped compatible checking");
return;
}
doExecute();
}
public boolean i... | File testPom = getTestFile("src/test/resources/unit/pom.xml");
assertNotNull(testPom);
assertTrue(testPom.exists());
DependencyMediatorMojo myMojo = (DependencyMediatorMojo) lookupMojo("check", testPom);
assertNotNull(myMojo);
myMojo.execute();
}
} |
24989037_0 | class TrackerNetJaxbContext {
public <T> T unmarshall( String s )
throws JAXBException
{
return jaxb.unmarshall( s );
}
public Function<String, Root> fromXML();
public Function<Root, String> toXML();
@PostConstruct void start();
public String marshall( Root p );
pub... | for( String srcFile : PREDICTIONS )
{
try( InputStream is = getClass().getResourceAsStream( srcFile ) )
{
Root root = trackerNetJaxbContext.unmarshall( is );
assertNotNull( "no root from unmarshall", root );
assertNotNull( root.get... |
25021196_0 | class Wenku8API {
static Map<String, String> getEncryptedMAP(String str) {
Map<String, String> params = new HashMap<>();
params.put("appver=" + BuildConfig.VERSION_NAME
+ "&request", LightBase64.EncodeBase64(str)
+ "&timetoken=" + System.currentTimeMillis());
... | final String str = "test";
Map<String, String> map = Wenku8API.getEncryptedMAP(str);
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(map.get("request"), LightBase64.EncodeBase64(str + "&timetoken=" + CURRENT_TIME));
}
} |
25029544_7 | class Asn implements SingleInternetResource<Asn, AsnRange>, Comparable<Asn> {
public static Asn parse(String text) {
try {
String asnString = Validate.notNull(text, "AS Number must not be null").trim().toUpperCase();
if (asnString.startsWith("AS")) {
asnString = asnS... | assertEquals(new Asn(65536l), Asn.parse("AS1.0"));
}
} |
25040159_5 | class MethodsViaProxy implements Methods<T> {
@Override
public Method<T> get(Consumer<T> consumer) {
return getMethod(consumer);
}
public MethodsViaProxy(Class<T> type, ProxyBuilder<T> proxyBuilder);
@Override public Method<T> get(BiConsumer<T, P> biConsumer);
@Override public Method... | final MethodsViaProxy<I> methods = new MethodsViaProxy<I>(I.class, new NativeProxyBuilder<>());
assertEquals("m1", methods.get(I::m1).name());
assertEquals("m2", methods.get(I::m2).name());
assertEquals("m3", methods.get(I::m3).name());
assertEquals("m4", methods.get(I::m4).name(... |
25125959_2 | class EntradaDao {
public Entrada findById(int id) {
Connection con = null;
PreparedStatement ps = null;
try {
con = ds.getConnection();
ps = con.prepareStatement(
"select * from entrada where id = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Entrada e = new ... |
Entrada entrada = entradaDao.findById(1);
assertNotNull(entrada);
assertEquals("Curso Spring MVC", entrada.getDescricao());
assertEquals(new Integer(1), entrada.getIdUsuario());
assertEquals(Prioridade.Importantissimo, entrada.getPrioridade());
}
} |
25138352_715 | class LocationMonitorState implements Serializable, IsSerializable {
public boolean atLeastOneMonitorStarted() {
if (m_monitorsStarted.size() > 0) {
return true;
}
return false;
}
public LocationMonitorState();
public LocationMonitorState(Collection<GWTLocationSpecificStatus> statuses);
public Locati... | Collection<GWTLocationMonitor> monitors = new ArrayList<GWTLocationMonitor>();
for (int i = 0; i < 5; i++) {
monitors.add(getMonitor("DISCONNECTED"));
}
monitors.add(getMonitor("CONFIG_CHANGED"));
LocationMonitorState lms = new LocationMonitorState(monitors, null);
assertTrue("at least one monitor is CON... |
25151498_1 | class StreamJsonCollapser extends DefaultStreamPipe<StreamReceiver> {
@Override
public void endRecord() {
flushValues();
getReceiver().endRecord();
}
@Override public void startRecord(final String identifier);
@Override public void startEntity(final String name);
@Override public void endEntity();
@Overrid... | collapser.endRecord();
Mockito.verify(mockedReceiver).endRecord();
}
} |
25156526_2 | class ImageWebservice extends LdpWebService {
@GET
@Produces("image/*")
public Response GET(@Context final UriInfo uriInfo,
@HeaderParam(HttpHeaders.ACCEPT) @DefaultValue(MediaType.WILDCARD) final String type,
@HeaderParam(LdpWebService.HTTP_HEADER_PREFER) Pr... |
byte[] img = Resources.toByteArray(Resources.getResource("lions.jpg"));
Response response1 = RestAssured
.given()
.content(img)
.header(HttpHeaders.CONTENT_TYPE, "image/jpeg")
.expect()
.statusCode(201)
.when()
... |
25205317_5 | class FileTool {
public static File create(String fileName) {
String[] filePath = fileName.split(Pattern.quote(File.separator));
String name = filePath[filePath.length - 1];
return create(fileName.replace(name, ""), name);
}
private FileTool();
public static List<String> reader(String fileName)... |
String fileName =
System.getProperty("java.io.tmpdir")
+ File.separator
+ "tata2"
+ File.separator
+ "titi2"
+ File.separator
+ "toto2"
+ File.separator
+ "toto.txt";
File file = FileTool.create(fileName);
... |
25206330_0 | class JsonUserRepository implements UserRepository {
@Override
public List<UserDTO> fetchAllUsers() {
LOGGER.info("Fetching all users");
return users;
}
@Override public UserDTO firstUser();
@Override public UserDTO userByFirstNameAndLastName(String firstName, String lastName);
@Autowired
private UserR... | assertThat(repo.fetchAllUsers().size(), is(equalTo(3)));
}
} |
25213631_2 | class HtmlTextFilter {
public static String filter(String text) {
if ( text == null ) {
return text;
}
Document document = Jsoup.parse(text);
document.outputSettings(new Document.OutputSettings().prettyPrint(false));
document.select("br").append("\\n");
document.select("p").prepend("\\n\\n");
Stri... | String text = "XSS <script type=\"text/javascript\">alert('XSS')</script>.";
Assertions.assertEquals("XSS .", HtmlTextFilter.filter(text));
}
} |
25239318_56 | class InnerHtmlContainsCondition extends Condition<WebElement> {
@Override
public boolean apply(final WebElement element) {
try {
return ignoreCase ?
StringUtils.containsIgnoreCase(element.getAttribute("innerHTML"), text) :
element.getAttribute("inner... | when(mockElement.getAttribute("innerHTML")).thenThrow(new StaleElementReferenceException("stale"));
InnerHtmlContainsCondition condition = new InnerHtmlContainsCondition("blah");
assertThat(condition.apply(mockElement), equalTo(false));
}
} |
25344951_7 | class CollectionUtil {
public static String[] shift(String[] array) {
return shift(array, 1);
}
public static void addIfNotExist(List<T> list, T obj);
public static String[] shift(String[] array, int n);
@SafeVarargs public static String array2String(T... array);
public static String l... | String[] s1 = new String[]{"aaa", "bbb", "ccc", "ddd"};
String[] s2 = CollectionUtil.shift(s1);
Assert.assertEquals(3, s2.length);
Assert.assertEquals("bbb", s2[0]);
Assert.assertEquals("ddd", s2[2]);
}
} |
25345432_0 | class AutoMatterTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
final TypeAdapter<T> materialized;
final AutoMatter annotation = type.getRawType().getAnnotation(AutoMatter.class);
... | gson = new GsonBuilder()
.registerTypeAdapterFactory(new AutoMatterTypeAdapterFactory())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
final String json = gson.toJson(BAR); //isPrivate -> private
final Bar parsed = gson.fromJson(json, Bar.class); //p... |
25397566_0 | class ReqIF10Iterator {
public void iterateRecursivelyThrough(
final EList<Specification> specifications,
final SpecificationCallback specificationCallback,
final SpecObjectCallback specObjectCallback) {
for (Specification specification : specifications) {
this.iterateRecursivelyThrough(specification,
... | final TestSpecification testSpecification = new TestSpecification();
final List<TestSpecObject> testSpecObjects = new ArrayList<TestSpecObject>();
ReqIF10Iterator iterator = new ReqIF10Iterator();
final EList<Specification> specs = reqif.getCoreContent()
.getSpecifications();
iterator.iterateRecursivelyT... |
25405542_165 | class URLParser {
public static Map<DomainParts, String> splitDomain(String domain) {
Map<DomainParts, String> domainParts = null;
String[] dottedParts = domain.trim().toLowerCase(Locale.ENGLISH).split("\\.");
if(dottedParts.length==2) {
domainParts = new HashM... | logger.info("splitDomain3");
String domain = "www.example.com";
Map<URLParser.DomainParts, String> expResult = new HashMap<>();
expResult.put(URLParser.DomainParts.TLD, "com");
expResult.put(URLParser.DomainParts.DOMAINNAME, "example");
expResult.put(URLParser.DomainParts... |
25453552_0 | class TravelFactory implements Iterable<TravelStrategy> {
public TravelStrategy get(TravelId id) throws NullPointerException {
TravelStrategy strategy = allModules.get(id);
if (strategy == null) {
throw new NullPointerException();
}
return strategy;
}
private T... | TravelStrategy strategy = factory.get(null);
Assert.assertNull(strategy);
}
} |
25461048_104 | class AuthorServiceImpl implements AuthorService {
@Override
public int addAuthor(Author author) {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.getSqlSession();
AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
int authorId... | Assert.assertEquals(true, authorService.addAuthor(new Author(3, "year")) > 0);
}
} |
25461792_114 | class RemoteFSController extends AbstractController implements Initializable {
void deleteBoxObject(ButtonType confim, BoxPath path, BoxObject object) throws QblStorageException {
if (confim != ButtonType.OK) {
return;
}
transferManager.addUpload(new ManualUpload(DELETE, volume... | initTreeTable();
BoxFolder folder = nav.listFolders().get(0);
controller.deleteBoxObject(ButtonType.OK, testFolder, folder);
executeTransactions();
assertThat(controller.nav.listFolders().size(), is(0));
assertThat(controller.nav.listFiles().size(), is(0));
}
} |
25507370_1330 | class RpcProgramNfs3 extends RpcProgram implements Nfs3Interface {
@Override
public READDIRPLUS3Response readdirplus(XDR xdr, RpcInfo info) {
return readdirplus(xdr, getSecurityHandler(info), info.remoteAddress());
}
public RpcProgramNfs3(NfsConfiguration config, DatagramSocket registrationSocket,
... | HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
FileHandle handle = new FileHandle(dirId);
XDR xdr_req = new XDR();
handle.serialize(xdr_req);
xdr_req.writeLongAsHyper(0);
xdr_req.writeLongAsHyper(0);
xdr_req.writeInt(3);
xdr_req.write... |
25546146_5 | class InstallOptions implements Serializable {
public String[] getExcludeDependencyFilterPatterns() {
return excludeDependencyFilterPatterns;
}
public InstallOptions(String id, String name, OpenMavenURL url, boolean offline, String[] optionalDependencyPatterns,
String[] ... | assertNotNull(options.getExcludeDependencyFilterPatterns());
assertEquals(0, options.getExcludeDependencyFilterPatterns().length);
}
} |
25569063_2 | class CatchException {
public static void verifyException(ThrowingCallable actor) {
verifyException(actor, Exception.class);
}
public static E caughtException();
public static E caughtException(Class<E> caughtExceptionType);
public static void verifyException(ThrowingCallable actor, Class<... |
// test validation of the arguments
try {
verifyException(() -> list.get(0), null);
fail("IllegalArgumentException is expected");
} catch (IllegalArgumentException e) {
assertEquals("exceptionClazz must not be null", e.getMessage());
}
}
} |
25573672_2 | class RecordingSession {
static RecordingInfo calculateRecordingInfo(int displayWidth, int displayHeight,
int displayDensity, boolean isLandscapeDevice, int cameraWidth, int cameraHeight,
int cameraFrameRate, int sizePercentage) {
// Scale the display size before any maximum size calculations.
di... | RecordingInfo size = calculateRecordingInfo(1080, 1920, 160, false, 1920, 1080, 30, 100);
assertThat(size.width).isEqualTo(1080);
assertThat(size.height).isEqualTo(1920);
assertThat(size.density).isEqualTo(160);
}
} |
25573964_23 | class VncRecorderLifecycleManager {
public void stopRecording(@Observes After afterTestMethod, TestResult testResult,
CubeDroneConfiguration cubeDroneConfiguration, SeleniumContainers seleniumContainers) {
try {
if (this.vnc != null) {
vnc.stop();
Path ... |
final File destination = temporaryFolder.newFolder("destination");
final File video = temporaryFolder.newFile("file.flv");
Files.write(video.toPath(), "Hello".getBytes());
when(seleniumContainers.getVideoRecordingFile()).thenReturn(video.toPath());
when(after.getTestClass()).th... |
25582637_44 | class BasicAuthenticationHeaderParser {
public Credentials<UserPasswordToken> extractCredentials(final Request request) {
final String basicAuthHeader = request.getHeader(BASIC_AUTHORIZATION_HEADER);
if (StringUtils.isNotBlank(basicAuthHeader) && basicAuthHeader.startsWith(BASIC_PREFIX)) {
return extra... | when(request.getHeader("Authorization")).thenReturn("user:password");
final Credentials<UserPasswordToken> extractedCredentials = parser.extractCredentials(request);
assertNull(extractedCredentials);
}
} |
25598822_70 | class ChangelogDiffMaker {
public Collection<Changeset> computeChangesetsToInsert(ExecutionContexts executionContexts,
Collection<Changeset> declaredChangesets,
Collection<Changeset> persistedChang... | Collection<Changeset> changesets = diffMaker.computeChangesetsToInsert(
DEFAULT_CONTEXT,
Arrays.asList(
changeset("ID", "fbiville", "CREATE n2 RETURN n2", "baz", false, true),
changeset("ID2", "fbiville", "CREATE m", "foo", false, true)
),
... |
25603410_10 | class LogCatSerializer {
public void serializeLogs(List<LogCatMessage> logCatMessages) {
List<LogCatMessage> filterLogCatMessages = filterLogCatMessages(logCatMessages);
logCatWriter.writeLogs(test, filterLogCatMessages);
}
LogCatSerializer(TestIdentifier test, LogCatWriter logCatWriter);
private List<LogC... | TestIdentifier test = new TestIdentifier(CLASS1_NAME, TEST1_NAME);
SpyLogCatWriter logCatWriter = new SpyLogCatWriter();
LogCatSerializer serializer = new LogCatSerializer(test, logCatWriter);
List<LogCatMessage> logCatMessages = new ArrayList<>();
addTestStartEnd(logCatMessages... |
25619981_1 | class JaxRs_Parser implements JaxRs_Compatibility {
@Override
public String getSupportedReferenceImplementation() {
return "Jersey";
}
public JaxRs_Parser();
@Override public String getSupportedJaxRSVersion();
@Override public String getResourceName();
@Override public ArrayList<... | assertNotNull(this.parser.getSupportedReferenceImplementation());
}
} |
25623941_13 | class ResourceRequest {
boolean isSatisfied() {
return this.satisfied == req.getResourceCount();
}
ResourceRequest(final ResourceRequestEvent req);
void satisfyOne();
ResourceRequestEvent getRequestProto();
}
class ResourceRequestTest {
@Test()
public void testInitializer() {
| final ResourceRequest rr = get(1);
Assert.assertFalse("A fresh request should not be satisfied.", rr.isSatisfied());
}
} |
25623942_4 | class SyncopeWAEventRepository extends AbstractCasEventRepository {
@Override
public void saveInternal(final CasEvent event) {
SyncopeClient syncopeClient = waRestClient.getSyncopeClient();
if (syncopeClient == null) {
LOG.debug("Syncope client is not yet ready to store audit record... | CasEvent event = new CasEvent(1L, "Auth", "principalId", "creationTime", Map.of("timestamp", "1"));
SyncopeWAEventRepository eventRepository = new SyncopeWAEventRepository(CasEventRepositoryFilter.noOp(),
getWaRestClient());
eventRepository.saveInternal(event);
verify(log... |
25650668_1 | class ParsingTools {
protected static byte getByte(BsonType bsonType) throws NettyBsonReaderException {
switch (bsonType) {
case DOUBLE:
return 0x01;
case STRING:
return 0x02;
case DOCUMENT:
return 0x03;
case ARRAY:
return 0x04;
case BINARY:
r... | BsonType[] types = BsonType.values();
Map<Byte, BsonType> foundBytes = new HashMap<>(types.length);
for (BsonType value : types) {
byte asByte = ParsingTools.getByte(value);
BsonType old = foundBytes.put(asByte, value);
assertNull(old + " and " + value + " has the same associated byte (" ... |
25706873_16 | class Bencode {
public static byte[] byteStringToArray(String str) {
byte[] result = new byte[str.length()];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c > 0xFF)
throw new IllegalArgumentException("Character value outside of byte range");
result[i] = (byte)c;
}
return re... | assertArrayEquals(new byte[]{}, Bencode.byteStringToArray(""));
assertArrayEquals(new byte[]{10}, Bencode.byteStringToArray("\n"));
assertArrayEquals(new byte[]{'C','o','D','e'}, Bencode.byteStringToArray("CoDe"));
assertArrayEquals(new byte[]{-1,-128,127}, Bencode.byteStringToArray("\u00FF\u0080\u007F"));
}
... |
25712818_3 | class Inspector {
public static Class<?> getGenericClassOfList(Class<?> type, Type listGenericClass) {
if(type.isArray()) {
return type.getComponentType();
}
if (listGenericClass instanceof ParameterizedType) {
for (Type typeArgument : ((ParameterizedType) listGenericClass).getActualT... | assertThat(Inspector.getGenericClassOfList(methodWithStringResponse.getReturnType(), methodWithStringResponse.getGenericReturnType()), is(nullValue()));
}
} |
25722021_7 | class ChoiceOfTwoLoadBalancer implements LoadBalancerStrategy<T> {
public static <T> ChoiceOfTwoLoadBalancer<T> create(final Comparator<T> func) {
return new ChoiceOfTwoLoadBalancer<T>(func);
}
public ChoiceOfTwoLoadBalancer(final Comparator<T> func2);
@Override public T choose(List<T> candi... | BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
source.onNext(Lists.newArrayList(0,1));
AtomicIntegerArray counts = new AtomicIntegerA... |
25732604_117 | class MasterInfo extends ImageWriter {
public List<Integer> listFiles(String path, boolean recursive) throws InvalidPathException,
FileDoesNotExistException {
List<Integer> ret = new ArrayList<Integer>();
synchronized (mRoot) {
Inode inode = getInode(path);
if (inode == null) {
thro... | HashSet<Integer> ids = new HashSet<Integer>();
for (int i = 0; i < 10; i ++) {
String dir = "/i" + i;
mMasterInfo.mkdir(dir);
for (int j = 0; j < 10; j ++) {
ids.add(mMasterInfo.createFile(dir + "/j" + j, 64));
}
}
HashSet<Integer> listedIds = new HashSet<Integer>(mMaster... |
25823015_88 | class SimpleMessageListenerContainer extends AbstractMessageListenerContainer {
protected AsyncTaskExecutor getTaskExecutor() {
return this.taskExecutor;
}
public void setTaskExecutor(AsyncTaskExecutor taskExecutor);
public long getBackOffTime();
public void setBackOffTime(long backOffTime);
public long getQu... | SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setAmazonSqs(mock(AmazonSQSAsync.class, withSettings().stubOnly()));
container.setMessageHandler(mock(QueueMessageHandler.class));
container.afterPropertiesSet();
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTask... |
25857692_1 | class WordCount {
public void insertWordCount(String tablename, String word, int count) {
try (SqlSession sqlSession = sqlSessionFactory.openSession();) {
WordCountDao wordCountDao = sqlSession.getMapper(WordCountDao.class);
wordCountDao.insertWordCount(new InsertWordCount(tablename, word, count));
sqlSess... | long actualReturn = 0;
try {
wordCount.insertWordCount("wordcount", "词语1", 10);
wordCount.insertWordCount("wordcount", "词语2", 15);
wordCount.insertWordCount("wordcount", "词语3", 9);
} catch (Exception e) {
actualReturn = -1;
}
assertEquals(0L, actualReturn);
}
} |
25858016_0 | class Help implements ShellCommand {
@Override
public void run() {
parent.usage();
}
public Help(JCommander parent);
}
class HelpTest {
@Test
public void shouldProperlyShowHelpMessage() {
| InputStream stream = toInputStream("help\n");
ByteArrayOutputStream result = new ByteArrayOutputStream();
new Shell(stream, result, "") {
@Override
public List<Object> buildCommands(JCommander jCommander) {
return Arrays.<Object>asList(
... |
25873783_80 | class JoinTable implements SchemaOperation {
JoinTable(String sourceTable, String alias, String... columns) {
checkArgument(!Strings.isNullOrEmpty(sourceTable), "You must specify a 'sourceTable'.");
checkArgument(!Strings.isNullOrEmpty(alias), "You must specify a 'alias'.");
this.sourceTables = Maps.newLinkedH... | JoinTable operation = SchemaOperations.joinTable("users", "u", "id", "name")
.with("addresses", "a", "u.id = a.user_id", "address")
.into("users");
ImmutableMap<String, List<String>> expectedSourceColumns = ImmutableMap.<String, List<String>>builder()
.put("u", Lists.newArrayList("id", "name"))
.pu... |
25889832_0 | class JsonFormatter extends Formatter {
@Override
public String format(LogRecord record) {
Instant timestamp = Instant.ofEpochMilli(record.getMillis());
StringWriter out = new StringWriter();
// Write using a simple JsonWriter rather than the more sophisticated Gson as we generally
... | LogRecord record = new LogRecord(Level.INFO, "message");
record.setMillis(12345_678);
record.setLoggerName("logger");
LogContext context = new LogContext(Collections.singletonMap("traceId", "abcdef"));
String logLine = context.execute(() -> formatter.format(record));
ass... |
25900801_1 | class DhcpV6MessageHandler {
public static DhcpV6Message handleMessage(InetAddress localAddress, DhcpV6Message dhcpMessage)
{
DhcpV6Message replyMessage = null;
if (dhcpMessage instanceof DhcpV6RelayMessage) {
if (dhcpMessage.getMessageType() == DhcpConstants.V6MESSAGE_TYPE_RELAY_FORW) {
Dh... | DhcpV6RelayMessage relayMessage = TestDhcpRelayMessage.buildMockDhcpRelayMessage();
// change the mock relay_reply message to a relay_forward
relayMessage.setMessageType(DhcpConstants.V6MESSAGE_TYPE_RELAY_FORW);
DhcpV6Message dhcpMessage =
new DhcpV6Message(new InetSocketAddress("2001:db8:... |
25962820_2 | class ProductFlavorCombo {
@NonNull
public String getName() {
if (name == null) {
boolean first = true;
StringBuilder sb = new StringBuilder();
for (ProductFlavor flavor : flavorList) {
if (first) {
sb.append(flavor.getName());
... | assertEquals("flavor1Flavor2", new ProductFlavorCombo(f1, f2).getName());
}
} |
25968648_46 | class SimpleFeaturePointFigure extends AbstractPointFigure implements SimpleFeatureFigure {
@Override
public Point getGeometry() {
return (Point) simpleFeature.getDefaultGeometry();
}
public SimpleFeaturePointFigure(SimpleFeature simpleFeature, SceneTransformProvider provider, FigureStyle sty... | SimpleFeatureType type = createShipTrackFeatureType();
SimpleFeature feature = createFeature(type, 1, 53.1F, 13.2F, 0.5);
sceneTransformProvider = new SceneTransformProvider() {
@Override
public MathTransform2D getModelToSceneTransform() {
return MathTra... |
25979437_90 | class EhcacheSessionDataStorage implements SessionDataStorage {
@Override
public void delete(String sessionId) {
this.sessions.remove(sessionId);
}
public EhcacheSessionDataStorage();
public EhcacheSessionDataStorage(String name);
public EhcacheSessionDataStorage(Cache cache);
... | System.out.println("delete");
EhcacheSessionDataStorage instance = new EhcacheSessionDataStorage();
SessionData sessionData = instance.create();
String sessionId = sessionData.getId();
sessionData.put(KEY, VALUE);
instance.save(sessionData);
instance.delete(sessio... |
26027834_1 | class JfrPageCacheTracer implements PageCacheTracer {
@Override
public EvictionRunEvent beginPageEvictions( int expectedEvictions )
{
long evictionRunId = evictionRunCounter.incrementAndGet();
JfrEvictionRunEvent event = new JfrEvictionRunEvent( evictionEventStarter );
event.begin(... | try ( EvictionRunEvent evictionRunEvent = tracer.beginPageEvictions( 2 ) )
{
try ( EvictionEvent evictionEvent = evictionRunEvent.beginEviction() )
{
FlushEvent flushEvent = evictionEvent.flushEventOpportunity().beginFlush( 0, 0, swapper );
flushEv... |
26057756_10 | class FileUtils {
public static void deleteDir(Path dir, DeleteVisitor visitor) {
try{
if(Files.exists(dir) && Files.isDirectory(dir)) {
Files.walkFileTree(dir, visitor);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private FileUtils();
public static void delete(Path path);... | Path parentdir = Files.createTempDirectory("DIR");
Path parentdirfile1 = createTempFile(parentdir, "FILE_1", ".tmp");
Path parentdirfile2 = createTempFile(parentdir, "FILE_2", ".tmp");
FileUtils.deleteDir(parentdir, new DeleteVisitor("*.tmp"));
assertThat(exists(parentdir), is(true));
assertThat(exis... |
26065781_2 | class JNAAccess {
public static native int sum(int[] intArr, int arrayLength)public static native int sum(int[] intArr, int arrayLength);
public static native int sum(int[] intArr, int arrayLength)public static native int inc(int arg);
}
class JNAAccessTest {
@Test
public void testSum() {
| assertEquals(6, JNAAccess.sum(new int[]{0, 1, 2, 3}, 4));
}
} |
26072381_3 | class ExecMojo extends AbstractMojo {
Collection<String> getResourceFiles(final Iterable<? extends FileSet> fileSets,
final boolean followLinks, final boolean allowDuplicates, final boolean allowFiles,
final boolean allowDirs) throws MojoExecutionException {
final Set<String> result = new LinkedHashS... | final Collection<String> actualFiles =
mojo.getResourceFiles(getFileSets(rootDir), mojo.isFollowLinks(), true, true, false);
assertThat(actualFiles).isNotNull().doesNotContainNull().hasSameSizeAs(expectedFiles)
.containsOnlyElementsOf(expectedFiles);
// the following is the same as above, ... |
26088168_0 | class LineIterator implements Iterator<String> {
public LineIterator (String str) {
this.str = str;
this.strLength = str.length();;
while (strLength > 0
&& Character.isWhitespace(str.charAt(strLength - 1))) {
--strLength;
}... |
LineIterator lineIter;
lineIter = new WordWrapLineIterator("this is a string", 10);
Assert.assertEquals("this is a", lineIter.next());
Assert.assertEquals("string", lineIter.next());
lineIter = new WordWrapLineIterator("this is a string", 4);
As... |
26088996_0 | class ChameleonTargetConfiguration {
public Node getContainerDefinitionAsXml() {
Document containerDocument = DomManipulation.createDocumentFromContainerTemplate();
// we can get directly the properties since template only set one container element
final NodeList properties = containerDocu... |
// given
final ChameleonTargetConfiguration chameleonTargetConfiguration =
new ChameleonTargetConfiguration("tomcat:8.0.0:managed");
// when
final Element containerDefinition = (Element) chameleonTargetConfiguration.getContainerDefinitionAsXml();
// then
fi... |
26094155_5 | class MessagePollExecutor implements Runnable {
@Override
public void run() {
Log.debug("Message pooling starts ...");
// is there message for processing?
Message msg = null;
int lockFailureCount = 0;
while (true) {
try {
msg = messagesPool.g... | // prepare threads
int threads = 5;
final CountDownLatch latch = new CountDownLatch(threads);
Runnable task = new Runnable() {
@Override
public void run() {
try {
messagePollExecutor.run();
} finally {
... |
26125896_0 | class DefaultTypeProcessor implements TypeProcessor {
@Override
public Result processType(Type javaType, Context context) {
if (Objects.equals(javaType, Object.class)) {
return new Result(TsType.Any);
}
if (javaType instanceof Class) {
final Class<?> javaClass = ... | TypeProcessor converter = new DefaultTypeProcessor();
final TypeProcessor.Context context = getTestContext(converter);
assertEquals(context.getSymbol(A.class).getFullName(), converter.processType(A.class, context).getTsType().toString());
assertEquals(context.getSymbol(B.class).getFullNa... |
26127972_0 | class Bundler {
public Bundler put(String key, boolean value) {
delegate.putBoolean(key, value);
return this;
}
private Bundler(Bundle delegate);
public static Bundler copyOf(Bundle source);
public static Bundler of(Bundle source);
public static Bundler create();
public Bundler put(String key,... | ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
integerArrayList.add(3);
Bundle b = new Bundle();
ArrayList<String> stringArrayList = new ArrayList<String>();
stringArrayList.add("a string");
ArrayList<CharSequence> charSequenceArrayList = new ArrayList<CharSequence>();
charS... |
26136655_58 | class Int2IntHashMap implements Map<Integer, Integer>, Serializable {
public boolean containsValue(final int value)
{
boolean found = false;
if (value != missingValue)
{
@DoNotSub final int length = entries.length;
@DoNotSub int remaining = size;
for... | assertFalse(map.containsValue(1));
}
} |
26172294_0 | class ArchetypeBuilder extends AbstractBuilder {
public void generateArchetypes(String containerType, File baseDir, File outputDir, boolean clean, List<String> dirs) throws IOException {
LOG.debug("Generating archetypes from {} to {}", baseDir.getCanonicalPath(), outputDir.getCanonicalPath());
File... | File srcDir = new File(basedir, "src/test/examples").getCanonicalFile();
try {
List<String> dirs = new ArrayList<String>();
archetypeBuilder.generateArchetypes("java", srcDir, new File(basedir, "target/test-archetypes"), true, dirs);
} finally {
LOG.info("Com... |
26193137_1 | class Assemblys {
static public Assembly process(Path archiveFile) throws IOException {
Path tempDir = Files.createTempDirectory("stork-deploy.");
CloseablePath closeablePath = new CloseablePath(tempDir);
return process(archiveFile, tempDir, Arrays.asList(closeablePath));
}
static ... | Path archiveFile = TestHelper.getResource("/fixtures/hello-console-1.2.4.tar.gz");
try (Assembly assembly = Assemblys.process(archiveFile)) {
assertThat(assembly.getName(), is("hello-console"));
assertThat(assembly.getVersion(), is("1.2.4"));
assertThat(assem... |
26238360_29 | class ConverterBoolean implements FieldConverter<Boolean> {
@Override
public Boolean convert( String aValue ) throws SdiException
{
if ( !StringUtils.hasText( aValue ) )
{
myLog.debug( "Given value is null" );
return null;
}
String value = aValue.tri... |
myLog.debug( "testing 'ja' fail" );
Boolean received = myClassUnderTest.convert( "ja" );
Assert.assertTrue( received );
myLog.debug( "testing 'nein' fail" );
received = myClassUnderTest.convert( "nein" );
Assert.assertFalse( received );
}
} |
26262349_108 | class DoubleLinkedPoiCategory implements PoiCategory {
@Override
public int getID() {
return this.id;
}
public DoubleLinkedPoiCategory(String title, PoiCategory parent);
public DoubleLinkedPoiCategory(String title, PoiCategory parent, int id);
private void addChildNode(DoubleLinkedP... | Assert.assertEquals(0, this.fastFood.getID());
Assert.assertEquals(1, this.bars.getID());
Assert.assertEquals(2, this.restaurants.getID());
Assert.assertEquals(3, this.electronics.getID());
Assert.assertEquals(4, this.clothes.getID());
Assert.assertEquals(5, this.shops.ge... |
26282952_7 | class CollectionHelper {
public static <T> int singleIndexOf(Collection<T> items, Predicate<T> predicate) {
int result = NOT_FOUND_INDEX;
if (!isEmpty(items)) {
int index = 0;
for (T item : items) {
if (predicate.apply(item)) {
if (result... | int indexOf = CollectionHelper.singleIndexOf(Arrays.asList(1, 5, 3, 7, 9, 5), new Predicate<Integer>() {
@Override public boolean apply(Integer object) {
return object == 3;
}
});
assertEquals(2, indexOf);
}
} |
26284658_0 | class BaseProducer {
public static byte[] serializeAvro(Schema schema, GenericRecord event) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(stream, null);
DatumWriter<GenericRecord> datumWriter = new Generic... |
Schema schema = new Schema.Parser().parse("{\n" +
"\t\"type\":\"record\",\n" +
"\t\"name\":\"test_schema_1\",\n" +
"\t\"fields\" : [ {\n" +
"\t\t\"name\":\"a\",\n" +
"\t\t\"type\":\"int\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\"name\":\"b\",\n" +
... |
26308814_18 | class Luhn {
public static boolean isValid(String number) {
checkLongerThan("The number must have at least 2 characters.", number, 2);
checkIsDigitsOnly("Only digits are allowed", number);
int length = number.length();
// We will study all the digits but the last
char[] cha... | // GIVEN
String number = "123456789";
// WHEN
boolean valid = Luhn.isValid(number);
// THEN
assertFalse(valid);
}
} |
26311068_4 | class UserDao {
public User findUserByUserName(final String userName) {
String sqlStr = " SELECT user_id,user_name "
+ " FROM t_user WHERE user_name =? ";
final User user = new User();
jdbcTemplate.query(sqlStr, new Object[]{userName},
new RowCallbackHandler(... | User user = userDao.findUserByUserName("admin");
assertNotNull(user);
assertEquals(user.getUserName(), "admin");
}
} |
26323526_83 | class GVELayout implements LogicalGraphLayout<EPGMGraphHead, EPGMVertex, EPGMEdge>,
GraphCollectionLayout<EPGMGraphHead, EPGMVertex, EPGMEdge> {
@Override
public DataSet<GraphTransaction> getGraphTransactions() {
DataSet<Tuple2<GradoopId, EPGMGraphElement>> graphVertexTuples = getVertices()
.map(new Ca... | GraphTransaction tx0 = new GraphTransaction(g0, Sets.newHashSet(v0, v1), Sets.newHashSet(e0));
assertEquals(tx0,
from(singletonList(g0), asList(v0, v1), singletonList(e0)).getGraphTransactions().collect().get(0));
}
} |
26344305_1 | class Matrix {
static int[][] SpiralMatrix(int n) {
int[][] a = new int[n][n];
int c = 1, x = 0, y = 0;
int d = 0;
while (c <= n * n) {
if (a[x][y] == 0) {
a[x][y] = c++;
} else {
d++;
d = d % 4;
}
switch (d) {
case 0:
if (y < n - 1 && a[x][y + 1] < 1)
y++;
else {
... | int[][] expecteds = new int[1][1];
expecteds[0][0] = 1;
int n = 1;
int[][] actuals = Matrix.SpiralMatrix(n);
for (int i = 0; i < n; i++) {
Assert.assertArrayEquals(expecteds[i], actuals[i]);
}
n = 2;
actuals = Matrix.SpiralMatrix(n);
expecteds = new int[][]{{1,2},{4,3}};
for (int i = 0; i <... |
26347416_4 | class MavenColaProvider implements IColaProvider {
@Override
public List<String> getTargetClasses() {
if (deltas != null) {
return deltas;
}
final String[] resolvedIncludes = resolveIncludes();
final DirectoryScanner scanner = new DirectoryScanner();
if (re... | // When
final List<String> classes = uut.getTargetClasses();
// Then
assertThat(classes.isEmpty(), is(false));
assertThat(classes, hasItem(binaryToOsClass(getClass().getCanonicalName())));
}
} |
26403452_9 | class FilterEngine {
public void filterRequest(RequestFilterContext request) {
for (RequestFilter filter : filterManager.getRequestFilters()) {
filter.filter(request);
}
}
public FilterEngine(FilterManagerImpl filterManager);
public void filterResponse(Request request, Re... | // Given
RequestFilterContext request = mock(RequestFilterContext.class);
// When
engine.filterRequest(request);
// Then
verify(requestFilter).filter(request);
}
} |
26424110_10 | class Problem0001TwoSum {
public int[] solution001(int[] nums, int target) {
final Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
final int delta = target - nums[i];
if (!map.containsKey(delta)) {
map.put(nums[i], i);
continue;
}
... | final int[] testSrc = {2, 7, 8, 8, 0};
final int[] result = problem.solution001(testSrc, 10);
Assert.assertEquals(testSrc[result[0]] + testSrc[result[1]], 10);
}
} |
26442054_5 | class MultipartReplyMessageFactory implements OFSerializer<MultipartReplyMessage>, SerializerRegistryInjector {
@Override
public void serialize(MultipartReplyMessage message, ByteBuf outBuffer) {
ByteBufUtils.writeOFHeader(MESSAGE_TYPE, message, outBuffer, EncodeConstants.EMPTY_LENGTH);
outBuff... | builder.setType(MultipartType.forValue(10));
MultipartReplyMeterConfigCaseBuilder meterConfigCase = new MultipartReplyMeterConfigCaseBuilder();
MultipartReplyMeterConfigBuilder meterConfigBuilder = new MultipartReplyMeterConfigBuilder();
meterConfigBuilder.setMeterConfig(createMeterConfi... |
26444805_0 | class AreaProcess extends AbstractStatisticsProcess {
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> execute(Map<String, Object> input, ProgressListener monitor)
throws ProcessException {
SimpleFeatureCollection features = (SimpleFeatureCollection) Params.getValue(i... | SimpleFeatureSource source = dataStore.getFeatureSource("polygon");
assertTrue(source.getCount(Query.ALL) > 0);
Map<String, Object> input = new HashMap<String, Object>();
input.put(AreaProcessFactory.inputFeatures.key, source.getFeatures());
// direct
org.geotools.proce... |
26461674_4 | class StringUtils {
public static Iterable<String> splitRespectEscape(String s, char c) {
String cs = shouldEscape(c) ? "\\" + c : Character.toString(c);
Pattern p = Pattern.compile("[^\\\\]" + cs);
//return Splitter.on(c).omitEmptyStrings().trimResults().split(s);
return Splitter.o... | String s = "a\\ b";
Iterator<String> r = splitRespectEscape(s, ' ').iterator();
assertTrue(r.hasNext());
assertEquals("a\\ b", r.next());
}
} |
26525416_12 | class CubeMetastoreClient {
public XFact getXFactTable(String tableName) throws LensException {
return getXFactTable(getFactTable(tableName));
}
private CubeMetastoreClient(HiveConf conf);
public DataCompletenessChecker getCompletenessChecker();
public boolean isDataCompletenessCheckEnabled();
priva... | List<FieldSchema> factColumns = new ArrayList<>(cubeMeasures.size());
for (CubeMeasure measure : cubeMeasures) {
factColumns.add(measure.getColumn());
}
// add one dimension of the cube
factColumns.add(new FieldSchema("zipcode", "int", "zip"));
FieldSchema itPart = new FieldSchema("it", "... |
26525663_6 | class LoadBalanceProxyFactoryBean extends ServiceMultiInterfaceAccessor implements BeanClassLoaderAware,
FactoryBean, InitializingBean, MethodInterceptor, DisposableBean, BeanNameAware {
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
if (getServiceInterface()... | LoadBalanceProxyFactoryBean loadBalanceProxyFactoryBean = newLoadBalanceProxyFactoryBean(null, null);
try {
loadBalanceProxyFactoryBean.afterPropertiesSet();
Assert.fail("loadBalanceProxyFactoryBean with null service interface property should throw exception.");
} catch ... |
26554573_3 | class MyResource {
@POST
@Produces(MediaType.APPLICATION_JSON)
public Model postIt()
{
return new Model("todd", "http://www.toddfredrich.com/");
}
@GET @Produces(MediaType.TEXT_PLAIN) public String getIt();
private HttpServer server;
private WebTarget target;
}
class MyResourceTest {
private H... | Response response = target.path("myresource").request().post(null);
assertEquals(200, response.getStatus());
MyResource.Model model = response.readEntity(MyResource.Model.class);
assertEquals("todd", model.getName());
assertEquals("http://www.toddfredrich.com/", model.getHref());
... |
26558278_5 | class Block extends Super {
public abstract void set( int i, int j, double value ) throws JWaveExceptionpublic abstract void set( int i, int j, double value ) throws JWaveException;
public abstract void set( int i, int j, double value ) throws JWaveExceptionpublic Block( );
public abstract void set( int i, int j, do... |
try {
Block block = genBlockFullObject( _noOfRows, _noOfCols );
for( int i = 0; i < block.getNoOfRows( ); i++ )
for( int j = 0; j < block.getNoOfCols( ); j++ )
block.set( i, j, (double)( i + j + 1 ) );
for( int i = 0; i < block.getNoOfRows( ); i++ )
for( int j = 0; j ... |
26574771_3 | class Product {
public Long getId() {
return id;
}
public Product(String sku, String name);
public void setId(Long id);
public String getSku();
public void setSku(String sku);
public String getName();
public void setName(String name);
public static Product byName(String name);
private stati... |
LoadExampleData.load();
try (Transaction txn0 = DB.beginTransaction()) {
Product newProd = new Product("Copper", "COP");
DB.save(newProd);
List<Product> list = new QProduct()
.name.istartsWith("c")
.orderBy()
.name.asc()
.forUpdate()
.findList();
... |
26628954_3 | class RoutingContextImpl extends RoutingContextImplBase {
@Override
public HttpServerResponse response() {
return request.response();
}
public RoutingContextImpl(String mountPoint, RouterImpl router, HttpServerRequest request, Set<RouteImpl> routes);
private String ensureNotNull(String string);
priv... | router.route().handler(event -> {
assertTrue(event.is("application/json"));
event.response().end();
});
testRequest(HttpMethod.POST, "/", req -> {
req.setChunked(true);
req.putHeader("Content-Type", "application/json");
req.write(Buffer.buffer("{ \"foo\": \"bar\" }"));
}, H... |
26629839_7 | class Ditaa implements DiagramGenerator {
@Override
public ResponseData generate(Request request) throws IOException {
MimeType format = request.headers.getValue(HTTPHeader.ACCEPT);
if (format == null) {
format = DEFAULT_OUTPUT_FORMAT;
}
if (!format.equals(MimeType.... | HTTPHeaders h = new HTTPHeaders();
h.putValue(HTTPHeader.CONTENT_TYPE, MimeType.TEXT_PLAIN_UTF8);
h.putValue(HTTPHeader.ACCEPT, MimeType.PNG);
ResponseData response = new Ditaa().generate(new Request(
URI.create("/ditaa"),
h,
DITAA... |
26633479_0 | class Value implements IValue {
public Value getConvert(IClass type) {
Value newVal = value(type.getClassHolder(), value);
convert(newVal, type);
return newVal;
}
private Value(ClassHolder holder, Boolean value);
private Value(ClassHolder holder, Byte value);
private Val... | ASMSupportClassLoader classLoader = CachedThreadLocalClassLoader.getInstance();
Value value = Value.value(classLoader, 1);
Value newValue = value.getConvert(classLoader.getType(double.class));
Assert.assertEquals(Type.DOUBLE_TYPE, newValue.getType());
Assert.assertTrue(newValue.getV... |
26646135_10 | class HexUtilities {
public static String encodeToHex(byte[] bytes, boolean uppercase, boolean semicolons) {
final char[] lookupTable = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
final int multiplier = semicolons ? 3 : 2;
final char[] hexChars = new char[... | assertEquals("4b:6e:61:62", HexUtilities.encodeToHex(new byte[] { 75, 110, 97, 98 }, false, true));
}
} |
26649305_0 | class MinMax {
public Pair calculate() {
return calculate(new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return ((Comparable<T>) o1).compareTo(o2);
}
});
}
public MinMax(T[] array);
public Pair calculate(Comparator... | MinMax.Pair p1 = new MinMax<>(ARRAY_INT).calculate();
assertEquals(new MinMax<>(null).new Pair(-5, 123), p1);
MinMaxStatic.Pair p2 = MinMaxStatic.calculate(ARRAY_INT);
assertEquals(new MinMaxStatic.Pair<>(-5, 123), p2);
}
} |
26653760_4 | class GoogleSafeBrowsingUrlVerifier implements UrlVerifier {
public final boolean isSafe(String url) {
final Map<String, String> formParameters = this.config.getParameters();
formParameters.put(PARAMETER_URL, url);
boolean safe = true;
try {
final ResponseEntity<String> response = client.getFo... | ResponseEntity<String> verifierResult = new ResponseEntity<>("", HttpStatus.NO_CONTENT);
given(restTemplate.getForEntity(anyString(), eq(String.class),
Matchers.<Map<String, String>>any())).willReturn(verifierResult);
boolean isSafe = verifier.isSafe(LONG_URL);
assertThat(i... |
26662929_0 | class WebSocketResourceProviderFactory extends WebSocketServlet implements WebSocketCreator {
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
try {
Optional<WebSocketAuthenticator> authenticator = Optional.ofNullable(environment.getAuthenticator()... | JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class );
WebSocketEnvironment environment = mock(WebSocketEnvironment.class );
WebSocketAuthenticator authenticator = mock(WebSocketAuthenticator.class);
ServletUpgradeRequest request = mock(ServletUpgradeReque... |
26669439_0 | class ContactEditText extends AppCompatEditText {
public ArrayList<Contact> getContacts() {
final Editable message = getEditableText();
ImageSpan[] spans = message.getSpans(0, message.length(), ImageSpan.class);
Arrays.sort(spans, new Comparator<ImageSpan>() {
@Override
... | mEditText.append(ALICE.getDisplayName() + ";");
assertEquals(ALICE, mEditText.getContacts().get(0));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.