id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
5054234_1 | class TagValue {
protected CharSequence getValue(String key) {
CharSequence val = tagValues.get(key);
if (val == null)
return getDefault(key);
else
return val;
}
public TagValue(String data);
protected Set<String> tagSet();
protected boolean contai... | TagValue t = new TagValue("\r\n\tp = hi\t");
Assert.assertEquals("hi", t.getValue("p"));
}
} |
5054237_27 | class ArgumentParser {
public Integer getNumericValueForTag(String tag, String exceptionMessage) throws SyntaxException {
Argument argument = retrieveArgumentIfExists(tag, exceptionMessage);
if (argument == null) {
return null;
}
return retrieveNumericValue(argument, exc... | ArgumentParser argumentParser = new ArgumentParser(Lists.newArrayList(ANY_TAG_ARGUMENT, NUMBER_ARGUMENT));
assertThat(argumentParser.getNumericValueForTag(ANY_TAG, EXCEPTION_MESSAGE)).isEqualTo(NUMERIC_VALUE);
}
} |
5061371_1 | class IPv4PacketImpl extends AbstractPacket implements IPv4Packet {
@Override
public int getTotalIPLength() {
// byte 3 - 4
return this.headers.getUnsignedShort(2);
}
public IPv4PacketImpl(final Packet parent, final Buffer headers, final int options, final Buffer payload);
@Overr... | final List<IPv4Packet> ipPackets = loadIPPackets("sipp.pcap");
assertThat(ipPackets.get(0).getTotalIPLength(), is(533));
assertThat(ipPackets.get(1).getTotalIPLength(), is(334));
assertThat(ipPackets.get(2).getTotalIPLength(), is(493));
assertThat(ipPackets.get(3).getTotalIPLengt... |
5074598_40 | class VersionUpdater {
public void run(List<File> files)
throws Exception
{
for (File file : files)
{
logger.info("processing: " + file.getPath());
try
{
PomWrapper wrapped = new PomWrapper(file);
boolean changed = possibly... | logger.info("*** testAutomaticVersionDetectionRegulaToSnapshot ***");
String oldVersion = "1.0.1";
String newVersion = "1.0.2-SNAPSHOT";
List<File> poms = createTestPoms("basepom.xml", 1);
File pom = poms.get(0);
updatePom(pom, PomPaths.PROJECT_VERSION, oldVersion);
... |
5084932_20 | class JobServiceImpl extends WaspMessageHandlingServiceImpl implements JobService {
@Override
public List<Job> getJobsAwaitingLibraryCreation(){
List<Job> JobsAwaitingLibraryCreation = new ArrayList<Job>();
for (Job job : getActiveJobs()){
for (Sample sample: job.getSample()){
if (sampleService.isSampleAw... |
List<Job> JobsAwaitingLibraryCreation = new ArrayList<Job>();
Job job = new Job();
job.setJobId(1);
Sample sample = new Sample();
sample.setSampleId(1);
JobSample js = new JobSample();
js.setJobSampleId(1);
js.setJob(job);
js.setSample(sample);
List<JobSample> jobSamples = new Arra... |
5093728_1 | class FeatureChecker {
public T run() {
T result = null;
if(context.hasFeature(featureName)) {
result = onFeatureEnabled();
} else {
result = onFeatureDisabled();
}
return result;
}
public FeatureChecker(FeatureContext storage, String featureName);
public abstract T onFeatureEnabled();
publi... | when(context.hasFeature("test.feature")).thenReturn(false);
assertEquals("checker should return 'disabledStatus' string", "disabledStatus", checker.run());
}
} |
5094929_0 | class Sum {
static void sum(InputStream in, PrintStream out) {
try (
Scanner scanner = new Scanner(in);) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int s = a + b;
out.print(s);
}
}
public static void main(String[] args);
}
class SumTest {
@Test
public... | PipedOutputStream pos = new PipedOutputStream();
InputStream in = new PipedInputStream(pos);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos);
pos.write("3\n4\n".getBytes());
Sum.sum(in, out);
String output = new String(baos.toB... |
5104280_226 | class ANCClient implements ANCSmartRegisterClient {
@Override
public boolean satisfiesFilter(String filterCriterion) {
return name.toLowerCase(Locale.getDefault()).startsWith(filterCriterion.toLowerCase())
|| String.valueOf(ec_number).startsWith(filterCriterion)
|| Strin... | boolean filterMatches = getClient().satisfiesFilter("xyz");
assertFalse(filterMatches);
}
} |
5109749_18 | class LocalizationUtil {
public static String getEnumLocalizationKey(Enum<?> e) {
//Enumy zurnalovanych objektu pouzivaji klice, aby se nemusely prekladat dvakrat
if (Localizable.class.isAssignableFrom(e.getClass()))
return ((Localizable) e).getKey();
return new StringBuilder(e.getDeclaringClass().getN... | Assert.assertEquals("cz.datalite.localization.TestEnumPlain.FOO", LocalizationUtil.getEnumLocalizationKey(TestEnumPlain.FOO));
try {
LocalizationUtil.getEnumLocalizationKey(null);
fail("Should fail on NPE");
} catch (NullPointerException expexted) {
//expected
}
Assert.assertEquals("foo.bar", Localiz... |
5122021_99 | class CompositeJSONProvider implements JSONProvider {
@Override
public JSONObject get() throws JSONException {
JSONObject mergedJsonObject = new JSONObject();
for (JSONProvider jsonProvider : jsonProviderList) {
JSONObject jsonObject = jsonProvider.get();
mergeInto(mergedJsonObject, jsonObjec... | JSONObject jsonObject = compositeJSONProvider1.get();
Assert.assertEquals(jsonObject.get("key1"), "value1");
Assert.assertEquals(jsonObject.get("key2"), "value2");
Assert.assertEquals(jsonObject.get("key3"), "value3");
Assert.assertEquals(jsonObject.getJSONObject("key4").get("key5"), "value5");
... |
5123943_1 | class Functions {
public static double zeta(double x, double q)
{
// * Check arguments
if(x == 1.0)
return Double.POSITIVE_INFINITY;
if(q < 1.0)
return Double.NaN;
if(q <= 0.0)
if(q == floor(q))
return Double.POSITIVE_INFINITY;
else
return Double.NaN;
double s = pow(q, -x);
double... | assertEquals(1.64493406684822, zeta(2.0), 10E-12);
assertEquals(1.13182783346272, zeta(3.456), 10E-12);
assertEquals(1.00000089006735, zeta(20.1), 10E-12);
assertEquals(2.61237534868548, zeta(1.5), 10E-12);
assertEquals(1.34148725725091, zeta(2.5), 10E-12);
assertEquals(1.18338365211190, zeta(3.1), 10E-12... |
5151102_34 | class Timeout {
public BigDecimal getTimeToRepetitionInMinutes() {
return new BigDecimal(timeToRepetition.orElse(0).doubleValue() / 1000 / 60);
}
public Timeout(String key, int value);
public Timeout(String key, int value, int timeToRepetition, Category category, PlaceOfUse placeOfUse);
... | Timeout timeout = new Timeout(engine, step, value);
assertEquals("The timeToRepetition in min should be 0, if there was no value set.", new BigDecimal(0), timeout.getTimeToRepetitionInMinutes());
}
} |
5158290_56 | class GEIndividual extends AbstractIndividual {
public static GEIndividual getIndividual(final GEGrammar grammar, final Phenotype phen, final Genotype genotype, final Fitness fitness) {
final GEIndividual gei;
if(grammar instanceof GEGrammar) {
gei = new GEIndividual(grammar, phen, genotype, fitness)... | System.out.println("* GEIndividualTest: getIndividual");
GEGrammar geg = new GEGrammar();
Phenotype p = new Phenotype();
int[] ia2 = {0};
Genotype geno2 = new Genotype();
geno2.add(new GEChromosome(1, ia2));
Fitness f = new BasicFitness();
GEIndividual gei... |
5171172_70 | class MutationFactory {
public List<Put> insert(long tableId, final Row row) {
return insert(tableId, row, store.getSchema(tableId).getIndices());
}
@Inject public MutationFactory(HBaseStore store);
@Inject public void setColumnFamily(final @Named(ConfigConstants.COLUMN_FAMILY) String column... | List<Put> puts = factory.insert(tableId, row);
byte[] rowCounts = countRowTypes(puts);
assertEquals("data row count", 1, rowCounts[DATA_PREFIX]);
assertEquals("ascending index count", 2, rowCounts[ASC_PREFIX]);
assertEquals("descending index count", 2, rowCounts[DESC_PREFIX]);
... |
5175291_2 | class AdminResource {
@GET
@Path("/coordinator")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllCoordinators(@Context UriInfo uriInfo)
{
Predicate<CoordinatorStatus> coordinatorPredicate = CoordinatorFilterBuilder.build(uriInfo);
List<CoordinatorStatus> coordinators = c... | URI requestUri = URI.create("http://localhost/v1/admin/coordinator");
Response response = resource.getAllCoordinators(MockUriInfo.from(requestUri));
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
assertNull(response.getMetadata().get("Content-Type")); // content ... |
5176685_4 | class AqlQueryBuilder {
public AqlQueryBuilder or(AqlItem... items) {
if (isNotEmpty(items)) {
root.putAll(AqlItem.or((Object[]) items).value());
}
return this;
}
public AqlQueryBuilder item(AqlItem item);
public AqlQueryBuilder elements(AqlItem... items);
publi... | String result = new AqlQueryBuilder()
.or(aqlItem("repo", "myrepo1"), aqlItem("repo", "myrepo2"))
.build();
assertThat(result, notNullValue());
assertThat(result, is("items.find("
+ "{\"$or\":["
+ "{\... |
5185108_32 | class Services {
@JsonProperty
public Set<Service> getServices()
{
return services;
}
public Services(String environment, Set<Service> services);
@JsonProperty public String getEnvironment();
@Override public boolean equals(Object o);
@Override public int hashCode();
@Ove... | Service blue = new Service(Id.<Service>random(), Id.<Node>random(), "blue", "pool", "/location", ImmutableMap.of("key", "value"));
Services services = new Services("testing", Sets.newHashSet(blue));
try {
services.getServices().add(new Service(Id.<Service>random(), Id.<Node>random()... |
5194874_8 | class HL7TemplateFunctions {
public String evaluateTemplate(String templateName, Map<String, Object> bindings) {
// what is this user thinking?
if (templateName == null) {
log.info("Template name is null");
return "";
}
HL7Template template = getHl7queryService().getHL7TemplateByName(templateName);
... | // add a simple template to our db
HL7Template t = new HL7Template();
t.setName("nonexistantgptemplate");
t.setLanguage(HL7QueryService.LANGUAGE_GROOVY);
t.setTemplate("-${ func.getGlobalProperty('nonexistantgp') }-");
Context.getService(HL7QueryService.class).saveHL7Template(t);
HL7TemplateFunctions f... |
5203853_12 | class StoreService {
public Instance newInstance(String sourceAET, Attributes data,
Attributes modified, StoreContext storeContext) throws DicomServiceException {
StoreParam storeParam = storeContext.getStoreParam();
Availability rnAvailability =
storeParam.getRejectionN... | Attributes mpps_create = load("testdata/mpps-create.xml");
IDWithIssuer pid = IDWithIssuer.pidWithIssuer(mpps_create, null);
String sourceAET = mpps_create.getString(Tag.PerformedStationAETitle);
clearData(pid);
StoreParam storeParam = ParamFactory.createStoreParam();
Sto... |
5208272_30 | class GitAdd {
public GitAddResponse add(File repositoryPath, GitAddOptions options, List<File> paths)
throws IOException, JavaGitException {
CheckUtilities.checkFileValidity(repositoryPath.getAbsoluteFile());
IClient client = ClientManager.getInstance().getPreferredClient();
IGitAdd gitAdd = clien... | File file1 = FileUtilities.createFile(repoDirectory, "fileA.txt", "This is file fileA.txt");
File tmpDir = new File(repoDirectory.getPath() + File.separator + "dirA");
if (tmpDir.mkdir()) {
File file2 = FileUtilities.createFile(repoDirectory, "dirA" + File.separator + "fileB.txt",
"Sample Co... |
5210246_2 | class Parameter implements Expression {
public int compareTo(Expression e) {
if (this == e) return 0;
if (e instanceof Parameter) {
Parameter o = (Parameter) e;
return order - o.order;
} else {
return getClass().getName().compareTo(e.getClass().getName());
}
}
public Paramet... | Parameter param2 = new Parameter();
assertTrue(param2.compareTo(param) > 0);
assertTrue(param.compareTo(param2) < 0);
}
} |
5212656_133 | class FieldSelection extends Selection {
public Field replaceWithSimpleField(Field.FieldType fieldType) {
int leftLength = textSelection.getText().length();
int index = textSelection.getIndex();
prepareSpanContainer(leftLength, index);
Field field = null;
switch (fieldType) {
case DATE_FIELD:
field = F... | try {
search = new TextNavigation("ReplaceDateTarget", doc);
// count the initial date field count. should be 1.
OdfContentDom contentDom = doc.getContentDom();
NodeList nodeList = contentDom.getElementsByTagName(TextTimeElement.ELEMENT_NAME.getQName());
int i = nodeList.getLength();
OdfStylesDom st... |
5223349_1 | class ProtocolFormatter {
public static String formatRequest(String url, Position position) {
return formatRequest(url, position, null);
}
public static String formatRequest(String url, Position position, String alarm);
}
class ProtocolFormatterTest {
@Test
public void testFormatRequest... |
Position position = new Position("123456789012345", new Location("gps"), 0);
position.setTime(new Date(0));
String url = ProtocolFormatter.formatRequest("http://localhost:5055", position);
assertEquals("http://localhost:5055?id=123456789012345×tamp=0&lat=0.0&lon=0.0&speed=0.0&bear... |
5225735_6 | class EntityNameExtractorFactory {
public static EntityNameExtractor<?> forNamedPersistentEntity(String name) {
return new NamedPersistentEntityNameExtractor(name);
}
public static EntityNameExtractor<?> forPersistentEntity(PersistentEntity persistentEntity);
public static EntityNameExtractor<... | final EntityNameExtractor entityNameExtractor = forNamedPersistentEntity("name");
assertEquals("Domain Type Object Name", entityNameExtractor.apply(new DomainType()));
}
} |
5243160_0 | class FvdlStAXParser {
Fvdl parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {
SMInputFactory inputFactory = FortifyUtils.newStaxParser();
try {
SMHierarchicCursor rootC = inputFactory.rootElementCursor(inputStream);
rootC.advance(); // <FVDL>
... | FvdlStAXParser parser = new FvdlStAXParser();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("report/dummy-report.xml");
Fvdl fvdl = parser.parse(inputStream);
assertThat(fvdl.getBuild().getSourceBasePath()).isEqualTo("/a/dummy/path");
Collection<Vulnerability> vulnerabili... |
5243237_3 | class VersionHelper {
public VersionRange range(final int... parts) {
checkNotNull(parts);
checkArgument(parts.length != 0);
StringBuilder buff = new StringBuilder()
.append("[");
for (int i = 0; i < parts.length; i++) {
buff.append(parts[i]);
if (i + 1 < parts.length) {
... | VersionRange range = underTest.range(1, 2, 3);
log(range);
assertThat(range.toString(), is("[1.2.3,1.2.4)"));
}
} |
5244017_8 | class CalabashCapabilityMatcher implements CapabilityMatcher {
@Override
public boolean matches(Map<String, Object> nodeCapability, Map<String, Object> requestedCapability) {
if (nodeCapability == null || requestedCapability == null) {
return false;
}
for (String key : requestedCapability.keySet(... | CalabashCapabilities reqCapa = new CalabashCapabilities();
reqCapa.setAut(APP);
reqCapa.setLocale(LOCALE);
reqCapa.setSDKVersion(SDK_VERSION);
Assert.assertTrue(matcher.matches(nodeCapability.getRawCapabilities(),
reqCapa.getRawCapabilities()));
}
} |
5244445_9 | class FeedItemPermutors {
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) ->... | Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DURATION_LONG_SHORT);
List<FeedItem> itemList = getTestList();
itemList.get(1) // itemId 3
.setMedia(null);
assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting
permutor.reorder(itemL... |
5258499_1 | class TransformingProxyPlugin extends ProxyPlugin {
public HttpUrl createHttpsGatewayUrl(String gatewayUrl)
throws MalformedURLException, URIException {
HttpMethod method = new GetMethod(gatewayUrl);
method.setQueryString("ssl=true");
String url = method.getURI().getEscapedURI();
return new HttpUrl(url);
... | String url = "http://www.scotty-transporter.org:9001";
String expected = "http://www.scotty-transporter.org:9001/?ssl=true";
HttpUrl actualUrl = underTest.createHttpsGatewayUrl(url);
String actual = actualUrl.toString();
Assert.assertEquals(expected, actual);
}
} |
5265034_1 | class App {
public static MTEF parse(InputStream is) throws ParseException, IOException {
PushbackInputStream pis = new PushbackInputStream(is);
// hack - throw away 28 byte OLE header
pis.read(new byte[28]);
return new MTEFParser().parse(pis);
}
private static final Logger... | InputStream is = AppTest.class.getResourceAsStream("/ole/fraction.bin");
MTEF mtef = App.parse(is);
assertEquals("Windows", mtef.getGeneratingPlatform());
XmlGeneratorVisitor visitor = new XmlGeneratorVisitor();
mtef.accept(visitor);
Element root = visitor.getRoot();
... |
5265087_58 | class BalanceIndexOperation extends AbstractIndexOperation {
@Override
public List<OperationId> execute(MasterContext context, List<MasterOperation> runningOperations) throws Exception {
InteractionProtocol protocol = context.getProtocol();
IndexMetaData indexMD = protocol.getIndexMD(_indexName);
if (i... | // add nodes and index
List<Node> nodes = Mocks.mockNodes(2);
List<NodeQueue> nodeQueues = Mocks.publisNodes(_protocol, nodes);
deployIndexWithError();
// index deployed on 2 nodes / desired replica is 3
for (NodeQueue nodeqQueue : nodeQueues) {
assertEquals(1, nodeqQueue.size());
}
... |
5279091_17 | class GraphVisualizer {
String shortName(String key) {
Matcher matcher = KEY_PATTERN.matcher(key);
if (!matcher.matches()) throw new IllegalArgumentException("Unexpected key: " + key);
StringBuilder result = new StringBuilder();
String annotationSimpleName = matcher.group(1);
if (annotationSimpl... | String key = fieldKey("annotatedKeyWithParameters");
// We intentionally omit parameters on annotated keys!
assertThat(graphVisualizer.shortName(key)).isEqualTo("@Named String");
}
} |
5284141_13 | class PathHelper {
public static String packageNameToDirName(final String packageName) {
return "/" + packageName.replace('.', '/');
}
private PathHelper();
public static boolean isValid(final String path);
public static boolean isRelative(final String path);
public static String getParent(final Str... | public void testPackageNameToDirName() {
assertEquals("/foo/bar", packageNameToDirName("foo.bar"));
assertEquals("/foo/toto/bar", packageNameToDirName("foo.toto.bar"));
assertEquals("/bar", packageNameToDirName("bar"));
}
} |
5291703_32 | class ProfileSettings {
public <ValueType> MutableProperty<ValueType> getProperty(
PropertyDef<?, ValueType> propertyDef) {
return new DomTrackingProperty<>(propertyDef);
}
public ProfileSettings();
private static Document tryCreateDocument();
public static boolean isEventThr... | ProfileSettings settings = new ProfileSettings();
readFromSettings1(settings);
List<ConfigPath> configPaths1 = Arrays.asList(
getConfigPath("target-platform-name"),
getConfigPath("target-platform"));
List<ConfigPath> configPaths2 = Arrays.asList(
... |
5294661_0 | class JSONDocTemplateBuilder {
public static JSONDocTemplate build(Class<?> clazz, Set<Class<?>> jsondocObjects) {
final JSONDocTemplate jsonDocTemplate = new JSONDocTemplate();
if(jsondocObjects.contains(clazz)) {
try {
Set<JSONDocFieldWrapper> fields = getAllDeclaredFields(clazz);
for (JSONDocFi... | ObjectMapper mapper = new ObjectMapper();
Set<Class<?>> classes = Sets.<Class<?>>newHashSet(TemplateObject.class);
Map<String, Object> template = JSONDocTemplateBuilder.build(TemplateObject.class, classes);
Assert.assertEquals(0, template.get("my_id"));
Assert.assertEquals(0, template.get("idint"));
Ass... |
5312808_68 | class Acls {
public static nfsace4[] compact(nfsace4[] acl) {
int size = acl.length;
if (size == 0) {
return acl;
}
for(int i = 0; i < size; i++) {
nfsace4 a = acl[i];
utf8str_mixed pricipal = a.who;
int processedMask = a.access_ma... | nfsace4[] acl = new nfsace4[]{
toACE(new utf8str_mixed("user1"), ACE4_ACCESS_DENIED_ACE_TYPE, ACE4_READ_DATA, ACE4_IDENTIFIER_GROUP),
toACE(new utf8str_mixed("user1"), ACE4_ACCESS_DENIED_ACE_TYPE, ACE4_READ_DATA),};
assertEquals(2, Acls.compact(acl).length);
}
} |
5320077_16 | class Util {
public static String camelToUpper(String name) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (Character.isUpperCase(c)) {
buf.append('_');
} else {
c = Character.toUpperCase(c);
}
buf... | assertEquals("MY_JDBC_DRIVER", Util.camelToUpper("myJdbcDriver"));
assertEquals("MY_J_D_B_C_DRIVER", Util.camelToUpper("myJDBCDriver"));
assertEquals("AB_CDEF_G_HIJ", Util.camelToUpper("abCdefGHij"));
assertEquals("_JDBC_DRIVER", Util.camelToUpper("JdbcDriver"));
assertEquals("", Util.camelToUpper("... |
5346043_623 | class Bag {
public static int distance (String str1, String str2){
return distance(Transformations.convertStringToIntArray(str1),Transformations.convertStringToIntArray(str2));
}
public static int distance(int str1[], int str2[]);
}
class TestBag {
@Test
//jdsalazar
public void test1(){
| String str1 = "kitten";
String str2 = "sitting";
int res = Bag.distance(str1,str2);
Asserts.assertEquals(res, 3);
}
} |
5346068_0 | class EtagCache implements Flushable {
public EtagCache resetStats() {
hits.set(0);
misses.set(0);
return this;
}
public EtagCache(final File file, final long size);
public static EtagCache create(final File file, final long size);
private static String getKey(final String uri);
private stat... | String url = setUp(new RequestHandler() {
@Override
public void handle(Request request, HttpServletResponse response) {
response.setHeader(HEADER_ETAG, "1234");
if ("1234".equals(request.getHeader(HEADER_IF_NONE_MATCH)))
response.setStatus(HTTP_NOT_MODIFIED);
else {
... |
5349536_0 | class YahooFinanceWebClient implements ContractDataSource<FundamentalData>, HistoricalDataSource {
public OHLC[] getHistoricalData(Contract contract, Date endDate, int numPeriods, int periodUnit) throws IOException
{
if (!(periodUnit == HistoricalDataSource.PERIOD_1_DAY
|| periodUnit == HistoricalDataSource.PE... | OHLC data[] = client.getHistoricalData(Contract.stock("MSFT"), new Date(), 20, HistoricalDataSource.PERIOD_1_DAY);
assertNotNull(data);
assertTrue(data.length > 10);
for (OHLC ohlc : data)
assertValidOHLC(ohlc);
data = client.getHistoricalData(Contract.stock("GOOG"), new Date(), 5, HistoricalDataSource.... |
5380818_17 | class FilesResultMapper {
@VisibleForTesting
@Nullable
String getFilenameFromPath(@Nullable String filePath) {
String filename;
if (!isEmpty(filePath) && filePath.contains(File.separator) && filePath.contains(".")) {
filename = filePath.substring(filePath.lastIndexOf(File.separa... | String path = new FilesResultMapper().getFilenameFromPath("/123/123/123.jpg");
assertEquals("123.jpg", path);
}
} |
5402142_0 | class CdiInstantiator extends AbstractCdiInstantiator {
@Override
public <T extends Component> T createComponent(Class<T> componentClass) {
Unmanaged<T> unmanagedClass = new Unmanaged<T>(componentClass);
Unmanaged.UnmanagedInstance<T> instance = unmanagedClass.newInstance();
instance.pr... | SingletonComponent component = instantiator
.createComponent(SingletonComponent.class);
Assert.assertNotNull(component);
Assert.assertNotNull(component.beanManager);
}
} |
5402462_72 | class BatchJob implements Job {
@Override
public JobReport call() {
start();
try {
openReader();
openWriter();
setStatus(JobStatus.STARTED);
while (moreRecords() && !isInterrupted()) {
Batch<O> batch = readAndProcessBatch();
... | when(pipelineListener.beforeRecordProcessing(record1)).thenReturn(record1);
when(pipelineListener.beforeRecordProcessing(record2)).thenReturn(record2);
doThrow(exception).when(writer).writeRecords(new Batch(record1, record2));
JobReport jobReport = job.call();
assertThat(jobRep... |
5405905_273 | class RemoteDataSetDefAttributesEditor implements IsWidget, org.jbpm.dashboard.dataset.editor.RemoteDataSetDefAttributesEditor {
@PostConstruct
public void init() {
view.init(this);
view.initWidgets(queryTarget.view, serverTemplateId.view, dataSource.view, dbSQL.view);
queryTarget.setS... | presenter.init();
verify(view, times(1)).init(presenter);
verify(view, times(1)).initWidgets(any(DropDownEditor.View.class), any(DropDownEditor.View.class), any(ValueBoxEditor.View.class), any(ValueBoxEditor.View.class));
verify(dataSource, times(1)).addHelpContent(anyString(), anyString... |
5418564_0 | class CreateOnWriteList implements List<E> {
@Override
public E set(int index, E element) {
if (wrapped != null) {
return wrapped.set(index, element);
}
throw new UnsupportedOperationException();
}
public abstract List<E> newList();
private List<E> getWrapped();
@Override public boolean add(E e);
@Ove... | assertNull(_list);
List<String> l = getListPreset();
assertTrue(_list instanceof CreateOnWriteList);
assertTrue(l instanceof CreateOnWriteList);
assertNull(getListPreset().set(0, "a"));
}
} |
5426219_354 | class AnalyticsIndexerService {
public int index(
Experiment experiment,
Map<String, Map<BioentityPropertyName, Set<String>>> bioentityIdToProperties, int batchSize) {
List<SolrInputDocument> toLoad = new ArrayList<>(batchSize);
int addedIntoThisBatch = 0;
int added... | BaselineExperimentDataPoint[] nullArray = {null};
mockExperimentDataPointStreamFactory(experimentDataPointStreamFactory, experiment, nullArray);
Map<String, Map<BioentityPropertyName, Set<String>>> bioentityIdToIdentifierSearch = new HashMap<>();
int batchSize = Integer.parseInt(DEFAULT... |
5445246_4 | class LiteralExtractor implements Extractor<T>, Serializable, PortableObject {
public LiteralExtractor() {
}
public LiteralExtractor();
public LiteralExtractor(T literal);
@Override public T extract(Object o);
@SuppressWarnings("unchecked") @Override public void readExternal(PofReader reade... | assertEquals("blah", new LiteralExtractor("blah").extract(null));
assertEquals(5, new LiteralExtractor(5).extract(null));
}
} |
5449213_0 | class TimeZoneRoundingCache {
public long round(final long timestamp) {
final long rounded = _cache.get(timestamp);
if(rounded == _noEntryKey)
return roundAndCache(timestamp);
else
return rounded;
}
public TimeZoneRoundingCache(final TimeZoneRounding tzRoun... | final int cacheSize = 1000;
final int reps = 2000;
final long[] input = new long[reps];
final long[] expected = new long[reps];
final long[] actual = new long[reps];
final Chronology chronology = ISOChronology.getInstanceUTC();
final TimeZoneRounding tzRounding = ... |
5455271_0 | class ClusterSubdomainAffinityAlgorithm extends CallIDAffinityBalancerAlgorithm {
public void loadSubclusters(String subclustersString) {
ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<String, List<String>>();
if(subclustersString != null) {
subclustersString = subclustersString.replaceAll... | ClusterSubdomainAffinityAlgorithm algorithm = new ClusterSubdomainAffinityAlgorithm();
try {
algorithm.loadSubclusters(groups2);
} catch (Exception e) {
return;
}
fail("Excpeted excpetion");
}
} |
5455433_389 | class Text implements CharSequence {
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (!(other instanceof Text)) {
return false;
}
Text t = (Text) other;
if (this.len != t.len) {
return ... | Text t1 = new Text("test");
Text t2 = new Text("test");
assertTrue("Must be equals", t1.equals(t2));
}
} |
5455441_14 | class OidContainer {
public String getSerializedData() {
if (this.data == null)
return "";
else {
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
for (long l : data) {
if (isFirst)
isFirst = false;
... | public void testEncode() throws Exception {
OidContainer oid = new OidContainer(getSourceData());
String s1 = oid.getSerializedData();
assertEquals(s1, getString());
}
} |
5455452_5 | class AsnInputStream extends InputStream {
public byte[] readIndefinite() throws AsnException, IOException {
int startPos = this.pos;
this.advanceIndefiniteLength();
byte[] res = new byte[this.pos - startPos - 2];
System.arraycopy(this.buffer, this.start + startPos, res, 0, this.pos - startPos - 2);
r... | byte[] data = new byte[] { (byte)0x80, (byte)0x80, 0x09, (byte)0x96, 0x02, 0x24, (byte)0x80,
0x03, 0x00, (byte)0x80, 0x00, (byte)0xf2, (byte)0x81, 0x07, (byte)0x91, 0x13, 0x26,
(byte)0x98, (byte)0x86, 0x03, (byte)0xf0, 0x00, 0x00 };
AsnInputStream asnIs = new AsnInputStream(data);
int length = asnIs.re... |
5455458_5 | class AsrSignal {
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
if (!initialPrompts.isEmpty()) {
buffer.append("ip=");
for (int index = 0; index < initialPrompts.size(); index++) {
buffer.append(initialPrompts.get(... | String expectedResult = "ip=hello.wav dr=no_name_driver ln=en-US eik=# mrt=100 wit=100 pst=50 hw=57616974 in=dtmf_speech mn=1 mx=1 pr=true";
AsrSignal asrSignal = new AsrSignal(driver, DEFAULT_LANG, initialPrompts, endInputKey, maximumRecTimer, waitingInputTimer,
timeAfterSpeech, hotWord... |
5455474_2 | class HomeRoutingManagement implements HomeRoutingManagementMBean {
@Override
public void addCcMccmnc(String countryCode, String mccMnc, String smsc) throws Exception {
CcMccmncImpl ccMccmnc = new CcMccmncImpl(countryCode, mccMnc, smsc);
ccMccmncCollection.addCcMccmnc(ccMccmnc);
this.st... | public void testFunc() throws Exception {
CcMccmncCollection original = new CcMccmncCollection();
original.addCcMccmnc(new CcMccmncImpl("1111", "222", "00001"));
original.addCcMccmnc(new CcMccmncImpl("", "555", ""));
original.addCcMccmnc(new CcMccmncImpl("3333", "444", null));
... |
5487921_15 | class Version implements Comparable<Object> {
public static int compare(String oneVersion, String anotherVersion) {
return new Version(oneVersion).compareTo(new Version(anotherVersion));
}
public Version(String version);
public boolean isAlpha();
public boolean isBeta();
public boolean isFinal();
public in... | Assert.assertTrue(Version.compare("1.1.3 Alpha", "1.1.3 Beta") < 0);
}
} |
5495870_6 | class UpdateManager {
protected static boolean installedFromMarket(WeakReference<? extends Context> weakContext) {
boolean result = false;
Context context = weakContext.get();
if (context != null) {
try {
String installer = context.getPackageManager().getInstall... | // On Android Nougat, installing packages using HockeyApp (using the package manager) will list the following installer identifier
when(mockPackageManager.getInstallerPackageName(any(String.class))).thenReturn("com.android.packageinstaller");
// When not on Android Nougat this is considered "sto... |
5502061_0 | class LoggerFactory implements org.slf4j.ILoggerFactory {
@Override
public org.slf4j.Logger getLogger(String name)
{
LoggerAdapter logger = loggers.get(name);
if (logger == null) {
logger = createLogger(name);
LoggerAdapter logger2 = loggers.putIfAbsent(name, logger);
if (logger2 != null) logger = logg... | Logger log = LoggerFactory.getLogger(LoggerFactoryTest.class);
Assert.assertNotNull(log);
Logger log2 = LoggerFactory.getLogger(LoggerFactoryTest.class);
verifySame(log, log2, true);
verifySame(((LoggerAdapter)log).getDelegate(), ((LoggerAdapter)log2).getDelegate(), true);
log2 = LoggerFactory.getLogger("an... |
5509523_13 | class DefaultHost implements Host {
@Override
public Stats stats() {
return this.statistics;
}
DefaultHost(@NotNull final Bucket bckt);
DefaultHost(
@NotNull final Bucket bckt,
@NotNull final Host.CloudWatch cwatch
);
@Override public String toString();
@Ov... | final long sum = 10;
final CloudWatch cloudwatch = this.cloudWatch();
final GetMetricStatisticsResult result = new GetMetricStatisticsResult()
.withDatapoints(new Datapoint().withSum(Double.valueOf(sum)));
Mockito.doReturn(result).when(cloudwatch.get())
.getMetric... |
5510832_6 | class ReadOnlyMemory extends RandomAccessMemory {
@Override
public boolean write(boolean isByteMode, int address, int value) {
return false;
}
public ReadOnlyMemory(String id, int startAddress, short[] data);
public ReadOnlyMemory(String id, int startAddress, byte[] data);
@Override... | byte[] romData = new byte[] { 0, (byte) 0377 };
ReadOnlyMemory rom = new ReadOnlyMemory("TestRom", 01000, romData);
rom.write(true, 01000, 0377);
assertEquals(0377 << 8, rom.read(false, 01000));
rom.write(true, 01001, 0);
assertEquals(0377 << 8, rom.read(false, 01000));
... |
5517956_3 | class RelationshipComparator implements Comparator<ProjectRelationship<?, ?>> {
@Override
public int compare( final ProjectRelationship<?, ?> one, final ProjectRelationship<?, ?> two )
{
if ( one.getType() == two.getType() )
{
if ( one.getPomLocation()
.equal... | final ProjectVersionRef nodeW = projectVersion( "w", "w", "1.0" );
final ProjectVersionRef nodeX = projectVersion( "x", "x", "1.0" );
final ProjectVersionRef nodeY = projectVersion( "y", "y", "1.0" );
final ProjectVersionRef nodeZ = projectVersion( "z", "z", "1.0" );
DependencyR... |
5529658_109 | class LayerBuilder {
protected List<ModuleBuildFuture> collectFutures(ModuleList moduleList, HttpServletRequest request)
throws IOException {
final String sourceMethod = "collectFutures"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(sourceCl... | IAggregator mockAggregator = TestUtils.createMockAggregator();
HttpServletRequest mockRequest = TestUtils.createMockRequest(mockAggregator);
ICache mockCache = createMock(ICache.class);
IModuleCache mockModuleCache = createMock(IModuleCache.class);
expect(mockCache.getModules()).andReturn(mockModuleCache).any... |
5551767_0 | class Preprocessor {
public static void main(String[] args) {
String file = "C:/Users/Kerwyn/Desktop/pg17989.txt";
String preprocessed_file = "";
try {
preprocessed_file = preprocess(file);
} catch (FileNotFoundException e) {
/* file doesn't exist */
System.err.println(file + " doesn't exists. Pick ... | fail("Not yet implemented");
}
} |
5561881_3 | class Script {
public Object run(final String functionReference, final Object... values) {
// Create a local copy of the bindings so we can multi-thread.
Context context = enterContext();
try {
Scriptable object = this.localScope;
Iterator<String> parts = Splitter.on('.').split(functionRefere... | final Script s = new Script("test", "function tester() { return test.me(); }", LoadPaths.defaultPath(), "hegemon/test");
Assert.assertEquals("here", s.run("tester"));
}
} |
5598875_74 | class ScheduledTaskImpl implements ScheduledTask {
public synchronized boolean cancel(boolean block)
{
switch (state) {
case COMPLETED:
case CANCELLED:
// the task has already completed or been cancelled
return false;
case RUNNING:
... | setTaskState("RUNNABLE");
Assert.assertTrue(task.cancel(false));
Assert.assertEquals("CANCELLED", getTaskState());
}
} |
5601676_139 | class ApplicationConfiguration {
public String getApplicationDescription() {
return applicationDescription;
}
public ApplicationConfiguration();
public String getApplicationID();
public void setApplicationID(final String applicationID);
public String getApplicationName();
public ... | final String expected = "NAME";
config.setApplicationDescription(expected);
assertEquals(expected, config.getApplicationDescription());
}
} |
5610434_1 | class DataObjectFactory {
public static Page createPage(String rawJSON) throws FacebookException {
try {
JSONObject json = new JSONObject(rawJSON);
return pageConstructor.newInstance(json);
} catch (InstantiationException e) {
throw new FacebookException(e);
... | facebook.setMockJSON("mock_json/page/f4j.json");
Page page = facebook.getPage();
String rawJSON = DataObjectFactory.getRawJSON(page);
Page actual = DataObjectFactory.createPage(rawJSON);
assertThat(actual, is(page));
assertThat(actual.toString(), is(page.toString()));
... |
5615967_1 | class MapCommand extends Command {
protected ModelEvent remove(EditorModel em, String key) {
elementMap.remove(key);
return new DefaultModelEvent(commandName, this, null, null, changed);
}
protected MapCommand(EAdMap<V> map, V value, String oldKey, String newKey,
DependencyNode... changed);
protected Mod... | System.out.println("remove");
MapCommand<String> a;
for (int i = 0; i < 4; i++) {
a = new MapCommand.RemoveFromMap<String>(m1, "key" + i, root);
cm.performCommand(a);
assert (!m1.containsKey("key" + i));
}
for (int i = 0; i < 4; i++) {
cm.undoCommand();
assert (m1.containsKey("key" + (4 - i - ... |
5626414_3 | class ResourceHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
if (lookupPath.startsWith(serviceRootPathWithSlash)) {
doHandleMatch(doCreateRequestMappingInfo(), lookupPath, request);
... |
final String lookupPath = "/service-root/a/b/c";
Method expectedMethod = resourceController.getClass().getMethod("handle", WebRequest.class,
RequestMessageContainer.class);
HandlerMethod expected = new HandlerMethod(resourceController, expectedMethod);
new NonStrictExpectations() {
{
// requestに対... |
5632139_73 | class LibShapeDraw {
public String getInstanceId() {
return instanceId;
}
public LibShapeDraw();
public LibShapeDraw(String ownerId);
public boolean unregister();
@Deprecated public static String getVersion();
@Deprecated public static boolean isControllerInitialized();
publ... | LibShapeDraw lib2 = new LibShapeDraw();
assertFalse(lib.getInstanceId().equals(lib2.getInstanceId()));
}
} |
5634637_2 | class ParquetStorer extends StoreFunc implements StoreMetadata {
private Schema getSchema() {
try {
return Utils.getSchemaFromString(getProperties().getProperty(SCHEMA));
} catch (ParserException e) {
throw new RuntimeException("can not get schema from context", e);
}
}
public ParquetSt... | String out = "target/out";
PigServer pigServer = new PigServer(ExecType.LOCAL);
Data data = Storage.resetData(pigServer);
Collection<Tuple> list = new ArrayList<Tuple>();
for (int i = 0; i < 1000; i++) {
list.add(tuple("a"+i, bag(tuple("o", "b"))));
}
for (int i = 10; i < 2000; i++) {
... |
5661262_0 | class TcpClient {
public boolean changeCallSiteTarget(String methodType, String oldTarget, String newTarget) throws IOException {
Map obj = new LinkedHashMap();
obj.put("call", "changeCallSiteTarget");
obj.put("methodType", methodType);
obj.put("oldTarget", oldTarget);
obj.p... | final String expected_answer = "{\"result\":\"ok\",\"calledMethod\":\"changeCallSiteTarget\"}" + END_OF_INSTRUCTION;
final String sent_call = "changeCallSiteTarget";
final String sent_methodType = "virtual";
final String sent_oldTarget = "HelloWorld.tick:(HelloWorld)void";
final... |
5683980_4 | class SonarQubeTask extends Task {
@SuppressWarnings("unchecked")
@Override
public void execute() {
log(Main.getAntVersion());
log("SonarQube Ant Task version: " + SonarQubeTaskUtils.getTaskVersion());
log("Loaded from: " + SonarQubeTaskUtils.getJarPath());
Map<String, String> allProps = new Has... | project = mock(Project.class);
Properties props = new Properties();
File out = folder.newFile();
props.put("sonar.scanner.dumpToFile", out.getAbsolutePath());
when(project.getProperties()).thenReturn(props);
task = new SonarQubeTask();
File baseDir = folder.newFolder();
when(project.ge... |
5704054_2 | class BasicClient implements SLIClient {
@Override
public void update(final Entity e) throws URISyntaxException, MessageProcessingException, IOException,
SLIClientException {
URL url = URLBuilder.create(restClient.getBaseURL()).entityType(e.getEntityType()).id(e.getId()).build();
Re... | Entity e = new GenericEntity(ResourceNames.STUDENTS, studentData);
Response r = mock(Response.class);
when(r.getStatus()).thenReturn(204);
when(restClient.putRequest(any(URL.class), anyString())).thenReturn(r);
underTest.update(e);
verify(restClient).putRequest(new URL("h... |
5706983_1 | class ChartSampleSearch {
static public int findSampleLessOrEqual(ChartSampleSequence samples, double x)
{
synchronized (samples)
{
ChartSampleSearch binary = new ChartSampleSearch();
if (binary.search(samples, x))
return binary.mid;
// Didn't... | double x;
int i;
// Exact find
x = 4.0;
i = ChartSampleSearch.findSampleLessOrEqual(samples, x);
//System.out.println("Looking for " + x + ", found " + samples.get(i).getX());
assertTrue(i >= 0);
assertTrue(i < samples.size());
assertTrue(samples.... |
5722110_54 | class JTransfoImpl implements JTransfo, ConfigurableJTransfo, ConvertSourceTarget {
@Override
public <T> T convert(Object source, T target, String... tags) {
if (null == source || null == target) {
throw new JTransfoException("Source and target are required to be not-null.");
}
... | when(reflectionHelper.newInstance(SimpleClassDomain.class)).thenReturn(null);
JTransfoException exc = Assertions.assertThrows(JTransfoException.class, () ->
jTransfo.convert(new SimpleClassNameTo()));
assertThat(exc.getMessage()).startsWith("Cannot create instance of target cla... |
5726012_9 | class MicrochipPotentiometerDeviceController {
public DeviceControllerDeviceStatus getDeviceStatus() throws IOException {
// get status from device
int deviceStatus = read(MEMADDR_STATUS);
// check formal criterias
int reservedValue = deviceStatus & STATUS_RESERVED_MASK;
if (reservedValue != STATUS_RESERV... |
// test io-exception
try {
controller.getDeviceStatus();
fail("Excpected IOException (but there is no) because "
+ "I2CDevice-mock is not initialized yet!");
} catch (IOException e) {
// expected
}
// test for proper write-argument -> see FIGURE 7-5 and TABLE 4-1
testForWriteAndRead((byt... |
5745625_3 | class ObjectQueue implements Iterable<T>, Closeable {
public abstract int size()public abstract int size();
public abstract int size()public static ObjectQueue<T> create(QueueFile qf, Converter<T> converter);
public abstract int size()public static ObjectQueue<T> createInMemory();
public abstract int size()public abs... | assertThat(queue.size()).isEqualTo(3);
}
} |
5754848_4 | class TodoResource {
@DELETE
public void deleteAll() {
dao.deleteAll();
}
public TodoResource(TodoDao dao);
@GET public List<Todo> list();
@GET @Path("{id}") public Todo get(@PathParam("id") String id);
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response create(@FormParam("email... | final String id = UUID.randomUUID().toString();
final Todo todo = Todo.newBuilder().id(id).created(new Date()).build();
dao.insert(todo);
dao.insert(todo.toBuilder().id("dummy").build());
assertThat(dao.findAll()).hasSize(2);
ClientResponse response = client().resource("/todos").delete(ClientR... |
5770443_0 | class EnumBuilder {
public JDefinedClass build() {
JPackage _package = determinePackage();
try {
definedClass = _package._enum(typeName);
} catch (JClassAlreadyExistsException e) {
throw new RuntimeException(e.getExistingClass().fullName() + " is already defined in ... | SmiCodeNamingStrategy namingStrategy = new StraightNamingStrategy("");
SmiType type = new SmiType(new IdToken(null, "MyEnum"), new SmiModule(new SmiMib(null, null), new IdToken(null, "MyModule")), SmiPrimitiveType.ENUM);
type.getModule().getMib().setCodeNamingStrategy(new StraightNamingStrategy(... |
5793618_42 | class ServiceLoader {
public Collection<T> createAll(final Object... arguments) {
Collection<T> instances = new ArrayList<T>(classes.size());
for (String className : classes) {
T instance = createInstance(className, arguments);
if (instance != null) {
instances.add(instance);
}
}
return instanc... | ServiceLoader<?> loader = new ServiceLoader<>(List.class);
assertThat(loader.createAll())
.hasSize(2)
.hasAtLeastOneElementOfType(ArrayList.class)
.hasAtLeastOneElementOfType(LinkedList.class);
}
} |
5793738_15 | class TaskVariablesPayloadValidator {
public CreateTaskVariablePayload handleCreateTaskVariablePayload(CreateTaskVariablePayload createTaskVariablePayload) {
checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(),
"Variable has not a valid ... | //given
CreateTaskVariablePayload payload = TaskPayloadBuilder.createVariable()
.withVariable("date",
"1970-01-01T01:01:01.001Z")
.build();
//calculate number of milliseconds after 1970-01-01T00:00:00.000Z
long time = Duration... |
5832036_1 | class SetNetworkListAdapter extends AbstractListAdapter<Network> {
@Override
public void add(Network network) {
switch (network.getType()) {
case WIFI:
addWiFi( network );
break;
case CDMA:
case GSM:
case WCDMA:
... | SetBackedNetworkList netlist = new SetBackedNetworkList();
System.out.print("Inserting WiFi Large Set into SetBackedNetworkList...");
long start = System.currentTimeMillis();
netlist.addAll(wifiLarge);
long end = System.currentTimeMillis();
System.out.println(" Inserted i... |
5839179_20 | class PKPass implements Cloneable, Serializable {
public String getForegroundColor() {
return foregroundColor;
}
protected PKPass();
public String getSerialNumber();
public String getPassTypeIdentifier();
public URL getWebServiceURL();
public String getAppLaunchURL();
public ... | assertThat(this.builder
.foregroundColor(COLOR_STRING)
.build()
.getForegroundColor()).isEqualTo(COLOR_STRING);
assertThat(this.builder
.foregroundColor((String) null)
.build()
.getForegroundColor()).isNull()... |
5841522_1 | class JochreIndexBuilder implements Runnable, TokenExtractor {
public void updateIndex() {
long startTime = System.currentTimeMillis();
try {
if (searchStatusHolder.getStatus() != SearchStatus.WAITING) {
throw new IndexingUnderwayException();
}
JochreSearchManager manager = JochreS... | System.setProperty("config.file", "src/test/resources/test.conf");
ConfigFactory.invalidateCaches();
String configId = "yiddish";
JochreIndexBuilder builder = new JochreIndexBuilder(configId, false);
builder.updateIndex();
JochreSearchManager manager = JochreSearchManager.getInstance(configId)... |
5853673_2 | class OracleNamingStrategy extends ImprovedNamingStrategy {
@Override
public String classToTableName(String className) {
return super.classToTableName(className).toUpperCase();
}
@Override public String propertyToColumnName(String propertyName);
@Override public String tableName(String tableName);
@Ov... | OracleNamingStrategy namingStrategy = new OracleNamingStrategy();
for (int i = 0; i < classNames.length; i++) {
String tableName = namingStrategy.classToTableName(classNames[i]);
assertThat(tableName).isEqualTo(tableNames[i].toUpperCase());
}
}
} |
5861549_2 | class GeneratePnPObservation {
boolean renderMarker(List<Point3D_F64> marker, Se3_F64 BodyToCamera, List<Point2D_F64> pixels) {
Point3D_F64 p3 = new Point3D_F64();
for (int indexCorner = 0; indexCorner < marker.size(); indexCorner++) {
BodyToCamera.transform(marker.get(indexCorner), p3)... | GeneratePnPObservation generator = new GeneratePnPObservation(60,640,480);
generator.random = new Random(1234);
generator.stdevPixel = 0;
List<Point3D_F64> marker = new ArrayList<>();
Se3_F64 BodyToCamera = SpecialEuclideanOps_F64.eulerXyz(0,0,5,0,0,0,null);
marker.add(... |
5874016_2 | class LexicalAlignerFromLexicalResource implements AlignmentComponent {
@Override
public void annotate(JCas aJCas) throws AlignmentComponentException {
// get T lemma sequence as one single string
String tLemmaSeq = null; // TEXTVIEW Lemma sequences (ordered) as one string, for quick existence check
// S... |
try {
// Annotate the first pair with tokens and lemmas
logger.info("Tokenize and lemmatize the sentence pair #1");
JCas pair1 = lap.generateSingleTHPairCAS(t1, h1);
// Call the aligner to align T and H of pair 1
logger.info("Aligning pair #1");
alignerWordNetEN.annotate(pair1);
lo... |
5947247_22 | class CoordinateSequence2D implements CoordinateSequence, Cloneable {
public void setOrdinate(int index, int ordinateIndex, double value) {
switch (ordinateIndex) {
case 0:
x[index] = value;
break;
case 1:
y[index] = value;
... |
CoordinateSequence2D cs = new CoordinateSequence2D(2);
cs.setOrdinate(0, 0, 1.1);
cs.setOrdinate(0, 1, 1.2);
cs.setOrdinate(1, 0, 2.1);
cs.setOrdinate(1, 1, 2.2);
assertEquals(1.1, cs.getX(0), TOL);
assertEquals(1.2, cs.getY(0), TOL);
ass... |
5970660_5 | class ICalVCardHelper {
public String createDate(Date d) {
// Shift the timezone to UTC
SimpleDateFormat dateFormatter = new SimpleDateFormat(YEAR_MONTH_DAY_FORMAT);
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// ICal DATE pattern: <yyyyMMdd>
return dateFormatter.format(d);
}
pub... | ICalVCardHelper helper = BEANS.get(ICalVCardHelper.class);
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.set(2019, 7, 23, 15, 22, 00); // month is 0 based 8 (august)
assertEquals("20190823", helper.createDate(cal.getTime()));
}
} |
5973879_0 | class ContentTypeValidator implements StorageItemBeforeSave {
@Override
public void beforeSave(StorageItem storageItem, StorageItemUploadPart part) throws IOException {
if (part == null) {
return;
}
String fileContentType = part.getContentType();
if (fileContentTy... | validator.beforeSave(null, null);
verify(part, times(0)).getContentType();
}
} |
5999841_31 | class LogEntryDAOMysqlImpl extends AbstractTableCreatingDAOImpl implements LogEntryDAO {
public List<LogEntry> getLogEntriesForTenant(int tenantId, int offset, int limit) {
Preconditions.checkArgument(offset >= 0, "offset must be greater than or equal to 0");
Preconditions.checkArgument(limit >= 0,... | List<LogEntry> logEntries = logEntryDAO.getLogEntriesForTenant(1, 0, 0);
assertThat(logEntries, is(not(nullValue())));
assertThat(logEntries.size(), is(0));
}
} |
6002930_4 | class MapNotSerializable extends FieldConstraint {
@Override
protected void check(MappedClass mc, MappedField mf, Set<ConstraintViolation> ve) {
if (mf.isMap()) {
if (mf.hasAnnotation(Serialized.class)) {
Class<?> keyClass = ReflectionUtils.getParameterizedClass(mf.getField(... | morphia.map(Map1.class);
new AssertedFailure() {
public void thisMustFail() throws Throwable {
morphia.map(Map2.class);
}
};
new AssertedFailure() {
public void thisMustFail() throws Throwable {
morphia.map(Map3.class);
}
};
}
} |
6010090_33 | class Registry {
public Collection<Link> getAll() {
return links;
}
public Registry(final String name, final String title, final List<Link> links);
public String getName();
public String getTitle();
public Link findByHref(final URI href);
public Link asLinkFor(final URI baseUri);... | final Registry registry = new Registry("foo", "", Collections.<Link>emptyList());
assertTrue(registry.getAll().isEmpty());
}
} |
6017453_1 | class Exceptions {
public static <T extends Throwable> T anyCauseOf(Throwable ex, Class<T> type) {
if (type.isInstance(ex)) {
return (T) ex;
}
Throwable cause = ex.getCause();
if (cause != null) {
return anyCauseOf(cause, type);
}
return null;
}
private Exceptions();
public static Throwable r... | A top=new A("a",new B("b",new D("d",new B("root"))));
Throwable anyCauseOf = Exceptions.anyCauseOf(top,B.class);
Assert.assertEquals("type", B.class,anyCauseOf.getClass());
Assert.assertEquals("message", "b",anyCauseOf.getMessage());
anyCauseOf = Exceptions.anyCauseOf(top,C.class);
Assert.assert... |
6022685_4 | class BitmapUtil {
public static Picture fromBitmap(Bitmap src) {
return inst().fromBitmapImpl(src);
}
private static BitmapUtil inst();
public static void fromBitmap(Bitmap src, Picture dst);
public static Bitmap toBitmap(Picture pic);
public static void toBitmap(Picture src, Bitmap d... | Bitmap src = mock(Bitmap.class);
when(src.getWidth()).thenReturn(16);
when(src.getHeight()).thenReturn(16);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
int[] pix = invocation.getArgumen... |
6064729_0 | class HazelcastSerializedBroadcaster extends HazelcastBroadcaster {
@Override
public void outgoingBroadcast(Object message) {
getTopic().publish(message);
}
}
class HazelcastSerializedBroadcasterTest {
@Test
public void test() {
| HazelcastSerializedBroadcaster hazelcastSerializedBroadcaster = spy(new HazelcastSerializedBroadcaster());
ITopic topic = mock(ITopic.class);
when(hazelcastSerializedBroadcaster.getTopic()).thenReturn(topic);
Object message = new Object();
hazelcastSerializedBroadcaster.outgoingB... |
6090885_1 | class RequestHandlerUtil {
public static List<String> getGroups(String path, String regex) {
List<String> captures = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(path);
if (m.lookingAt()) {
for (int i = 1; i <= m.groupCount(); i++) {
if (m... | List<String> result = RequestHandlerUtil.getGroups("/createStream/2", CreateStreamRequestHandler.PATH_REGEX);
assertEquals("one captures expected", 1, result.size());
assertEquals("First is '2'", "2", result.get(0));
}
} |
6092163_487 | class SocketServerInstanceImpl implements SocketServerInstance {
@Override
public synchronized <T> T getService(Class<T> iface) {
Object service = this.serviceMap.get(iface);
if (service == null) {
service = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface... | final FakeObjectChannel channel = new FakeObjectChannel(Arrays.asList(new Handshake(), new SocketTimeoutException()));
SocketServerInstanceImpl instance = createInstance(channel);
//no remote server is hooked up, so this will timeout
ILogon logon = instance.getService(ILogon.class);
... |
6104876_0 | class DeviceHeader {
@Override
public String toString() {
StringBuffer outBuf = new StringBuffer();
outBuf.append(this.DeviceType.name());
outBuf.append(": MAC(" + this.GetMacAddressString() + "), ");
outBuf.append("IP(" + this.IpAddress.toString() + "), ");
outBuf.append("Protocol Ver(" + this... | byte[] headerPacket = { (byte) 0x00, (byte) 0x02, (byte) 0xf7, (byte) 0xf0,
(byte) 0xc0, (byte) 0x99, (byte) 0x0a, (byte) 0x49, (byte) 0x26,
(byte) 0xa6, (byte) 0x02, (byte) 0x01, (byte) 0x02, (byte) 0x00,
(byte) 0x01, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03,
(byte) 0x00, ... |
6114161_12 | class MathUtil {
public static long getPercentile(List<Long> longList, int p, long defaultValue) {
if (longList == null || longList.isEmpty()) {
return defaultValue;
}
if (p < 0 || p > 100) {
return defaultValue;
}
int size = longList.size();
if (((long) size * (long) p) % 100L == 0) {
// 割り切... |
List<Long> list = Arrays.asList(new Long[] { 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L, 18L, 19L });
assertEquals(18L, MathUtil.getPercentile(list, 90, 0L));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.