id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
1097987_0
class MySimilarity extends DefaultSimilarity { @Override public float lengthNorm(String fieldName, int numTerms) { if (numTerms < 20) { // this shouldn't be possible, but be safe. if (numTerms <= 0) return 0; // return ARR[numTerms]; retur...
MySimilarity s = new MySimilarity(); assertEquals(0, s.lengthNorm("test", 0), 1e-6); assertEquals(0.289400, s.lengthNorm("test", 10), 1e-6); assertEquals(0.234860, s.lengthNorm("test", 19), 1e-6); assertEquals(0.223606, s.lengthNorm("test", 20), 1e-6); } }
1107344_0
class AardvarkHelpMode extends GosuMode { static void printHelp(PrintWriter out) { out.println("Usage:"); out.println(" vark [-f FILE] [options] [targets...]"); out.println(); out.println("Options:"); IArgKeyList keys = Launch.factory().createArgKeyList(); for (IArgKey key : AardvarkO...
StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); AardvarkHelpMode.printHelp(out); String eol = System.getProperty("line.separator"); assertEquals( "Usage:" + eol + " vark [-f FILE] [options] [targets...]" + eol + ...
1110934_2
class CprAbbsResponseParser { public List<String> extractCprNumbers(String soapResponse) throws CprAbbsException { int start = soapResponse.indexOf("<?xml"); if(start == -1) { throw new CprAbbsException("Invalid message body on call to CPR Abbs"); } String soapRespon...
CprAbbsResponseParser parser = new CprAbbsResponseParser(); List<String> extractCprNumbers = parser.extractCprNumbers(exampleResponseWithHeaders); assertEquals(2, extractCprNumbers.size()); assertEquals("0101822231", extractCprNumbers.get(0)); assertEquals("0101821234", extractCp...
1116314_32
class HasTypesCollectors { public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( T hasTypes ) { return hasTypesToListCollector( hasTypes, new HasAssignableToType<>( hasTypes ) ); } private HasTypesCollectors(); public static Collector<T, ?, Optional<T>> matchingType( ...
List<ValueType> list = new ArrayList<ValueType>() {{ add( ValueType.of( String.class ) ); add( ValueType.of( Identity.class ) ); }}; List<ValueType> result = list.stream() .collect( HasTypesCollectors.closestTypes( StringIdent...
1146205_24
class ClientInputStream extends InputStream { @Override public int read() throws IOException { return remote.read(); } public ClientInputStream(RemoteInputStream remote); @Override public int read(byte[] buf, int off, int len); @Override public long skip(long n); @Override public void close(); ...
bi.reset(); byte[] r = new byte[100]; assertEquals(buf.length, ci.read(r)); for (int i = 0; i < buf.length; i++) assertEquals(buf[i], r[i]); assertEquals(-1, ci.read()); bi.reset(); r = new byte[0]; assertEquals(0, ci.read(r)); } }
1149947_21
class SCAInvoker extends BaseServiceHandler { @Override public void handleMessage(Exchange exchange) throws HandlerException { // identify ourselves exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) .addLabels(BehaviorLabel.TRA...
V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { @Override public String getName() { return "testBinding"; } public CompositeReferenceModel getReference() { return new V1CompositeReferenceModel()...
1155836_1
class PaxLoggerImpl implements PaxLogger { @Override public LogLevel getLogLevel() { Level level = m_delegate.getEffectiveLevel(); return getLogLevel(level); } PaxLoggerImpl(Bundle bundle, Logger delegate, String fqcn, PaxLoggingServiceImpl service, boolean printfFormatting); @O...
Constructor<Logger> c = Logger.class.getDeclaredConstructor(String.class); c.setAccessible(true); Logger logger = c.newInstance("test"); PaxLoggerImpl loggerImpl = new PaxLoggerImpl(null, logger, null, null, false); logger.setLevel(null); assertEquals(LogLevel.AUDIT, lo...
1155961_9
class StudyEJB3DAO extends AccessibleEJB3DAO<Study> implements StudyDAO { public Study getByAccForUser(String acc, String userName) { Query query = entityManager.createQuery("SELECT s " + "FROM Study s join s.users user " + "WHERE " + "s.acc =:acc AND (user.userName =:userName" + " OR s.status =:st...
//Test for private study Study study = dao.getByAccForUser("BII-ST-1", "test_user"); assertNotNull(study); //Test for private study with curator user study = dao.getByAccForUser("BII-ST-1", "curator"); assertNotNull(study); //Test for private study with guest user Exception exception = null; try { ...
1156021_8
class PermissionManager { public void setStudyOwners(CommandLine cmdl) { String specs[] = cmdl.getOptionValues("o"); if (specs == null) { return; } for (String spec : specs) { setStudyOwners(spec); } } public PermissionManager(EntityManager ...
Person user = createTestUser(); session.clear(); user.setId(null); user.setUserName("zakmck1"); createTestUser(user); session.clear(); user.setId(null); user.setUserName("zakmck2"); createTestUser(user); session.clear(); SimplePi...
1158118_0
class DashOTransformer implements Transformer { public static String decrypt(String input) { if (isEmpty(input)) { return input; } char[] inputChars = input.toCharArray(); int length = inputChars.length; char[] inputCharsCopy = new char[length]; int j =...
final String outputActual = DashOTransformer.decrypt(input); assertEquals(outputActual, outputExpected); } }
1158315_44
class LocationEnhancementEngine extends AbstractEnhancementEngine<IOException,RuntimeException> implements EnhancementEngine, ServiceProperties { @Override public void computeEnhancements(ContentItem ci) throws EngineException { IRI contentItemId = ci.getUri(); Graph graph = ci.getMetadata(); ...
//create a content item ContentItem ci = getContentItem("urn:org.apache:stanbol.enhancer:text:content-item:person", CONTEXT); //add three text annotations to be consumed by this test getTextAnnotation(ci, PERSON, CONTEXT, DBPEDIA_PERSON); getTextAnnotation(ci, ORGANISATION, CONTE...
1161604_0
class MulgaraConnector extends TriplestoreConnector { @Override public TriplestoreReader getReader() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } return m_reader; } @Override public void close(); @Override public GraphElementFactory...
TriplestoreReader reader = _connector.getReader(); assertEquals(0, reader.countTriples(null, null, null, -1)); } }
1163806_197
class CheckoutAction { static String determineCheckoutPath(final FilePath workspacePath, final String localFolder) { final FilePath combinedPath = new FilePath(workspacePath, localFolder); final String result = combinedPath.getRemote(); return result; } public CheckoutAction(Strin...
final VirtualChannel vc = mock(VirtualChannel.class); final String nixPath = "/opt/.jenkins/jobs/tfs-plugin/workspace"; final FilePath workspacePath = new FilePath(vc, nixPath); final String actual = CheckoutAction.determineCheckoutPath(workspacePath, "../files"); Assert.assert...
1164965_50
class WebClassesFinder extends AbstractClassFinder { public WebClassesFinder(ServletContext servletContext, ClassLoader classLoader, PackageFilter packageFilter) { super(servletContext, classLoader, packageFilter); } public WebClassesFinder(ServletContext servletContext, ClassLoader classLoader, Pa...
// URLs of simulated directories and files URL classesUrl = new URL("file:/somewhere/WEB-INF/classes/"); URL packageUrl = new URL("file:/somewhere/WEB-INF/classes/package/"); URL classUrl = new URL("file:/somewhere/WEB-INF/classes/package/TestClass.class"); // Contents of directories ...
1165813_0
class SSHPublicKeyExtractor { public static String extract(final String pem, final String passPhrase) throws IOException { final Object priv = PEMDecoder.decode(pem.toCharArray(), passPhrase); if (priv instanceof RSAPrivateKey) { return "ssh-rsa " + DatatypeConverter.printBase64Binary(R...
String pub = SSHPublicKeyExtractor.extract(RSA_PEM, null); assertEquals(RSA_EXPECTED, pub); } }
1167439_0
class CamelConsumerEndpoint extends ConsumerEndpoint implements AsyncProcessor { public void process(final MessageExchange messageExchange) throws Exception { final ContinuationData data = continuations.remove(messageExchange.getExchangeId()); if (data == null) { logger.error("Unexpect...
// sending a message to start the producers and create the external endpoint client.sendBody("direct:a", "<hello>world</hello>"); String endpointName = jbiContainer.getRegistry().getExternalEndpointsForService(CamelConsumerEndpoint.SERVICE_NAME)[0].getEndpointName(); ...
1169309_3
class FindBugsPlugin extends Plugin { public static boolean isFindBugs2x(final MojoExecution mojoExecution) { try { String[] versions = StringUtils.split(mojoExecution.getVersion(), "."); if (versions.length > 1) { int major = Integer.parseInt(versions[0]); ...
MojoExecution execution = mock(MojoExecution.class); when(execution.getVersion()).thenThrow(new NoSuchMethodError()); assertFalse(WRONG_MAVEN_DETECTION, FindBugsPlugin.isFindBugs2x(execution)); } }
1171506_0
class EventBus { public void subscribe(Class<? extends Subscriber> subscriber) { try { monitor.lock(); if (subscriber.isAnnotationPresent(InterestedEvent.class)) { InterestedEvent ann = subscriber.getAnnotation(InterestedEvent.class); for (Class<? extends Event> interestedEvent : ann.events()) { ...
replay(this.consumerOne, this.consumerTwo, this.publisher); assertFalse(bus.subscribers.containsKey(EventOne.class)); assertFalse(bus.subscribers.containsKey(EventTwo.class)); bus.subscribe(SubscriberOne.class); bus.subscribe(SubscriberTwo.class); assertTrue(bus.subscribers.containsKey(EventOne.class)); ...
1176274_2
class TeleportPlayerJob extends BukkitRunnable { boolean hasPlayerMoved() { final double MAX_MOVE_TOLERANCE = 1.5; return distance3D(player.getLocation(), originalLocation) > MAX_MOVE_TOLERANCE; } public TeleportPlayerJob(Player player, Location location); @Override public void run(); boolean hasPlayerTak...
when(player.getLocation()).thenReturn(new Location(world, 5, 1, 3)); assertTrue(job.hasPlayerMoved()); } }
1181284_260
class ScanDescriptorForHostClassesStage implements TransformStage { @SuppressWarnings("unchecked") public void execute(TransformContext context) throws PluginTransformationException { XPath xpath = DocumentHelper.createXPath("//@class"); List<Attribute> attributes = xpath.selectNodes(context.ge...
when(registration.getMainInterfaceClasses()).thenReturn(new Class<?>[]{SomeInterface.class}); List<HostComponentRegistration> registrations = new ArrayList<HostComponentRegistration>(1); registrations.add(registration); final File plugin = new PluginJarBuilder("testUpgradeOfBundledPlugi...
1184582_8
class ConverterUtils { public String parseOutput(String right) { return parseOutput(null, right); } public ConverterUtils(Spec spec); private void addType(Spec spec, String name, String type); public String parseOutput(String left, String right); private String getStringRightSide(Str...
Spec spec = buildSpec(); spec.setOutput("Results"); ConverterUtils converter = new ConverterUtils(spec); assertEquals("output.setAverage((math.getNumber() + physics.getNumber() + biology.getNumber()) / 3);", converter.parseOutput("average", "($math + $physics + $biology) / 3")); ...
1193862_8
class IdeaProfileExporter extends ProfileExporter { public void exportProfile(RulesProfile profile, Writer writer) { try { appendXmlHeader(writer); SortedMap<String, Rule> defaultRules = new TreeMap<String, Rule>(DefaultRules.get()); for (ActiveRule activeRule : pr...
RulesProfile profile = createSimpleProfile(); assertSimilar(exportProfile(profile), "simpleIdeaRulesToExport.xml"); } }
1194243_15
class XmlUtil { public static void removeEntities(Reader reader, Writer writer) throws IOException { int curChar = -1; StringBuffer ent = null; if (reader == null) { throw new IllegalArgumentException("null reader arg"); } else if (writer == null) { ...
try { StringReader reader = new StringReader("&#;"); StringWriter writer = new StringWriter(); XmlUtil.removeEntities(reader, writer); assertEquals("&#;", writer.toString()); } catch (Exception excep) { fail("Unhandled exception: " + excep.getMessage()); } } }
1195109_0
class ListObject extends WeiboResponse implements java.io.Serializable { public void setFullName(String fullName) { this.fullName = fullName; } ListObject(Response res, Weibo weibo); ListObject(Response res, Element elem, Weibo weibo); ListObject(JSONObject json); private void init(Response res, Elemen...
fail("Not yet implemented"); } }
1204957_0
class JsonParser implements Parser { @SuppressWarnings("ConstantConditions") @Override public List<MovieInfo> parseMovieInfo(String content, int maxCount, int posterCount, int backdropCount) throws ParseException { // Minus if (posterCount < 0) { posterCount = Integer.MAX_VALUE;...
// Mock Movie MovieFactory movieFactory = mock(MovieFactory.class); MovieInfo movieInfo = mock(MovieInfo.class); MovieImage movieImage = mock(MovieImage.class); when(movieFactory.createMovieInfo()).thenReturn(movieInfo); when(movieFactory.createMovieImage()).thenReturn(mo...
1205446_0
class Utils { public static long calculateNotifTime(Long nowMillis, int hourToNotify) { DateTime now = new DateTime(nowMillis); DateTime timeToNotify = new DateTime(nowMillis); timeToNotify = timeToNotify.withHourOfDay(hourToNotify); if (timeToNotify.isBefore(now)) { tim...
DateTime time = new DateTime(); time = time.withHourOfDay(8); DateTime notifyTime = new DateTime(Utils.calculateNotifTime(time.getMillis(), 7)); assertEquals(1000 * 60 * 60 * 23, notifyTime.getMillis() - time.getMillis()); notifyTime = new DateTime(Utils.calculateNotifTime(time...
1205842_1
class GraphTaskOperations implements TaskOperationsDefinition { @Override public List<String> getOperations(String state) { List<String> operationsList = new ArrayList<String>(); for (OperationsDefinition def : this.definition) { if (state.equals(def.getName())) { if ((def.getTransitions() != null)) { ...
List<String> tasks = operations.getOperations("READY"); Assert.assertEquals(2, tasks.size()); Assert.assertTrue(tasks.contains("claim")); Assert.assertTrue(tasks.contains("suspend")); } }
1206855_188
class JQueryUiTooltip extends JQueryDurableAjaxBehavior { public JQueryUiTooltip setPosition(JsOption... options) { this.widget.setOption("position", asString(options)); return this; } public JQueryUiTooltip(JQueryResourceReference customJQueryUiTooltipJs); public JQueryUiTooltip(String componentSelector, ...
JsOption my = new JsOption("my", "'left+15 center'"); JsOption at = new JsOption("at", "'right center'"); tooltip.setPosition(my, at); verify(widget).setOption("position", "{my:'left+15 center',at:'right center'}"); } }
1216286_1
class QueryScriptEngine { public void execute(String script) throws QueryScriptException { try { Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); scope.put(ARAS_SCRIPT_ENGINE_CONTEXT, scope, arasCtx); loadRhinoBinding(scope, cx); ...
final String query = "'x'='y'"; final String walkPredicate = "rdf:type"; ScriptEngineContext ctx = mock(ScriptEngineContext.class); NodeSet nodeSet = mock(NodeSet.class); when(ctx.query(anyString())).thenReturn(nodeSet); when(nodeSet.walk(anyString())).thenReturn(nodeSe...
1228775_2
class SpringApplicationBeanDefinitionParser extends AbstractSpringBeanDefinitionParser { @Override public Class<?> getBeanClass(Element element) { return ApplicationDecorator.class; } @Override public void prepareInjection(Element element, BeanDefinitionBuilder bean); } class SpringApplicati...
SpringApplicationBeanDefinitionParser parserToTest = new SpringApplicationBeanDefinitionParser(); Class<?> beanClass = parserToTest.getBeanClass(null); assertThat(beanClass, typeCompatibleWith(ApplicationDecorator.class)); } }
1229527_2
class BndUtils { public static Properties parseInstructions( final String query ) throws MalformedURLException { final Properties instructions = new Properties(); if( query != null ) { try { // just ignore for the moment and try out if we ...
Properties p = BndUtils.parseInstructions( "foo=bar&sing=sang&cheese=bacon" ); assertEquals( "bar", p.getProperty( "foo" ) ); assertEquals( "sang", p.getProperty( "sing" ) ); assertEquals( "bacon", p.getProperty( "cheese" ) ); } }
1231687_1
class BitMask { public boolean isBitSet(int bit) { long bitMask = Long.rotateLeft(1, bit); long result = this.bitMaskValue & bitMask; if (result != 0) { return true; } return false; } public BitMask(); public BitMask(long currentValue); public...
for (int bitNumber = 0; bitNumber < 64; bitNumber++) { long bitMask = Long.rotateLeft(1, bitNumber); BitMask bm = new BitMask(bitMask); assertEquals(true, bm.isBitSet(bitNumber)); } } }
1251091_0
class UrgBinner implements Binner { public List<Float> getBinned() { if (last == -1) return null; return new ImmutableList.Builder<Float>().addAll(binned).build(); } public UrgBinner(String channel, int bins, double fov); public void setLidar(Lidar lidar); public ...
for (int i = 1; i < 10; ++i) { UrgBinner ub1 = new UrgBinner("URG_RANGE", i, Math.PI); assertEquals(ub1.getBinned().size(), i); } } }
1251538_7
class AbstractEnvironment implements EnvironmentConnector, EnvironmentServiceProvider, TimeDriven { @SuppressWarnings("unchecked") @Override public <T extends EnvironmentService> T getEnvironmentService(Class<T> type) throws UnavailableServiceException { // force NullPointerException if type is null type.t...
final TestAbstractEnvironment envUnderTest = new TestAbstractEnvironment(mockStorage); try { @SuppressWarnings("unused") final EnvironmentService envService = envUnderTest.getEnvironmentService(null); fail("No exception thrown by AbstractEnvironment.getEnvironmentService(null), NullPointerException expecte...
1251856_8
class FileOperation implements FileAction { boolean isIgnored(File file){ boolean ignore = false; while(file != null){ String end = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(System.getProperty("file.separator")) + 1); for(String pathToIgnore: ignoredPaths){ ignore = end.matches...
// not sure why idea ide's would be a problem... TODO: testing this specifically smells like a bigger problem... assertTrue(new FileOperation(".*\\.idea") { public void onDirectory(File dir) throws IOException {} public void onFile(File file) throws IOException {} public void onNull(File nullFile) throws I...
1269176_202
class Snapshot { public static Snapshot readSnapshot(IdReader reader, Snapshot oldSnapshot) throws IOException { assert reader.idManager == oldSnapshot.idManager; reader.readDiffs(); int snapshotId = reader.readInt(); boolean hasTool = reader.readBoolean(); Tool tool = hasTo...
System.out.println("readSnapshot"); IdManager idManager = new IdManager(); IdReader reader = new IdReader(new DataInputStream(new ByteArrayInputStream(emptyDiffEmpty)), idManager); Snapshot oldSnapshot = idManager.getInitialSnapshot(); ImmutableArrayList<CellBackup> expCellBack...
1273791_99
class Tokenizer extends TokenizerBase { @Override public List<Token> tokenize(String text) { return createTokenList(text); } public Tokenizer(); private Tokenizer(Builder builder); private Tokenizer tokenizer; } class TokenizerTest { private Tokenizer tokenizer; @Test ...
List<Token> tokens = tokenizer.tokenize("合い方"); assertEquals(1, tokens.size()); Token token = tokens.get(0); // Feature is escaped in quotes ("0,4") assertEquals( "名詞,普通名詞,一般,*,*,*,アイカタ,合方,合い方,アイカタ,合い方,アイカタ,和,*,*,*,*,アイカタ,アイカタ,アイカタ,アイカタ,*,*,\"0,4\",C2,*", ...
1274071_4
class AdaptationExecutor { public static Result execute(List<AdaptationCommand> cmds) { Result result = new Result(); for (AdaptationCommand cmd : cmds) { try { cmd.execute(); result.executedCmds.add(cmd); } catch (KevoreeAdaptationException ...
List<AdaptationCommand> cmds = new ArrayList<>(); AdaptationCommand ok0 = new ExecSuccessCmd(); AdaptationCommand ok1 = new ExecSuccessCmd(); AdaptationCommand ok2 = new ExecSuccessCmd(); cmds.add(ok0); cmds.add(ok1); cmds.add(ok2); cmds.add(new ExecFailCm...
1274332_10
class LdapModule extends AbstractQuercusModule { public static BooleanValue ldap_unbind (LdapLinkResource linkIdentifier) { // Avoid NPEs from this being called on non-existent linkIdentifiers. if (linkIdentifier == null) { return BooleanValue.create(false); } boolea...
BooleanValue result = LdapModule.ldap_unbind(null); assertFalse("Unbinding should fail when link identifier is null", result.toBoolean()); } }
1287669_60
class JsonAssert { public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); } public static JsonAsserter with(Reader reader); public static JsonAsserter with(InputStream is); public static CollectionMatcher collectionWithSize(Matcher<? super ...
with(JSON).assertNotDefined("$.store.bicycle[?(@.color == 'red' )]"); } }
1293378_2
class Population { public float getMutation() { return mutation; } public Population(int size, float crossoverRatio, float elitismRatio, float mutationRatio); public void evolve(); public Chromosome[] getPopulation(); public float getElitism(); public float getCrossover(); private Chromosome[] selectP...
Population pop = new Population(1024, 0.8f, 0.1f, 0.05f); assertEquals(5, (int) (pop.getMutation() * 100)); pop = new Population(1024, 0.8f, 0.1f, 0.0f); assertEquals(0, (int) (pop.getMutation() * 100)); pop = new Population(1024, 0.8f, 0.1f, 1.0f); assertEquals(100, (int) (pop.getMutation() * 100)); ...
1294371_16
class Paths { public static String getParentOf(String path) { int i = path.lastIndexOf(DELIM); if (i == -1) return ""; if (i == 0) i = 1; return path.substring(0, i); } public static String getNameOf(String path); public static String appended(String path, String child); public static String...
assertEquals("dir1/dir2", Paths.getParentOf("dir1/dir2/file")); assertEquals("", Paths.getParentOf("file")); assertEquals("c:", Paths.getParentOf("c:/file")); assertEquals("/", Paths.getParentOf("/file")); assertEquals("/dir", Paths.getParentOf("/dir/file")); } }
1307005_0
class ExtendedTemporaryFolder extends ExternalResource { public File newFolder(String folder) throws IOException { return newFolder(new String[]{folder}); } public ExtendedTemporaryFolder(); public ExtendedTemporaryFolder(File parentFolder); @Override protected void before(); @Overr...
for (int i = 0; i < 1000; i++) { File temporary = this.temporaryFolder.newFolder(); Assert.assertEquals(true, temporary.exists()); // Should writable Assert.assertEquals(true, temporary.canWrite()); // Should writable Assert.assertEquals(true, temporary.canRead()); } } }
1312627_5
class Version extends Service { public static String getKernelRevision() { return KERNEL_VERSION.getRevision(); } protected Version( String atrifactId, String version ); @Override public String toString(); public String getVersion(); public String getRevision(); private stati...
assertFalse( "Kernel revision not specified", "".equals( Version.getKernelRevision() ) ); } }
1313372_4
class BetterMimeMessage extends MimeMessage { protected boolean isAutomaticMessage() throws MessagingException { String[] autoSubmittedHeaders = this.mimeMessage.getHeader(AUTO_SUBMITTED_HEADER); if (autoSubmittedHeaders != null) { for (String autoSubmittedHeader : autoSubmittedHeaders) { if ("...
MimeMessage automatic = mock(MimeMessage.class); when(automatic.getHeader("Auto-Submitted")).thenReturn(new String[]{"bart", "auto-replied"}); BetterMimeMessage instance = new BetterMimeMessage(automatic); assertTrue(instance.isAutomaticMessage()); automatic = mock(MimeMessage.class); when(auto...
1318639_2
class OrbTrackerMemberDataServiceImpl extends RemoteServiceServlet implements OrbTrackerMemberDataService, Watcher { @Override public String[] getJobsInProgress() throws NodeDoesNotExistException, ZooKeeperConnectionException, WatcherExc...
OrbTrackerMemberDataServiceImpl server = new OrbTrackerMemberDataServiceImpl(); int num_jobs = 10; CountDownLatch jobsLatch = new CountDownLatch(1); CountDownLatch updateLatch = new CountDownLatch(1); CountDownLatch removeLatch = new CountDownLatch(1); server.enterTestingMode(jobsLatch, removeLa...
1319605_35
class DomainValidator implements ConstraintValidator<Domain, CharSequence> { @Override public boolean isValid(CharSequence domain, ConstraintValidatorContext context) { Matcher matcher = DOMAIN_NAME_REGEX.matcher(domain); if (matcher.matches()) { domain = matcher.group(1); ...
assertTrue("b\u00fccher.ch in IDN should validate", validator.isValid("www.xn--bcher-kva.ch", null)); } }
1320181_158
class InfrastructureRep extends DefaultRepBase { public Datastore findDatastoreById(final Integer id) { assert id != null; return datastoreDao.findById(id); } public InfrastructureRep(); public InfrastructureRep(final EntityManager entityManager); public Datacenter findById...
Datastore datastore = datastoreGenerator.createUniqueInstance(); ds().persistAll(datastore); EntityManager em = ds().createEntityManagerAndBeginRollbackTransaction(); InfrastructureRep rep = new InfrastructureRep(em); assertNotNull(rep.findDatastoreById(datastore.getId())); ...
1322545_0
class Utility { public static boolean validateUrl(String url) { if (TextUtils.isEmpty(url)) { return false; } pattern = Pattern.compile(URL_PATTERN); matcher = pattern.matcher(url); if (matcher.matches()) { return true; } return false...
boolean actual = Utility.validateUrl("http://demo.ushahidi.com/smssync"); assertTrue("The provided URL is not a valid one", actual); } }
1328283_24
class EchoReader implements Reader { @Override public void get(ByteBuffer key, ReaderResult result) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("Original value: "); sb.append(BytesUtils.bytesToHexString(key)); sb.append(" Assigned to partition number: "); sb.append(pa...
EchoReader r = new EchoReader(57); ReaderResult result = new ReaderResult(); r.get(ByteBuffer.wrap(new byte[]{1, 2, 3}), result); assertTrue(result.isFound()); assertEquals("Original value: 01 02 03 Assigned to partition number: 57", new String(result.getBuffer().array())); } }
1338456_1
class LabelCounters { public void add(final LabelCounters diff) { if (diff.totalBytes != null) { this.totalBytes += diff.totalBytes; } if (diff.totalMessages != null) { this.totalMessages += diff.totalMessages; } if (diff.unreadMessages != null) { this.unreadMessages += diff.unreadMessages; } ...
LabelCounters c1 = new LabelCounters(); LabelCounters c2 = new LabelCounters(); LabelCounters c3 = new LabelCounters(); c1.setTotalBytes(123L); c1.setTotalMessages(23L); c1.setUnreadMessages(335L); c2.setTotalBytes(223L); c2.setTotalMessages(223L); c2.setUnreadMessages(685L); c3.setTotalBytes(1...
1341207_31
class IntMsdRadixSort implements ArrayNonComparisonSort<Integer> { @Nonnull Integer getMaxAbsNumber(@Nonnull Integer[] numbers) { Integer maxAbsNumber = 0; for (Integer number : numbers) { if (number >= 0) { if (number > maxAbsNumber) { maxAbsNumber = number; } } else if (number == Integer.MIN...
final IntMsdRadixSort sort = newSort(); assertEquals(Integer.valueOf(1), sort.getMaxAbsNumber(new Integer[]{1})); assertEquals(Integer.valueOf(2), sort.getMaxAbsNumber(new Integer[]{-2})); assertEquals(Integer.valueOf(Integer.MAX_VALUE), sort.getMaxAbsNumber(new Integer[]{Integer.MAX_VALUE, Integer.MIN_VALUE}))...
1342891_5
class JndiTreeParser { public CellTree parse(List<Property> model) { stack.push(root); parseSiblings(model, ""); return cellTree; } public JndiTreeParser(); SingleSelectionModel<JndiEntry> getSelectionModel(); private void parseSiblings(List<Property> siblings, String pa...
JndiTreeParser jtp = new JndiTreeParser(); ModelNode children = new ModelNode(); ModelNode inner = new ModelNode(); inner.get("class-name").set("org.acme.MyClass"); inner.get("value").set("org.acme.MyClass@xyz"); children.get("SomeEJB").set(inner); ModelNode par...
1346655_17
class Geometry { public static Point offset(int amount, Point point) { return offset(new Point(amount, amount), point); } public static Dimension increase(int amount, Dimension dimension); public static Point offset(Point offset, Point point); public static Point opposite(Point point); } ...
Point originalPoint = new Point(0, 0); Geometry.offset(11, originalPoint); assertEquals(0, originalPoint.x); assertEquals(0, originalPoint.y); } }
1350993_0
class Smoothie { public static synchronized SmoothieContainer getContainer() { if (container == null) { // This should really be done by a ServletContextListener when the webapp loads, but for now we are not modifying hudson-core, so bootstrap the container here. return new Smoothie...
SmoothieContainer container = Smoothie.getContainer(); assertNotNull(container); log.debug("Container: {}", container); } }
1358036_51
class SparqlPreParser { public Set<IRI> getReferredGraphs(String queryString, IRI defaultGraph) throws ParseException { Set<IRI> referredGraphs; JavaCCGeneratedSparqlPreParser parser = new JavaCCGeneratedSparqlPreParser(new StringReader(queryString)); SparqlUnit sparqlUnit; sparqlUn...
String queryStr = "PREFIX ns: <http://example.org/ns#> " + "INSERT DATA { <http://example/book1> ns:price 42 }; " + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1> ns:price 42 } }"; SparqlPreParser parser; parser = new SparqlPrePar...
1361294_0
class PersonRepo { public List<Person> list() { try (Connection con = ds.getConnection()) { ArrayList<Person> persons = new ArrayList<Person>(); ResultSet rs = con.createStatement().executeQuery(QUERY); while (rs.next()) { persons.add(read(rs)); ...
JdbcDataSource ds = new JdbcDataSource(); ds.setUrl("jdbc:h2:mem:person;DB_CLOSE_DELAY=-1"); new Migrator().prepare(ds); PersonRepo personRepo = new PersonRepo(); personRepo.ds = ds; List<Person> persons = personRepo.list(); Person person = persons.iterator().next...
1365016_6
class KeyboardState { public EnumSet<Key> getKeysReleasedSince(final KeyboardState previous) { final EnumSet<Key> result = EnumSet.copyOf(previous._keysDown); result.removeAll(_keysDown); return result; } public KeyboardState(final EnumSet<Key> keysDown, final KeyEvent keyEvent)...
ks1 = new KeyboardState(EnumSet.of(Key.A, Key.B), KeyEvent.NOTHING); ks2 = new KeyboardState(EnumSet.noneOf(Key.class), KeyEvent.NOTHING); final EnumSet<Key> released = ks2.getKeysReleasedSince(ks1); assertEquals("2 key", 2, released.size()); assertTrue("a released", released.c...
1365306_97
class LocalDateTimeValue { public static LocalDateTimeValue from(LocalDateTime value) { LocalDateTimeValue result = new LocalDateTimeValue(); result.setValue(value); return result; } public LocalDateTime getValue(); public void setValue(LocalDateTime value); @Override publi...
LocalDateTimeValue value = LocalDateTimeValue.from(LOCAL_DATE_TIME); assertEquals(LOCAL_DATE_TIME, value.getValue()); } }
1365699_2
class FilteringWordCount extends HadoopJob { @Override public int run(String[] args) throws Exception { Map<String,String> parsedArgs = parseArgs(args); Path inputPath = new Path(parsedArgs.get("--input")); Path outputPath = new Path(parsedArgs.get("--output")); Job wordCount = prepareJob(inputPa...
File inputFile = getTestTempFile("lotr.txt"); File outputDir = getTestTempDir("output"); outputDir.delete(); writeLines(inputFile, "One Ring to rule them all,", "One Ring to find them,", "One Ring to bring them all", "and in the darkness bind them"); Configuration ...
1367811_46
class Functions { public static boolean isAuthor(Job job) { User user = User.current(); return !(user == null || job == null || job.getCreatedBy() == null) && job.getCreatedBy().equals(user.getId()); } public Functions(); public String generateId(); public static boolean isModel(...
mockStatic(User.class); User user = createMock(User.class); expect(user.getId()).andReturn(USER); expect(User.current()).andReturn(user); Job job = createMock(FreeStyleProject.class); expect(job.getCreatedBy()).andReturn("user").times(2); replay(User.class, user, ...
1379319_1
class Physics { public static PVector calculateImpulse(PVector v1, PVector v2, float m1, float m2, float elasticity, PVector normal) { assert v1 != null : "Physics.calculateImpulse: v1 must be a valid PVector"; assert v2 != null : "Physics.calculateImpulse: v2 must be a valid PVector"; assert normal != null...
MassedBeing being1 = new MyBeing(1.0f, 1.0f); MassedBeing being2 = new MyBeing(1.0f, 1.0f); // very simple case (body hits body of equal mass at rest, transferring velocity) being1.setPosition(zeroVector()); being1.setVelocity(zeroVector()); being2.setPosition(makeVector(-1.0f,0.0f)); being2.setVelocit...
1381837_0
class ComplexityThresholdsUtils { public static List<ComplexityThreshold> convertAbacusThresholdsToComplexityThresholds(String[] propertyThresholds) { List<ComplexityThreshold> complexityThresholds = new ArrayList<ComplexityThreshold>(); String[] temp; for (String propertyThreshold : propertyThresholds...
List<ComplexityThreshold> complexityThresholds; complexityThresholds = ComplexityThresholdsUtils.convertAbacusThresholdsToComplexityThresholds(new String[] {"Simple"}); Assert.assertNotNull(complexityThresholds); Assert.assertEquals(complexityThresholds.size(), 1); Assert.assertEquals(complexityTh...
1381874_35
class Documents { public static String getId(Object document) { return getAccessor(document).getId(document); } public static void registerAccessor(Class<?> documentType, DocumentAccessor accessor); public static void setId(Object document, String id); public static String getRevision(Object document); public...
assertEquals("jsonNode_id", Documents.getId(nodeDoc)); } }
1387581_34
class BPMN2ServiceUtil { public static String getOperationName(TMessage message) { String ret=Character.toLowerCase(message.getName().charAt(0))+ message.getName().substring(1); ret = ret.replaceAll("Request", ""); ret = ret.replaceAll("Response", ""); ret = ret.replaceAll("Req", ""); ret = ret.rep...
TMessage m=new TMessage(); m.setName("BuyRequest"); String opName=BPMN2ServiceUtil.getOperationName(m); if (opName == null) { fail("No op name"); } if (!opName.equals("buy")) { fail("Expecting 'buy', but got: "+opName); } } }
1390800_7
class PipLogParser { static Map<String, String> parse(String installationLog, Log logger) { Map<String, String> downloadedDependencies = new HashMap<>(); String[] lines = installationLog.split("\\R"); MutableBoolean expectingPackageFilePath = new MutableBoolean(false); String packag...
// Build result map. Map<String, String> expectedResult = new HashMap<String, String>() {{ put("ecopkg1", "ecoPkg1-3.11.tar.gz"); put("ecopkg2", ""); put("ecopkg3", ""); put("ecopkg4", "ecoPkg4-1.1.1-py2.py3-none-any.whl"); put("ecopkg5", ""); ...
1406218_11
class TransformationContext implements Cloneable { @Override public TransformationContext clone() { TransformationContext newContext; try { newContext = (TransformationContext) super.clone(); } catch (CloneNotSupportedException e) { // Should never happen ...
TransformationContext context = new TransformationContext(); context.setId("id"); context.setSyntax(Syntax.XWIKI_2_0); XDOM xdom = new XDOM(Arrays.<Block>asList(new WordBlock("test"))); context.setXDOM(xdom); TransformationContext newContext = context.clone(); as...
1407946_8
class PanLine extends JPanel { public void setCustomWidthUnit(EnumWidthUnit enumWidthUnit) { comboBoxWidthUnit.setSelectedItem(enumWidthUnit); } public PanLine(); public String getAlign(); public String getThickness(); public String getCustomWidth(); public String getCustomWidthUnit(); public String getCo...
JComboBox comboBox = new JComboBox(); for (EnumWidthUnit enumWidthUnit : EnumWidthUnit.values()) { comboBox.addItem(enumWidthUnit); } comboBox.setSelectedIndex(0); Whitebox.setInternalState(panLine, "comboBoxWidthUnit", comboBox); panLine.setCustomWidthUnit(EnumWidthUnit.PIXEL); String actual = ((EnumW...
1415645_1
class CustomerStatementReader implements ItemReader<Statement> { public Statement read() throws Exception, UnexpectedInputException, ParseException { Customer customer = customerReader.read(); if(customer == null) { return null; } else { ...
Customer customer = new Customer(); customer.setId(5l); when(customerReader.read()).thenReturn(customer); when(tickerDao.getTotalValueForCustomer(5l)).thenReturn( new BigDecimal("500.00")); when(tickerDao.getStocksForCustomer(5l)).thenReturn( new ...
1421692_13
class CollectionUtils { public static <K, V> Map<K, List<V>> groupBy(Collection<V> list, Closure<K, V> closure) { if (null == closure) { throw new IllegalArgumentException("closure must not be null!"); } Map<K, List<V>> ret = new HashMap<K, List<V>>(); if (null != list) { for (V v : list) { K k = cl...
Map<K, List<V>> map = CollectionUtils.groupBy(list, closure); Assert.assertEquals(map, expected); } }
1443269_38
class BlockCache { public BlockCache(BlurMetrics metrics, boolean directAllocation, long totalMemory) { this(metrics,directAllocation,totalMemory,_128M); } public BlockCache(BlurMetrics metrics, boolean directAllocation, long totalMemory); public BlockCache(BlurMetrics metrics, boolean directAllocation,...
int blocksInTest = 2000000; int blockSize = 1024; int slabSize = blockSize * 4096; long totalMemory = 2 * slabSize; BlockCache blockCache = new BlockCache(new BlurMetrics(new Configuration()), true,totalMemory,slabSize,blockSize); byte[] buffer = new byte[1024]; Random random = new...
1446919_9
class ScreenNameValidator extends ScreenNameValidatorDB { public String checkName(String name) { build(); String rval = checkName(name, malesDB); if (rval == null) { rval = checkName(name, femalesDB); } return rval; } public ScreenNameValidator(); private void build(); public String checkName(Stri...
Assert.assertTrue(validator.checkName("mary", false).equals("Mary")); Assert.assertTrue(validator.checkName("JANE", false).equals("Jane")); Assert.assertTrue(validator.checkName("lIZ", false).equals("Liz")); Assert.assertTrue(validator.checkName("ShArOn", false).equals("Sharon")); Assert.assertTrue(validator...
1450115_60
class Uri { public String toRelativeUrl() { StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder(); if (MiscUtils.isNonEmpty(path)) sb.append(path); else sb.append('/'); if (query != null) sb.append('?').append(query); return sb.toString(); } public Uri(String schem...
Uri uri = new Uri("http", "user", "example.com", 44, null, "query=4", null); String relativeUrl = uri.toRelativeUrl(); assertEquals(relativeUrl, "/?query=4", "toRelativeUrl returned incorrect url"); } }
1452945_0
class PrototypeWrapper { public AbstractPE getPE(String keyValue) { AbstractPE pe = null; try { pe = (AbstractPE) lookupTable.get(keyValue); if (pe == null) { pe = (AbstractPE) prototype.clone(); pe.initInstance(); } //...
MockPE prototype = new MockPE(); PrototypeWrapper prototypeWrapper = new PrototypeWrapper(prototype, new WallClock()); assertEquals(0, prototype.getInitializeCount()); MockPE instance = (MockPE)prototypeWrapper.getPE("asd"); assertNotNull(instance); ...
1458461_1
class MetadataTask { public void setPropertyFile(File file) { this.propertyFile = file; } public void setPersistenceUnit(String pU); public void setConfigFile(File file); public void setType(String type); public void addConfiguredFileSet(FileSet fileSet); public MetadataDescriptor createMetadataDescriptor();...
MetadataTask mdt = new MetadataTask(); assertNull(mdt.propertyFile); File f = new File("."); mdt.setPropertyFile(f); assertSame(f, mdt.propertyFile); } }
1463490_1023
class XMLScriptService implements ScriptService { public String transform(Source xml, Source xslt) { return XMLUtils.transform(xml, xslt); } public XMLScriptService(); public static String escape(Object content); public static String escapeForAttributeValue(Object content); publi...
String d = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a b='c'>d</a>"; String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>" + "<xsl:output method='xml' omit-xml-declaration='yes'/>" ...
1469749_197
class MetadataValue { public void setConfidence(int value) { this.confidence = value; } public MetadataValue(TableRow row); public MetadataValue(); public MetadataValue(MetadataField field); public int getFieldId(); public void setFieldId(int fieldId); public int getIte...
int value = 5; mv.setConfidence(value); assertThat("testSetConfidence 0",mv.getConfidence(), equalTo(value)); } }
1475915_4
class TextTranslator { public String translate(String text) { for (TagTranslator translator : tagTranslators) { text= translator.translate(text); } return text; } public TextTranslator(Mapping mapping); private TextTranslator target; } class TextTranslatorTest { private TextTranslator...
assertEquals("", target.translate("")); assertEquals("", target.translate(null)); assertEquals("hello", target.translate("hello")); assertEquals("<a href=\"\">click</a>", target.translate("<a href=''>click</a>")); assertEquals("<a href=\"yahoo\">click</a>", target.translate("<a href='yahoo'>click</a...
1481910_4
class ResourceCodeWriter extends CodeWriter { @Override public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { FileObject resource = filer.createResource(StandardLocation.SOURCE_OUTPUT, pkg.name(), fileName); return resource.openOutputStream(); } public ResourceCodeWriter(Filer fi...
Filer filer = mock(Filer.class); FileObject fileObject = mock(FileObject.class); when(filer.createResource(Mockito.<Location> any(), anyString(), anyString())).thenReturn(fileObject); ResourceCodeWriter resourceCodeWriter = new ResourceCodeWriter(filer); JPackage jPackage = new JCodeModel()._package("some...
1484463_8
class RateTransform extends Transform { @Override public Object process(Object value) { Long time = System.currentTimeMillis(); if (this.lastValue == null) { this.lastUpdate = time; this.lastValue = value; return null; // no value at this time } if (!(value instanceof Number)) { thro...
RateTransform rt = new RateTransform(); assertEquals(null, rt.process(new Double(12))); } }
1493029_0
class ClasspathResources extends JarResources { public void loadResource(URL url) { try { // Is Local loadResource( new File( url.toURI() ), "" ); } catch (IllegalArgumentException iae) { // Is Remote loadRemoteResource( url ); } catch (URISyn...
final String name = "test"; ClasspathResources jarResources = getClasspathResources(name); URL resourceURL = jarResources.getResourceURL("test.properties"); Properties props = getProperties(resourceURL); assertEquals("testval", props.getProperty("testkey")); } }
1495584_7
class FunkyFunction implements ClassFunction<T> { public T execute() { try { return constructor.newInstance(constructionArguments); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); /* * Due to constraints on the constructor, ca...
final int test = 2; // @off class Instantiated {{ assertEquals(2, test); }} // @on FunkyFunction<Instantiated> executor = new FunkyFunction<Instantiated>(Instantiated.class); executor.execute(); } }
1502367_17
class Converter { public static List<Long> typeConvert(Iterable<String> list) { List<Long> result = new ArrayList<Long>(); for (String element : list) { if (StringUtils.isNotBlank(element)) { result.add(NumberUtils.toLong(element)); } } return result; } } class ConverterTest { @Test public voi...
ArrayList<String> a = Lists.newArrayList("1", "2", "3"); List<Long> b = Converter.typeConvert(a); Assert.assertEquals(a.size(), b.size()); } }
1511246_13
class CompilingProxyFactory extends ProxyFactory { @SuppressWarnings("unchecked") public <T> T createProxy(T obj, final InvocationHandler handler) { Class<?> c = obj.getClass(); Class<?> pc = getClassProxy(c); Constructor<?> cons; try { cons = pc.getConstructor(new C...
createProxy(new ClassWithBridgeMethod()).clone(); assertEquals("clone = ClassWithBridgeMethod", buff.toString()); // even bridge methods should be intercepted (there are two clone methods) callCloneMethods(0, new ClassWithBridgeMethod()); callCloneMethods(1, createProxy(new Class...
1516026_123
class CustomValidator implements FieldHookDefinition, ErrorMessageDefinition { @Override public boolean call(final Entity entity, final Object oldValue, final Object newValue) { if (fieldHook.call(entity, oldValue, newValue)) { return true; } if (entity.getError(fieldDefinit...
// given Map<String, ErrorMessage> errors = Maps.newHashMap(); errors.put("another" + FIELD_NAME, new ErrorMessage(CUSTOM_MSG)); stubFieldHookDef(false, errors); // when boolean isValid = customValidator.call(entity, oldValue, newValue); // then assertFa...
1520524_34
class SingleMappingHandler implements IResults { @Override public synchronized AtomAtomMapping getFirstAtomMapping() { if (allAtomMCS.iterator().hasNext()) { return allAtomMCS.iterator().next(); } return new AtomAtomMapping(source, target); } public SingleMappingHa...
////////System.out.println("getFirstMapping"); IAtom atomSource = new Atom("R"); IAtom atomTarget = new Atom("R"); IAtomContainer source = new AtomContainer(); source.addAtom(atomSource); IAtomContainer target = new AtomContainer(); target.addAtom(atomTarget); ...
1535924_5
class Activator implements BundleActivator, ServiceListener { @Override public void stop( BundleContext bundleContext ) throws Exception { AccessManagerFactoryTracker managerFactoryTracker = getAccessManagerFactoryTracker(); if (null != managerFactoryTracker) { managerFactoryTracke...
BundleContext bundleContext = mock(BundleContext.class); final AccessManagerFactoryTracker accessManagerFactoryTracker = mock(AccessManagerFactoryTracker.class); Activator activator = new Activator() { @Override protected AccessManagerFactoryTracker getAccessManagerFact...
1548514_2
class RubyKlassNavigator extends KlassNavigator<RubyModule> { @Override public List<Function> getFunctions(RubyModule clazz) { // implemented as a fallback to Java through reified class, but maybe there's a better way to do this return new ClassDescriptor(toJavaClass(clazz)).methods; } ...
final ScriptingContainer ruby = createRubyInstance(); final RubyKlassNavigator navigator = new RubyKlassNavigator(ruby.getProvider().getRuntime(), ClassLoader.getSystemClassLoader()); final MyRubyModule myModule = new MyRubyModule(ruby.getRuntime(), new MyRubyClass(ruby.getRuntime()), true); ...
1553760_291
class JavadocShortcutUriProcessor implements UriProcessor { @Override public String process(String uri) { String newUri = preprocessUri(uri); if (!newUri.equals(uri)) { newUri = prependWithBasePackage(newUri); if (SourceVersion.isName(newUri)) { if (isPotentialPackageName(newUri)) { return toPacka...
assertEquals("../index.html?org/eclipse/mylyn/wikitext/foo/package-summary.html", processor.process("@.foo")); assertEquals("../index.html?org/eclipse/mylyn/wikitext/foo/bar/package-summary.html", processor.process("@.foo.bar")); } }
1554165_0
class ValueMap { public HashMap<Enum, String> getDb() { return db; } private ValueMap(List<Value> valueList); public HashMap<String, Enum> getVal(); } class ValueMapTest { @Test public void testGetDb() {
System.out.println("getDb"); ValueMap instance = ValueMap.FINGERPRINT_TYPE; HashMap<Enum, String> result = instance.getDb(); assertNotNull(result); String dbValue = result.get(Fingerprint.Type.leftIndexFinger); assertEquals("2", dbValue); } }
1555964_9
class BitMask2 { public boolean isBitSet(int bit) { long bitMask = Long.rotateLeft(1, bit); long result = this.bitMaskValue & bitMask; if (result != 0) { return true; } return false; } public BitMask2(); public BitMask2(long currentValue); pub...
for (int bitNumber = 0; bitNumber < 64; bitNumber++) { long bitMask = Long.rotateLeft(1, bitNumber); BitMask2 bm = new BitMask2(bitMask); assertEquals(true, bm.isBitSet(bitNumber)); } } }
1557148_32
class CalendarUtil { public static Calendar getCalendar(String yyyy, String mm, String dd) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.valueOf(yyyy)); cal.set(Calendar.MONTH, Integer.valueOf(mm) - 1); cal.set(Calendar.DATE, Integer.valueOf(dd)); c...
Calendar actual = CalendarUtil.getCalendar(2000, 2, 3, 4, 5, 6); assertTrue(2000 == actual.get(Calendar.YEAR)); assertTrue(1 == actual.get(Calendar.MONTH)); assertTrue(3 == actual.get(Calendar.DATE)); assertTrue(4 == actual.get(Calendar.HOUR)); assertTrue(5 == actual.get(...
1558503_0
class DateUtils { public static Date create(int year, int month, int date) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(year, month - 1, date); return cal.getTime(); } public static Date create(int year, int month, int date, int hour, int minute, int second); } class DateUtilsTest { @T...
Date date = DateUtils.create(2010, 4, 12); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); assertThat(df.format(date), is("2010-04-12 00:00:00")); } }
1574061_514
class CategorizeFunction implements Function { public Object evaluate(Object object) { return evaluate(object, Object.class); } public CategorizeFunction(); public CategorizeFunction(List<Expression> parameters, Literal fallback); public String getName(); public List<Expression> get...
System.out.println(" testPrecedingThresholds"); final String[] categories = {"low", "mid", "high", "super"}; final Double[] thresholds = {0.0, 50.0, 100.0}; setupParameters(categories, thresholds); parameters.add(ff2.literal("preceding")); Function fn = finder.findFun...
1575956_121
class BookKeeperAdmin implements AutoCloseable { public static boolean areEntriesOfLedgerStoredInTheBookie(long ledgerId, BookieId bookieAddress, LedgerManager ledgerManager) { try { LedgerMetadata ledgerMetadata = ledgerManager.readLedgerMetadata(ledgerId).get().getValue(); ...
int lastEntryId = 10; long ledgerId = 100L; BookieId bookie0 = new BookieSocketAddress("bookie0:3181").toBookieId(); BookieId bookie1 = new BookieSocketAddress("bookie1:3181").toBookieId(); BookieId bookie2 = new BookieSocketAddress("bookie2:3181").toBookieId(); BookieId ...
1577630_11
class ListMemoizer { public M get(final ListNode<T> list) { if (null == list) { throw new IllegalArgumentException("null key"); } return (null == helper) ? null : helper.get(list); } public ListMemoizer(final Comparator<T> comparator); ...
ListMemoizer<String, Integer> m = createMemoizer(); assertNull(m.get(createList())); assertNull(m.get(createList("foo"))); assertNull(m.get(createList("foo", "bar"))); } }
1579900_0
class Percentiler { public int getPercentile (float value) { if (value < _min) { return 0; } else if (value > _max) { return 100; } else { return _percentile[toBucketIndex(value)]; } } public Percentiler(); public Percentiler(in...
Percentiler tiler = createGaussian(); assertEquals(0, tiler.getPercentile(tiler.getMinScore())); assertEquals(0, tiler.getPercentile(tiler.getMinScore()-1)); assertEquals(100, tiler.getPercentile(tiler.getMaxScore())); assertEquals(100, tiler.getPercentile(tiler.getMaxScore()+1)...
1579936_3
class GeneratedSourceMerger { public String merge (String newlyGenerated, String previouslyGenerated) throws Exception { // Extract the generated section names from the output and make sure they're all matched Map<String, Section> sections = Maps.newLinkedHashMap(); Matcher m = ...
String disabled = "// GENERATED VARIABLE DISABLED\n" + before; assertEquals(disabled, new GeneratedSourceMerger().merge(generated, disabled)); } }
1581151_6
class MacAddress { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final MacAddress that = (MacAddress) o; return Arrays.equals(array, that.array); } public MacAddress(final long macAddress); pu...
assertTrue(new MacAddress(MAC_BYTES).equals(new MacAddress(MAC_BYTES))); assertTrue(new MacAddress(MAC_HEX_STRING).equals(new MacAddress(MAC_BYTES))); assertTrue(new MacAddress(MAC_DEC_STRING).equals(new MacAddress(MAC_BYTES))); assertTrue(new MacAddress(MAC_BIN_STRING).equals(new MacAddress(MAC_BYTES))); a...
1583138_2
class Paging { public int getTotalPages() { return totalPages; } public Paging(List<T> items, int itemsPerPage); public Paging(T[] items, int itemsPerPage); public int getCurrentPage(); public int getTotalItems(); public Object getItem(int index); public void nextPage(); private int getLastPage(); publ...
Paging paging = new Paging(new Object[] {}, 2); assertEquals(0, paging.getTotalPages()); paging = new Paging(new Object[] { 0, 1 }, 2); assertEquals(1, paging.getTotalPages()); paging = new Paging(new Object[] { 0, 1, 2 }, 2); assertEquals(2, paging.getTotalPages()); paging = new Paging(new Object[] { ...