id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
14892701_84 | class DiskDGraph implements DGraph<String>, FastWalkable<String, DNode<String>> {
public boolean equals(Object other)
{
if(!(other instanceof DGraph<?>))
return false;
DGraph<Object> oth = (DGraph<Object>) other;
if(! oth.level().equals(level()))
return false;
if(size() != oth.size())
return ... | Global.randomSeed();
DGraph<String> g1 = new DiskDGraph(r());
DTGraph<String, String> g2 = new MapDTGraph<String, String>();
assertFalse(g1.equals(g2));
assertFalse(g2.equals(g1));
}
} |
14894883_34 | class Decomposer {
public Map<Path,Object> decompose(Map<Path,Object> structures) {
if (structures == null) {
throw new IllegalArgumentException("structures is null");
}
Map<Path,Object> decomposed = new HashMap<Path,Object>(structures.size());
for (Map.Entry<Path,Objec... | Map<Path,Object> structures = new HashMap<Path,Object>();
Map<String,Object> nestedMap = new HashMap<String,Object>();
nestedMap.put("y", "test");
structures.put(DefaultPath.fromStrings("x"), nestedMap);
Map<Path,Object> expected = new HashMap<Path,Object>();
expected.p... |
14920951_3 | class ReflectionHelper {
public static void parseServiceMetadataString(String metadataField, Map<String, List<String>> metadata) {
StringBuffer sb = new StringBuffer(metadataField);
int dot = 0;
int nextEquals = sb.indexOf(EQUALS_STRING, dot);
while (nextEquals > 0) {
S... | HashMap<String, List<String>> metadata = new HashMap<String, List<String>>();
try {
ReflectionHelper.parseServiceMetadataString(BADLY_FORMED_METADATA, metadata);
Assert.fail("Should have failed due to parse");
}
catch (IllegalStateException ise) {
... |
14965293_1 | class Protocol {
public static int parseInt(ByteBuffer buf, byte delimiter) {
int sign = 1;
if (buf.get(buf.position()) == (byte)'-') {
buf.get();
sign = -1;
}
int result = 0;
for (;;) {
byte ch = buf.get();
if (ch == delimiter) {
break;
}
result *= 10;... | assertEquals(-123, parseInt("-123\1"));
assertEquals( 0, parseInt("0\1"));
assertEquals( 123, parseInt("123\1"));
}
} |
14969366_10 | class Base64 {
public static byte[] fromBase64String(final String encoded) {
if (encoded == null) {
return new byte[0];
}
try {
return decode(encoded, NO_OPTIONS);
} catch (IOException e) {
e.printStackTrace(System.err);
return new by... | byte[] foobarBytes = "foobar".getBytes();
String encoded = new String(encodeBase64(foobarBytes, false), Constants.CHARSET);
assertEquals("foobar (encoded) should be decoded the same way as in commons-codec",
new String(decodeBase64(encoded.getBytes(Constants.CHARSET))),
... |
14975201_0 | class MyResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
@GET @Path("/empty") public Response empty();
private HttpServer server;
private WebTarget target;
}
class MyResourceTest {
private HttpServer server;
private WebTarget t... | String responseMsg = target.path("myresource").request().get(String.class);
assertEquals("Got it!", responseMsg);
}
} |
14996402_11 | class CellProvider {
public List<Cell> getCellsOnPath(Iterable<?> sourcePath) {
return getCellsOnPath(sourcePath.iterator());
}
private CellProvider(Mapper<?, ?> enclosingMapper);
public static CellProvider fromMapper(Mapper<?, ?> mapper);
public List<Cell> getCells(final HasParent<?> source);
publi... | assertTrue(provider.getCellsOnPath(Collections.emptyList()).isEmpty());
}
} |
14997161_0 | class ServletMappings {
@Nonnull
public String getClassForURL(@Nonnull String path) {
String servletName = findServletName(path);
for (ClassMapping entry : servlets) {
if (entry != null && servletName.equals(entry.getServletName())) {
return entry.getClassWithPackage();
}
}
return DEFAULT_... | List<Entry<String,String>> tests;
ServletMappings mappings = getTestMappings();
tests = makeMappingsList(
"/fruit/summer/index.html", "myservlets.watermelon",
"/fruit/summer/index.abc", "myservlets.watermelon",
"/seedlist", "myservlets.list",
"/seedlist/pear.abc", ... |
15032904_120 | class InterfaceMap {
@SuppressWarnings("unchecked")
public static <T> T createInstance(Class<T> interfaceClass, Map<String, Object> backingMap) {
return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass },
new BackingMapInvocationHandler(backingMap, interfaceClass... | setSomeValues(q);
setSomeOtherValues(q);
PossibleProperties other = InterfaceMap.createInstance(PossibleProperties.class, new HashMap<String, Object>(map));
assertEquals(q, other);
assertEquals(other, q);
}
} |
15040596_16 | class Sender {
public CompletableFuture<Result> send(Message message) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.header("Authorization", authorizationHeader)
.header("... | MockResponse success = new MockResponse().setResponseCode(200)
.setBody(fixture("fixtures/response-success.json"));
MockResponse error = new MockResponse().setResponseCode(503);
server.enqueue(error);
server.enqueue(error);
server.enqueue(error);
se... |
15042909_0 | class Migratron {
public void updateMigration(Migration update) {
updateMigration = update;
}
public void addMigration(int versionCode,Migration migration);
public void migrate();
@SneakyThrows(NameNotFoundException.class) private int appVersion();
private Migratron migratron;
pri... | //given
Migration update = mock(Migration.class);
migratron.updateMigration(update);
//when
migratron.migrate();
//then
verify(update,times(1)).migrate(eq(Robolectric.application));
}
} |
15057896_8 | class JsonSerializer implements Serializer {
@Override
public byte[] serialize(Event event) throws RedisSerializerException {
JsonObject jsonObject = new JsonObject();
for (Map.Entry<String, String> entry : event.getHeaders().entrySet()) {
jsonObject.addProperty(entry.getKey(), entr... | String res = serialize(new HashMap<String, String>());
assertTrue(res.equals("{}"));
}
} |
15070657_18 | class FieldBuilder {
public Collection<Field> createFields(Collection<TokenStream> tokenStreams,
FieldDescription fieldDescription) throws FieldBuildingException {
TokenStream tokenStream = createFieldTokenStream(tokenStreams,
fieldDescription);
this.fieldDescription = fieldDescription;
String fieldNam... |
fieldDescription.setIndex(FieldBuilder.FIELD_INDEX_YES);
fieldDescription.setStored(FieldBuilder.FIELD_STORE_YES);
tokenStreams.remove(1);
expect(filterBuilder.filter(isA(TokenStream.class), isA(Collection.class))).andReturn(tokenStream1);
replay(filterBuilder);
Collection<Field> fields = fieldBu... |
15070661_39 | class ForEachBlock extends RutaBlock {
@Override
public ScriptApply apply(RutaStream stream, InferenceCrowd crowd) {
BlockApply result = new BlockApply(this);
getEnvironment().ensureMaterializedInitialValues(new MatchContext(this), stream);
crowd.beginVisit(this, result);
setRuleElementAnchor();
... | String script = "CONDITION isSmall() = REGEXP(\".\");\n";
script += "FOREACH(num) NUM{} {\n";
script += "num{isSmall()-> T1};";
script += "}";
CAS cas = RutaTestUtils.getCAS("1 22 333");
Ruta.apply(cas, script);
RutaTestUtils.assertAnnotationsEquals(cas, 1, 1, "1");
}
} |
15070665_72 | class AnalysisEngineFactory {
public static AnalysisEngineDescription createEngineDescription(PearSpecifier pearSpecifier,
Object... configurationData) throws InvalidXMLException, IOException {
ConfigurationParameterFactory.ensureParametersComeInPairs(configurationData);
if (configurationData ... | {
AnalysisEngineDescription desc1 = AnalysisEngineFactory.createEngineDescription(
PristineAnnotatorClass.class, (Object[]) null);
assertTrue(
"Multiple deployment should be allowed on " + desc1.getAnnotatorImplementationName(),
desc1.getAnalysisEngineMetaData()... |
15078952_47 | class OrderPreservingMap implements Map<K, V>, Cloneable {
public Object[] keyArray() {
return this.orderKeys.toArray();
}
public OrderPreservingMap();
@SuppressWarnings("unchecked") public OrderPreservingMap(OrderPreservingMap<K, V> other);
public OrderPreservingMap(Map<K, V> map, Coll... | Object[] keyArray = map.keyArray();
for (int i = 0; i < keys.length; i++) {
assertEquals("map.keyArray()[" + i + "]", keys[i], keyArray[i]);
}
}
} |
15090793_3 | class Cloner {
@SuppressWarnings("unchecked")
public static <T> T shallowCopy(T original) {
Class<? extends T> clazz = (Class<? extends T>) original.getClass();
BeanClass<? extends T> beanClass = (BeanClass<? extends T>) classes.get(clazz);
if (beanClass == null) {
beanClass = BeanClass.buildFrom(claz... | G g = new G();
g.setA("aaa");
g.setB(5);
g.setC(null);
g.setD(new D("abcD"));
g.setF(true);
g.setG("ggg");
G clone = Cloner.shallowCopy(g);
Assert.assertEquals(g, clone);
}
} |
15092109_3 | class ClientLibOptimizerServlet extends SlingSafeMethodsServlet {
private List<String> getSortedDependentCategories(Set<String> originalCategories, LibraryType type, List<String> existingCategories) {
final Collection<ClientLibrary> libraries = htmlLibraryManager.getLibraries(
originalCateg... | ClientLibrary clientLibraryA = new MockClientLibraryBuilder(MockClientLibraryBuilder.MockClientLibraryType.CSS, "categoryA").getClientLibrary();
ClientLibrary clientLibraryB = new MockClientLibraryBuilder(MockClientLibraryBuilder.MockClientLibraryType.JSANDCSS, "categoryB").setDependentLibraries(clientLibraryA).ge... |
15104745_22 | class DataConverter {
public String convert(Object val) {
if (val == null) {
return null;
}
String converted;
if (val instanceof String) {
converted = val.toString();
} else if (val instanceof InetAddress) {
converted = val.toString();
} else if (val instanceof UUID) {
converted = val.toStri... | assertEquals("1393832026821", converter.convert(BigInteger.valueOf(1393832026821L)));
}
} |
15106163_0 | class XmlUtil {
public static <T> T extractFromXml(@Nonnull File xmlFile, String xPath, Class<T> clazz)
throws IOException {
return Objects.requireNonNull(FileUtil.executeIoOperation(new ThreadUtil.Operation<T>() {
@Nonnull
@Override
public T run() throws IOE... | File tempDir = null;
try {
tempDir = FileUtil.createTemporaryDirectory("test-xml");
File testFile = new File(tempDir, "test.xml");
FileUtil.writeFile(testFile, getBytes("test.xml"));
Assert.assertEquals(
"Failed XmlUtil.extractFromXml... |
15106392_80 | class DisplayHierarchyNode {
public List<DisplayHierarchyNode> siblings() {
return siblings;
}
public DisplayHierarchyNode( PropertyPath pathTo, DisplayHierarchyNode parent,
DisplayRdfNode rdfNode, ShortNameRenderer shortNameRenderer );
public PropertyPath pa... | assertEquals( 0, dhn.siblings().size() );
assertFalse( dhn.hasSiblings() );
Resource r0 = ResourceFactory.createResource( "http://example/foo#r0");
DisplayHierarchyNode c1 = new DisplayHierarchyNode( new PropertyPath(), null, new DisplayRdfNode( rm.page(), r0 ), null );
dhn.add... |
15120144_1 | class DefaultWordCounter implements WordCounter {
@Override
public int countChars (Note note) {
String titleAndContent = note.getTitle() + "\n" + note.getContent();
return Observable
.from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split(""))
.filter(s -> !s.matches("\\s"))
... | Note note = getNote(1L, "one two", "three four five\nAnother line");
assertEquals(30, new DefaultWordCounter().countChars(note));
}
} |
15132790_17 | class Hashing {
public static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
private static MessageDigest getSHA1MessageDigest();
private static MessageDigest getSHA256MessageDigest();
public static int identityHash(int h);
public static int juHashMapHash(int h);
p... | assertEquals(Boolean.FALSE.hashCode(), Hashing.hashcode(false));
assertEquals(Boolean.TRUE.hashCode(), Hashing.hashcode(true));
assertEquals(Byte.valueOf((byte) -1).hashCode(), Hashing.hashcode((byte) -1));
assertEquals(Character.valueOf('a').hashCode(), Hashing.hashcode('a'));
... |
15137325_82 | class NubMatchingServiceImpl implements NameUsageMatchingService, NameUsageMatchingService2 {
@VisibleForTesting
protected static void interpretGenus(ParsedName pn, String genus) {
// test if name has an abbreviated genus
if (pn != null && !Strings.isNullOrEmpty(genus) && pn.getGenusOrAbove() != null && ge... | ParsedName pn = new ParsedName();
pn.setGenusOrAbove("P.");
pn.setSpecificEpithet("concolor");
NubMatchingServiceImpl.interpretGenus(pn, "Puma");
assertEquals("Puma concolor", pn.canonicalName());
pn.setGenusOrAbove("P.");
NubMatchingServiceImpl.interpretGenus(pn, "Felis");
assertEqual... |
15138385_7 | class InBloomFilterTool extends SingleJobTool<InBloomFilterOptions> {
@Override
protected Class<? extends Mapper> getMapperClass() {
return InBloomFilterMapper.class;
}
@Override protected String getName();
@Override protected void validateOptions();
@Override protected Class<? extends... | Job job=inBloomFilterTool.createJob(new String[] {
"-input",
"/basekb-sandbox/someLocation",
"-k",
"7",
"-output",
"/basekb-sandbox/anotherLocation",
"-bloomFilter",
"/camels/"
... |
15162009_6 | class BaseHandler {
protected static final boolean isValidNeutronID(String id) {
if (id == null) {
return false;
}
boolean isValid = false;
logger.trace("id - {}, length - {} ", id, id.length());
/**
* check the string length
* if length is 36 i... | assertFalse(BaseHandler.isValidNeutronID(nullString));
assertTrue(BaseHandler.isValidNeutronID(uuid));
assertTrue(BaseHandler.isValidNeutronID(tenantId));
assertTrue(BaseHandler.isValidNeutronID(neutronId));
}
} |
15209448_1 | class StructuredJsonExamplesMessageBodyReader implements MessageBodyReader<ExamplesIterable> {
@Override
public ExamplesIterable readFrom(Class<ExamplesIterable> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOExcep... |
final CountDownLatch readThreadIsReadyLatch = new CountDownLatch(1);
final Exchanger<Example> exampleExchanger = new Exchanger<Example>();
final PipedInputStream pipedInputStream = new PipedInputStream(); //the reading thread will read from this stream
final PipedOutputStream pipedOutputStream = new PipedOutp... |
15221298_30 | class ExternalDescriptionLoader {
public void addHtmlDescription(RulesDefinition.NewRule rule) {
URL resource = ExternalDescriptionLoader.class.getResource(resourceBasePath + "/" + rule.key() + ".html");
if (resource != null) {
addHtmlDescription(rule, resource);
}
}
pu... |
// given
final ExternalDescriptionLoader loader = new ExternalDescriptionLoader(LANGUAGE_KEY);
final NewRule rule = repository.createRule("ruleWithoutExternalInfo").setName("name1");
// when
final Throwable thrown = catchThrowable(() -> loader.addHtmlDescription(rule, new URL("... |
15227263_10 | class MercatorProjection {
public static long pixelXToTileX(double pixelX, byte zoomLevel) {
return (long) Math.min(Math.max(pixelX / Tile.TILE_SIZE, 0), Math.pow(2, zoomLevel) - 1);
}
private MercatorProjection();
public static double calculateGroundResolution(double latitude, byte zoomLevel);
public static... | for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
Assert.assertEquals(0, MercatorProjection.pixelXToTileX(0, zoomLevel));
}
}
} |
15284049_26 | class CreateEdgeLogEntry implements LogEntry {
@Override
public void appendToLog(LogOutput dbLog) {
dbLog.newEdge(edge);
StreamIterator.stream(edge.properties())
.filter(property -> !propertiesToIgnore.contains(property.key()))
.forEach(dbLog::newProperty);
}
publi... | Edge edge = edge().withProperty("prop1", "value")
.withProperty("prop2", "value")
.withProperty("prop3", "value")
.build();
CreateEdgeLogEntry instance = new CreateEdgeLogEntry(edge);
LogOutput dbLog = mock(LogOutput.class);
instance.app... |
15289581_19 | class StandardExceptionPropagator implements ExceptionPropagator {
@Override
public RuntimeException propagateException(Object key,
ExceptionInformation exceptionInformation) {
long expiry = exceptionInformation.getUntil();
String txt = "";
if (expiry > 0) {... | System.currentTimeMillis();
RuntimeException t = STANDARD_PROPAGATOR.propagateException(
null, toInfo(new RuntimeException("serious thing"), Long.MAX_VALUE));
assertTrue(t.toString().contains("expiry=ETERNAL"));
}
} |
15292023_0 | class RandomAccessPattern extends AbstractEternalAccessPattern {
@Override
public int next() {
return rng.nextInt(upper);
}
public RandomAccessPattern(int _upper);
}
class RandomAccessPatternTest {
@Test
public void test0() throws Exception {
| RandomAccessPattern p = new RandomAccessPattern(1);
assertTrue(p.isEternal());
assertTrue(p.hasNext());
assertEquals(0, p.next());
assertTrue(p.isEternal());
assertTrue(p.hasNext());
assertEquals(0, p.next());
}
} |
15293721_6 | class JavaToHumanTranslator {
public String humanize(final Method method) {
if (method.isAnnotationPresent(Text.class)) {
return method.getAnnotation(Text.class).value();
} else {
return humanize(method.getName());
}
}
public String humanize(Class<?> classUn... | JavaToHumanTranslator tested = new JavaToHumanTranslator();
Assert.assertEquals("Underscores are replaced by space",tested.humanize("underscores_are_replaced_by_space"));
}
} |
15303802_2 | class OpusToWaveConverter {
public void convert(URL pdmlUrl, File waveFileDir, SampleRate sampleRate, Channels channels) throws Exception {
if (!waveFileDir.isDirectory())
throw new IllegalArgumentException();
Pdml pdml = new PdmlReader().unmarshall(pdmlUrl);
RtpStream[] streams... | URL pdmlUrl = RtpExtracterTest.class.getResource("sipcall.pdml");
Assert.assertNotNull(pdmlUrl);
File[] waveFiles = new File[2];
for (int i=0; i<waveFiles.length; ++i)
waveFiles[i] = File.createTempFile(OpusToWaveConverterTest.class.getSimpleName(), ".wav");
try {
... |
15322987_4 | class EmployeeResource {
@GET
@Produces({ "application/json", "application/xml" })
@Path("{id}")
public Employee get(@PathParam("id") int id) {
if (id < bean.getEmployees().size())
return bean.getEmployees().get(id);
else
return null;
}
@GET @Produces({ "application/xml... | JsonArray json = target.request().accept(MediaType.APPLICATION_JSON).get(JsonArray.class);
assertEquals(3, json.size());
for(int i = 0; i < json.size(); i++) {
JsonObject obj = json.getJsonObject(i);
String name = obj.getString("name");
int age = obj.getInt("age"... |
15373368_79 | class NumberOfTradesCriterion extends AbstractAnalysisCriterion {
@Override
public double calculate(TimeSeries series, TradingRecord tradingRecord) {
return tradingRecord.getTradeCount();
}
@Override public double calculate(TimeSeries series, Trade trade);
@Override public boolean betterTh... | Trade trade = new Trade();
NumberOfTradesCriterion tradesCriterion = new NumberOfTradesCriterion();
assertEquals(1d, tradesCriterion.calculate(null, trade), TATestsUtils.TA_OFFSET);
}
} |
15374337_40 | class EngineConfiguration {
static protected List<String> getPropertyAsList(Properties props, String key) {
List<String> retVal = null;
String listProp = props.getProperty(key);
if (listProp != null) {
String[] valueArray = listProp.split(",\\s*");
retVal = Arrays.as... | System.out.println("getPropertyAsList");
Properties props = new Properties();
String key = "testProp";
props.setProperty(key, "alpha, beta, gamma");
List<String> expResult = Arrays.asList("alpha", "beta", "gamma");
List<String> result = EngineConfiguration.getPropertyAs... |
15403409_1 | class GCodeWord implements Comparable {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GCodeWord)) return false;
GCodeWord gCodeWord = (GCodeWord) o;
if (!word.equals(gCodeWord.word)) return false;
return true;
}
publi... | GCodeWord t1 = new GCodeWord("G4", null);
GCodeWord t2 = new GCodeWord("G4", null);
assertTrue("Same GCode must return equal", t1.equals(t2));
t1 = new GCodeWord("G4", 12.0);
t2 = new GCodeWord("G4", 13.0);
assertTrue("Same GCode must return equal", t1.equals(t2));
}... |
15416636_13 | class BarcodeExtractor {
public String extractFromPdf(String input) {
if (input != null && input.endsWith(".pdf")) {
Matcher m = p.matcher(input);
if (m.find())
return m.group();
}
return "";
}
public String extract(String input);
}
class B... | assertThat(instance.extractFromPdf(null), equalTo(""));
}
} |
15472368_4 | class LogBuffer {
public Logs parallel() {
Collection<Dir> dirs = initalizeDirs();
Stream<Log> result = null;
for (Dir d : dirs) {
Stream<Log> stream = Guavas.toStream(new Dirs.LogIterator(d), true);
if (result == null) {
result = stream;
} else {
result = Stream.concat(... | Log[] written = LogUtil.writeList(logBuffer, 1, 5000).toArray(new Log[0]);
Log[] logs = logBuffer.parallel().stream()
.sorted().collect(Collectors.toList()).toArray(new Log[0]);
assertArrayEquals(logs, written);
}
} |
15475337_118 | class PatternGenerator {
@Nonnull
public static String acceptStrings(@Nonnull String[] input) {
StringBuilder builder = new StringBuilder();
builder.append("(");
for (int i = 0; i < input.length; i++) {
builder.append(Pattern.quote(input[i]));
if (i < input.len... | String[] input = new String[3];
input[0] = "foo";
input[1] = "bar";
input[2] = "baz";
String regex = PatternGenerator.acceptStrings(input);
Pattern pattern = Pattern.compile(regex);
assertTrue(pattern.matcher("foo").find());
assertTrue(pattern.matcher("b... |
15491874_16 | class RxViewBinder {
public void bind() {
unbind();
compositeDisposable = new CompositeDisposable();
bindInternal(compositeDisposable);
}
public void unbind();
protected abstract void bindInternal(@NonNull final CompositeDisposable compositeDisposable);
private RxViewBinde... | binder.bind();
// The test subscriber changes with each bind.
TestObserver<String> firstTestObserver = testObserver;
testObserver = null;
binder.bind();
testSubject.onNext("testString");
assertNotNull(firstTestObserver);
assertNotNull(testObserver);
... |
15496005_2 | class Dhcp6Options implements Iterable<Dhcp6Option> {
public boolean contains(@Nonnull Class<? extends Dhcp6Option> type) {
return !options.get(Dhcp6OptionsRegistry.getInstance().getOptionTag(type)).isEmpty();
}
public boolean isEmpty();
@Override public Iterator<Dhcp6Option> iterator();
@... | Dhcp6Options options = new Dhcp6Options();
options.add(StatusCodeOption.create((short) 0));
assertTrue(options.contains(StatusCodeOption.class));
}
} |
15523927_4 | class ArchonStorage {
public void addARC(String arcPath) throws Exception {
log.info("Persisting new arc-file: " + arcPath);
String[] splitPath = splitPath(arcPath);
String folder = splitPath[0];
String arcId = splitPath[1];
boolean aRCIDExist = aRCIDExist(arcId);
... |
ArcVO arc = null;
try{
arc = storage.getArcByID(arcFile1);
fail();
}
catch (Exception e){
//Expected
}
storage.addARC(arcFile1);
arc = storage.getArcByID("arcfile1");
assertEquals(arcFile1, arc.getFileName());
... |
15554335_4 | class EventValidator {
public Validated validateEvent(VersionedEventsModel eventsModel, ObjectNode eventNode) {
final EventModel ingressEvent = EventModel.builder(eventNode, false).build();
Validated.ValidatedBuilder builder = Validated.build();
LOG.inc("validated_events");
if (even... |
Mockito.when(eventsProvider.getCurrentEventsVersion(tenantId))
.thenReturn(version, version);
Mockito.when(eventsProvider.getEvents(Mockito.any(EventsProcessorId.class)))
.thenReturn(Arrays.asList(event));
ObjectNode instance = mapper.createObjectNode();
... |
15555290_0 | class ElasticSearchSearchIndex extends ElasticSearchSearchIndexBase {
public String createJsonForElement(Graph graph, Element element, Authorizations authorizations) {
try {
String indexName = getIndexName(element);
IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName, g... | Metadata prop1Metadata = new Metadata();
prop1Metadata.add("metadata1", "metadata1Value", VISIBILITY_A);
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("va... |
15590153_0 | class CSVToARFFHeaderMapTask implements OptionHandler, Serializable {
public Instances getHeader() {
return makeStructure();
}
public CSVToARFFHeaderMapTask();
public CSVToARFFHeaderMapTask(boolean suppressQuantileOptions);
public CSVToARFFHeaderMapTask(boolean suppressQuantileOptions,
boolean s... | // tests getting a header without any processing of incoming
// CSV data - i.e. all attributes are assumed to be numeric
CSVToARFFHeaderMapTask task = new CSVToARFFHeaderMapTask();
// task.setOptions(args);
Instances i = task.getHeader(10, null);
for (int j = 0; j < i.numAttributes(); j++) {
... |
15590229_0 | class Utils {
static String toDebugString(final byte[] bytes, final int len, final Charset charset) {
if (charset == null) {
return toDebugString(new String(bytes, 0, len, Charset.defaultCharset()));
}
return toDebugString(new String(bytes, 0, len, charset));
}
private ... | assertEquals(toDebugString(null), "null");
assertEquals(toDebugString((Object) null), "null");
assertEquals(toDebugString("ABC"), "ABC");
final char[] chars = new char[1000];
Arrays.fill(chars, 'x');
final int length = toDebugString(String.valueOf(chars)).length();
... |
15596189_0 | class CommandHelper {
public static String getRawCommand(String chatMessage) {
Preconditions.checkArgument(chatMessage.charAt(0) == '/',
"getRawCommand('%s') requires a command, starting with a slash, to be passed!",
chatMessage);
String result;
int spaceInd... | assertThat(CommandHelper.getRawCommand("/help"), is("help"));
assertThat(CommandHelper.getRawCommand("/help test"), is("help"));
assertThat(CommandHelper.getRawCommand("/minecraft:help"), is("minecraft:help"));
assertThat(CommandHelper.getRawCommand("/minecraft:help test"), is("minecraft... |
15611804_5 | class FilePreferences implements Preferences, LifecycleCallback {
@Override
public <T> T get(String key, Class<T> clazz) {
return rootNode.get(key, clazz);
}
public FilePreferences(File preferencesFile);
@Override public void put(String key, Object value);
@Override public void merge... | FilePreferences filePreferences = getPreferencesFile("morePropertiesThanPojoPreferences.json");
FakePojo fakePojo = filePreferences.get(USELESS_POJO_KEY, FakePojo.class);
assertThat(FakePojo.getDumbInstance()).isEqualToComparingFieldByField(fakePojo);
OtherPojo otherPojo = filePrefere... |
15684181_47 | class ObjectHolder {
public ObjectHolder() {
}
public ObjectHolder();
public ObjectHolder(final T value);
public T getValue();
public void setValue(final T value);
}
class ObjectHolderTest {
@Test
public void testObjectHolder() {
| final ObjectHolder<Integer> it = new ObjectHolder<>();
assertNull(it.getValue());
}
} |
15693035_46 | class Main {
static Matcher validateZkUrl(final String zkUrl) {
final Matcher matcher = zkURLPattern.matcher(zkUrl);
if (!matcher.matches()) {
throw new SystemExitException(String.format("Invalid zk url format: '%s' expected '%s'", zkUrl, validZkUrl), 7);
}
return match... | final Matcher m = validateZkUrl("zk://host:2181/cassandra-mesos/ring1");
assertThat(m.group(1)).isEqualTo("host:2181");
assertThat(m.group(2)).isEqualTo("/cassandra-mesos/ring1");
}
} |
15698466_508 | class ProxyForURI implements Function<URI, Proxy> {
@Override
public Proxy apply(URI endpoint) {
if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) {
return Proxy.NO_PROXY;
}
if (config.getProxy().isPresent()) {
SocketAddress addr = new InetSocketAddress(config.... | ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds);
URI uri = new URI("socket://ssh.example.com:22");
assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY);
}
} |
15717111_2 | class DiscoveryClient {
public Map<String, MetaData> findInstances() {
Map<String, MetaData> instances = new TreeMap<String, MetaData>();
init();
try {
for (String path : filters) {
logger.debug("checking entries with path filter: " + path);
//... | DiscoveryClient client = new TestableDiscoveryClient(null, basePath, "/b/bb");
instances = client.findInstances();
Assert.assertEquals(2, instances.size());
Assert.assertTrue(instances.containsKey(basePath + "/" + "b/bb/bbb"));
}
} |
15722026_3 | class PaginationParams {
@SuppressWarnings("checkstyle:MultipleStringLiterals")
public static PaginationParams previousPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException {
if (pagination.getPreviousUri() == null) {
return null;
}
try {
... | // Given
PagedResponse.Pagination pagination = new PagedResponse.Pagination();
pagination.setPreviousUri("/path");
// When
PaginationParams.previousPage(pagination);
// Then
Assertions.fail("Should throw an " + IllegalArgumentException.class);
}
} |
15728671_30 | class BitDatum extends Datum {
@Override
public int size() {
return size;
}
public BitDatum(byte val);
public BitDatum(byte[] bytes);
@Override public char asChar();
@Override public int asInt4();
@Override public long asInt8();
@Override public byte asByte();
@Override public byte[] asByte... | Datum d = DatumFactory.createBit((byte) 1);
assertEquals(1, d.size());
}
} |
15729898_5 | class OutboundApi {
@GET
@Path("/outbound")
@Produces("application/json")
/**
* retrieve the news posted by an individual participant
* fetch a participant news
* @param id uniquely identifies the participant (required)
* @return List<Outbound>
*/
public List<Outbound> getOutbound(@PathPar... | assertTrue("Fetch outbound feed did not return expected results.", api.getOutbound(TEST_FROM).equals(outFeed));
}
} |
15751803_10 | class CautiousStrategy extends Strategy {
@Override
public Move nextMove(int availableMana, int currentHealth, List<Card> availableCards) {
if (currentHealth < 20) {
return new Move(lowestCard(availableMana, availableCards), Action.HEALING);
} else {
return new Move(high... | assertThat(strategy.nextMove(withMana(10), andHealth(1), fromCards(1, 2, 3, 8, 9)), is(move(card(1), HEALING)));
assertThat(strategy.nextMove(withMana(9), andHealth(2), fromCards(2, 3, 8, 9)), is(move(card(2), HEALING)));
assertThat(strategy.nextMove(withMana(7), andHealth(4), fromCards(3, 8, 9)... |
15779685_47 | class Skeleton {
public static SkeletonOutput skeleton(List<Point2d> polygon) {
return skeleton(polygon, null);
}
public static VisualDebugger initVisualDebugger();
public static SkeletonOutput skeleton(List<Point2d> polygon, List<List<Point2d>> holes);
public static SkeletonOutput skeleto... |
vd.clear();
List<Point2d> polygon = new ArrayList<Point2d>();
polygon.add(new Point2d(50, 50));
polygon.add(new Point2d(150, 50));
polygon.add(new Point2d(150, 100));
polygon.add(new Point2d(50, 100));
List<Point2d> expected = new ArrayList<Point2d>();
... |
15784931_0 | class ExtraBinderGenerator extends BaseGenerator {
String emitHumanDescription(List<Binding> bindings) {
StringBuilder builder = new StringBuilder();
switch (bindings.size()) {
case 1:
builder.append(bindings.get(0).getDescription());
break;
case 2:
builder
.ap... | Binding one = new TestBinding("one");
Binding two = new TestBinding("two");
Binding three = new TestBinding("three");
String actual1 = extraBinderGenerator.emitHumanDescription(asList(one));
assertThat(actual1).isEqualTo("one");
String actual2 = extraBinderGenerator.emitHumanDescription(asList... |
15800167_1 | class Utils {
public static Attributes mergeAndNormalize(Attributes... attrsList) {
SpecificCharacterSet globalCs = null;
for (Attributes attrs : attrsList) {
SpecificCharacterSet cs = attrs.getSpecificCharacterSet();
if (globalCs == null) {
globalCs = cs... |
Attributes patientAttrs = new Attributes();
patientAttrs.setString(Tag.PatientID, VR.LO, "patID");
patientAttrs.setString(Tag.IssuerOfPatientID, VR.LO, "issuer");
Attributes otherids = new Attributes();
otherids.setString(Tag.PatientID, VR.LO, "otherID");
patientAttrs.ne... |
15801589_0 | class HttpServiceFactoryImpl implements ServiceFactory {
public Object getService( final Bundle bundle, final ServiceRegistration serviceRegistration )
{
LOG.info( "Binding bundle: [" + bundle + "] to http service" );
return createService( bundle );
}
public void ungetService( final Bu... | // prepare
replay( m_bundle, m_serviceRegistration, m_httpService );
// execute
Object result = m_underTest.getService( m_bundle, m_serviceRegistration );
assertNotNull( "expect not null", result );
// verify
verify( m_bundle, m_serviceRegistration, m_httpService ... |
15801780_4 | class RollbackCommand extends RollbackListCommand implements CommandSuccessIndicator {
void setRollbackCommandConf(RollbackCommandConf rollbackCommandConf) {
this.rollbackCommandConf = rollbackCommandConf;
}
public RollbackCommand(EnvSettings envSettings);
@SuppressWarnings("unchecked") prot... | command.setRollbackCommandConf(new RollbackCommandConf(RollbackCommandConf.Action.STOP_ON, "010.patch1"));
command.execute();
Assert.assertArrayEquals(new Integer[]{ }, dbValues());
}
} |
15802014_105 | class APNS {
public static ApnsServiceBuilder newService() {
return new ApnsServiceBuilder();
}
private APNS();
public static PayloadBuilder newPayload();
}
class APNSTest {
@Test
public void newServiceGetNewInstances() {
| assertNotSame(APNS.newService(), APNS.newService());
}
} |
15830023_4 | class TimeSum {
public void reset() {
hours = 0;
minutes = 0;
}
public void set(int hours, int minutes);
public void add(int hoursToAdd, int minutesToAdd);
public void substract(int hoursToSubstract, int minutesToSubstract);
public void addOrSubstract(TimeSum timeSum);
private void balance();
@Override pu... | set(-1, 0);
underTest.reset();
assertTime("0:00");
}
} |
15831475_79 | class Synset extends PointerTarget implements DictionaryElement {
public List<Pointer> getPointers() {
return pointers;
}
public Synset(Dictionary dictionary, POS pos);
public Synset(Dictionary dictionary, POS pos, long offset);
public DictionaryElementType getType();
public Object ... | Synset hyponym = new Synset(dictionary, POS.NOUN, 100);
Pointer hyponymPtr = new Pointer(PointerType.HYPONYM, testObj, hyponym);
testObj.getPointers().add(0, hyponymPtr);
ListIterator<Pointer> i = testObj.getPointers().listIterator();
Assert.assertTrue(i.hasNext());
Asser... |
15841047_19 | class WorkflowKernel {
public ItemCollection process(final ItemCollection workitem) throws PluginException, ModelException {
// check document context
if (workitem == null)
throw new ProcessingErrorException(WorkflowKernel.class.getSimpleName(), UNDEFINED_WORKITEM,
... | ItemCollection itemCollectionProcessed = null;
ItemCollection itemCollection = new ItemCollection();
itemCollection.replaceItemValue("txtTitel", "Hello");
itemCollection.setTaskID(100);
itemCollection.setEventID(10);
itemCollection.replaceItemValue("$modelversion", MokMod... |
15841325_4 | class DisplayHelperBase implements DisplayHelper {
protected final Context getContext() {
return mContext;
}
public DisplayHelperBase(final Context context);
protected final Display getDefaultDisplay();
@SuppressWarnings("deprecation") @Override public int getDisplayAngle();
@SuppressWarnings("deprecation")... | assertNotNull(new DisplayHelperBase(Robolectric.application).getContext());
}
} |
15845284_1 | class ChooseGroupActivity extends ListActivity {
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Group g = (Group) getListView().getAdapter().getItem(position);
if (!g.isSectionHeader()) {
DataSource.getInstance().storeGroup(g);
In... | // create a Group that is a section header
Group g = new Group("groupName");
g.setSectionHeader(true);
g.setId(0);
// set adapter
GroupListAdapter groupListAdapter = new GroupListAdapter(mActivity, new Group[] { g });
mActivity.getListView().setAdapter(groupListA... |
15861701_165 | class NodeMaxPartitionLimitConstraint extends HardConstraint {
@Override
boolean isAssignmentValid(AssignableNode node, AssignableReplica replica,
ClusterContext clusterContext) {
boolean exceedMaxPartitionLimit =
node.getMaxPartition() < 0 || node.getAssignedReplicaCount() < node.getMaxPartition... | when(_testNode.getAssignedReplicaCount()).thenReturn(10);
when(_testNode.getMaxPartition()).thenReturn(5);
Assert.assertFalse(_constraint.isAssignmentValid(_testNode, _testReplica, _clusterContext));
}
} |
15878497_18 | class JavaCode extends Code {
public String methodReturns(String method) {
return getMethodPart(method, 2);
}
public JavaCode();
public String typeName();
private Matcher getTypeNameMatcher();
public boolean isClass();
public Collection<String> typeAnnotations();
public Collection<String> import... | String method = "m" + someValue();
String returns = someValue();
code.add("public class C {");
code.add(" public %s %s(int foo) {", returns, method);
code.add(" }");
code.add("}");
assertEquals("Returns", returns, code.methodReturns(method));
assertEquals("Returns of non-existing meth... |
15904020_1 | class ValidatorMain {
static Date getEarliestDate(Optional<Date> o, Date d){
if (o.isPresent()){
d = o.get().before(d) ? o.get() : d;
}
return d;
}
public static void main(String[] args);
public static String getValidationSummary(ValidationResult result);
public static String getValidationReport(Validat... |
Optional<Date> o = Optional.of(new Date(10L));
Date d = new Date(0L);
Date returned = ValidatorMain.getEarliestDate(o, d);
assertSame(d, returned);
}
} |
15912903_21 | class JaroBagFuzzyMatcher implements FuzzyMatcher {
@Override
public boolean sequencesMatching(final String phrase1, final String phrase2) {
final String phrase1LowerCase = removeNonAlphanumeric(phrase1).toLowerCase();
final String phrase2LowerCase = removeNonAlphanumeric(phrase2).toLowerCase()... | assertThat(matcher.sequencesMatching("t,e,r,r,o,r,i,s,t", "terrorist"), is(true));
}
} |
15928650_0 | class FileDownloadAction implements Action {
String sanitizeInputPath( String value ) {
if (value != null && value.toUpperCase().contains("WEB-INF")) {
return null;
}
return value;
}
public String execute();
public void setInputPath(String value);
public InputStream getInputStream();
private FileDownl... | assertEquals("foo", fileDownloadAction.sanitizeInputPath("foo"));
}
} |
15951171_0 | class HzUnitOfWorkJournal implements UnitOfWorkJournal<K> {
public void append(final K id, final UnitOfWork uow) {
checkNotNull(id);
checkNotNull(uow);
final AggregateRootHistory history = getHistoryFor(id);
if (!history.getLastVersion().equals(uow.getTargetVersion())){
throw new ConcurrentModificationExce... |
UUID id = UUID.randomUUID();
Command command = new IncreaseInventory(UUID.randomUUID(), id, 1, 0L);
Event event1 = new InventoryIncreased(id, 1);
List<Event> events = Arrays.asList(event1);
UnitOfWork t = UnitOfWork.create(UUID.randomUUID(), command, events);
AggregateRootHistory toStore = new AggregateR... |
15958676_25 | class Utils {
public static String getArrayDimensionString(Object array) {
if (!array.getClass().isArray()) {
return "";
}
StringBuilder sb = new StringBuilder();
Object current = array;
int len = Array.getLength(current);
sb.append('[').append(len).appe... | String[][][] value = new String[5][4][3];
String expected = "[5][4][3]";
String actual = Utils.getArrayDimensionString(value);
assertEquals(expected, actual);
}
} |
15979754_15 | class SystemPropertiesBean implements CommandListener {
@Command
public String osVersion() {
return System.getProperty("os.version");
}
@Command public String home();
@Command public String home(@Exists @Directory File file);
@Command public String user();
@Command public String di... | assertEquals(System.getProperty("os.version"), main.exec("osVersion"));
}
} |
15997656_31 | class HttpUtil {
public static Response post(String url)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), null, null);
}
public static Response get(String url);
public static Response get(Strin... | Response response = HttpUtil.post(URL, POST_KEY_VALUE_PAIRS, USERNAME, PASSWORD, REQ_HEADERS);
assertNotNull(response);
}
} |
16004885_1 | class MigrationsInDir implements Migrations {
@Override
public Iterable<File> asIterable() {
ArrayList<File> list = new ArrayList<File>(Arrays.asList(migrationFiles));
Collections.sort(list, comparator);
return list;
}
public MigrationsInDir(File directory);
public MigrationsInDir(File directory, Compara... | Iterator<File> iterator = migrations.asIterable().iterator();
assertStartsWithNumber(iterator.next(), 1);
assertStartsWithNumber(iterator.next(), 2);
assertStartsWithNumber(iterator.next(), 3);
}
} |
16006160_9 | class StringFunctions {
public static String urlDecode(final String encoded, final Charset charset) throws MyRuleException {
final byte[] buff = new byte[encoded.length()]; // バイト長は文字列長を超えない。
int buffIndex = 0;
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) =... | Assert.assertEquals("てすとスレ", StringFunctions.urlDecode("%82%C4%82%B7%82%C6%83X%83%8C", Charset.forName("Shift_JIS")));
Assert.assertEquals("名無し", StringFunctions.urlDecode("%96%BC%96%B3%82%B5", Charset.forName("Shift_JIS")));
Assert.assertEquals("新規スレッド作成", StringFunctions.urlDecode("%90V%8BK%83... |
16037437_0 | class DaggerComponentProviderFactory implements IoCComponentProviderFactory {
@Override
public IoCComponentProvider getComponentProvider(Class<?> clazz) {
return getComponentProvider(null, clazz);
}
public DaggerComponentProviderFactory(ResourceConfig config, ObjectGraph objectGraph, Object[]... | ResourceConfig config = new DefaultResourceConfig();
ObjectGraph objectGraph = ObjectGraph.create(SomeInjectableProvidesModule.class,
new SomeOtherInjectableProvidesModule());
IoCComponentProviderFactory factory = new DaggerComponentProviderFactory(config, objectGraph,
... |
16047008_14 | class StringStack implements Iterable<String> {
public int size() {
return start_byte.size() - 1;
}
public StringStack(String... xs);
public StringStack(Iterable<String> xs);
public boolean isEmpty();
public boolean contains(String o);
public boolean add(String e);
public void clear();
public String get... | assertEquals(0, new StringStack().size());
assertEquals(1, new StringStack("moo").size());
assertEquals(2, new StringStack("foo", "bar").size());
}
} |
16050719_0 | class Gantt extends AbstractComponent implements HasComponents {
public TimeZone getTimeZone() {
if (timezone == null) {
return getCalendar().getTimeZone();
}
return timezone;
}
public Gantt();
@Override public void attach();
@Override public GanttState getSta... | TimeZone timezone = TimeZone.getTimeZone("Asia/Tehran");
Locale locale = Locale.GERMANY;
DateTime week1_2014 = new DateTime(2014, 1, 1, 0, 0, 0, 000,
DateTimeZone.forTimeZone(timezone));
DateTime week2_2014 = new DateTime(2014, 1, 6, 0, 0, 0, 000,
DateTi... |
16057180_0 | class KPiece implements Iterable<KUnitSquare> {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + pieceId;
result = prime * result
+ ((unitSquares == nul... | KPiece rot = KPieces.TETRAMINO_T_1;
int r0 = rot.hashCode(); // 0deg
rot = rot.rotatedNinetyDegrees();
int r90 = rot.hashCode(); // 90deg
rot = rot.rotatedNinetyDegrees();
Assert.assertTrue(!(r90 == r0));
int r180 = rot.hashCode(); // 180deg
rot = rot.rotatedNinetyDegrees();
Assert.assertTrue(!(... |
16077092_0 | class CategoricalAttribute extends Attribute {
public List<String> getCategoricalInstances() {
return ImmutableList.copyOf(categoricalInstances);
}
@JsonCreator public CategoricalAttribute(@NotBlank @JsonProperty("name") String name,
@JsonProperty("categoricalInsta... | assertEquals("Nominal values were not set properly", nominal_values, field.getCategoricalInstances());
assertEquals("Instance name not set properly", name, field.getName());
int index = 0;
for(String v : nominal_values) {
assertEquals("Known value must be unchanged", index, ... |
16091126_6 | class Hits implements Closeable {
public float[] weightHistogram(int firstindex,
int lastindex,
int start,
int stop,
int stepsize,
int dedup... | for (int q = 0; q < 300; q++) {
int start = (int)Math.round(Math.random() * MAXVALUE);
int end = start + (int)(Math.round(Math.random() * MAXVALUE) % (MAXVALUE - start));
if (end < start) {
throw new RuntimeException("end < start");
}
i... |
16100959_68 | class IndexingUtils {
public static byte[] getByteContent(Resource resource, String sourceURL)
throws RegistryException {
try {
InputStream is = null;
if (sourceURL != null) {
is = new URL(sourceURL).openStream();
} else {
Object content = resource.getContent();... | ResourceImpl resource = mock(ResourceImpl.class);
String contentString = "Testing Content";
when(resource.getContent()).thenReturn(contentString);
when(resource.getContentStream()).thenReturn(null);
byte[] byteContent = IndexingUtils.getByteContent(resource, null);
assert... |
16115996_3 | class CoinChangeSolution {
public static int countOptimal(int[] coins, int amt) {
// solutions[i] contains the no. of solutions for value i.
// We build from bottom up using the base case (n = 0)
int solutions[] = new int[amt + 1];
solutions[0] = 1;
for (Integer i : coins)
for (int j = ... |
int coins[] = { 2, 5, 3, 6, 10, 7, 8, 12, 17, 19, 20 };
assertEquals(227491942, CoinChangeSolution.countOptimal(coins, 250));
}
} |
16121108_8 | class Domain extends BaseEntity {
public String getIdentifierPrefix() {
StringBuilder sb = new StringBuilder();
URL baseUrl = this.getRuntime().getServerBaseUrl();
// protocol
Boolean httpsEnabled = getBooleanAttribute("https.identifier.enabled");
final String protocol;
if (httpsEnabled != null) {
pro... | URL url = new URL("http://example1.com/jos-webapp/");
domain.getRuntime().setServerBaseUrl(url);
domain.setName("example1.com");
domain.setType(Domain.TYPE_SUBDOMAIN);
assertEquals("http://", domain.getIdentifierPrefix());
}
} |
16132708_5 | class ContextAwareSail extends SailWrapper {
@Override
public SailConnection getConnection() throws SailException {
return new ContextAwareSailConnection(super.getConnection(),context);
}
public ContextAwareSail(Sail baseSail, Resource context);
protected ContextAwareSail cas;
}
class ... | final SailConnection con = cas.getConnection();
try {
con.begin();
assertTrue(hasStatement(con, null, null, null));
con.clear();
assertFalse(hasStatement(con, null, null, null));
con.commit();
} catch (final Throwable t) {
... |
16156598_0 | class JsonMessageConverter implements MessageConverter {
@Override
public String toDDP(final Object object) {
final String json = GSON.toJson(object, object.getClass());
final StringBuilder buffer = new StringBuilder(json);
buffer.insert(1, "\"msg\":\"" + MessageRegistry.get(object.getC... | MyTestClass foo = new MyTestClass();
foo.setName("Hello, world!");
foo.setDate(new Date());
JsonMessageConverter converter = new JsonMessageConverter();
String result = converter.toDDP(foo);
System.out.println(result);
Assert.assertTrue(result.contains("Hello, wor... |
16162461_3 | class SinaUserBaseInfoDaoImpl implements SinaUserBaseInfoDao {
public SinaUserBaseInfoDaoImpl(List<String> tokens) {
this.tokens = tokens;
user = new Users();
}
public SinaUserBaseInfoDaoImpl(List<String> tokens);
@Override public User getUserBaseInfo(String uid);
private String getRandomToken();
}
class... |
List<String> tokens = new ArrayList<String>();
tokens.add("2.00eEQZzBdcZIJCdb7f41b1ebOlNq3B");
tokens.add("2.0000onHtdcZIJC5ded8d28dc0CtU8F");
SinaUserBaseInfoDao sinaUserBaseinfoDao = new SinaUserBaseInfoDaoImpl(tokens);
// User userInfo = sinaUserBaseinfoDao.getUserBaseInfo("1768044590");
// assertEqu... |
16185077_9 | class Encoder {
public static AztecCode encode(byte[] data) {
return encode(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS);
}
private Encoder();
public static AztecCode encode(byte[] data, int minECCPercent, int userSpecifiedLayers);
private static void drawBullsEye(BitMatrix matrix, int center, int ... | // Compact(4) con hold 608 bits of information, but at most 504 can be data. Rest must
// be error correction
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// encodes as 26 * 5 * 4 = 520 bits of data
String alphabet4 = alphabet + alphabet + alphabet + alphabet;
byte[] data = alphabet4.getByte... |
16189524_3 | class MeasurementsResource {
@POST
@Path("/{resource}")
@Timed
public Collection<Collection<MeasurementDTO>> getMeasurements(
ResultDescriptorDTO descriptorDTO,
@PathParam("resource") Resource resource,
@QueryParam("start") Optional<TimestampParam> start,
... |
final Results<Measurement> results = new Results<>();
when(
m_repository.select(
eq(Context.DEFAULT_CONTEXT),
eq(new Resource("localhost")),
eq(Optional.of(Timestamp.fromEpochSeconds(900000000))),
... |
16204287_28 | class IrmGPCM extends AbstractItemResponseModel {
public double probability(double theta, double[] iparam, int category, double D){
double t = numer(theta, iparam, category, D);
double b = denom(theta, iparam, D);
return t/b;
}
public IrmGPCM(double discrimination, double[] step, ... | System.out.println("Probability test");
double[] theta = {-4.0, -3.9, -3.8, -3.7, -3.6, -3.5, -3.4, -3.3, -3.2, -3.1, -3.0, -2.9, -2.8, -2.7, -2.6,
-2.5, -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1,
-1.0, -0.9, -0.8, -0.7, -0.6, -0.... |
16283971_24 | class Sort {
public int[] sort(int[] m)
{
if (m.length <= 1)
return m;
int middle = m.length / 2;
int[] left = Arrays.copyOf(m,middle);
int[] right = Arrays.copyOfRange(m,middle,m.length);
right = sort(right);
left = sort(left);
int[... | for (int i = 0; i < 50; i++) {
int[] random = getEqualArray(new Random().nextInt(200)+1);
assertArrayEquals(sort(random), new Sort().sort(random));
}
}
} |
16293572_17 | class RedisStore extends AbstractLifecycle implements RedisStoreManagement, Store {
@Override
public String[] keys() {
return this.lockTemplate.withReadLock(new LockTemplate.LockedOperation<String[]>() {
@Override
public String[] invoke() {
try {
... | Set<String> response = new HashSet<String>(Arrays.asList("test-id"));
when(this.jedisClient.getSessions(SESSIONS_KEY)).thenReturn(response);
String[] result = this.store.keys();
assertEquals(1, result.length);
assertArrayEquals(new String[]{"test-id"}, result);
}
} |
16294920_10 | class RaftSessionInvoker {
public CompletableFuture<byte[]> invoke(PrimitiveOperation operation) {
CompletableFuture<byte[]> future = new CompletableFuture<>();
switch (operation.id().type()) {
case COMMAND:
context.execute(() -> invokeCommand(operation, future));
break;
case QUER... | RaftSessionConnection connection = mock(RaftSessionConnection.class);
when(connection.command(any(CommandRequest.class)))
.thenReturn(CompletableFuture.completedFuture(CommandResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(10)
.withResult("Hello worl... |
16319386_107 | class DefaultBuildContextState implements Serializable {
public static DefaultBuildContextState emptyState() {
return new DefaultBuildContextState(Collections.<String, Serializable>emptyMap() // configuration
, Collections.<Object, ResourceHolder<?>>emptyMap() // inputs //
, Collections.<File>emp... | Assert.assertTrue(DefaultBuildContextState.loadFrom(temp.newFile()).configuration.isEmpty());
}
} |
16338837_0 | class Upper {
@Path("rest/upper/{param}")
@GET
public String toUpper(@PathParam("param") String param) {
return param.toUpperCase();
}
}
class UpperTest {
@Test
public void testUpper() {
| Upper upper = new Upper();
assertEquals("FOO",upper.toUpper("foo"));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.