id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
2742247_3 | class InfinispanSessionManager extends ManagerBase {
public String getCacheName(){
return this.cache.getName();
}
@Override public String getInfo();
@Override public String getName();
@Override public void load();
@Override public void unload();
@Override protected synchronized voi... | InfinispanSessionManager managerOne = createSessionManager("zzz");
InfinispanSessionManager managerTwo = createSessionManager("zzz");
InfinispanSessionManager managerThree = createSessionManager("zzz");
assertEquals("tc_session_contextNamezzz", managerOne.getCacheName());
assert... |
2747986_8 | class SOAPMailSender extends MailSender {
public MimeMessage createMessage(String from, String to, String cc,
String subject, SOAPMessage soapMessage) throws ConnectionException {
return createMessage(from, to, cc, subject, soapMessage, createSession());
}
public SOAPMailSender(String... | SOAPMessage soapMessage = null;
MimeMessage mimeMsg = null;
MimeHeaders mimeHeaders = new MimeHeaders();
InputStream contentStream = FIXTURE_LOADER.getResourceAsStream("mime_message_content.dat");
mimeHeaders.setHeader("Content-Type", "text/xml; charset=utf-8");
... |
2752522_464 | class JTextReporter {
public static Connection showDialog(String title) {
return showDialog(title, null);
}
public static Connection showDialog(String title, String initialText);
public static Connection showDialog(String title, String initialText, int flags);
public static Connection show... | Connection conn = showDialog(TITLE, TEXT[0] + "\n").get();
final int N = 10;
conn.appendSeparatorLine(N);
char[] chars = new char[N];
Arrays.fill(chars, JTextReporter.DEFAULT_SEPARATOR_CHAR);
String expected = String.format("%s%n%s%n", TEXT[0], String.valueOf(chars));
... |
2755429_1 | class NicoLiveSAXHandler extends DefaultHandler {
public String innerText() {
return sbuf.toString();
}
public void start(String uri,
String localName,
String qName,
Attributes attributes);
@Override public final void startEleme... | SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
sax.parse(in, new NicoLiveSAXHandler() {
@Override
public void end(String uri, String localName, String qName) {
if (qName.equals("elem")) {
assertThat(innerText(), is("content"));... |
2784782_5 | class IconController extends ApiController {
@RequestMapping(value = "/{icon:.+}", method = RequestMethod.GET)
public HttpEntity raw(@PathVariable String icon) throws IOException {
return raw(null, icon);
}
@Autowired public IconController(GeoServer geoServer);
@RequestMapping(value = "/... | MockGeoServer.get().catalog()
.resources()
.resource("workspaces/foo/styles/one.yaml", "title: raw")
.directory("workspaces/foo/styles")
.resource("workspaces/foo/styles/icon.png", "PNG8")
.resource("workspaces/foo/styles/symbols.TTF", "TTF")
.directory(... |
2791813_183 | class ParalysisEffect implements Effect {
@Override
public boolean appliesTo(Character caster, Character target) {
if (target.isDead()) {
return false;
}
return true;
}
@Override public void apply(Character caster, Character target);
@Override public boolean appliesTo(Character caster, WorldObject wo... | final Character caster = mock(Character.class);
final Character deadTarget = mock(Character.class);
when(deadTarget.isDead()).thenReturn(Boolean.TRUE);
final Character aliveTarget = mock(Character.class);
// Paralyzing a dead char is invalid.
assertFalse(paralysisEffect.appliesTo(caster, deadTarget));
/... |
2803695_0 | class CoherenceCacheProvider implements CachingProvider {
@Override
public boolean isSupported(OptionalFeature optionalFeature) {
return false;
}
@Override public CacheManagerFactory getCacheManagerFactory();
}
class CoherenceCacheProviderTest {
@Test
public void testIsSupported() {... | CachingProvider cacheProvider = getCachingProvider();
for (OptionalFeature feature: OptionalFeature.values()) {
assertFalse(cacheProvider.isSupported(feature));
}
}
} |
2818491_3 | class AnnotationDetector {
public void detect() throws IOException {
detect(new ClassFileIterator());
}
public AnnotationDetector(final Reporter reporter);
public void detect(final String... packageNames);
public void detect(final File... filesOrDirectories);
private File toFile(fina... | final long time = System.currentTimeMillis();
@SuppressWarnings("unchecked")
final CountingReporter counter = new CountingReporter(Test.class);
final AnnotationDetector cf = new AnnotationDetector(counter);
cf.detect("eu.infomas"); // only this package and sub package(s) are sca... |
2845921_1 | class Calculator {
public void enter(char c) {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
state.processDigit(c);
break;
case '.':
state.processDot();
... | try {
calculator.enter('A');
throw new AssertionFailureNotDetectedError();
}
catch (IllegalArgumentException e) {
assertEquals(e.getMessage(), "Character 'A' is not supported");
}
}
} |
2851858_9 | class CheckBoxPropertyEditor extends AbstractFormComponentPropertyEditor {
public static PropertyEditorProvider getProvider() {
return PROVIDER;
}
public CheckBoxPropertyEditor(String id, PropertyMetaData propertyMetaData, CheckBox checkBox);
@Override public void required(boolean required);... | BeanMetaData beanMetaData = Wicketopia.get().getBeanMetaData(EditableBean.class);
EditableBean bean = new EditableBean();
final IModel<Boolean> model = new PropertyModel<Boolean>(bean, "bool");
bean.setBool(true);
Context context = new Context(Context.CREATE);
EditorBuild... |
2854377_35 | class PartnerConnectionImpl extends AbstractSalesforceConnection implements PartnerConnection {
@Nonnull
@Override
public synchronized List<SObject> retrieve(@Nonnull String sObjectType, @Nonnull List<Id> ids,
@Nonnull List<String> fieldList) throws ApiException {
logger.entry(sObjectTy... | List<Id> ids = new ArrayList<Id>();
ids.add(new Id("0035000000km1oh"));
List<SObject> results = this.conn.retrieve("Contact", ids, Arrays.asList("FirstName", "LastName"));
assertEquals(1, results.size());
SObject contact = results.get(0);
assertEquals("0035000000km1oh", ... |
2858655_84 | class FeatureServiceReflectionFactory extends AbstractFeatureServiceFactory {
protected Environment getEnvironment(final Properties properties, String... packagesToSearch)
{
final Environment environment = new Environment();
if (properties != null)
{
environment.setProperti... | Environment environment = factory.getEnvironment(null, "com.tacitknowledge.flip.fixtures", "com.tacitknowledge.flip.otherfixtures");
assertNotNull(environment);
Assert.assertTrue(environment.getProperties().isEmpty());
assertTrue(isListHasItemOfType(environment.getPrope... |
2874089_0 | class XMLUtils {
public static boolean validate( File f ) {
try {
SAXParser parser = factory.newSAXParser();
parser.setProperty( Constants.XML_SCHEMA_PROPERTY, Constants.XML_SCHEMA_LANGUAGE );
SimpleErrorHandler errorHandler = new SimpleErrorHandler();
SAXReader reader = new SAXReader( ... | boolean valid = XMLUtils.validate(new File("src/test/resources/valid.xml"));
Assert.assertTrue(valid);
}
} |
2882681_1 | class TrackingManager {
public static Tracking search(String id) throws EncomendaZException {
return search(id, null, null, null);
}
private static void validateParameters(String id);
public static boolean isValidId(String id);
public static Tracking search(String trackId, Integer start, Integer end, String cl... | Tracking tracking = TrackingManager.search("PB261442824BR");
assertTrue(tracking.isCompleted());
}
} |
2885102_12 | class JSONDecoder {
public JSONValue decode() {
char current = reader.current();
if(current == Opener.OBJECT.sign) {
return decodeObject();
} else if(current == Opener.STRING.sign) {
return decodeString();
} else if(current == Opener.ARRAY.sign) {
... | JSONDecoder decoder =
new JSONDecoder("[null,true,12,false,\"BLA\"]");
JSONValue result = decoder.decode();
TestCase.assertEquals("[null,true,12,false,\"BLA\"]", result.toJSON());
}
} |
2885902_8 | class TriangulatingFaceReader implements ElementReader {
@Override
public ElementType getElementType() {
return reader.getElementType();
}
TriangulatingFaceReader(final ElementReader reader);
@Override public int getCount();
@Override public Element readElement();
@Override publ... |
ElementType type = new ElementType(
"face",
new ListProperty(
DataType.UCHAR,
"vertex_index", DataType.INT));
ElementReader reader = mock(ElementReader.class);
when(reader.getElementType()).thenReturn(type);
Triangulating... |
2899580_56 | class AggregateSnapshotter extends AbstractSnapshotter {
@SuppressWarnings("unchecked")
@Override
protected DomainEventMessage createSnapshot(Class<?> aggregateType,
String aggregateIdentifier,
DomainEventStream... | void testCreateSnapshot_AggregateMarkedDeletedWillNotGenerateSnapshot() {
String aggregateIdentifier = UUID.randomUUID().toString();
DomainEventMessage firstEvent = new GenericDomainEventMessage<>("type", aggregateIdentifier, (long) 0,
... |
2907398_1 | class SendEmailTask implements DeferredTask {
@Override
public void run() {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);
try {
if (email.getFromPersonal().equals(EmailBuil... | //given
Email email = mock(Email.class);
when(email.getFromAddress()).thenReturn("a@a.com");
when(email.getFromPersonal()).thenReturn("A Personal");
when(email.getTo()).thenReturn("b@b.com");
when(email.getReplyToAddress()).thenReturn("c@c.com");
Transport transpo... |
2916790_3 | class PostgresKB implements KnowledgeBase {
@Override
public ResultSetCursor getOutgoingRelations(int[] instances)
throws Exception {
final StringBuilder b = new StringBuilder();
for (int i : instances) {
b.append('(');
b.append(i);
b.append(')');
b.append(',');
}
String sql = "SELECT relatio... | Connection conn = pool.getConnection();
ResultSet rs = conn.createStatement().executeQuery(
"SELECT uri FROM index_resources");
while (rs.next()) {
String uriFromDB = rs.getString(1);
int key = kb.getUriIndex(uriFromDB);
RemoteCursor cursor = kb
.getOutgoingRelations(new int[] { key });
whi... |
2928039_24 | class NumberFormatTransformer extends Transformer {
@SuppressWarnings("unchecked")
public Object transformRow(Map<String, Object> row, Context context) {
VariableResolver resolver = context.getVariableResolver();
for (Map<String, String> fld : context.getAllEntityFields()) {
String style = resolver.r... | List fields = new ArrayList();
fields.add(AbstractDataImportHandlerTest.createMap(DataImporter.COLUMN,
"inputs"));
fields.add(AbstractDataImportHandlerTest.createMap(DataImporter.COLUMN,
"outputs", RegexTransformer.SRC_COL_NAME, "inputs",
NumberFormatTransformer.FORMAT_ST... |
2930574_3 | class LocalStreamService extends AbstractService {
Map<Path, Path> populateTrashCommitPaths(Set<FileStatus> trashSet) {
// find trash paths
Map<Path, Path> trashPaths = new TreeMap<Path, Path>();
Path trash = cluster.getTrashPathWithDateHour();
Iterator<FileStatus> it = trashSet.iterator();
while... | FileStatus[] status = new FileStatus[10];
String[] expectedstatus = new String[10];
status[0] = new FileStatus(20, false, 3, 23823, 2438232, new Path(
"/databus/data/test1/testcluster1/test1-2012-08-29-07-09_00000"));
status[1] = new FileStatus(20, false, 3, 23823, 2438232, new Path(
... |
2934254_65 | class OpenTSDBMessageFormatter {
public Iterable<String> formatResults(Iterable<Result> results, final Server server) {
return from(results).transformAndConcat(new Function<Result, List<String>>() {
@Override
public List<String> apply(Result input) {
return formatResult(input, server);
}
}).toList(... |
Map<String, String> tagMap;
// Verify tag map with multiple values.
tagMap = newHashMap();
tagMap.put("x-tag1-x", "x-tag1val-x");
tagMap.put("x-tag2-x", "x-tag2val-x");
tagMap.put("x-tag3-x", "x-tag3val-x");
OpenTSDBMessageFormatter formatter =
new OpenTSDBMessageFormatter(ImmutableList.of("Type", ... |
2945916_56 | class Fields {
public static AddressListField cc(Address address) {
return addressList0(FieldName.CC, Collections.singleton(address));
}
private Fields();
public static MimeVersionField version(String ver);
public static ContentTypeField contentType(String contentType);
public static... | Mailbox mailbox1 = DefaultAddressParser.DEFAULT.parseMailbox("JD <john.doe@acme.org>");
Mailbox mailbox2 = DefaultAddressParser.DEFAULT.parseMailbox("jane.doe@example.org");
Mailbox mailbox3 = DefaultAddressParser.DEFAULT.parseMailbox("Mary Smith <mary@example.net>");
Group group = new G... |
2948043_16 | class LinksInjector {
public void inject(Object entity, RESTServiceDiscovery restServiceDiscovery) {
Field injectionField = findInjectionField(entity);
if (injectionField == null) {
return;
}
RESTServiceDiscovery fieldValue = null;
try {
injectionFie... | RESTServiceDiscovery initialLinks = new RESTServiceDiscovery();
initialLinks.addLink(URI.create("https://resteasy.github.io"), "resteasy");
EntityWithLinks entity = new EntityWithLinks(initialLinks);
RESTServiceDiscovery newLinks = new RESTServiceDiscovery();
newLinks.addLink(UR... |
2964129_9 | class SocketIOFrameHelper {
public static String encodeJSONMessage(final long messageID, final String endPoint, final String data) {
return SocketIOFrameGenerator.encode(FrameType.JSON, messageID, false, endPoint, data, null);
}
public static String encodeDisconnect();
public static String encodeDisconnect(fina... | String expected = "4:" + MSGID + ":" + ENDPOINT + ":" + JSONData;
String result = SocketIOFrameHelper.encodeJSONMessage(MSGID, ENDPOINT, JSONData);
assertTrue(result.equals(expected));
}
} |
2974683_0 | class InputBytes extends ByteArrayInputStream implements Input {
@Override
public synchronized int read(long pos, byte[] b, int start, int len)
throws IOException {
this.pos = (int)pos;
return read(b, start, len);
}
public InputBytes(byte[] data);
public InputBytes(ByteBuffer data);
@Overri... | Random random = new Random();
int length = random.nextInt(SIZE);
byte[] data = new byte[length];
random.nextBytes(data);
Input in = new InputBytes(data);
for (int i = 0; i < COUNT; i++) {
int p = random.nextInt(length);
int l = Math.min(random.nextInt(SIZE/10), length-p);
... |
2978404_14 | class JmsPropertyScanner {
public void scan(Object object) {
try {
scan(object, "", false, new ArrayList<Object>());
} catch (JMSException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
... | MapContainer pojo = new MapContainer();
scanner.scan(pojo);
verify(visitor).visit("map", pojo, MapContainer.class.getField("map"));
}
} |
2988101_135 | class ResetSchema {
@OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel target) throws OperationException {
resetSchemaProperties(target);
if (saveDocument) {
target = session.saveDocument(target);
if (save) {
... | String schema = "common";
assertTrue(target1.hasSchema(schema));
target1.setProperty(schema, "icon-expanded", "icon-expanded1");
target1.setProperty(schema, "icon", "icon1");
context.setInput(target1);
OperationChain chain = new OperationChain("testSingleTargetFullSchem... |
2988709_13 | class JenaGraph implements Graph {
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
@SuppressWarnings( { "ThrowableInstanceNeverThrown" }) protected static RuntimeException wrapException(Exception e);
protected GraphConnection openGraph();
protect... | Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("dummy", "http://dummy");
boolean forceReload = false;
Model jenaGraph = graph.openGraph(forceReload).getGraph();
Map<String, String> map = jenaGraph.getNsPrefixMap();
// old namespaces are ke... |
2988715_4 | class NavTreeService extends DefaultComponent {
public List<NavTreeDescriptor> getTreeDescriptors() {
return registry.getTreeDescriptors(getDirectoryTreeService());
}
@Override public void activate(ComponentContext context);
@Override public void deactivate(ComponentContext context);
@Over... | NavTreeService service = Framework.getLocalService(NavTreeService.class);
assertNotNull(service);
List<NavTreeDescriptor> descs = service.getTreeDescriptors();
assertEquals(2, descs.size());
NavTreeDescriptor desc = descs.get(0);
assertEquals("/incl/tag_cloud.xhtml", de... |
2988721_0 | class PackageBuilder {
public PackageBuilder() {
def = new PackageDefinitionImpl();
platforms = new ArrayList<>();
dependencies = new ArrayList<>();
conflicts = new ArrayList<>();
provides = new ArrayList<>();
entries = new LinkedHashMap<>();
installForms = n... | PackageBuilder builder = new PackageBuilder();
builder.name("nuxeo-automation").version("5.3.2").type(
PackageType.ADDON);
builder.title("Nuxeo Automation").description(
"The automation framework");
builder.platform("dm-5.3.2");
builder.dependency(... |
2988725_41 | class LDAPSession extends BaseSession implements EntrySource {
@Override
public DocumentModelList getEntries() throws DirectoryException {
try {
SearchControls scts = directory.getSearchControls();
if (log.isDebugEnabled()) {
log.debug(String.format(
... | Session session = getLDAPDirectory("userDirectory").getSession();
try {
DocumentModelList entries = session.getEntries();
assertNotNull(entries);
assertEquals(4, entries.size());
List<String> entryIds = new ArrayList<String>();
for (DocumentMod... |
2989006_0 | class SampleOperation {
@OperationMethod
public DocumentModel run() {
if (StringUtils.isBlank(path)) {
return session.getRootDocument();
} else {
return session.getDocument(new PathRef(path));
}
}
@Inject
protected CoreSession session;
@Inject
... | OperationContext ctx = new OperationContext(session);
DocumentModel doc = (DocumentModel) automationService.run(ctx, SampleOperation.ID);
assertEquals("/", doc.getPathAsString());
}
} |
2990192_10 | class SkippingOutputStream extends FilterOutputStream {
public void write(int b) throws IOException {
if (toSkip > 0) {
toSkip--;
} else {
out.write(b);
}
}
public SkippingOutputStream(long toSkip, OutputStream wrapped);
public void write(byte[] b);
public void write(byte[] b, int ... | // GIVEN
byte[] expected = new byte[]{1, 2, 3, 4, 5};
SkippingOutputStream testSubject = new SkippingOutputStream(0, outputStream);
// WHEN
testSubject.write(expected, 1, 3);
// THEN
assertEquals(3, outputStream.toByteArray().length);
assertArrayEquals(new byte[]{2, 3,... |
2992799_3 | class ConditionalAttributeBehavior extends ModifyingTagBehavior {
@Override
public String toString() {
return "ConditionalAttributeBehavior{" +
"expression=" + expression +
", attribute=" + attribute +
", line=" + line +
", col=" + col +
... | try {
TemplateTokenizer tokenizer = new TemplateTokenizer(ConditionalAttributeBehaviorTest.class.getResourceAsStream("conditionalattribute.html"));
TemplateParser parser = new TemplateParser(tokenizer, Expressions.cambridgeExpressionLanguage);
ExpressionContext context = new MapExpressi... |
2995118_78 | class AssociationMappingErrorService {
public Map<String, String> createAssociationErrorMap(AssociationReport associationReport) {
Map<String, String> associationErrorMap = new HashMap<>();
//Create map of errors
if (associationReport != null) {
if (associationReport.getSnpErr... |
// Checking return type
HashMap map = new HashMap();
Map<String, String> returnedMap = associationMappingErrorService.createAssociationErrorMap(associationReport);
assertEquals(returnedMap, map);
// Stubbing behaviour of AssociationReport
when(associationReport.getSnpEr... |
2997701_136 | class StatsBuffer {
public int getCount() {
return curSize;
}
public StatsBuffer(int size, double[] percentiles);
private static boolean validPercentiles(double[] percentiles);
public void reset();
public void record(long n);
public void computeStats();
private void computePercentiles(int curSiz... | StatsBuffer buffer = getNoWrap();
assertEquals(buffer.getCount(), SIZE / 2 + 1);
}
} |
3010630_0 | class WSBACoordinatorCompletionParticipant extends WSBAParticipantCompletionParticipant implements
BusinessAgreementWithCoordinatorCompletionParticipant {
public void complete() throws WrongStateException, SystemException {
invoke(Complete.class);
}
public WSBACoordinatorCompletionPartic... |
LifecycleImpl lifecycle = new LifecycleImpl();
ServiceInvocationMeta serviceInvocationMeta = new ServiceInvocationMeta(lifecycle, LifecycleImpl.class, null);
WSBACoordinatorCompletionParticipant participant = new WSBACoordinatorCompletionParticipant(serviceInvocationMeta, new HashMap());
... |
3016145_9 | class LayeredTokenPattern {
public LayeredTokenMatcher matcher(LayeredSequence seq)
throws SequenceException {
String encoded = encodeSequence(seq);
Matcher m = encodedPattern.matcher(encoded);
return new LayeredTokenMatcher(m);
}
public LayeredTokenPattern(String patt... | String patternStr = "There_w are_w CD_p [B-NP_n I-NP_n]+ (IN_p [B-NP_n I-NP_n]+)*";
LayeredTokenPattern pat = new LayeredTokenPattern(patternStr);
LayeredTokenMatcher m = pat.matcher(seq);
assertTrue(m.find());
assertEquals(0, m.start());
assertEquals(6, m.end());
}
} |
3020895_48 | class ProducingDoubleDataSource extends BufferedDoubleDataSource implements Runnable {
public void start() {
dataProducingThread = new Thread(this);
dataProducingThread.setDaemon(true);
dataProducingThread.start();
}
protected ProducingDoubleDataSource();
protected ProducingDoubleDataSource(long numDataTh... | int numDoubles = 10;
TestProducer producer = new TestProducer(numDoubles);
producer.start();
assertEquals(numDoubles, producer.getDataLength());
double[] data = producer.getAllData();
assertEquals(numDoubles, data.length);
}
} |
3026246_81 | class BCHelper {
public static void registerProvider() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null)
Security.addProvider(new BouncyCastleProvider());
}
public static MessageDigest getMessageDigest(String algorithm);
}
class BCHelperTest {
@Test
pub... | if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) != null)
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
Assert.assertNull(Security.getProvider(BouncyCastleProvider.PROVIDER_NAME));
BCHelper.registerProvider();
Provider provider = Security.getProv... |
3028163_81 | class TogglzEndpoint {
@WriteOperation
public TogglzFeature setFeatureState(@Selector String name, boolean enabled) {
final Feature feature = featureManager.getFeatures().stream()
.filter(f -> f.name().equals(name))
.findFirst()
.orElseThrow(() -> new Ill... | contextRunner.withConfiguration(AutoConfigurations.of(
DispatcherServletPathConfig.class,
TogglzAutoConfiguration.class,
TogglzEndpointAutoConfiguration.class))
.withPropertyValues(
"management.endpoints.web.exposure.include... |
3050780_1 | class URLInformation {
public String getPublicationId() {
if (this.publicationId == null) {
this.publicationId = extractBeforeSlash(this.url);
}
return this.publicationId;
}
public URLInformation();
private void setSourceURL(String webappUrl);
public String ge... | URLInformation urli = new URLInformation();
String pubId = urli.getPublicationId();
assertEquals(pubId,"test");
}
} |
3061876_8 | class LogUtils {
public static String maskApiKey(final String key) {
int visibleChars = (int) (0.1 * key.length());
int right = visibleChars / 2;
int left = visibleChars - right; // left >= right
String beginning = key.substring(0, left);
String end = key.substring(key.length() - right);
return beginning... |
Assert.assertEquals("N708W...5015S", LogUtils.maskApiKey("N708W589120i0Tn984uwX6Z9c8582ccyN42Ah9PG18sO66bOCGf46sann382306D203304s2RowSA628G7KeWx1h2A8657H5015S"));
Assert.assertEquals("PJGt...ube", LogUtils.maskApiKey("PJGttqarjMhhBYddWFKxwfZEqGERCDJCZHuveHwfUFJgokYfxupwKWyFHDGlcVRDCzgBDnRHeube"));
Assert.assertE... |
3069429_0 | class TweetParser {
protected Map<String, Integer> tokenize(String text) {
Map<String, Integer> tokenMap = newHashMap();
StringTokenizer st = new StringTokenizer(text, "\"{}[]:;|<>?`'.,/~!@#$%^&*()_-+= \t\n\r\f\\");
while (st.hasMoreTokens()) {
String token = st.nextToken();
... | String text = "Twitter is an online social networking service and microblogging service" //
+ " that enables its users to send and read text-based posts of up to 140 characters," //
+ " known as \"tweets\". You can signup and test it yourself.";
Map<String, Integer> token... |
3086072_0 | class SettingActivity extends PreferenceActivity {
@Background
public void loadProject() {
try {
projectUserRelationDao.delete(projectUserRelationDao.queryForAll());
List<Status> statuses = backlogService.getStatuses();
for (Status status : statuses) {
statusDao.createOrUpdate(status);
Ln.d("pu... | Robolectric.application.onCreate();
SettingActivity activity = new SettingActivity();
assertThat(activity, is(notNullValue()));
((RoboApplication)Robolectric.application).getInjector().injectMembers(activity);
assertThat(activity.priorityDao , is(notNullValue()));
BacklogService backlogService = create... |
3102907_0 | class AccessRequest extends RadiusPacket {
protected String createMSCHAPV2Response(String username, byte[] password, byte ident, byte[] ntResponse, byte[] peerChallenge, byte[] authenticator) {
byte[] authResponse = Authenticator.GenerateAuthenticatorResponse(
password,
ntResponse,
peerCh... | String username = "gerhard";
String password = "test12345";
/*
* byte[] authenticatorChallenge = new byte[] { 0x54, 0x6c, (byte) 0xa8,
* (byte) 0x9c, 0x30, 0x36, 0x49, (byte) 0xcf, 0x30, 0x2d, (byte) 0x89,
* 0x79, (byte) 0x99, (byte) 0xcc, 0x70, (byte) 0xa0 };
*
* byte[] responseData = new byte[]... |
3110085_1 | class BankingService {
@Compensatable
public void transferMoney(String fromAccount, String toAccount, Double amount) {
accountManager.debitAccount(fromAccount, amount);
accountManager.creditAccount(toAccount, amount);
}
private DBCollection accounts;
@Inject BankingService banking... |
//Initiate a 'high value' transfer that will fail
try {
bankingService.transferMoney("A", "B", 600.0);
Assert.fail("Expected a TransactionCompensatedException to be thrown");
} catch (TransactionCompensatedException e) {
//expected
}
assertBal... |
3113319_1 | class FlatStrategyPriceCalculator implements StrategyPriceCalculator {
@Override
public BigDecimal getPrice(Carrier carrier, Map<Purchasable, Long> items)
{
BigDecimal price = carrier.getPerShipping() != null ? carrier.getPerShipping() : BigDecimal.ZERO;
Long numberOfItems = 0l;
for... | Carrier carrier = new Carrier();
carrier.setPerShipping(BigDecimal.TEN);
carrier.setPerItem(BigDecimal.ONE);
Map<Purchasable, Long> items = Maps.newHashMap();
BigDecimal price = this.componentManager.getComponentUnderTest().getPrice(carrier, items);
Assert.assertEquals... |
3114475_22 | class Number160 extends Number implements Comparable<Number160> {
public String toString(final boolean removeLeadingZero) {
boolean removeZero = removeLeadingZero;
final StringBuilder sb = new StringBuilder("0x");
for (int i = 0; i < INT_ARRAY_SIZE; i++) {
toHex(val[i], removeZe... | Number160 ki2 = new Number160(0x2c);
Assert.assertEquals("0x2c", ki2.toString());
}
} |
3116751_0 | class Formatter {
protected String buildFullMessage(String message, Object... args) {
StringBuilder stringBuilder = new StringBuilder(message.length());
int lastIndex = 0;
int argIndex = 0;
while (true) {
int argPos = message.indexOf(ARGS_PATTERN, lastIndex);
if (argPos == -1) {
break;
}
str... | Assert.assertEquals("This is a test", formatter.buildFullMessage("{} is a test", "This"));
Assert.assertEquals("This is a test", formatter.buildFullMessage("This is a {}", "test"));
Assert.assertEquals("This is a test", formatter.buildFullMessage("This {} {} test", "is", "a"));
Assert.assertEquals("This is a te... |
3119164_27 | class SpeculativeGammaConfiguration {
public SpeculativeGammaConfiguration newWithLocks() {
if (locksDetected) {
return this;
}
return new SpeculativeGammaConfiguration(
true, listenersDetected, commuteDetected, nonRefTypeDetected, orelseDetected, true,
... | SpeculativeGammaConfiguration config = new SpeculativeGammaConfiguration()
.newWithLocks();
assertTrue(config.fat);
assertFalse(config.nonRefTypeDetected);
assertFalse(config.commuteDetected);
assertFalse(config.orelseDetected);
assertFalse(config.listen... |
3125904_1 | class DataStore implements Closeable {
@SuppressWarnings("unchecked")
public <Model> void inject(@NotNull Model model) {
try {
for (Class type = model.getClass(); type != null && type != Object.class && type != Enum.class; type = type.getSuperclass()) {
for (Field field : ty... | String name = TMP + "/inject";
ChronicleTools.deleteOnExit(name);
for (int i = 0; i < 10; i++) {
ExampleDataModel model = new ExampleDataModel();
Chronicle chronicle = new IndexedChronicle(name);
DataStore dataStore = new DataStore(chronicle, ModelMode.MASTER... |
3130403_11 | class PageableCollectionBase extends PropertyChangeSupportedBase implements PageableCollection<T_ITEM> {
@Override
public Selection<T_ITEM> getSelection() {
return getSelectionHandler().getSelection();
}
public PageableCollectionBase(QueryOptions queryOptions);
@Override public final QueryParams getQu... | doSelect(collection, 0, 0, true, "a");
resetCallCounter();
assertEquals("[a]", IterableUtil.asCollection(collection.getSelection()).toString());
}
} |
3139136_1 | class BeanAnalyzer {
public static Map<String, PropertyDescriptor>
getAllProperties(GenericType root)
throws IntrospectionException {
Map<String, PropertyDescriptor> properties =
cPropertiesCache.get(root);
if (properties == null) {
GenericType rootType = root.g... | Map<String, PropertyDescriptor> properties =
BeanAnalyzer.getAllProperties(new GenericType(IntGenerics.class));
PropertyDescriptor value = properties.get("value");
assertEquals(Integer.class, value.getPropertyType());
assertEquals(Integer.class, value.getReadMethod().getRetur... |
3149437_2 | class KerberosAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
JaasSubjectHolder subjectHol... | when(userDetailsService.loadUserByUsername(TEST_USER)).thenReturn(USER_DETAILS);
when(kerberosClient.login(TEST_USER, TEST_PASSWORD)).thenReturn(JAAS_SUBJECT_HOLDER);
Authentication authenticate = provider.authenticate(INPUT_TOKEN);
verify(kerberosClient).login(TEST_USER, TEST_PASSWORD... |
3149449_52 | class ArtifactResolutionProfileImpl extends ArtifactResolutionProfileBase {
protected HostConfiguration getHostConfiguration(URI uri, SAMLMessageContext context) throws MessageEncodingException {
try {
HostConfiguration hc = httpClient.getHostConfiguration();
if (hc != null) {
... | HttpClient client = new HttpClient();
ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(client);
URI uri = new URI("http", "test", "/artifact", null);
HostConfiguration hostConfiguration = artifactResolutionProfile.getHostConfiguration(uri, null)... |
3175956_0 | class HelloWorld {
public String hello(String message) {
return "Hello " + message;
}
private static EJBContainer ejbContainer;
private static Context ctx;
}
class HelloWorldTest {
private static EJBContainer ejbContainer;
private static Context ctx;
@Test
public void hello... | // Retrieve a reference to the session bean using a portable
// global JNDI name
HelloWorld helloWorld = (HelloWorld) ctx.lookup("java:global/classes/HelloWorld");
// Do your tests
assertNotNull(helloWorld);
String expected = "World";
String hello = helloWorld.he... |
3192456_15 | class ShaderPopulator {
public void pushTransforms(Matrix4 modelTransform, ShaderProgram shader, Camera camera) {
Matrix3 normalMatrix = new Matrix3(modelTransform).invert().transpose();
//Matrix4 modelViewProjection = modelTransform.multiply(camera.getViewProjectionMatrix());
Matrix4 viewMatrix = camera.getVi... | MatrixBasedCamera camera = new MatrixBasedCamera(new CameraPerspective(45, 4.0f/3.0f, 1, 1000));
ShaderProgram shaderProgram = MockUtil.deepMock(ShaderProgram.class);
Matrix4 model = new Matrix4(1, 0, 0, 3,
0, 1, 0, 2,
0, 0, 1, -1,
0, 0, 0, 1);
camera.translate(new Vector3(5, -1, 10));
Quaternion... |
3192987_254 | class ConfigurationFolder {
@Override
public int hashCode() {
return Objects.hash(id, name, path);
}
public ConfigurationFolder();
public ConfigurationFolder(final String id, final String name, final String path);
public String getId();
public void setId(final String id);
pu... | ConfigurationFolder folder = new ConfigurationFolder("id", "name", "path");
ConfigurationFolder folder2 = new ConfigurationFolder("id", "name", "path");
ConfigurationFolder folder3 = new ConfigurationFolder("id3", "name", "path");
assertEquals(folder.hashCode(), folder2.hashCode());
... |
3206489_2 | class PhotoTaker {
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
onResultCanceled(requestCode);
return;
}
if (resultCode != Activity.RESULT_OK) {
onResultNotOk(requestCode);
return;
}
... | taker.onActivityResult(OTHER_ACTION, RESULT_FIRST_USER, null);
verify(listener, never()).onError(anyInt());
taker.onActivityResult(OTHER_ACTION, RESULT_CANCELED, null);
verify(listener, never()).onCancel(anyInt());
}
} |
3216014_3 | class LoremIpsum {
public static double variance(double[] values) {
double[] squared = new double[values.length];
for (int i = 0; i < values.length; i++) {
squared[i] = values[i] * values[i];
}
double meanVal = mean(values);
return mean(squared) - (meanVal * mea... | double[] ia1 = { 6.0d, 6.0d, 4.0d, 4.0d };
assertEquals(1.0d, LoremIpsum.variance(ia1), 0.01d);
double[] ia2 = { 1.0d, 2.0d, 3.0d, 4.0d };
assertEquals(1.25d, LoremIpsum.variance(ia2), 0.01d);
}
} |
3224235_1 | class SoftmaxClassifier implements ProbabilisticClassifier<F,L>, Serializable {
public Accuracy train(List<LabeledDatum<F,L>> Data)
{
trainScores = getTrainingResults(Data);
int[] GTLabels = makeLabelVector(Data);
int[] Predictions = trainScores.columnArgmaxs();
TrainAccuracy = new Accuracy(Predictions, GTL... | int numItems = 400;
String dir = "data/parsed";
DataSet<LabeledDatum<Double, Integer>,Double> Dataset
= new DataSet<LabeledDatum<Double, Integer>,Double>(numItems);
int l = 0;
double[] x = new double[2];
try {
FileInputStream fstream = new FileInputStream(dir + "/fournary_test.txt");
DataInputS... |
3242289_6 | class AuthenticatorActivity extends AccountAuthenticatorFragmentActivity implements Injectable {
@OnClick(R.id.auth_btn_login)
public void login() {
String username = mTxtUsername.getText().toString();
String password = mTxtPassword.getText().toString();
if (username.isEmpty() || passw... | final String username = "username";
final String password = "password";
authenticator.mAuthenticator = mock(fi.bitrite.android.ws.auth.Authenticator.class);
when(authenticator.mAuthenticator.login(
new Account(username, MOCK_ACCOUNT_TYPE),
password,
... |
3249257_3 | class BulkJSONDataESSink extends SimpleJSONDataESSink {
protected String getBulkData(List<SimpleDataEvent> events) {
StringBuilder builder = new StringBuilder();
for (SimpleDataEvent event : events) {
builder.append(JSONUtils.getElasticSearchBulkHeader(event, this.indexName, this.typeName));
buil... | BulkJSONDataESSink sink = new BulkJSONDataESSink();
Map<String, String> properties = new HashMap<String, String>();
properties.put(SimpleJSONDataESSink.ES_BASE_URL_KEY, "http://localhost:9200");
properties.put(SimpleJSONDataESSink.ES_INDEX_NAME_KEY, "test");
properties.put(SimpleJSONDataESSink.ES_TY... |
3250434_237 | class MapIdField {
public void remove(String mapId) {
mappedObjects.remove(mapId);
}
public MapIdField();
public void put(String mapId, Object value);
public Object get(String mapId);
public boolean containsMapId(String mapId);
private MapIdField mapIdField;
}
class MapIdField... | mapIdField.put("aMapId", "aMapIdValue");
mapIdField.remove("aMapId");
assertFalse(mapIdField.containsMapId("aMapId"));
}
} |
3256677_0 | class FormatProfiler extends Configured implements Tool {
public void createJobConf(JobConf conf, String[] args) throws IOException {
log.info("Loading paths...");
String line = null;
List<Path> paths = new ArrayList<Path>();
BufferedReader br = new BufferedReader( new FileReader( args[ 0 ] ) );
while( ( li... | // prepare for test
//createTextInputFile();
log.info("Checking input file is present...");
// Check that the input file is present:
Path[] inputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
input, new OutputLogFilter()));
Assert.assertEquals(1, inputFiles.length);
// Set up arguments fo... |
3263787_707 | class FormSubmissionRouter {
public void route(String instanceId) throws Exception {
FormSubmission submission = formSubmissionsRepository.findByInstanceId(instanceId);
FormSubmissionHandler handler = handlerMap.get(submission.formName());
if (handler == null) {
logger.warn("Cou... | FormSubmission formSubmission = new FormSubmission("anm id 1", "instance id 1", "child_close", "entity id 1", 0L, "1", null, 0L);
when(formSubmissionsRepository.findByInstanceId("instance id 1")).thenReturn(formSubmission);
router.route("instance id 1");
verify(formSubmissionsRepositor... |
3291848_10 | class RedirectionActionHelper {
public static String buildFormPostContent(final WebContext context) {
final String requestedUrl = context.getFullRequestURL();
final Map<String, String[]> parameters = context.getRequestParameters();
final StringBuilder buffer = new StringBuilder();
b... | final String content = RedirectionActionHelper.buildFormPostContent(MockWebContext.create().setFullRequestURL(CALLBACK_URL));
assertEquals("<html>\n<body>\n<form action=\"" + CALLBACK_URL + "\" name=\"f\" method=\"post\">\n"
+ "<input value='POST' type='submit' />\n</form>\n" +
"... |
3293934_46 | class KafkaAdapter extends CommAdapter<String> {
public Flowable<String> messages (String destination) {
return messageReceiver.messages(destination).map(incomingMessage -> incomingMessage.message);
}
KafkaAdapter(MessageSender messageSender,
MessageReceiver messageReceiver,
... | String topic = "topic4SubsErrorTest";
ensureTopicsExists(topic);
// send two good and one bad message
KafkaProducer<String, String> stringProducer = kafkaHelper.createStringProducer();
stringProducer.send(new ProducerRecord<>(topic, "1")).get();
logger.error("Sent 1");
... |
3296177_17 | class JsonUtils {
public static boolean nodeAbsent(Object json, String path, Configuration configuration) {
return nodeAbsent(json, Path.create(path), configuration);
}
public static Node convertToJson(Object source, String label);
public static Node convertToJson(Object source, String label, ... | // JSON string has to be double escaped (once for Java, once for JSON)
assertFalse(nodeAbsent("{\"test\\\\backslash\":{\"value\":1}}", Path.create("test\\backslash"), false));
}
} |
3308294_2 | class JavaDocUtils {
public String getParameterSummary(String paramName, Element element) {
String comment = elements.getDocComment(element);
if (StringUtils.isBlank(comment)) {
return null;
}
comment = comment.trim();
StringBuilder parameterCommentBuilder = ne... | when(elements.getDocComment(executableElement)).thenReturn("\n" +
" Bla bla bla\n" +
" \n" +
" @param name the name\n" +
" @param content the content");
JavaDocUtils javaDocUtils = new JavaDocUtils(elements);
assertE... |
3314133_111 | class UpdatePacketDecoder {
public BGPv4Packet decodeUpdatePacket(ByteBuf buffer) {
UpdatePacket packet = new UpdatePacket();
ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_UPDATE, -1);
if(buffer.readableBytes() < 2)
throw new MalformedAttributeListException();
// ... | (new AssertExecption() {
@Override
protected void doExecute() {
decoder.decodeUpdatePacket(buildProtocolPacket(new byte[] {
// (byte)0x03, // type code UPDATE
0x00, 0x00, // withdrawn routes length (0 octets)
0x00, 0x02, // Total path attributes length (2 octets), points to end of pa... |
3315140_46 | class ProvisioningCLI {
public static void main(String... args) {
loadJDKLoggingConfiguration();
// Injector injector = Guice.createInjector(new LoggerModule());
// ProvisioningCLI provisioningCLI = injector.getInstance(ProvisioningCLI.class);
new ProvisioningCLI().startCLI(args);
... | final String configPath = "/home/user/.clustermeister/configuration.properties";
final String argLine = "--config "+configPath+" --provider amazon";
provisioningCLI.parseArguments(buildArgs(argLine));
assertEquals(configPath, provisioningCLI.getConfigFilePath());
assertEquals(Pro... |
3319591_6 | class WktParser {
public Geometry parse(String wkt) {
if (wkt != null) {
tempWkt = wkt;
if (skip(org.geomajas.geometry.Geometry.MULTI_POLYGON.toUpperCase())) {
return parseMultiPolygon();
} else if (skip(org.geomajas.geometry.Geometry.POLYGON.toUpperCase())) {
return parsePolygon();
} else if (s... | Geometry geometry = parser.parse(MULTIPOLYGON1);
Assert.assertNotNull(geometry);
Assert.assertTrue(geometry instanceof MultiPolygon);
MultiPolygon mp = (MultiPolygon) geometry;
Assert.assertEquals(2, mp.getNumGeometries());
geometry = parser.parse(MULTIPOLYGON2);
Assert.assertNotNull(geometry);
Assert.... |
3328338_6 | class DuoShibboleth {
public boolean verifyResponseEqualsUsername(String duoResponse) {
try {
String duoVerifiedResponse = DuoWeb.verifyResponse(ikey, skey, akey, duoResponse);
boolean usernameMatches = duoVerifiedResponse.equals(username);
if (usernameMatches) {
... | String response = "";
assertFalse(duoShibboleth.verifyResponseEqualsUsername(response));
}
} |
3333998_352 | class BleutradeDigest extends BaseParamsDigest {
@Override
public String digestParams(RestInvocation restInvocation) {
String invocationUrl = restInvocation.getInvocationUrl();
Mac mac = getMac();
mac.update(invocationUrl.getBytes());
return String.format("%0128x", new BigInteger(1, mac.doFinal()... | // given
RestInvocation invocation =
new RestInvocation(null, null, null, null, "rest body", null, null, null);
String expected =
"6372f349eea659b26f5e01bc76e1485de744a1894d5e036b98eca724a8104719ea8767518286863d1becd0a1313ad5e7e507749f7cdb98a4dee92fec055643c4";
// when
String encode... |
3337772_506 | class EnableHlsTaskRunner extends BaseHlsTaskRunner {
public String performTask(String taskParameters) {
EnableStreamingTaskParameters taskParams =
EnableStreamingTaskParameters.deserialize(taskParameters);
String spaceId = taskParams.getSpaceId();
boolean secure = taskParams.i... | // Expect calls to get bucket name
EasyMock.expect(unwrappedS3Provider.getBucketName(EasyMock.isA(String.class)))
.andReturn(bucketName);
// Origin Access Id already exists and is reused
expectExistingOriginAccessId();
// Distribution exists, is set to OPEN stre... |
3352045_33 | class ESMClass {
public ESMClass setSpecificFeature(GSMSpecificFeature specificFeature) {
value = GSMSpecificFeature.compose(value, specificFeature);
return this;
}
public ESMClass();
public ESMClass(int value);
public ESMClass(byte value);
public ESMClass(MessageMode messa... | assertTrue(GSMSpecificFeature.DEFAULT.containedIn(esmClass));
esmClass.setSpecificFeature(GSMSpecificFeature.UDHI);
assertTrue(GSMSpecificFeature.UDHI.containedIn(esmClass));
}
} |
3360581_13 | class MessageUtils {
public static String serializeMsgstr(Message message) {
if (message.isPlural()) {
StringBuilder sb = new StringBuilder();
List<String> plurals = message.getMsgstrPlural();
for (Iterator<String> it=plurals.iterator(); it.hasNext(); ) {
... | Message msg = new Message();
msg.setMsgid("id");
msg.setMsgstr("str");
Assert.assertEquals("str", MessageUtils.serializeMsgstr(msg));
}
} |
3362935_1 | class OnDemandScreenshotService {
static Map<String, String> keyValueMapFor(String logLine) {
Map<String, String> keyValueMap = new HashMap<String, String>();
Matcher matcher = KEY_VALUE_HOLDER_PATTERN.matcher(logLine);
if (matcher.find()) {
for (String keyValuePair : matcher.gr... | assertThat(keyValueMapFor("{name=ConfigureMorseActivity-SOS}"),
IsMap.containingOnly("name", "ConfigureMorseActivity-SOS"));
}
} |
3370128_31 | class Parser {
public static JdbcCallParseInfo modifyJdbcCall(String jdbcSql, boolean stdStrings,
int serverVersion, int protocolVersion, EscapeSyntaxCallMode escapeSyntaxCallMode) throws SQLException {
// Mini-parser for JDBC function-call syntax (only)
// TODO: Merge with escape processing (and param... | assertEquals("select * from pack_getValue(?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue}", true, ServerVersion.v9_6.getVersionNum(), 3, EscapeSyntaxCallMode.SELECT).getSql());
assertEquals("select * from pack_getValue(?,?) as result", Parser.modifyJdbcCall("{ ? = call pack_getValue(?) }", true... |
3375991_0 | class QueryParser implements IQueryParser {
@Override
public Query parseQuery(String expression) {
if (expression == null) {
return null;
}
OqlParser parser = newParser(expression);
try {
parser.oql();
} catch (RecognitionException e) {
... |
String inOql = "DEFINE c='http://localhost:8181/onexus/onx/test' SELECT c (field) FROM c";
Query query = queryParser.parseQuery(inOql);
String outOql = query.toString(new StringBuilder(), false).toString();
assertEquals(inOql, outOql);
}
} |
3376848_2 | class WebDriverThreadLocalContainer implements WebDriverContainer {
@Override
@CheckReturnValue
public boolean hasWebDriverStarted() {
WebDriver webDriver = threadWebDriver.get(currentThread().getId());
return webDriver != null;
}
@Override public void addListener(WebDriverEventListener listener);
... | assertThat(container.hasWebDriverStarted()).isFalse();
}
} |
3382195_492 | class MfaRegisterQRGenerator {
public static String getQRCode(String issuer,
String accountName,
String secretKey) throws WriterException, IOException {
if(!StringUtils.hasText(issuer) || issuer.contains(":")) {
throw new Ill... | GoogleAuthenticator authenticator = new GoogleAuthenticator();
GoogleAuthenticatorKey key = authenticator.createCredentials();
String encodedQrCode = MfaRegisterQRGenerator.getQRCode("testIssuer", "accountName", key.getKey());
String result = decodeQrPng(encodedQrCode);
String[]... |
3398614_3 | class ChannelWriter extends AtmosphereInterceptorWriter {
protected String constructStatusAndHeaders(AtmosphereResponse response, int contentLength) {
StringBuffer b = new StringBuffer("HTTP/1.1")
.append(" ")
.append(response.getStatus())
.append(" ")
... | String contentType = "application/json";
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", contentType);
headers.put("X-Custom-Header", "value");
AtmosphereResponse response = setupResponse(headers);
int contentLength = 100;
... |
3407114_33 | class ParseUtil {
public static Pair<String, String> parseLspciMachineReadable(String line) {
Matcher matcher = LSPCI_MACHINE_READABLE.matcher(line);
if (matcher.matches()) {
return new Pair<>(matcher.group(1), matcher.group(2));
}
return null;
}
private ParseU... | Pair<String, String> pair = ParseUtil.parseLspciMachineReadable("foo [bar]");
assertEquals("foo", pair.getA());
assertEquals("bar", pair.getB());
assertNull(ParseUtil.parseLspciMachineReadable("Bad format"));
}
} |
3407162_17 | class CombinedMessageSelector implements MessageSelector {
@Override
public boolean matches(final OSCMessageEvent messageEvent) {
return logicOperator.matches(selector1.matches(messageEvent), selector2.matches(messageEvent));
}
@SuppressWarnings("WeakerAccess") public CombinedMessageSelector(
final MessageS... |
final MessageSelector matcher = new CombinedMessageSelector(
new OSCPatternAddressMessageSelector("/hello"),
new OSCPatternTypeTagsMessageSelector("i"),
CombinedMessageSelector.LogicOperator.AND);
Assert.assertFalse(matches(matcher, "/", ""));
Assert.assertFalse(matches(matcher, "/hello", ""));
As... |
3409328_0 | class Subnet implements Serializable {
@JsonIgnore
public String getId() {
return id;
}
public String getName();
public void setName(String name);
@JsonIgnore public boolean isEnableDHCP();
public Boolean getEnableDHCP();
public void setEnableDHCP(Boolean enableDHCP);
publi... | Subnet subnet = objectMapper.readValue(SUBNET_JSON, Subnet.class);
assertThat(subnet.getId(), is(equalTo(ID)));
}
} |
3411081_27 | class IOExceptionFactory extends AbstractExceptionFactory<IOException> {
@Override
public IOException createException(String message)
{
return new IOException(message);
}
public IOExceptionFactory();
@Override public boolean indicatesFailure(IOException exception, Dialect dialect);
@Override public Excepti... | IOException exception = new IOException();
IOException result = this.factory.createException(exception);
assertSame(exception, result);
}
} |
3423262_43 | class DeferredValueMatcher implements ValueMatcher {
public boolean matches(Class<?> parentEntityType, String propertyName,
Object value) {
if (value == null) {
return _value == null;
} else if (_value == null) {
return false;
}
if (_resolvedValueSet) {
return value.equals(_re... | DeferredValueMatcher matcher = matcher(1);
assertTrue(matcher.matches(Stop.class, "locationType", 1));
assertFalse(matcher.matches(Stop.class, "locationType", 2));
}
} |
3424353_158 | class AssignmentDaoImpl implements AssignmentDao {
@Override
@Transactional(rollbackFor = Throwable.class)
public void delete(Assignment assignment) {
getSession().delete(assignment);
}
@Autowired @Qualifier("assignmentSessionFactory") public void setSessionFactory(SessionFactory sessionFa... |
Date currentServiceDate = currentServiceDate();
Assignment retrievedAssignment = _dao.getAssignment("blockId", currentServiceDate);
assertNull(retrievedAssignment);
Assignment assignment = new Assignment("blockId", "vehicleId", currentServiceDate);
_dao.save(assignment);
... |
3425475_5 | class SiriClientSubscriptionManager implements StatusProviderService {
public void clearPendingSubscription(SiriClientRequest request,
SubscriptionRequest subscriptionRequest) {
_log.info("clear pending subscription: {}", request);
_initiateSubscriptionsManager.clearPendingSubscription(request,
... | SiriClientRequest request = new SiriClientRequest();
SubscriptionRequest subscriptionRequest = new SubscriptionRequest();
_manager.clearPendingSubscription(request, subscriptionRequest);
Mockito.verify(_initiateSubscriptionsManager).clearPendingSubscription(
request, subscriptionRequest);
}
} |
3429525_9 | class TwilioAdapter {
protected String renderOpenQuestion(Question question, ArrayList<String> prompts, String sessionKey) {
TwiMLResponse twiml = new TwiMLResponse();
String typeProperty = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.TYPE);
if (typeProperty != nu... |
Question question = getOpenQuestion( false, false );
AdapterConfig adapter = createTwilioAdapter();
Session session = createSession(adapter, remoteAddressVoice);
String result = renderQuestion(question, adapter, session);
log.info( "Result Open Question: " + result );
... |
3430789_14 | class Namespace {
public Namespace child(List<String> values) {
ImmutableList<String> child = ImmutableList.<String>builder().addAll(this.values).addAll(values).build();
return Namespace.of(child);
}
private Namespace(List<String> values);
public static Namespace root();
public static Namespace of(List<Str... | Namespace namespace = Namespace.of("root");
Namespace child = namespace.child("child");
Assert.assertEquals(child.toString(), "root/child");
}
} |
3433581_0 | class JFXtrasFontRoboto {
public static void loadAll() {
for (AvailableFonts f : AvailableFonts.values()) {
load(f);
}
}
synchronized public static void load(AvailableFonts font);
private VBox box;
List<String> EXCLUDED_CLASSES;
}
class JFXtrasFontRobotoTest {
private VBox box;
List<Stri... | // load the fonts and set one on the label
TestUtil.runThenWaitForPaintPulse( () -> {
JFXtrasFontRoboto.loadAll();
Label l = new Label("xxxxx");
l.setStyle("-fx-font-family: 'Roboto Italic'; -fx-font-size:32pt;");
box.getChildren().clear();
box.getChildren().add(l);
});
/... |
3444675_9 | class FlattrAuthenticator {
protected String buildScopeString() {
StringBuilder sb = new StringBuilder();
if (scope.contains(Scope.FLATTR )) sb.append(" flattr");
if (scope.contains(Scope.THING )) sb.append(" thing");
if (scope.contains(Scope.EMAIL )) sb.append(" e... | ConsumerKey ck = new ConsumerKey("ck-abc", "ck-123");
FlattrAuthenticator auth = new FlattrAuthenticator(ck);
auth.getScope().add(Scope.FLATTR);
assertThat(auth.buildScopeString(), is("flattr"));
auth.getScope().add(Scope.THING);
assertThat(auth.buildScopeString(), is("... |
3447638_7 | class DateTimeFieldMappingFactory implements FieldMappingFactory {
@Override
public FieldMapping createFieldMapping(EntitySchemaFactory schemaFactory,
Class<?> entityType, String csvFieldName, String objFieldName,
Class<?> objFieldType, boolean required) {
return new DateTimeFieldMapping(entityType... |
DateTimeFieldMappingFactory factory = new DateTimeFieldMappingFactory();
FieldMapping mapping = factory.createFieldMapping(null,
NycTestLocationRecord.class, "dt", "timestamp", Long.class, true);
NycTestLocationRecord record = new NycTestLocationRecord();
record.setTimestamp(1284377940000L);
... |
3449807_27 | class TopologicalSorter {
public List<VertexClass> sort() // toplogical sort
{
while (numVerts > 0) // while vertices remain,
{
// get a vertex with no successors, or -1
int currentVertex = noSuccessors();
if (currentVertex == -1) // must be a cycle
... | TestNode n4 = new TestNode(buildTypeId4);
TestNode n3 = new TestNode(buildTypeId3, n4);
TestNode n2 = new TestNode(buildTypeId2, n3);
TestNode n1 = new TestNode(buildTypeId1, n2);
List<TestNode> sorted = new TopologicalSorter<TestNode>(ImmutableList.of(n1, n2, n3, n4)).s... |
3460824_46 | class ConfigPropertyUtils {
public static <T extends Enum<T>> Pattern createValidationPatternFromEnumType(Class<T> enumType) {
String regEx = Stream.of(enumType.getEnumConstants())
.map(Enum::name)
.collect(Collectors.joining("|", "(?i)", ""));
//Enum constants may... | Pattern actual = ConfigPropertyUtils.createValidationPatternFromEnumType(BadBadEnum.class);
assertEquals("(?i)This_Enum_Val_Cointains_Really_\\$_BAD_CHARS_£", actual.pattern());
assertTrue(actual.matcher(BadBadEnum.This_Enum_Val_Cointains_Really_$_BAD_CHARS_£.name()).matches());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.