id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
13325401_358 | class TypeUtil {
public static ValueMap toValueMap(final Map<String, ?> map) {
final Map<String, Object> objectMap = new LinkedHashMap<String, Object>(map.size());
for (final Map.Entry<String, ?> entry : map.entrySet()) {
objectMap.put(entry.getKey(), entry.getValue());
}
... | final Map<String, String> stringMap = new LinkedHashMap<String, String>();
stringMap.put("one", "uno");
stringMap.put("two", "dos");
stringMap.put("three", "tres");
final Map<String, Object> objectMap = new LinkedHashMap<String, Object>();
objectMap.put("one", "uno");
... |
13343738_8 | class JUGMemberServiceBean {
public List<JUGMember> findByExperience(int experience) {
return entityManager.createNamedQuery(
"JUGMember-findByExperience")
.setParameter( 1, experience )
.getResultList();
}
public void save( JUGMember member );
p... | List<JUGMember> list = service.findByExperience(5);
assertNotNull(list);
assertEquals( 2, list.size() );
}
} |
13349691_13 | class LoopPerformances implements Serializable {
public TestPerformances getPerformancesFor(final String msg) {
return map.get(msg);
}
@SuppressWarnings("unchecked") private LoopPerformances();
public LoopPerformances(final long iterations,
final Map<String, Long> timeMap);
... | final TestPerformances tp = loopPerformances
.getPerformancesFor("second");
assertEquals(1000L, tp.getElapsedNanoseconds());
assertEquals(1000L / ITERATIONS, tp.getElapsedNanosecondsPerCycle(), 1E-3);
assertEquals("second", tp.getName());
assertEquals(66.666, tp.g... |
13363729_38 | class HttpHelper {
public List<String> queryXml(String url, String username, String password, String... xpathQueries) throws IOException {
byte[] xmlContent = doGet(url, username, password);
List<String> results = new ArrayList<>();
try {
InputSource is = new InputSource(new Byt... | String xmlResponse = "<xml>" +
"<test>" +
OK_RESPONSE +
"</test>" +
"</xml>";
respond(SC_OK, xmlResponse);
String xPath = "//test/child::text()";
List<String> xmls = httpHelper.queryXml(baseUrl, A_USERNAME, A_PASSWORD, xPat... |
13379760_81 | class Formats {
public static String formatAlertMessage(TransactionSeenEvent event) {
// Decode the "transaction seen" event
final Coin amount = event.getAmount();
final Coin modulusAmount;
if (amount.compareTo(Coin.ZERO) >= 0) {
modulusAmount = amount;
} else {
modulusAmount = amou... |
bitcoinConfiguration.setBitcoinSymbol(BitcoinSymbol.ICON.name());
final BitcoinURI bitcoinURI = new BitcoinURI("bitcoin:1AhN6rPdrMuKBGFDKR1k9A8SCLYaNgXhty?amount=0.01&label=Please%20donate%20to%20multibit.org");
assertThat(Formats.formatAlertMessage(bitcoinURI).get()).isEqualTo("Payment \"Please donate t... |
13383431_28 | class PetriNetController implements Serializable {
public UndoableEdit delete(PetriNetComponent component) throws PetriNetComponentException {
return deleteComponent(component);
}
public PetriNetController(PetriNet model, UndoableEditListener undoListener, GUIAnimator animator,
... | Place place = new DiscretePlace("", "");
net.addPlace(place);
UndoableEdit edit = controller.delete(place);
DeletePetriNetObject deleteAction = new DeletePetriNetObject(place, net);
assertEquals(edit, deleteAction);
}
} |
13414290_2 | class Schemas {
public Schema getSchema(int version) {
return new Schema(version);
}
private Schemas(int currentRevision,
Map<String, ImmutableList<? extends TableDefinitionOperation>> tables,
ImmutableMap<Integer, ImmutableMap<String, ImmutableList<? extends TableDowngradeOperation>>> downgrad... | Schemas db = Schemas.Builder
.currentSchema(2900)
.build();
assertThat(db.getSchema(1500)).isNotNull();
}
} |
13471496_3 | class DownloadMediaOptions {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
boolean firstTime = true;
for (String key : mParams.keySet()) {
builder.append(firstTime ? "?" : "&");
if (firstTime) firstTime = false;
St... | DownloadMediaOptions.Builder builder = new DownloadMediaOptions.Builder();
builder.maxHeight(100)
.maxHeight(200)
.maxHeight(300)
.maxHeight(400);
assertNotNull(builder.build());
String finalURL = builder.build().toString();
asser... |
13486560_0 | class MimeTypes {
public String guessMimeType(String path) {
int lastDot = path.lastIndexOf('.');
if (lastDot == -1) {
return null;
}
String extension = path.substring(lastDot + 1);
extension = extension.toLowerCase();
String mimeType = extensionToMimeT... | assertEquals("text/plain", MimeTypes.INSTANCE.guessMimeType("hello.txt"));
assertEquals("application/msword", MimeTypes.INSTANCE.guessMimeType("hello.doc"));
assertEquals("text/html", MimeTypes.INSTANCE.guessMimeType("hello.htm"));
assertEquals("text/html", MimeTypes.INSTANCE.guessMimeTy... |
13486910_2 | class SpringConfigRegistry {
public void removeAllSpringConfig() {
mSpringConfigMap.clear();
}
SpringConfigRegistry(boolean includeDefaultEntry);
public static SpringConfigRegistry getInstance();
public boolean addSpringConfig(SpringConfig springConfig, String configName);
public boolean removeSpri... | SpringConfig configA = new SpringConfig(0, 0);
SpringConfig configB = new SpringConfig(0, 0);
SpringConfig configC = new SpringConfig(0, 0);
mSpringConfigRegistrySpy.addSpringConfig(configA, "a");
mSpringConfigRegistrySpy.addSpringConfig(configB, "b");
mSpringConfigRegistrySpy.addSpringConfig(c... |
13490595_330 | class OkuriganaValidator extends Validator {
@Override
public void validate(Sentence sentence) {
invalidOkurigana.stream().forEach(value -> {
int startPosition = sentence.getContent().indexOf(value);
if (startPosition != -1) {
addLocalized... | String sampleText = "そこを押える時、";
Configuration config = Configuration.builder("ja")
.addValidatorConfig(new ValidatorConfiguration("Okurigana"))
.build();
DocumentParser parser = DocumentParser.MARKDOWN;
List<Document> documents = new ArrayList<>();
... |
13512175_99 | class EntityVersionStoreJdbc extends AbstractVersionStoreJdbc<Id, M, V, EntityUpdateBatch<Id, M, V>, EntityStoreOptions<Id, M, V>> {
@Override
public EntityUpdateBatch<Id, M, V> updateBatch(Id id) {
return updateBatch(singleton(id));
}
@SuppressWarnings("unused") protected EntityVersionStoreJ... | final String comment = "Comment metadata";
final String docId = randomId();
transactionTemplate.execute(status -> {
EntityUpdateBatch<String, String, JEntityVersion<String>> update = entityStore.updateBatch(docId);
ObjectVersion<String> version = ObjectVersion.<String>bui... |
13521187_28 | class Sprinkles {
public <T> void registerType(Class<T> clazz, TypeSerializer<T> serializer) {
typeSerializers.put(clazz, serializer);
}
private Sprinkles();
private void addStandardTypeSerializers();
public static synchronized Sprinkles init(Context context);
public static synchroni... | Sprinkles s = Sprinkles.init(Robolectric.application);
TypeSerializer serializer = new MyObjectSerializer();
s.registerType(MyObject.class, serializer);
assertEquals(s.getTypeSerializer(MyObject.class), serializer);
}
} |
13535208_210 | class StringType implements ArgumentType<String> {
public String toObject(String value) {
if (StringUtil.isEmpty(value)) {
return null;
}
return ArgumentUtil.decode(value);
}
public String toText(String value);
private StringType stringType;
}
class StringTypeTes... | assertEquals("", stringType.toObject("''"));
}
} |
13570618_2 | class TaskQueueImpl implements
TaskQueue,
ApplicationListener,
ApplicationEventPublisherAware,
DisposableBean {
@Override
public synchronized void cleanup()
{
logInfoWithQueueName("purging completed tasks");
// clear all tasks from the finished queue
final List<Futur... |
// by default we only have space for 2 completed tasks, but we're going to start 10
testWithMaxFinishedSize(10, 2);
queue.gracefulShutdown(false);
// now make a new queue with space for 10 completed tasks
queue = new TaskQueueImpl(
"testQueue",
3,
Sup... |
13621351_1 | class CustomRepositoryServiceImpl implements CustomRepositoryService {
@Override
@Transactional(readOnly = true)
public CustomRepository findByName(String name) {
return customRepositoryRepository.findByName(name);
}
@Override @Transactional public CustomRepository save(CustomRepository customRepository);
@Ov... |
CustomRepository customRepository = customRepositoryService.findByName("repo1");
Assert.assertNotNull(customRepository);
Assert.assertEquals("repo1", customRepository.getName());
}
} |
13651430_68 | class ExpressionLanguage {
public static DesiredRateReadWriteExpression<?, Object> formula(String formula) {
DesiredRateExpression<?> exp = parseFormula(formula);
if (exp instanceof LastOfChannelExpression) {
return new DesiredRateReadWriteExpressionImpl<>(exp, org.diirt.datasource.vty... | ReadExpressionTester exp = new ReadExpressionTester(formula("=3==4"));
assertThat(exp.getExpression().getName(), equalTo("(3 == 4)"));
VBoolean result = (VBoolean) exp.getFunction().readValue();
assertThat(result.getValue(), equalTo(false));
}
} |
13660977_8 | class AcmeClientSpi {
public X509CertificateChainAndSigningKey obtainCertificateChain(AcmeAccount account, boolean staging, String... domainNames) throws AcmeException {
return obtainCertificateChain(account, staging, null, -1, domainNames);
}
public Map<AcmeResource, URL> getResourceUrls(AcmeAcco... | try {
server = setupTestObtainCertificateWithUnsupportedPublicKey();
AcmeAccount account = populateAccount(ACCOUNT_7_V2);
String domainName = "iraclzlcqgaymrc.com";
obtainCertificateChain("DSA", 2048, account, domainName);
fail("Expected AcmeException ... |
13687370_0 | class GwtPlugin implements Plugin<Project> {
@Override
public void apply(final Project project) {
project.getPlugins().apply(GwtCompilerPlugin.class);
project.getPlugins().withType(WarPlugin.class,
(warPlugin) -> project.getPlugins().apply(GwtWarPlugin.class));
}
private Project project;
private TaskCon... | project.getPlugins().apply(WarPlugin.class);
assertThat(tasks.getByName(GwtWarPlugin.TASK_WAR_TEMPLATE), instanceOf(Copy.class));
assertThat(tasks.getByName(GwtWarPlugin.TASK_GWT_DEV), instanceOf(GwtDev.class));
assertThat(tasks.getByName(GwtWarPlugin.TASK_DRAFT_WAR), instanceOf(War.class));
}
} |
13702023_0 | class StringUtils {
public static String implode(String delimiter, String[] strings)
{
if (strings.length == 0)
{
return "";
}
else
{
StringBuilder sb = new StringBuilder(strings[0]);
for (int i = 1; i < strings.length; i++)
... | assertEquals("a.b.c", StringUtils.implode(".", new String[]{"a", "b", "c"}));
}
} |
13719326_26 | class MeteredMethodBean {
@Metered(name = "meteredMethod")
public void meteredMethod() {
}
private final static String METER_NAME;
private final static AtomicLong METER_COUNT;
@Inject
private MetricRegistry registry;
@Inject
private MeteredMethodBean bean;
}
class MeteredMethodBe... | assertThat("Meter is not registered correctly", registry.getMeters(), hasKey(METER_NAME));
Meter meter = registry.getMeters().get(METER_NAME);
// Call the metered method and assert it's been marked
bean.meteredMethod();
// Make sure that the meter has been marked
assert... |
13745124_126 | class DosAttributeProvider extends AttributeProvider {
@Override
public void set(File file, String view, String attribute, Object value, boolean create) {
if (supports(attribute)) {
checkNotCreate(view, attribute, create);
file.setAttribute("dos", attribute, checkType(view, attribute, value, Boolea... | for (String attribute : DOS_ATTRIBUTES) {
assertSetAndGetSucceeds(attribute, true);
assertSetFailsOnCreate(attribute, true);
}
}
} |
13796699_2 | class HttpGet {
public String getSomeThing(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(3000);
urlConn.setRequestMethod("GET");
urlConn.connect();
... | String response = "Hello, The World!";
_mock.start(response, "text/plain");
String content = _httpGet.getSomeThing("http://localhost:9191/hello");
assertEquals(response, content);
}
} |
13865967_128 | class OperationKey {
public Type getType() {
return type;
}
public OperationKey(OperationKey key, String namespace);
public OperationKey(final ServiceVersion version, final String serviceName, final String operationName);
public OperationKey(final ServiceVersion version, final String se... | assertEquals(new OperationKey(new ServiceVersion(1, 1), "b", "c").getType(), OperationKey.Type.Request);
}
} |
13867926_47 | class ConfigFileCreator {
public void create(String tebase) throws TEException {
File f = new File(tebase);
if (f.exists()) {
try {
process(tebase);
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new TEBaseNotFoundException(tebase);
}
}
public ConfigFileCreator();
publ... | File tebase = new File(classp, "tebase");
ConfigFileCreator configFileCreator = new ConfigFileCreator();
configFileCreator.create(tebase);
File configFile = new File(tebase, "config.xml");
try {
Document config = builder.parse(configFile);
Node node = XMLU... |
13869700_0 | class StringMatcher {
public boolean compare(String a, String b){
return true;
}
}
class StringMatcherTest {
@Test
public void accountMC() {
| if (verifyNoPropertyViolation()) {
StringMatcher matcher = new StringMatcher("abc");
matcher.compare("abc", "b");
}
}
} |
13870893_182 | class DeleteManager {
void close() {
for (DeleteOperation op : deleteOperations) {
// There is a rare scenario where the operation gets removed from this set and gets completed concurrently by
// the RequestResponseHandler thread when it is in poll() or handleResponse(). In order to avoid the complet... | setServerResponse(false);
testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout,
RouterErrorCode.RouterClosed, new ErrorCodeChecker() {
@Override
public void testAndAssert(RouterErrorCode expectedError) throws Exception {
future = router.d... |
13873695_72 | class FilteringGenerator implements Generator<T> {
@Override
public T next() {
T next;
do {
next = delegate.next();
} while (!predicate.apply(next));
return next;
}
public FilteringGenerator(@Nonnull Generator<T> delegate, @Nonnull Predicate<T> predicate);... | //Given
Generator<Integer> oddNumbers = new FilteringGenerator<>(new RandomFromCollectionGenerator<>(1, 2, 3, 4, 5), new Predicate<Integer>() {
@Override
public boolean apply(Integer input) {
return input % 2 != 0;//only odd numbers
}
});
... |
13886663_2 | class FileCarImage extends AbstractCarImage {
public void loadImage() throws IOException {
if (Files.exists(getFilepath()) && Files.isRegularFile(getFilepath())) {
InputStream inStream = Files.newInputStream(persistablePath.getPath());
loadImage(inStream);
return;
... | file.loadImage();
assertNotNull(file);
assertNotNull(file.getImage());
}
} |
13893381_10 | class StringUtils {
public static String ConvertArabicToLetters(int num) {
String letters = "";
while (num > 0) {
num--;
letters = Character.toString((char) (65 + (num % 26))) + letters;
num = num / 26;
}
return letters.toString();
}
publ... |
String str = StringUtils.ConvertArabicToLetters(27);
assertTrue(str.equals("AA"));
}
} |
13907695_14 | class Rectangle implements Distributable {
public Rectangle newSize(Size aNewSize) {
return new Rectangle(position, aNewSize);
}
public Rectangle();
public Rectangle(Position aPosition, Size aSize);
public boolean contains(Position aPosition);
public Rectangle newPosition(Position a... | Rectangle theOriginal = new Rectangle(new Position(10, 10), new Size(5, 7));
Rectangle theRectangle = theOriginal.newSize(new Size(20, 30));
assertNotSame(theOriginal, theRectangle);
assertTrue(theRectangle.contains(new Position(11, 11)));
assertTrue(theRectangle.contains(new P... |
13910968_3 | class TodoService {
public void deleteTodo(Long id) {
todoRepository.delete(id);
}
@Autowired public TodoService(TodoRepository todoRepository);
public void saveTodo(Todo todo);
public List<Todo> getTodos();
public List<Todo> getActive();
public List<Todo> getCompleted();
pu... |
service.deleteTodo(123L);
verify(todoRepository).delete(123L);
}
} |
13928240_0 | class I18Next {
public static boolean isI18NextKeyCandidate(CharSequence key) {
if (key != null && key.length() > 0) {
return key.toString().matches("([a-z0-9]+((\\_)([a-z0-9]+))*)+((\\.)[a-z0-9]+((\\_)([a-z0-9]+))*)+");
} else {
return false;
}
}
public I1... | String[] listKeyValid = {"test.dot", "test.double.dot", "test.test_underscore",
"test.test_double_underscore", "test.test_double_underscore.dot",
"test.dot_double_underscore", "test.test2"};
String[] listKeyInvalid = {"test", "space not accepted", "double..dot"};
... |
13968244_38 | class GenerateProcessor implements PropertiesProcessor {
@Override
public Properties process(Properties in) {
Properties out = new Properties();
for (Entry<Object, Object> entry : in.entrySet()) {
Matcher wordMatcher = Pattern.compile(PropertiesKeywords.GENERATE_WORD_REGEX.getKey())... | GenerateProcessor generateProcessor = new GenerateProcessor();
Properties properties = new Properties();
String dateFormat = "yyyy-MM-dd";
int offSet = -25;
String text = String.format("generate_date(%s;%d)", dateFormat, offSet);
String reg = "[0-9]{4}-[0-9]{2}-[0-9]{2}";... |
14057993_4 | class ElasticSearchClient extends DB {
@Override
public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
try {
final RangeFilterBuilder filter = rangeFilter("_id").gte(startkey);
final SearchResponse res... | System.out.println("scan");
int recordcount = 10;
Set<String> fields = MOCK_DATA.keySet();
Vector<HashMap<String, ByteIterator>> resultParam = new Vector<HashMap<String, ByteIterator>>(10);
int expResult = 0;
int result = instance.scan(MOCK_TABLE, MOCK_KEY1, recordcount, ... |
14066577_215 | class TreeViewAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.TreeViewListener {
public void selectModeChanged(org.apache.pivot.wtk.TreeView arg0, org.apache.pivot.wtk.TreeView.SelectMode arg1) {
if (selectModeChanged != null) {
selectModeChanged.call(arg0, arg1);
}
}
... | final boolean[] invoked = new boolean[1];
CallableWithArgs<Void> callable = new CallableWithArgs<Void>() {
public Void call(Object... args) {
invoked[0] = true;
return null;
}
};
assertNull(adapter.getSelectModeChanged());
... |
14082560_31 | class MatchBasedDiscoveryIO implements DiscoveryIO<E> {
@Override
public Set<Operation<E>> findOperationsProducing(E output) {
Map<E,T> sources = matchGraph.getSourceElementsThatMatch(output);
// For each target, get the services that uses the input
Set<Operation<E>> relevantOps = new H... | // Get all services that can provide y (Op1 and Op2)
Set<Operation<String>> result = matchDiscovery.findOperationsProducing("y");
assertNotNull(result);
assertEquals(2, result.size());
}
} |
14083998_16 | class HierarchyScanner extends AbstractScanner {
public List<Edge> getEdges() {
List<Edge> edges = new ArrayList<>();
for (Class<?> clazz : classes) {
Class<?> superclass = clazz.getSuperclass();
if (isDomainClass(superclass)) {
DomainObject child = new Domai... | List<Class<?>> hierarchicalClasses = Lists.newArrayList();
hierarchicalClasses.add(Child.class);
hierarchicalClasses.add(GrandChild.class);
HierarchyScanner scanner = new HierarchyScanner(hierarchicalClasses);
List<Edge> edges = scanner.getEdges();
assertThat(edges, cont... |
14094143_12 | class FileFilter {
public boolean match(final File file) {
boolean result = doMmatch(file);
return filterType == INCLUDE ? result : !result;
}
public FileFilter(int matchType, int filterType, boolean appliesToDir, FileFilterRule... rules);
public int getMatchType();
public int getFilterType();
public bool... | FileFilter filter = new FileFilter(FileFilter.MATCH_ALL, FileFilter.INCLUDE, true, alwaysTrue);
assertTrue(filter.match(testNode));
}
} |
14104548_0 | class ClassSchemaBuilder {
ClassInfo createClassInfo(Class<?> c) {
return createClassInfo(c, Collections.<String>emptySet(), false);
}
ClassSchemaBuilder();
void registerClass(Class<?> c, Set<String> ignoreFields);
void registerClass(Class<?> c, Set<String> ignoreFields, boolean withT... | ClassSchemaBuilder.ClassInfo classInfo = classSchemaBuilder.createClassInfo(TestClass.class);
Assert.assertEquals(7, classInfo.fieldInfos.length);
}
} |
14105280_19 | class WorkflowFilesDeployer {
URI getTargetJsFileUri(URI uri) throws URISyntaxException {
String path = uri.getPath() + File.separator + config.getWorkflowName() + ".js";
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(),
uri.getPort(), path, uri.getQuery(), uri.getFr... | CelosCiContext context = mock(CelosCiContext.class);
WorkflowFilesDeployer deployer = new WorkflowFilesDeployer(context);
doReturn("workflow").when(context).getWorkflowName();
Assert.assertEquals(deployer.getTargetJsFileUri(URI.create("sftp://user@server:999/home")), URI.create("sftp://... |
14106147_7 | class ObjectAddedUpdater implements ThreadSafeMultimap.ListUpdater<V> {
@Nullable
@Override
public List<V> update(@Nonnull List<V> values) {
if (values == ThreadSafeMultimap.NO_VALUE) {
return null;
} else if (!Iterables.contains(values, newObject)) {
final List<V> result = ThreadSafeMultimap.copy(values)... | int sizeBefore = multimap.get(3).size();
final TestObject oldObject = multimap.get(3).get(0);
multimap.update(3, new ObjectAddedUpdater<TestObject>(oldObject));
assertEquals(sizeBefore, multimap.get(3).size());
}
} |
14135467_11 | class BackoffHelper {
public <E extends Exception> void doUntilSuccess(final ExceptionalSupplier<Boolean, E> task)
throws InterruptedException, BackoffStoppedException, E {
doUntilResult(() -> {
Boolean result = task.get();
return Boolean.TRUE.equals(result) ? result : null;
});
}
publ... | ExceptionalSupplier<Boolean, RuntimeException> task =
createMock(new Clazz<ExceptionalSupplier<Boolean, RuntimeException>>() { });
expect(task.get()).andReturn(false);
expect(backoffStrategy.shouldContinue(0L)).andReturn(true);
expect(backoffStrategy.calculateBackoffMs(0L)).andReturn(42L);
... |
14135469_6 | class StartMojo extends JobActionMojoBase {
@Override
public void execute() throws MojoExecutionException {
final JobOperator jobOperator = getOrCreateOperator();
final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader loader = createStartLoader(... | final StartMojo mojo = mojo(StartMojo.class, "jobName", "simple");
mojo.execute();
final String output = BatchEEMojoTestFactory.output(mojo);
final long id = Long.parseLong(output.substring(output.lastIndexOf("#") + 1).trim());
waitForEnd(mojo.getOrCreateOperator(), id);
... |
14142718_56 | class JPAContainer implements EntityContainer<T>,
EntityProviderChangeListener<T>, HierarchicalEntityContainer<T>,
Container.Indexed {
public Property getContainerProperty(Object itemId, Object propertyId) {
Item item = getItem(itemId);
return item == null ? null : item.getItemPrope... | Person p = new Person();
p.setFirstName("Joe");
expect(entityProviderMock.getEntity(container, "myId")).andStubReturn(p);
expect(entityProviderMock.getEntity(container, "nonExistent")).andStubReturn(null);
replay(entityProviderMock);
container.setEntityProvider(entityPro... |
14145700_383 | class ValueComparisonEvaluator extends QueryEvaluator {
@Override
public boolean evaluate(QueryEvaluationContext ctx) {
ctx.setResult(false);
Object value = rvalue.getValue();
LOGGER.debug("evaluate {} {} {}", field, operator, value);
KeyValueCursor<Path, JsonNode> cursor = ctx.... | QueryExpression q = EvalTestContext.queryExpressionFromJson("{'field':'field4','op':'>','rvalue':3.5}");
QueryEvaluator qe = QueryEvaluator.getInstance(q, md);
QueryEvaluationContext ctx = qe.evaluate(jsonDoc);
Assert.assertTrue(ctx.getResult());
}
} |
14173210_42 | class BSN extends BasePacket {
@Override
public IPacket deserialize(byte[] data, int offset, int length)
throws PacketParsingException {
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
int magic = bb.getInt();
if (magic != BSN_MAGIC) {
throw new PacketPar... | Ethernet pkt = (Ethernet) new Ethernet().deserialize(probePkt, 0, probePkt.length);
assertTrue(Arrays.equals(probePkt, pkt.serialize()));
Ethernet expected = getProbePacket();
assertEquals(expected, pkt);
}
} |
14176513_11 | class SpoonCodeInstrument extends JfxInstrument implements Initializable {
String prettyPrintType(final Type type) {
if(type instanceof Class) {
return ((Class<?>) type).getSimpleName();
}
if(type instanceof ParameterizedType) {
final ParameterizedType paramType = (ParameterizedType) type;
return getUn... | final String string = spoonCodeInstrument.prettyPrintType(Stub.class.getMethod("meth").getGenericReturnType());
assertThat(string).isEqualTo("Stub3<CtStatement, ?>");
}
} |
14202062_0 | class GetFlights extends WebServiceGatewaySupport {
public GetFlights(WebServiceMessageFactory messageFactory) {
super(messageFactory);
}
public GetFlights(WebServiceMessageFactory messageFactory);
public void getFlights();
private void writeTicket(Ticket ticket);
private void writeName(Name name);
private... |
Source getFlightsRequest = new StringSource("<GetFlightsRequest xmlns='" + MESSAGES_NS + "'>" + "<from>AMS</from>"
+ "<to>VCE</to>" + "<departureDate>2006-01-31</departureDate>" + "</GetFlightsRequest>");
String flightInfo = "<t:number>KL1653</t:number>"
+ "<t:departureTime>2006-01-31T10:05:00.000+01:00</... |
14212940_20 | class HierarchicalShardSyncer {
public synchronized boolean checkAndCreateLeaseForNewShards(@NonNull final ShardDetector shardDetector,
final LeaseRefresher leaseRefresher, final InitialPositionInStreamExtended initialPosition,
final MetricsScope scope, final boolean ignoreUnexpectedChildSh... | final List<Shard> latestShards = constructShardListForGraphA();
final ArgumentCaptor<Lease> leaseCaptor = ArgumentCaptor.forClass(Lease.class);
when(shardDetector.listShards()).thenReturn(latestShards);
when(dynamoDBLeaseRefresher.listLeases()).thenReturn(Collections.emptyList());
... |
14230404_5 | class PropertyMatchers {
public static PropertyMatchers overriddenMatchers(String property, Matcher matcher) {
return new PropertyMatchers(newHashSet(entryOf(property, matcher)));
}
private PropertyMatchers(Map<String, Matcher> matchers);
private PropertyMatchers(Set<Map.Entry<String, Matche... | FixtureAssert.assertThat(testMap)
.toMatchSnapshotExactly(overriddenMatchers("x.a", nested(new BaseMatcher<Map>() {
@Override
public boolean matches(Object item) {
Map<String, Object> expected = (Map<String, Obje... |
14279760_53 | class NamesAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = convertView == null ? createView(parent) : (TextView) convertView;
textView.setText(names.get(position));
return textView;
}
public Na... | TextView existingView = new TextView(null);
TextView nameView = (TextView) namesAdapter.getView(2, existingView, new LinearLayout(new Activity()));
assertThat(nameView, sameInstance(existingView));
}
} |
14281190_10 | class SpscChannel implements Channel<E> {
@SuppressWarnings("unchecked")
private SpscChannelConsumer<E> newConsumer(Object... args) {
return mapper.newFlyweight(SpscChannelConsumer.class, "ChannelConsumerTemplate.java",
Template.fromFile(Channel.class, "ChannelConsumerTemplate.java"), ... | ChannelConsumer consumer = newConsumer();
shouldWriteAnObject();
assertTrue(consumer.read());
assertEmpty();
}
} |
14281911_49 | class FreeFlowAnalysis extends PeriodicAnalysis {
static Position centerOfVessel(Position aisPosition, float hdg, int dimStern, int dimBow, int dimPort, int dimStarboard) {
// Compute direction of half axis alpha
final double thetaDeg = compass2cartesian(hdg);
// Transform latitude/longitu... | Position p;
p = FreeFlowAnalysis.centerOfVessel(Position.create(56, 12), 0f, 0, 0, 0, 0);
assertEquals(56f, p.getLatitude(), 1e-16);
assertEquals(12f, p.getLongitude(), 1e-16);
p = FreeFlowAnalysis.centerOfVessel(Position.create(56, 12), 0f, 50, 50, 10, 10);
assertEqual... |
14285346_4 | class ResultSetHelperService implements ResultSetHelper {
public String[] getColumnValues(ResultSet rs) throws SQLException, IOException {
return this.getColumnValues(rs, false, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT);
}
public String[] getColumnNames(ResultSet rs);
public String[] getColumnValues(... | String[] expectedNames = {"BigInt", "Null BigInt"};
String[] realValues = {"100", null};
String[] expectedValues = {"100", ""};
int[] expectedTypes = {Types.BIGINT, Types.BIGINT};
ResultSetMetaData metaData = MockResultSetMetaDataBuilder.buildMetaData(expectedNames, expectedTypes);
ResultSet re... |
14290433_1 | class DumbPartitioner extends AbstractPartitioner {
@Override
public String getPartition() {
return "";
}
public DumbPartitioner();
@Override public Date getRefresh();
}
class DumbPartitionerTest {
@Test
public void testDumbPartitionerGetPartition(){
| DumbPartitioner d = new DumbPartitioner();
assertEquals("",d.getPartition());
}
} |
14305692_432 | class ChargingStationEventListener {
@EventHandler
public void handle(ChargingStationCreatedEvent event) {
LOG.debug("ChargingStationCreatedEvent creates [{}] in operator api repo", event.getChargingStationId());
ChargingStation station = new ChargingStation(event.getChargingStationId().getId()... | ChargingStation cs = repository.findOne(CHARGING_STATION_ID.getId());
assertTrue(cs.getConfItems().isEmpty());
listener.handle(new ConfigurationItemsReceivedEvent(CHARGING_STATION_ID, CONFIGURATION_ITEMS, REQUESTED_CONFIGURATION_KEYS, IDENTITY_CONTEXT));
cs = repository.findOne(CHARGING... |
14333932_44 | class MatrixUtils {
public static RealMatrix transposeTimesSelf(LongObjectMap<float[]> M) {
if (M == null || M.isEmpty()) {
return null;
}
RealMatrix result = null;
for (LongObjectMap.MapEntry<float[]> entry : M.entrySet()) {
float[] vector = entry.getValue();
int dimension = vector... | LongObjectMap<float[]> M = new LongObjectMap<float[]>();
M.put(1L, new float[] {4.0f, -1.0f, -5.0f});
M.put(2L, new float[] {2.0f, 0.0f, 3.0f});
RealMatrix MTM = MatrixUtils.transposeTimesSelf(M);
assertArrayEquals(new double[]{20.0, -4.0, -14.0}, MTM.getRow(0));
assertArrayEquals(new double[]{-... |
14339501_680 | class XmlFieldExtractor {
public Map<String, String> extract(InputStream xml, String[] fields) {
Map<String, String> parsedFields = Maps.newHashMap();
try {
DocumentBuilder documentBuilder = documentBuilderSupplier.get();
if (documentBuilder == null) {
logger.warn("Could not create Docume... | InputStream mockInputStream = mock(InputStream.class);
String message = "Intentionally throwing IOException";
IOException exception = new IOException(message);
when(mockInputStream.read()).thenThrow(exception);
Map<String, String> ret = xmlFieldExtractor.extract(mockInputStream, new String[] {"trigg... |
14340523_7 | class AdministratorLoginBean implements Serializable {
public String login() {
return isSuccess ? INDEX_PAGE : LOGIN_PAGE;
}
public void login(final ActionEvent ae);
public void setAdminAuthManager(final AuthenticationManager adminAuthManager);
public String getUsername();
public void... |
Mockito.when(manager.authenticate(request)).thenReturn(request);
final SecurityContext securityContext = Mockito
.mock(SecurityContext.class);
SecurityContextHolder.setContext(securityContext);
setCredentials(username, password);
loginBean.login(null);
assertEquals(loginBean.login(), Administrat... |
14366444_0 | class LocationExtractor {
public static ILexLocation extractLocation(INode node)
{
try
{
Method method = node.getClass().getMethod("getLocation");
return (ILexLocation) method.invoke(node);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| In... |
@SuppressWarnings("deprecation")
AInterleavingReplicatedAction node = new AInterleavingReplicatedAction(new LexLocation("test", "Test", 0, 0, 1, 1, 0, 1), null, null, null);
ILexLocation loc = LocationExtractor.extractLocation(node);
Assert.assertNotNull(loc);
Assert.assertEquals("Test", loc.getModule());... |
14372507_0 | class Annotator {
public boolean addAnnotations(InputStream inputClass, File outputClassFile, Collection<String> annotations)
throws Exception {
boolean classIsModified = false;
FileOutputStream outputClass = null;
ClassWriter cw = new ClassWriter(false);
try {
... | Collection<String> annotations = Collections.singletonList(ANNOTATIONS[0]);
inputStreamClass = getInputStream(ClassToAnnotateWithNoise.class);
annotator.addAnnotations(inputStreamClass, outputClassFile, annotations);
assertClassHasAnnotations(outputClassFile, annotations);
}
} |
14377751_5 | class AmzaBotUtil {
public static String truncVal(String s) {
if (s == null) {
return "";
}
int len = Math.min(s.length(), 10);
String postfix = "";
if (s.length() > len) {
postfix = "...";
}
return s.substring(0, len) + postfix;
... | Assert.assertEquals(AmzaBotUtil.truncVal(null), "");
Assert.assertEquals(AmzaBotUtil.truncVal(""), "");
String nine = "123456789";
Assert.assertEquals(AmzaBotUtil.truncVal(nine), nine);
String ten = "1234567890";
Assert.assertEquals(AmzaBotUtil.truncVal(ten), ten);
... |
14393731_0 | class InstantAdapter {
@ToJson public String toJson(Instant instant) {
return instant.toString();
}
@FromJson public Instant fromJson(String value);
private static final Instant EPOCH;
private static final Instant RECENT;
private final Moshi moshi;
private final JsonAdapter<Instant> adapter;
}
cl... | assertThat(adapter.toJson(EPOCH)).isEqualTo("\"1970-01-01T00:00:00Z\"");
assertThat(adapter.toJson(RECENT)).isEqualTo("\"2015-07-31T10:16:59Z\"");
}
} |
14398404_63 | class Consistency {
public List<NotConsistentRelation> checkConsitency(String rootPid, boolean repair) throws IOException, ProcessSubtreeException, LexerException, RepositoryException {
TreeProcess deep = new TreeProcess(this.fedoraAccess);
this.fedoraAccess.processSubtree(rootPid, deep);
L... | StatisticsAccessLog acLog = EasyMock.createMock(StatisticsAccessLog.class);
ProcessingIndexFeeder feeder = createMock(ProcessingIndexFeeder.class);
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
HazelcastServerNode.ensureHa... |
14401179_53 | class DetachedChannelPipeline {
public DetachedChannelPipeline addLast(String name, Func0<ChannelHandler> handlerFactory) {
return _guardedAddLast(new HandlerHolder(name, handlerFactory));
}
public DetachedChannelPipeline();
public DetachedChannelPipeline(final Action1<ChannelPipeline> nulla... | pipelineRule.pipeline.addLast(HANDLER_1.getNameIfConfigured(), HANDLER_1.getHandlerFactoryIfConfigured());
pipelineRule.pipeline.addLast(HANDLER_2.getNameIfConfigured(), HANDLER_2.getHandlerFactoryIfConfigured());
assertThat("Unexpected handlers count.", pipelineRule.pipeline.getHoldersInOrder(... |
14426728_4 | class Utils {
static String pluralize(String string) {
string = string.toLowerCase(Locale.US);
if (string.endsWith("s")) {
return string;
} else if (string.endsWith("ay")) {
return string.replaceAll("ay$", "ays");
} else if (string.endsWith("ey")) {
... | String expected = "whiskies";
String actual = Utils.pluralize("Whisky");
assertEquals(expected, actual);
expected = "ytitties";
actual = Utils.pluralize("YTitty");
assertEquals(expected, actual);
expected = "ways";
actual = Utils.pluralize("Way");
... |
14444698_1 | class InterceptingMessageReceiver implements WebServiceMessageReceiver {
public void receive(MessageContext messageContext) throws Exception {
interceptingTemplate.interceptRequest(messageContext, wrappedMessageReceiver);
}
public InterceptingMessageReceiver(WebServiceMessageReceiver wrappedMessag... | MessageContext messageContext = new DefaultMessageContext(getMessageFactory());
IMocksControl control = createControl();
WebServiceMessageReceiver wrappedMessageReceiver = new WebServiceMessageReceiver(){
public void receive(MessageContext messageContext) throws Exception {
SaajSoapMessage message = ... |
14469879_4 | class BoolVar extends AbstractVarType<Boolean> {
public static BoolVar boolVar(String id) {
return new BoolVar(id);
}
private BoolVar(String id);
private BoolVar(String id, String regex);
public static BoolVar boolVar(String id, String regex);
@Override public Boolean convert(String... | RestParser parser = parser("/users?active={}", boolVar("isActive"));
RestUrl url = parser.parse("http://www.mail.com/users?active=FaLsE");
assertThat(url, isValid());
assertThat((Boolean) url.variable("isActive"), is(false));
}
} |
14490363_74 | class DocumentResourceFacadeImp extends CoreDBServiceFacadeImp<Document, Long> implements DocumentResourceFacade {
@Override
public boolean isDocumentExists(Long id) throws PropertyNotSetException {
DocumentDTO dto = findDocumentByID(id);
return dto != null ? true : false;
}
public DocumentResourceFacadeImp... | try {
entityManager.getTransaction().begin();
documentDTO = documentResourceFacadeImp.addDocument(documentDTO);
entityManager.getTransaction().commit();
Long id = documentDTO.getDocumentID();
boolean result = documentResourceFacadeImp.isDocumentExists(id);
assertEquals(true, result);
entityManag... |
14496551_2 | class StringUtils {
public static String collapseLineBreaks(String string) {
return replaceLineBreaks(string, EMPTY);
}
private StringUtils();
public static String byteToHex(byte[] data);
public static String replaceLineBreaksWithSpace(String string);
public static String replaceLine... | Assert.assertNull(StringUtils.collapseLineBreaks(null));
Assert.assertEquals("", StringUtils.collapseLineBreaks(""));
Assert.assertEquals("foobar", StringUtils.collapseLineBreaks("foobar"));
Assert.assertEquals("foo bar", StringUtils.collapseLineBreaks("foo bar"));
Assert.assertE... |
14505236_4 | class WfsGetFeatureCommand implements CommandHasRequest<WfsGetFeatureRequest, WfsGetFeatureResponse> {
@Override
public void execute(WfsGetFeatureRequest request, WfsGetFeatureResponse response) throws Exception {
FeatureCollection<SimpleFeatureType, SimpleFeature> features = performWfsQuery(request);
int maxCoo... | WfsGetFeatureRequest request = new WfsGetFeatureRequest();
request.setBaseUrl("http://127.0.0.1:"+port+"/wfs");
request.setTypeName("dov-pub-bodem:Bodemassociatiekaart");
request.setCriterion(new FidCriterionDto(new String[] { "Bodemassociatiekaart.1", "Bodemassociatiekaart.2" }));
request.setCrs("EPSG:31370"... |
14514251_160 | class BlockChain extends AbstractBlockChain {
@Override
public boolean add(FilteredBlock block) throws VerificationException, PrunedException {
boolean success = super.add(block);
if (success) {
trackFilteredTransactions(block.getTransactionCount());
}
return success... | assertTrue(testNetChain.add(getBlock1()));
Block b2 = getBlock2();
assertTrue(testNetChain.add(b2));
Block bad = new Block(TESTNET, Block.BLOCK_VERSION_GENESIS);
// Merkle root can be anything here, doesn't matter.
bad.setMerkleRoot(Sha256Hash.wrap("aaaaaaaaaaaaaaaaaaaaaa... |
14518795_0 | class FirstApplicableAlg implements CombiningAlgorithm {
@Override
public DecisionType combine(DecisionType op1, DecisionType op2) {
if (op1 != DecisionType.NotApplicable) {
return op1;
}
if (op2 != DecisionType.NotApplicable) {
return op2;
}
re... | FirstApplicableAlg alg = new FirstApplicableAlg();
assertTrue(alg.combine(DecisionType.Indeterminate, DecisionType.Permit) == DecisionType.Indeterminate);
assertTrue(alg.combine(DecisionType.NotApplicable, DecisionType.Permit) == DecisionType.Permit);
assertTrue(alg.combine(DecisionType... |
14538599_0 | class FindByKeyQuery extends AbstractPojoQuery<P> {
@Override
protected Object[] convertParameters(Object[] params) {
List<Object> converted = getBinding().getKeyBinding().getKeyParameters(Arrays.asList(params));
return converted.toArray(new Object[converted.size()]);
}
public FindByK... | PojoDao<LogEntry> dao = createPojoDao(LogEntry.class);
Date now = new Date();
LogEntry expected = new LogEntry();
expected.setCategory("cat");
expected.setTimestamp(now);
expected.setMessage("Now is the time for all good men...");
dao.save(expected);
LogE... |
14561598_13 | class ManifestMatcher implements VersionMatcher {
public VersionMatchResult matches(DeploymentInfo info) {
// Skip if no manifest configuration
if(info.getManifest() == null || info.getManifest().size() == 0) {
return VersionMatchResult.SKIPPED;
}
for (Manifest... | Set<MavenInfo> maven = new HashSet<MavenInfo>();
ManifestInfo manifest = new ManifestInfo(new java.util.jar.Manifest(this.getClass().getResourceAsStream("/org/hotswap/agent/versions/matcher/TEST.MF")));
DeploymentInfo info = new DeploymentInfo(maven, Collections.singleton(manifest));
S... |
14573998_10 | class Index {
public <R> Stream<T2<Optional<L>, R>> rightOuterJoin(Index<K, R> other) {
return matchAndMerge(other, rightOuterJoinMerger());
}
private Index(Comparator<? super K> comparator, SortedMap<K, Set<L>> indexed);
public static Index<K, L> on(Stream<? extends L> stream, Function<? su... | Index<Character, String> left = Index.on(Stream.of("carrot", "banana", "apple"), indexOnFirstChar);
Index<Character, String> right = Index.on(Stream.of("catamorphism", "banausic", "ballistic", "dirigible"), indexOnFirstChar);
assertThat(left.rightOuterJoin(right).collect(Collectors.toList()), h... |
14581444_89 | class Results {
public static Result internalServerError() {
return status(Result.INTERNAL_SERVER_ERROR).noContentIfNone();
}
public static Result status(int statusCode);
public static Result ok();
public static Result ok(Document document);
public static Result ok(JsonNode node);
... | Result result = Results.internalServerError("nope");
assertThat(result.getStatusCode()).isEqualTo(Status.INTERNAL_SERVER_ERROR);
assertThat(result.getRenderable().content()).isEqualTo("nope");
assertThat(result.getContentType()).isEqualTo(MimeTypes.TEXT);
}
} |
14587858_44 | class OSGiELResolver extends BeanELResolver {
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
}
@Override public Object getValue(ELContext context, Object base, Object property);
private Object checkRegisteredServicesByLdapFilter(String filter);
priv... | assertThat(resolver.isReadOnly(null, null, null), is(true));
}
} |
14591946_17 | class ProcessorpathResolver {
public List<File> resolve(RepositorySystemSession session, MavenProject project, List<Dependency> dependencies) throws MojoExecutionException {
// copy&paste from org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DependencyResolutionRequest)
// aether is sad, r... | File basedir = resources.getBasedir();
MavenProject project = maven.readMavenProject(basedir);
maven.newDependency(temp.newFile()).setGroupId("g").setArtifactId("a").setVersion("1").addTo(project);
MavenSession mavenSession = maven.newMavenSession(project);
RepositorySystemSession repoSession = mav... |
14612017_22 | class VelocityBodyContent extends BodyContent {
@Override
public void write(char[] cbuf, int off, int len) throws IOException
{
getEnclosingWriter().write(cbuf, off, len);
}
public VelocityBodyContent(JspWriter jspWriter, ASTBlock block,
InternalContextAdapter context);
@... | jspWriter.write(aryEq("hello".toCharArray()), eq(1), eq(3));
replay(jspWriter, block, context);
content.write("hello".toCharArray(), 1, 3);
verify(jspWriter, block, context);
}
} |
14616420_40 | class PropertiesBasedTraceeFilterConfiguration implements TraceeFilterConfiguration {
@Override
public Map<String, String> filterDeniedParams(final Map<String, String> unfiltered, final Channel channel) {
final Map<String, String> filtered = new HashMap<>(unfiltered.size());
for (Map.Entry<String, String> entry ... | final Map<String, String> unfiltered = Collections.singletonMap("Foo", "Bar");
assertThat(unit.filterDeniedParams(unfiltered, Channel.IncomingRequest), equalTo(Collections.<String, String>emptyMap()));
}
} |
14640193_0 | class MiscUtils {
public static Date parseLogcatTimeStamp(String line) {
Matcher matcher = LOGCAT_TIMESTAMP_PATTERN.matcher(line);
if (matcher.find()) {
int month = Integer.valueOf(matcher.group(1));
int day = Integer.valueOf(matcher.group(2));
int hour = Integ... | Date date = MiscUtils.parseLogcatTimeStamp("03-31 01:04:39.348 14308-14308/com.SecUpwN.AIMSICD I/SignalStrengthTracker: Ignored signal sample for");
assertEquals(2, date.getMonth()); //Month is 0 based
assertEquals(31, date.getDate());
assertEquals(1, date.getHours());
assertEq... |
14660359_5 | class MigdalorHeaderByteSerializer implements MigdalorHeaderSerializer<BaseMigdalorHeader,String> {
@Override
public String getRevisionAndReposition(ByteBuffer payload) {
int version = payload.getInt();
if (version == PROTOCOL_VERSION){
int schemaVersionSize = payload.getInt();
... | ByteBuffer bytes = ByteBuffer.allocate(10);
bytes.putInt(1);
Assert.assertNull(migdalorHeaderByteSerializer.getRevisionAndReposition(bytes));
}
} |
14661616_12 | class ItemFormatBuilder {
public int getTokenCount(){
return this.tokens.size();
}
public ItemFormatBuilder();
public ItemFormatBuilder(Class<T> targetType);
public Class<T> getTargetType();
public ItemFormatBuilder<T> withStyle(LocalizationContext style);
public ItemFormatBuild... | ItemFormatBuilder<Double> b = new ItemFormatBuilder<Double>(
Double.class);
b.append("1");
b.append("2");
assertEquals(2, b.getTokenCount());
}
} |
14696091_353 | class DeclaringMethodMatcher extends ElementMatcher.Junction.AbstractBase<T> {
public boolean matches(T target) {
return matcher.matches(target.getDeclaredMethods());
}
public DeclaringMethodMatcher(ElementMatcher<? super MethodList<? extends MethodDescription>> matcher);
@Override public St... | when(typeDescription.getDeclaredMethods()).thenReturn((MethodList) methodList);
when(methodMatcher.matches(methodList)).thenReturn(true);
assertThat(new DeclaringMethodMatcher<TypeDescription>(methodMatcher).matches(typeDescription), is(true));
verify(methodMatcher).matches(methodList);
... |
14718267_48 | class AllureModelUtils {
public static Label createStoryLabel(String story) {
return createLabel(LabelName.STORY, story);
}
AllureModelUtils();
public static Validator getAllureSchemaValidator();
public static Label createFeatureLabel(String feature);
public static Label createSever... | Label label = AllureModelUtils.createStoryLabel("some-story");
assertThat(label.getValue(), is("some-story"));
assertThat(label.getName(), is(LabelName.STORY.value()));
}
} |
14734876_83 | class MultiLayerNetworkHandler implements INetworkHandler {
@Override
public void applyGradient(Gradients gradients, long batchSize) {
BaseNetwork.ModelCounters modelCounters = getModelCounters();
int iterationCount = modelCounters.getIterationCount();
Gradient gradient = gradients.getG... | // Arrange
setup(false);
Gradients gradientsMock = mock(Gradients.class);
final Gradient gradient = mock(Gradient.class);
INDArray gradientGradient = Nd4j.rand(1, 2);
when(gradient.gradient()).thenReturn(gradientGradient);
when(gradientsMock.getGradient(GRADIENT_N... |
14741882_14 | class ByteArray implements Comparable<ByteArray> {
@Override
public int compareTo(ByteArray that) {
int thisLength = this.byteArrayValue().length;
int res = thisLength - that.byteArrayValue().length;
if (res != 0)
return res;
for (int i = 0; i < thisLength; i++) {
... | byte[] a = new byte[] {1, 2, 3};
byte[] b = new byte[] {2, 3, 1};
assertTrue(new ByteArray(a).compareTo(new ByteArray(b)) < 0);
}
} |
14755049_47 | class HttpUtil {
public static HttpResponse httpGet(String url, int timeoutms)
throws IOException, URISyntaxException {
return httpGet(url, null, timeoutms);
}
public static HttpResponse httpGet(String url, Map<String, String> requestHeaders, int timeoutms);
public static InputStre... | List<byte[]> responses = HttpUtil.httpGet(urlList, 3, 0);
assertNotNull("null response list", responses);
for (byte[] response : responses) {
assertNotNull("null response", response);
}
}
} |
14775640_6 | class Actions {
public boolean perform(Class actionClass, Object... args)
throws ArgumentsValidationException {
Action action = getAction(actionClass);
if (action != null && action.isEnabled()) {
if (action.validate(args)) {
Gdx.app.debug("Controller",
ClassReflection.getSimpleName(actionClass)
... | try {
actions.perform(EmptyValidArguments.class);
actions.perform(TwoArgumentsAction.class, "", true);
// the three different possibilities for MultipleValidArguments
actions.perform(MultipleValidArguments.class, "", true);
actions.perform(MultipleValidArguments.class);
actions.perform(MultipleVal... |
14778255_0 | class GitBlitRepository {
public final static Long makeByteValue(String value){
if(value == null || value.isEmpty()){
return null;
}
try{
String size = value;
long f = 1L;
// Using 1000 instead of 1024 to avoid multiplications
size = size.trim().toLowerCase();
if(size.endsWith(" b")){
size... |
Long exp = new Long(12345678901L);
// Check formatting
assertEquals(exp, GitBlitRepository.makeByteValue("123.4567.8901,23456"));
assertEquals(exp, GitBlitRepository.makeByteValue("123,4567,8901.23456"));
assertEquals(exp, GitBlitRepository.makeByteValue("123'4567'8901,23456"));
assertEquals(exp, GitBlit... |
14792686_0 | class SongsGateway extends BaseApiGateway {
public void querySongsByChannelId(ReportType songType, String currentSongId, int playTime, int channelId, BitRate bitRate, Callback callback) {
if(channelId== ChannelConstantIds.PRIVATE_CHANNEL
||channelId== ChannelConstantIds.FAV){
th... | songsGateway.querySongsByChannelId(ReportType.NEXT_QUEUE, "1", 10, ChannelConstantIds.PRIVATE_CHANNEL,BitRate.HIGH, new Callback());
apiGateway.simulateTextResponse(200, TestResponses.ROCK_CHANNELS_SONGS_JSON, null);
assertNotNull(Douban.songs);
assertThat(Douban.songs.size(), equalTo(2)... |
14795578_4 | class Annotation extends AnnotationBase implements AnnotationImpl {
@Override
public void trim(IntPredicate aIsTrimChar) {
int begin = getBegin();
int end = getEnd();
String text = _casView.getDocumentText();
// If the span is empty, or there is no text, there is nothing to trim
if (begi... | cas.setDocumentText(" a b ");
AnnotationFS ann = cas.createAnnotation(cas.getAnnotationType(), 2, 5);
ann.trim();
assertThat(ann)
.extracting(AnnotationFS::getBegin, AnnotationFS::getEnd, AnnotationFS::getCoveredText)
.containsExactly(3, 4, "b");
}
} |
14807800_4 | class Split {
private Split() {
}
private Split();
public static void main(final String[] args);
private static final int USERS;
private static final int ITEMS;
}
class SplitTest {
private static final int USERS;
private static final int ITEMS;
@Test
public void testCros... | DataModelIF<Long, Long> dm = DataModelFactory.getDefaultModel();
for (long u = 1L; u <= USERS; u++) {
for (long i = 1L; i <= ITEMS; i++) {
dm.addPreference(u, i, 1.0 * u * i);
}
}
int nFolds = 5;
DataModelIF<Long, Long>[] splits = null;
... |
14829187_93 | class Datasets {
public static boolean moveToTrash(URI uri) {
return deleteWithTrash(uri, true);
}
@SuppressWarnings("unchecked") public static V load(URI uri, Class<E> type);
@SuppressWarnings("unchecked") public static V load(URI uri);
public static V load(String uriString, Class<E> type);
public st... | final URI datasetUri = new URIBuilder(repoUri, "ns", "test")
.with("field", 34)
.build();
TestHelpers.assertThrows("Should reject view URI",
IllegalArgumentException.class, new Runnable() {
@Override
public void run() {
Datasets.moveToTrash(datasetUri);
... |
14841479_3 | class ZoneMinderUtils {
public static boolean pingHost(String host) throws IOException {
InetAddress inet = InetAddress.getByName(host);
return inet.isReachable(5000);
}
public static String shutdownZmHost(String host, String username, String password);
}
class ZoneMinderUtilsTest {
@Test
@Ignore
public... | assertTrue(ZoneMinderUtils.pingHost("ubuntu-zm"));
}
} |
14865444_43 | class ClassUtil {
public static Object invoke(final Object instance, final Method method, final Object... args) {
Assertion.check()
.isNotNull(instance)
.isNotNull(method);
//-----
try {
return method.invoke(instance, args);
} catch (final IllegalAccessException e) {
throw WrappedException.wrap(... | final Method addMethod = ClassUtil.findMethod(MyMath.class, "add", long.class, long.class);
final Object result = ClassUtil.invoke(new MyMath(), addMethod, 4L, 6L);
assertEquals(10L, result);
}
} |
14882085_0 | class DefaultRequestHandler implements RequestHandler {
@Override
public SiriusResult handleGet(String key) {
String value = RefAppState.repository.get(key);
if (value == null) {
return SiriusResult.none();
}
return SiriusResult.some(value);
}
@Override pu... | String key = "a";
doReturn(null).when(mockRepository).get(key);
assertEquals(SiriusResult.none(), underTest.handleGet(key));
}
} |
14884127_0 | class ProgressEvent extends GwtEvent<Handler> {
public boolean isLengthComputable()
{
return 0 != _total;
}
public ProgressEvent( final int loaded, final int total );
public static GwtEvent.Type<Handler> getType();
public int getLoaded();
public int getTotal();
@Override public GwtEvent.Type<Han... | assertFalse( new ProgressEvent( 0, 0 ).isLengthComputable() );
assertTrue( new ProgressEvent( 1, 2 ).isLengthComputable() );
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.