id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
41247722_82
class ZipUtil { static long computeCrcOfCentralDir(RandomAccessFile raf, CentralDirectory dir) throws IOException { CRC32 crc = new CRC32(); long stillToRead = dir.size; raf.seek(dir.offset); int length = (int) Math.min(BUFFER_SIZE, stillToRead); byte[] buffer = ...
ZipFile zip = new ZipFile(zipFile); Enumeration<? extends ZipEntry> ref = zip.entries(); byte[] buffer = new byte[0x2000]; while (ref.hasMoreElements()) { ZipEntry refEntry = ref.nextElement(); if (refEntry.getSize() > 0) { File tmp = File.createTe...
41250653_1
class BookmarksPresenter implements BookmarksContract.UserInteraction { @Override public void bookmarkMovie(Movie movie) { bookmarksStorage.bookmarkMovie(movie); } @Inject public BookmarksPresenter(BookmarksStorage bookmarksStorage); public void onResume(BookmarksContract.BookmarksView v...
presenter.bookmarkMovie(BOOKMARKED_MOVIE); verify(bookmarksStorage).bookmarkMovie(BOOKMARKED_MOVIE); } }
41253781_127
class Option implements Iterable<T>, Serializable { public Option<T> orElse(T value) { return isDefined() ? this : of(value); } private Option(@Nullable T value); @Override public int hashCode(); @Override public boolean equals(@Nullable Object to); @Override public Iterator<T> itera...
Assertions.assertEquals("else", Option.none().orElse(Option.of("else")).get()); } }
41263845_144
class ConcurrentInvertedRadixTree implements InvertedRadixTree<O>, PrettyPrintable, Serializable { @Override public Iterable<KeyValuePair<O>> getKeyValuePairsForKeysPrefixing(final CharSequence document) { return new Iterable<KeyValuePair<O>>() { @Override public Iterator<KeyVal...
ConcurrentInvertedRadixTree<Integer> tree = new ConcurrentInvertedRadixTree<Integer>(getNodeFactory()); tree.put("1234567", 1); tree.put("1234568", 2); tree.put("123", 3); // ○ // └── ○ 123 (3) // └── ○ 456 // ├── ○ 7 (1) ...
41263864_17
class Locks { public static <L extends Lock> boolean tryLockAll(Iterable<L> locks) { Deque<L> stack = new LinkedList<L>(); boolean success = false; try { for (L lock : locks) { success = lock.tryLock(); if (success) { stack.pus...
HoldCountLock lock1 = new HoldCountLock(new ReentrantLock()); HoldCountLock lock2 = new HoldCountLock(new ReentrantLock()) { @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { throw new InterruptedException(); } ...
41286649_1
class XmlCreator extends AsyncTask<Void, Integer, Uri> { public static String cleanFilename(String fileName, String defaultName) { if (fileName == null || "".equals(fileName)) { fileName = defaultName; } else { fileName = fileName.replaceAll("\\W", ""); fileName ...
String dirty = ""; String clean = XmlCreator.cleanFilename(dirty, "Untitled"); Assert.assertEquals("Cleaned", "Untitled", clean); } }
41324285_8
class SmellMeasuresSensor implements Sensor { @Override public void execute(final SensorContext context) { final List<InputFile> inputFiles = Lists.newArrayList(this.fileSystem.inputFiles(this.javaFilesPredicate)); final SmellMeasurer measurer = new SmellMeasurer(context); for (final In...
final SmellMeasuresSensor sut = new SmellMeasuresSensor(this.fs); final File testFile = new File("src/test/resources/SmellMeasuresSensorTest_1.java"); Mockito.when(this.fs.inputFiles(this.predicate)) .thenReturn(ImmutableList.<InputFile> of(this.inputFile)); Mockito.when(this...
41327255_9
class WordUtil { public static int[] getWordColors(List<LetterSource> letters, String word) { int[] colors = new int[word.length()]; if (letters == null) { for (int i = 0; i < colors.length; ++i) { colors[i] = COLOR_MISSING; } return colors; } SpelledWord spelledWord = Wor...
LetterSource letterO = TestUtil.createLetterSource("O"); LetterSource letterA = TestUtil.createLetterSource("A"); LetterSource letterB = TestUtil.createLetterSource("B"); LetterSource letterC = TestUtil.createLetterSource("C"); LetterSource letterD = TestUtil.createLetterSource("D"); letterD.ava...
41351929_2
class Snmp implements Session, CommandResponder { public USM getUSM() { MPv3 mp = (MPv3) getMessageProcessingModel(MPv3.ID); if (mp != null) { return (USM)mp.getSecurityModel(SecurityModel.SECURITY_MODEL_USM); } return null; } public Snmp(); public Snmp(TransportMapping transportMappin...
assertNotSame(snmpCommandGenerator.getUSM(), snmpCommandResponder.getUSM()); } }
41361042_43
class Dump2HTMLCreator { public void dump(DumpMode mode, File dbDirectory, File htmlDirectory, @Nullable File imageDirectory) throws IOException { try (WikiDB db = new WikiDB(dbDirectory)) { if (mode == BOTH || mode == WRITE_TEMPLATES_AND_MODULES) { firstPass(db); ...
creator.dump(Dump2HTMLCreator.DumpMode.BOTH, dbDir, htmlDir, null); assertThat(dbDir).isDirectory(); assertThat(htmlDir).isDirectory(); assertThat(htmlDir.listFiles()).hasSize(3); } }
41395725_46
class CollectionUtil { public static String toString(final Collection<?> collection, final String separator) { if (collection == null || collection.isEmpty()) { // just return an empty String if the collection is null or empty return ""; } if (separator == null) { ...
Assert.assertEquals("", CollectionUtil.toString(Collections.emptyList(), ".")); } }
41414120_5
class RowKeyUtil { public static RowKey getEndRowKeyOfPrefix(RowKey prefixRowKey) { Util.checkRowKey(prefixRowKey); byte[] rowkeyBytes = prefixRowKey.toBytes(); Util.check(rowkeyBytes.length != 0); boolean isAllByteIsFF = true; for (byte b : rowkeyBytes) { if (...
try { RowKeyUtil.getEndRowKeyOfPrefix(null); Assert.fail(); } catch (Exception e) { //ignore. } try { RowKeyUtil.getEndRowKeyOfPrefix(new StringRowKey("")); Assert.fail(); } catch (Exception e) { //ignore. ...
41423327_23
class StringUtil { public static int findWhitespace(CharSequence s) { return findWhitespace(s, 0); } private StringUtil(); public static String fixSizeString(int size, boolean alignLeft, char filler, long value); public static String fixSizeString(int size, boolean alignLeft, String s); public static ...
final String s = "Bla\n\r\n\r \thello \r\r\n\nblabla"; Assert.assertEquals(3, StringUtil.findWhitespace(s)); for (int i = 0; i < s.length(); i++) { final int expected = i <= 3 ? 3 : i < 9 ? i : i < 14 ? 14 : i < s.length() - 6 ? i : s.length(); Assert.assertEquals(expected, StringUtil.findWhitespace(s, i));...
41460477_59
class PointHandlerDispatcher implements Runnable { @Override public void run() { try { AtomicInteger dispatchedCount = new AtomicInteger(0); long startMillis = System.currentTimeMillis(); digestsSize.set(digests.size()); // update size before flushing, so we show a higher value Iterato...
in.put(keyA, digestA); in.flush(); timeMillis.set(101L); subject.run(); assertThat(pointOut).hasSize(1); assertThat(blockedOut).hasSize(0); assertThat(backingStore).isEmpty(); ReportPoint point = pointOut.get(0); TestUtils.testKeyPointMatch(keyA, point); } }
41486933_66
class PersistentMap implements Initialisable { public boolean containsKey(final K key) throws DataAccessLayerException { return (key != null && _dao.contains(key)); } public PersistentMap(final Class<K> k, final Class<V> v, final String name, final boolean bidirectional, final V defaultValue); public void ...
for (String key : TESTDATA1.keySet()) { assertTrue(map.containsKey(key)); } for (String key : TESTDATA4.keySet()) { assertTrue(!map.containsKey(key)); } } }
41505622_33
class AdmobAdapterCalculator { public boolean canShowAdAtPosition(int position, int fetchedAdsCount) { // Is this a valid position for an ad? // Is an ad for this position available? return isAdPosition(position) && isAdAvailable(position, fetchedAdsCount); } public int getNoOfDat...
setupAdmobAdapterCalculatorHelper(10, 0, 0); assertThat(admobAdapterCalculator.canShowAdAtPosition(0, 100), is(false)); } }
41547678_77
class ParamUtils { public static String getterName(FormalParameter formalParameter, SymbolResolver resolver) { return Property.getterName(formalParameter.getType(), formalParameter.getName(), resolver); } private ParamUtils(); public static boolean verifyOrder(List<ActualParam> actualParams)...
SymbolResolver resolver = new ComposedSymbolResolver(Collections.emptyList()); assertEquals("getFoo", ParamUtils.getterName(new FormalParameterSymbol(new ReferenceTypeUsage(ReflectionTypeDefinitionFactory.getInstance().getTypeDefinition(Boolean.class, resolver)), "foo"), DUMMY_RESOLVER)); assert...
41548314_0
class DCAwareFailoverRoundRobinPolicy implements LoadBalancingPolicy, CloseableLoadBalancingPolicy { public HostDistance distance(Host host) { String dc = dc(host); // If the connection has switched to the backup DC and fulfills // the requirement for a back switch, make it happen. if(!switchBackCanNeverHap...
int i=0; for(Host host:hosts){ policy.onUp(host); if(i<=2){ // dc1 is local assertEquals(policy.distance(host),HostDistance.LOCAL); }else{ assertTrue(policy.distance(host).equals(HostDistance.REMOTE) || policy.distance(host).equals(HostDistance.IGNORED)); } i++; } } }
41627638_105
class Solution { public List<String> fizzBuzz(int n) { return IntStream.rangeClosed(1, n).boxed().map(i -> { boolean isFizz = i % 3 == 0; boolean isBuzz = i % 5 == 0; if (isFizz && isBuzz) { return "FizzBuzz"; } else if (isBuzz) { ...
Solution solution = new Solution(); List<String> strings = solution.fizzBuzz(3); assertThat(strings, hasItems("1", "2", "Fizz")); } }
41630081_12
class TodaysExpensePresenter { public void renderTodaysExpenses() { view.displayTodaysExpenses(expenses); } public TodaysExpensePresenter(TodaysExpenseView view, ExpenseDatabaseHelper expenseDatabaseHelper); public void renderTotalExpense(); private ExpenseDatabaseHelper database; private TodaysExp...
presenter.renderTodaysExpenses(); verify(view).displayTodaysExpenses(expenses); } }
41633076_0
class ClassDefinitionDao { public Set<ClassDefinition> parseClassFiles(Path path) { Set<ClassDefinition> set = new HashSet<>(); try { Map<String, Path> stringPathMap = preloadClassDefs(path, set); for (Map.Entry<String, Path> stringPathEntry : stringPathMap.entrySet()) { ...
Set<ClassDefinition> classDefinitions = classDefinitionDao.parseClassFiles(null); Assertions.assertSame(classDefinitions.size(), 1); ClassDefinition c = classDefinitions.iterator().next(); Assertions.assertEquals(c.getName(), "ClassExample1"); Assertions.assertEquals(c.getDescrip...
41636618_2
class GenerateMojo extends AbstractMojo { @Nullable @SneakyThrows({ MalformedURLException.class, NoSuchAlgorithmException.class }) @VisibleForTesting Dependency findArtifactInRepository(Artifact artifact, ArtifactRepository repository) throws MojoExecutionException { String artifac...
GenerateMojo mojo = new GenerateMojo(); mojo.setLog(new SystemStreamLog()); Dependency dependency = mojo.findArtifactInRepository( new DefaultArtifact("org.spigotmc", "spigot-api", "1.8-R0.1-SNAPSHOT", "compile", "jar", "jar", new DefaultArtif...
41688821_1
class NavigatorCodeGenerator { MethodSpec handleParamActivity(String group, NavigableAnnotatedClass value) { TypeName activityTypeName = AndroidSpecificClassProvider.getActivityTypeName(); TypeName intentTypeName = AndroidSpecificClassProvider.getIntentTypeName(); String activityQualifiedNa...
String className = TestConstants.testPackageName + ".AA"; NavigableAnnotatedClass navigableAnnotatedClass = Mockito.mock(NavigableAnnotatedClass.class); TypeElement typeElement = Mockito.mock(TypeElement.class); Name name = Mockito.mock(Name.class); when(typeElement.getQualif...
41741864_2
class MultiPathTrie { public void addOrAppendPath(final String path, final T payload) { if (path == null) { return; } Collection<T> currentPayload = delegate.get(path); if (currentPayload == null) { currentPayload = new LinkedList<>(); delegate.a...
MultiPathTrie<String> multiPathTrie = new MultiPathTrie<>(); multiPathTrie.addOrAppendPath("/a/b/c", "abc1"); multiPathTrie.addOrAppendPath("/a/b/c", "abc2"); multiPathTrie.addOrAppendPath("/a/b", "ab1"); Collection<String> strings1 = multiPathTrie.get("/a/b/c"); Asse...
41742830_0
class PokerUtils { public static double getChenScore(Card[] cards) { if (cards.length != 2) { throw new IllegalArgumentException("Invalid number of cards: " + cards.length); } // Analyze hole cards. int rank1 = cards[0].getRank(); int suit1 = cards[0].ge...
Card card1 = null; Card card2 = null; card1 = new Card(Card.ACE, Card.SPADES); card2 = new Card(Card.ACE, Card.HEARTS); Assert.assertEquals(20.0, PokerUtils.getChenScore(new Card[] {card1, card2}), DELTA); card1 = new Card(Card.ACE, Card.SPADES); card2 =...
41742943_7
class MessageParser { private static Data<?> parseData(byte[] data, int offset) throws SecsParseException { if (data.length < 2) { throw new SecsParseException("Invalid data length: " + data.length); } int formatByte = data[offset]; int formatCode = formatByte &...
Data<?> data = MessageParser.parseData("<U2>"); Assert.assertTrue(data instanceof U2); U2 u2 = (U2) data; Assert.assertEquals(0, u2.length()); data = MessageParser.parseData("<U2 0 1 65535>"); Assert.assertTrue(data instanceof U2); u2 = (U2) data; ...
41754174_4
class ElectrumMultiWallet extends SmartMultiWallet implements WalletExtension, StratumChain.Listener { @Override public void markKeysAsUsed(Transaction tx) { wallet.lock(); wallet.lockKeychain(); try { KeyChainGroup group = wallet.getKeychain(); List<Object> oldC...
control.replay(); DeterministicKey key1 = wallet.currentReceiveKey(); Transaction tx1 = FakeTxBuilder.createFakeTx(params, Coin.CENT, key1.toAddress(params)); multiWallet.addPendingDownload(tx1.getHash()); multiWallet.receive(tx1, 0); DeterministicKey key2 = wallet.curren...
41772834_20
class CommentParser { static Comment parse(String owningClass, String commentText) { return isBlank(commentText) ? Comment.createEmpty() : new Comment(parseElements(owningClass, commentText.trim())); } private static List<CommentElement> parseElements(String owningClass, String commentText); p...
List<CommentElement> elements = CommentParser.parse("TestClass", "{@value ClassName#member}").getElements(); assertEquals(1, elements.size()); assertEquals(new InlineValue(new Value("ClassName", "member")), elements.get(0)); } }
41812613_1
class IdGenerator { public String increment(String fullId, int proposedCutoff) { StringBuilder mutable = new StringBuilder(fullId); if (proposedCutoff <= fullId.length()) { // First try normal incrementing for (int i = proposedCutoff - 1; i > 0; i--) { int n...
IdGenerator testGenerator = new IdGenerator(IdAlphabets.COLLECTION_ID, true); String[] inputs = new String[]{ "0000", "A", "AZ00", "Az00", "Zz00", "zz00", "zzz0", "zzzz" ...
41817706_439
class CloudHubArtifactDeployer implements ArtifactDeployer { protected Map<String, String> resolveProperties(Map<String, String> originalProperties, Map<String, String> properties, boolean overrideProperties) { if (properties != null) { if (!overridePropert...
Map<String, String> originalProperties = new HashMap<>(); originalProperties.put("foo", "bar"); Map<String, String> properties = new HashMap<>(); Map<String, String> resolvedProperties = cloudHubArtifactDeployer.resolveProperties(originalProperties, properties, true); assertThat("resolvedProperties ...
41822437_0
class CustomIssueRegistry extends IssueRegistry { @Override public List<Issue> getIssues() { return mIssues; } public CustomIssueRegistry(); private CustomIssueRegistry mCustomIssueRegistry; } class CustomIssueRegistryTest { private CustomIssueRegistry mCustomIssueRegistry; @...
int size = mCustomIssueRegistry.getIssues().size(); assertThat(size).isEqualTo(3); } }
41889031_16
class ImportExportJsonHelper { public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } ...
final String emptySource = "{\"app_version\":\"0.11.6\",\"app_version_int\": 47,\"subscriptions\":[]}"; final List<SubscriptionItem> items = ImportExportJsonHelper.readFrom( new ByteArrayInputStream(emptySource.getBytes(StandardCharsets.UTF_8)), null); assertTrue...
41892061_2
class RecordingTransaction extends RecordingTransactionBase implements Transaction { public static RecordingTransaction wrap(Transaction tx) { return new RecordingTransaction(tx); } private RecordingTransaction(Transaction tx); private RecordingTransaction(Transaction tx, Predicate<LogEntry> filter); ...
TypedTransaction ttx = tl.wrap(rtx); ttx.mutate().row("r5").fam("cf5").qual("cq5").set("1"); ttx.mutate().row("r6").fam("cf6").qual("cq6").set("1"); List<LogEntry> entries = rtx.getTxLog().getLogEntries(); Assert.assertEquals(2, entries.size()); Assert.assertEquals("LogEntry{op=SET, row=r5, col=...
41930098_3
class RateLimiter { public boolean tryAcquire() { // current time millis is not monotonic - it can jump back depending on user choice or NTP long now = System.nanoTime() / 1_000_000; // after this the request should be expired long toBeExpired = now - expireTime; synchroniz...
// fill the size - 100ms should be reasonable high RateLimiter rateLimiter = new RateLimiter(1, 100); assertTrue("Filling up", rateLimiter.tryAcquire()); Thread.sleep(50); // still is full - should fail assertFalse("Expired too early", rateLimiter.tryAcquire()); ...
41933697_30
class MarketConfigYamlRepository implements MarketConfigRepository { @Override public List<MarketConfig> findAll() { LOG.info(() -> "Fetching all Market configs..."); return ConfigurationManager.loadConfig(MarketsType.class, MARKETS_CONFIG_YAML_FILENAME) .getMarkets(); } @Override public Marke...
expect(ConfigurationManager.loadConfig(eq(MarketsType.class), eq(MARKETS_CONFIG_YAML_FILENAME))) .andReturn(allTheInternalMarketsConfig()); PowerMock.replayAll(); final MarketConfigRepository marketConfigRepository = new MarketConfigYamlRepository(); final List<MarketConfig> marketConfigItems ...
41963293_1
class App { public int calculateSomething() { return 0; } public static void main( String[] args ); } class AppTest { @Test public void testApp() {
assertEquals(0,new App().calculateSomething()); } }
41971504_6
class Linky { public static String linkify(List<Link> links, String text) { //if(!hasLinks(links)) { return text; } int addedChars = 0; //offset for inserting for (Link link : links) { StringBuilder stringBuilder = new StringBuilder(text); int start = link.getStart(); int end = link...
//given no link links = new ArrayList<>(); final String expected = mockString; assertThat(linkify(links, mockString)).isEqualTo(expected); } }
41985062_6
class RxBroadcastReceiver { @CheckResult @NonNull // public static Observable<Intent> create(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { checkNotNull(context, "context == null"); checkNotNull(intentFilter, "intentFilter == null"); return Observable.create(new Obser...
try { //noinspection ResourceType RxBroadcastReceiver.create(null, null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("context == null"); } } }
41985966_3
class JsonConfigurationLoader implements ConfigurationLoader { @Override public Configuration loadFileConfiguration(String filePath) throws IOException { File configurationFile = new File(filePath); String configurationJson = FileUtils.readFileToString(configurationFile); return loadJsonConfiguration(...
String configFilePath = "src/test/resources/stylechecker/WildCardAllow.json"; JsonConfigurationLoader loader = new JsonConfigurationLoader(); Configuration config = loader.loadFileConfiguration(configFilePath); String methodNameFormatValue = config.getAttribute(StyleName.METHOD_NAME_FORMAT); asser...
42019073_2
class Utils { public static double angleDifference(double angle1, double angle2) { return ((((angle1 - angle2) % (Math.PI * 2.0)) + (Math.PI * 3)) % (Math.PI * 2)) - Math.PI; } public static double getHeading(Quaternion quaternion); public static double pointDirection(double x1, double y1,...
assertEquals(Utils.angleDifference(Math.PI * 8.0, Math.PI), -Math.PI, 0.01); } }
42046027_47
class CCRay3 extends CCLine3Base { public double distanceSquared(final CCVector3 thePoint, final CCVector3 theStore) { final CCVector3 vectorA = new CCVector3(); vectorA.set(thePoint).subtractLocal(_myOrigin); final double t0 = _myDirection.dot(vectorA); if (t0 > 0) { // d = |P - (O + t*D)| vectorA.set(...
final CCRay3 ray1 = new CCRay3(); assertTrue(25.0 == ray1.distanceSquared(new CCVector3(0, 5, 3), null)); final CCVector3 store = new CCVector3(); assertTrue(9.0 == ray1.distanceSquared(new CCVector3(0, 3, 3), store)); assertEquals(new CCVector3(0, 0, 3), store); assertT...
42050188_32
class SymbolTableService extends AbstractService<SymbolTableService> { public boolean hasStartProd() { return getStartProd().isPresent(); } public SymbolTableService(ASTCDCompilationUnit compilationUnit); public SymbolTableService(CDDefinitionSymbol cdSymbol); @Override public String getSubPackage();...
CD4AnalysisParser cd4AnalysisParser = new CD4AnalysisParser(); Optional<ASTCDDefinition> astcdDefinition = cd4AnalysisParser.parse_StringCDDefinition( "<<startProd=\"_ast.ASTFoo\">> public classdiagram Bar {}"); assertTrue(astcdDefinition.isPresent()); assertFalse(cd4AnalysisParser.hasErrors());...
42050815_55
class SonarScannerExecutor extends AbstractBuildExecutor<SonarRunner> { @Override BuildResult execute(SonarRunner build, Configuration config, Map<String, String> adjustedProperties, CommandExecutor create) { return execute(build, config, adjustedProperties, new SonarScannerInstaller(config.locators()), create...
SonarRunner build = SonarRunner.create() .setProjectDir(new File(".")) .setProjectKey("SAMPLE") .setTimeoutSeconds(30) .setDebugLogs(true) .setRunnerVersion("1.3"); Map<String, String> props = new TreeMap<>(); props.put("sonar.jdbc.dialect", "h2"); props.put("sonar.projectK...
42054620_2
class Fraction { static long gcd(long num, long den) { long left, right; if (num < den) { left = den; right = num; } else { left = num; right = den; } Function<LongBiFunction, LongBiFunction> lf = f -> (l, r) -> r == 0? l : f.a...
long gcd = gcd(784, 840); assertThat(gcd, is(56L)); } }
42057361_181
class TIntArrayList implements Externalizable, Cloneable { @Override public boolean equals(Object other) { if (other instanceof TIntArrayList) { return delegate.equals(((TIntArrayList) other).delegate); } return false; } public TIntArrayList(gnu.trove.list.array.TIntArrayList delegate); p...
assertEquals(new TIntArrayList(), new TIntArrayList()); assertNotEquals(new TIntArrayList(), new TIntArrayList().toString()); } }
42089429_26
class DefaultRxDockerClient implements RxDockerClient { @Override public HttpStatus checkAuth(final AuthConfig authConfig) { return checkAuthObs(authConfig).onErrorReturn(e -> { if (e instanceof ServiceException) { logger.info("checkAuth threw RestServiceCommunicationExcepti...
assumeTrue(System.getenv("CIRCLE_USERNAME") == null); HttpStatus httpStatus = client.checkAuth(AuthConfig.authConfig("xxx", "xxx", "xxxx")); assertThat(httpStatus.code(), is(equalTo(401))); assertThat(httpStatus.message(), is(equalTo("Unauthorized"))); } }
42098141_0
class DoubleColumn implements Column<DoubleColumnId> { public static Builder builder(DoubleColumnId id) { return new Builder(id); } private DoubleColumn(DoubleColumnId id, DoubleStream values, Map<String, String> metaData); public static DoubleColumn of(DoubleColumnId id, double value); ...
DoubleColumn column = builder().add(1d).addAll(2, 9).add(0d).build(); assertMultipleValues(column); } }
42109069_17
class PolicyIdpAccessEnforcer implements JsonMapper { public String authenticatingAuthority() { return federatedUser().getAuthenticatingAuthority(); } public void actionAllowed(PdpPolicy pdpPolicy, PolicyAccess policyAccess, String serviceProviderId, List<String> identityProviderIds); public b...
assertEquals(authenticatingAuthority, subject.authenticatingAuthority()); } }
42175803_8
class AngelixSynthesis { public Optional<Map<AngelixLocation, Node>> repair(Map<AngelixLocation, Expression> original, AngelicForest angelicForest, Map<AngelixLocation, Multiset<Node>> components, ...
Multiset<Node> components = HashMultiset.create(); components.add(x); components.add(y); components.add(Library.ADD); components.add(Library.SUB); Map<AngelixLocation, Multiset<Node>> componentsMap = new HashMap<>(); componentsMap.put(loc1, components); A...
42182481_0
class JpaProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Map<PersistentUnit, List<? extends AnnotationMirror>> units = new HashMap<PersistentUnit, List<? extends AnnotationMirror>>(); for (Element elem :...
JpaProcessor processor = new JpaProcessor(); Map<PersistentUnit, List<? extends AnnotationMirror>> units = new HashMap<>(); PersistentUnit pu = getTestPersitentUnit(); units.put(pu, Collections.emptyList()); URL url = this.getClass().getResource("/expected_persistence.xml"); ...
42186064_2
class ASMParameterAnalyzer implements ParameterAnalyzer { @Override public Parameter[] getParameters(InvokeTarget target) { return getParameters(target, null); } @Override @SuppressWarnings("unchecked") public Parameter[] getParameters(InvokeTarget target, Parameter[] parameters); private ThreadLocal<ASMParam...
ASMParameterAnalyzer analyzer = this.analyzer.get(); Class<?> controllerClass = ASMTestController.class; Object controller = controllerClass.newInstance(); InvokeTarget target = new InvokeTarget(null, controller, "method3"); Parameter[] parameters = analyzer.getParameters(target); Assert.assertEquals(3, p...
42191480_0
class DividerItemDecoration extends RecyclerView.ItemDecoration { @Override public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) { if (positionAdapter == null) { positionAdapter = new PositionAdapter(parent.getLayoutManager(), offset); } int childCount = parent.getC...
givenThatThereIsOneCellToRender(); Drawable drawableMock = mock(Drawable.class); when(drawableMock.mutate()).thenReturn(drawableMock); List<Layer> layers = getSingleDrawableLayer(drawableMock); dividerItemDecoration = new DividerItemDecoration(layers); dividerItemDecoration.onDrawOver(canvasMoc...
42201162_17
class PrivateAccess { public static <T> T callDefaultConstructor(Class<T> klass) throws Throwable{ //TODO: not only should be atMostOnce in a test, but in the whole suite/archive if(klass == null){ throw new IllegalArgumentException("No specified class"); } //RuntimeS...
FooConstructor.counter = 0; PrivateAccess.callDefaultConstructor(FooConstructor.class); assertTrue(FooConstructor.counter > 0); } }
42250911_1
class Utils { @SafeVarargs public static <T> Optional<T> firstPresent(Supplier<Optional<T>>... optionals) { return Arrays.stream(optionals) .map(Supplier::get) .flatMap(Utils::stream) .findFirst(); } public static Stream<T> stream(Optional<T> optional); public static String toBase64(String content)...
@SuppressWarnings("unchecked") Supplier<Optional<String>> notCalled = mock(Supplier.class); when(notCalled.get()).thenReturn(Optional.empty()); Utils.firstPresent(() -> Optional.of("present"), notCalled); verifyZeroInteractions(notCalled); } }
42256650_0
class VersionUtil { public static int compareVersions(String v1, String v2) { if (v1 == null && v2 == null) { return 0; } else if (v1 == null) { return -1; } else if (v2 == null) { return 1; } String[] v1Parts = v1.split("[.]"); String[] v2Parts = v2.split("[.]"); int maxLength = Math.max(v1...
assertEquals(VersionUtil.compareVersions("1.0", "1.0.0"), 0); assertEquals(VersionUtil.compareVersions("1.0", "1.0.1"), -1); assertEquals(VersionUtil.compareVersions("1.0", "0.0.0"), 1); assertEquals(VersionUtil.compareVersions("0.0.0.1", "1.0.0"), -1); assertEquals(VersionUtil.compareVersions(...
42271567_0
class MainActivity extends AppCompatActivity { public Toolbar getToolbar() { return toolbar; } @Override protected void onCreate(Bundle savedInstanceState); @Override public void onBackPressed(); @Override protected void onPause(); @Override protected void onResume(); private void ...
Toolbar expected = toolbar; Toolbar actual = activity.getToolbar(); assertEquals("Toolbar is different!", expected.hashCode(), actual.hashCode()); } }
42273328_17
class HMAC { public static byte[] sign(String toSign, String secret) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, UnsupportedEncodingException { validateParameters(toSign, secret); String password = secret; PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKe...
try { byte[] Signature = HMAC.sign("Some_String", "Password"); assertNotNull(Signature); assertTrue(!Signature.toString().equals("SOME_STRING")); } catch (Exception e) { assertTrue(e instanceof Exception); } } }
42290369_549
class HdfsUtils { public static List<String> listDirs(Configuration hadoopConf, String pathname) throws IOException { return Arrays .stream(FileSystem.get(hadoopConf).listStatus(new Path(pathname))) .filter(FileStatus::isDirectory) .map(x -> x.getPath().toStr...
Path tempDir = Files.createTempDirectory(this.getClass().getSimpleName()); Path subDir1 = Files.createTempDirectory(tempDir, "list_me"); Path subDir2 = Files.createTempDirectory(tempDir, "list_me"); // when List<String> paths = HdfsUtils.listDirs(new Configuration(), tempDir.toS...
42304749_177
class JobNodeStorage { public void removeJobNodeIfExisted(final String node) { if (isJobNodeExisted(node)) { regCenter.remove(jobNodePath.getFullPath(node)); } } public JobNodeStorage(final CoordinatorRegistryCenter regCenter, final String jobName); public boolean isJobNo...
when(regCenter.isExisted("/test_job/config")).thenReturn(false); jobNodeStorage.removeJobNodeIfExisted("config"); verify(regCenter).isExisted("/test_job/config"); verify(regCenter, times(0)).remove("/test_job/config"); } }
42324543_6
class Topics { public static Topic getTopic(String name) { return new TopicImpl(new String[] {name}); } public static Topic getSubtopic(Topic topic, String field); public static Topic getTopic(String... fields); public static Topic parse(String s); public static String toString(Topic topic); } class...
Topic joe = Topics.getTopic("Joe"); Topic joebob = Topics.getTopic("Joe", "Bob"); Topic bobjoe = Topics.getTopic("Bob", "Joe"); assertTrue(!joebob.equals(bobjoe)); assertTrue(joebob.compareTo(bobjoe) > 0); assertTrue(bobjoe.compareTo(joebob) < 0); assertTrue(!joe.equals(joebob)); asser...
42427904_0
class BaseFilter extends Base { public BaseFilter(Map config) { super(config); this.config = config; this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); final List<String> ifConditions = (List<String>) this.config.get("if"); if (ifConditions != null...
HashMap config = new HashMap(); config.put("remove_fields", new ArrayList(Arrays.asList("test1", "[a][b]"))); config.put("add_fields", new HashMap() {{ this.put("ok", true); this.put("[extra][value]", 11.11); this.put("[extra][metric][value]", 10); }})...
42446819_0
class KVOperationSerializer extends TypeSerializer<KVOperation<K, V>> { @SuppressWarnings("unchecked") @Override public KVOperation<K, V> copy(KVOperation<K, V> from, KVOperation<K, V> to) { KVOperationType type = from.type; to.type = from.type; to.queryID = from.queryID; to.isPartOfTransaction = from.isPa...
Random rnd = new Random(); KVOperation<Integer, Integer>[] ops = gen.generate(1000); KVOperationSerializer<Integer, Integer> serializer = gen.getSerializer(); for (KVOperation<Integer, Integer> op : ops) { assertEquals(op, serializer.copy(op)); } for (KVOperation<Integer, Integer> op : ops) { asse...
42452274_0
class EmailValidator { public static boolean isValidEmail(String email){ if (null==email || "".equals(email)) return false; //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配 Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配 Matc...
assertThat(EmailValidator.isValidEmail("name@email.com"), is(true)); } }
42510870_0
class S3FactoryCreator extends AbstractServiceConnectorCreator<SpringCloudBlobStoreContext, S3ServiceInfo> { public SpringCloudBlobStoreContext create(S3ServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { Properties storeProviderInitProperties = new Properties(); storeProvider...
S3ServiceInfo serviceInfo = createServiceInfo(); SpringCloudBlobStoreContext contextBuilder = testCreator.create(serviceInfo, null); assertConnectorProperties(serviceInfo, contextBuilder); } }
42525744_6
class Socks5Server { public boolean readRequest() throws IOException { checkProtocolVersion(); boolean correct = true; command = Command.fromCommandNumber(in.read()); if (command == null) { correct = false; } if (in.read() != 0x00) { correc...
Socks5Server server = getAuthenticatedSocks5Server((byte) 0x05, (byte) 0x01, (byte) 0x00, (byte) 0x05, (byte) 0x01, (byte) 0x00, (byte) 0xA8, (byte) 0xC0, (byte) 0xA8, (byte) 0x01, (byte) 0x01); assertFalse(server.readRequest()); } }
42537834_1
class MyReducer implements redux.api.Reducer<Integer> { @Override public Integer reduce(Integer state, Object action) { return action instanceof Action ? reduce(state, (Action) action) : state; } private Integer reduce(Integer state, Action action); private MyReducer reducer; } class My...
assertThat(reducer.reduce(0, Action.INCREMENT), is(1)); } }
42591563_14
class Patterns { public static List<Pattern> toStartsWithPatternList(List<String> list) { return toStartsWithPatternList(list.stream()); } public static List<Pattern> toStartsWithPatternList(String content); public static List<Pattern> toStartsWithPatternList(Stream<String> stream); } cl...
String[] array = {"cBioPortal", "GenomeNexus", "Make cBioPortal great again", "Also don't forget Genome Nexus"}; List<Pattern> patterns = Patterns.toStartsWithPatternList(Arrays.asList(array)); assertTrue(patterns.get(0).matcher("cBioPortal is amazing").matches()); assertFalse(patterns...
42615957_109
class MPUtility { public static boolean isAppDebuggable(Context context){ return ( 0 != ( context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) ); } public static long getAvailableMemory(Context context); public static boolean isSystemMemoryLow(Context context); public sta...
Context context = Mockito.mock(Context.class); ApplicationInfo applicationInfo = Mockito.mock(ApplicationInfo.class); applicationInfo.flags = ApplicationInfo.FLAG_DEBUGGABLE; Mockito.when(context.getApplicationInfo()).thenReturn(applicationInfo); assertTrue(MPUtility.isAppDebugga...
42624467_4
class LongTinyType { @Override public String toString() { return String.format("%s#%s", this.getClass().getSimpleName(), value); } public LongTinyType(long value); @Override public int hashCode(); @Override public boolean equals(Object obj); } class LongTinyTypeTest { @Test ...
final String expected = "Long"; final String toString = Samples.Long.of(1).toString(); Assert.assertTrue(toString.contains(expected)); } }
42658356_25
class HibernateRequest { @SuppressWarnings("unchecked") public List<T> list() { return HibernateSessionFactory.doInTransaction(new IRequest<List<T>>() { @Override public List<T> doInTransaction(Session session) { return tuneCriteriaForList(createCriteria(session)...
H.saveOrUpdateAll(rootsAB()); List<Root> roots = createRootRequest().list(); assertThat(roots).isNotNull().hasSize(2); } }
42678647_4
class JiraService { public List<String> extractIssuesFromMessage(String message) { List<String> issues = Lists.newArrayList(); Matcher matcher = ISSUE_PATTERN.matcher(message); while (matcher.find()) { issues.add(matcher.group(1)); } return issues; } ...
String message = "test(#TEST-1): issue related to #TEST-15289"; final List<String> issues = jiraService.extractIssuesFromMessage(message); assertThat(issues) .hasSize(2) .containsExactly("TEST-1", "TEST-15289"); } }
42691991_170
class NCMBPushService extends NCMBService { public void sendPushReceiptStatusInBackground(String pushId, ExecuteServiceCallback callback) { try { //null check if (pushId == null) { throw new NCMBException(NCMBException.INVALID_JSON, "pushId is must not be null."); ...
Assert.assertFalse(callbackFlag); NCMBPushService pushService = (NCMBPushService) NCMB.factory(NCMB.ServiceType.PUSH); pushService.sendPushReceiptStatusInBackground("7FrmPTBKSNtVjajm", new ExecuteServiceCallback() { @Override public void done(JSONObject json, NCMBExceptio...
42741668_0
class Request { public static Request GET(String path) { return Requests.GET(path); } public static Request PUT(String path, String body); public static Request lazy(F0<Request> requestExpression); public abstract X match(Cases<X> cases); @Override public abstract int hashCode(); @Override public a...
ImmutableList<GuavaRequest> gets = ImmutableList.of(GET("foo")); gets = FluentIterable.from(gets).transform(modPath(path -> "/" + path)).toList(); assertThat(gets.size(), is(1)); assertThat(getPath(gets.get(0)), is("/foo")); } }
42742666_46
class OAuth2Credentials { @Nullable public String getAuthorizationUrl() throws UnsupportedEncodingException { String authorizationCodeRequestUrl = authorizationCodeFlow.newAuthorizationUrl().setScopes(scopes).build(); if (redirectUri != null) { authorizationCodeReque...
OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("https://localhost:8181/OAuth2Callback") .setScopes(Arrays.asList(Scope.PROFILE)) .setCustomScopes(Arrays.asList("...
42751387_138
class DigdagClient implements AutoCloseable { public InputStream getProjectArchive(Id projId, String revision) { WebTarget webTarget = target("/api/projects/{id}/archive") .resolveTemplate("id", projId) .queryParam("revision", revision); webTarget = addDisableDir...
String redirectUrl = String.format("https://%s:%d/redirect/pathname", mockWebServer.getHostName(), mockWebServer.getPort()); mockWebServer.enqueue(new MockResponse().setResponseCode(303).setHeader("Location", redirectUrl)); mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("f...
42751554_195
class UserDAO { public User getByEmail(String email) throws NotFoundException { User user = userRepository.findOneByEmail(email); if (user == null) { throw new NotFoundException("Could not find the user with the email '" + email + "'!"); } return user; } @Autow...
User user = createUser(); BDDMockito.given(userRepository.findOneByEmail(user.getEmail())).willReturn(user); User userFromDB = userDAO.getByEmail(user.getEmail()); Assert.assertEquals(user, userFromDB); } }
42774632_5
class SortTokenParserAdapter { public SortNodeList parse(String sortExpression) { try { return createParser(sortExpression).parse(); } catch (ParseException | Error e) { throw new SortParsingException(e); } } private SortTokenParser createParser(String expre...
String sortExpression = "sort ( + employee.name, - company.code) "; SortNodeList sortNodeList = new SortTokenParserAdapter().parse(sortExpression); assertNotNull(sortNodeList); List<SortNode> sortNodes = sortNodeList.getNodes(); assertEquals(2, sortNodes.size()); SortNod...
42776453_23
class OverpassQuery extends AbstractOverpassQuery { public OverpassQuery output(int limit) { return output(BODY, CENTER, QT, limit); } public OverpassQuery(); OverpassQuery(OverpassQueryBuilder builder); public OverpassQuery format(OutputFormat outputFormat); public OverpassQuery t...
query.output(OutputVerbosity.META, OutputModificator.GEOM, OutputOrder.ASC, 100); verify(builder).append("; out meta geom asc 100"); } }
42781657_9
class Dint { public static int firstDayOfMonth(int dint) { return compose(year(dint), month(dint), 1); } public static int create(int year, int month, int day); public static int create(Calendar calendar); public static int create(Date date); public static int compose(int year, int mon...
assertEquals(20140901, firstDayOfMonth(20140912)); } }
42785683_13
class Cargo implements Serializable { public Delivery getDelivery() { return delivery; } public Cargo(); public Cargo(TrackingId trackingId, RouteSpecification routeSpecification); public TrackingId getTrackingId(); public void setOrigin(Location origin); public Location getOrig...
Cargo cargo = populateCargoOnHamburg(); assertEquals(SampleLocations.HAMBURG, cargo.getDelivery() .getLastKnownLocation()); } }
42810825_0
class LoginCommand implements Command { @Override public void execute(Session session, Message msg) { if (session.getSessionUser() != null) { log.info("User {} already logged in.", session.getSessionUser()); return; } else { LoginMessage loginMsg = (LoginMes...
LoginCommand loginCommand = new LoginCommand(userStore, sessionManager); LoginMessage login = new LoginMessage(); login.setSender(123L); login.setLogin("Jack"); login.setPass("qwerty"); Session session = new Session(); loginCommand.execute(session, login); ...
42830433_0
class CheckstyleSourceCodeFileAnalyzerPlugin implements SourceCodeFileAnalyzerPlugin, ConfigurableAnalyzerPlugin { @Override public FileMetrics analyzeFile(String filepath, byte[] fileContent) { File fileToAnalyze = null; try { fileToAnalyze = createTempFile(fileContent, filepath); auditListene...
byte[] fileContent = IOUtils.toByteArray(getClass().getResourceAsStream("/CheckstyleAnalyzer.java.txt")); CheckstyleSourceCodeFileAnalyzerPlugin analyzer = new CheckstyleSourceCodeFileAnalyzerPlugin(); FileMetrics metrics = analyzer.analyzeFile("abc.java", fileContent); Assertions.assertEqual...
42854263_0
class RetainState implements Iterable<Object> { @SuppressWarnings("unchecked") public <T> T retain(int id, OnCreate<T> onCreate) { if (state == null) { state = new SparseArray<>(); } T item = (T) state.get(id); if (item == null) { item = onCreate.onCreate...
RetainState retainState = new RetainState(null); String result = retainState.retain(0, new RetainState.OnCreate<String>() { @Override public String onCreate() { return "test"; } }); assertEquals("test", result); } }
42899767_43
class RegistryClients { public static RegistryClient createZookeeperClient(Config config) throws IOException { CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(getZookeeperConnectionString(config)) .retryPolicy(new RetryOneTime(1000)) .build(); ...
MockitoAnnotations.initMocks(this); testingServer = new TestingServer(); when(config.getList(eq(REGISTRY_ZOOKEEPER_SERVERS))) .thenReturn(Arrays.asList(testingServer.getConnectString())); RegistryClient registryClient = RegistryClients.createZookeeperClient(config); a...
42985510_2
class RemoteConfigWithCacheFactory extends RemoteConfigFactory { public Path getPath() { return path; } public RemoteConfigWithCacheFactory(Path localConfigPath, ProcessInfo info, CuratorFramework client); public static RemoteConfigWithCacheFactory getInstance(); @Override protected IChangeableConfig ...
String name = "factory.ini"; File f = factory.getPath().resolve(name).toFile(); TestHelper.writeFile(ZookeeperUtil.newBytes("a=-1"), f); ProcessInfo info = factory.getInfo(); String path = ZKPaths.makePath(info.getPath(), name, info.getProfile()); final AtomicInteger num = new AtomicInteger(0); ...
43031095_30
class LogSubscriber { @Before("classAnnotatedWithRxLogSubscriber(joinPoint) && onCompletedMethodExecution()") public void beforeOnCompletedExecution(JoinPoint joinPoint) { stopWatch.stop(); messageManager.printSubscriberOnCompleted(joinPoint.getTarget().getClass().getSimpleName(), stopWatch.getTota...
logSubscriber.beforeOnCompletedExecution(joinPoint); verify(stopWatch).stop(); verify(messageManager).printSubscriberOnCompleted(eq(subscriber.getClass().getSimpleName()), anyLong(), anyInt()); verify(counter).tally(); verify(counter).clear(); verify(stopWatch).getTotalTimeMillis(); ...
43075480_113
class EndpointManager { public synchronized void setDefaultEndpoint(Endpoint newEndpoint) { if (null == newEndpoint) { throw new NullPointerException("endpoint required!"); } URI uri = newEndpoint.getUri(); if (null == uri) { throw new IllegalArgumentException("Endpoint protocol not supported!"); } ...
// GIVEN a old and a new endpoint Endpoint oldEndpoint = EndpointManager.getEndpointManager().getDefaultEndpoint(); Endpoint endpoint = new CoapEndpoint.Builder().build(); // WHEN set the new default endpoint EndpointManager.getEndpointManager().setDefaultEndpoint(endpoint); // THEN get the same new defau...
43077304_2
class NestListParser { public static List<String> parseFunction(String str) { FunctionState state = FunctionState.START; ArrayList<String> list = new ArrayList<>(2); field.setLength(0); boolean parameters_ok = false; int quoteCount_InParentheses = 0; int leftNotMatc...
// t2("a", "a", ""); t2("a(b,c)", "a", "b,c"); t2("abc(b,c,d(e,f))", "abc", "b,c,d(e,f)"); //assertThrows(Throwable.class, () -> NestListParser.parseFunction("a,b,c")); } }
43088077_48
class InputStreamDelegateDecoder implements Decoder { @Override public Object decode(Response response, Type type) throws IOException, FeignException { if (type.equals(InputStream.class)) { byte[] body = response.body() != null ? Util.toByteArray(response.body().asInputS...
String returned = "string"; when(delegate.decode(any(), any())).thenReturn(returned); Response response = Response.create(200, "OK", ImmutableMap.of(), returned, StandardCharsets.UTF_8); String decodedObject = (String) inputStreamDelegateDecoder.decode(response, String.class); a...
43089983_1
class BasicAuthorizationHeaderModifier implements HeaderModifier { @Override public boolean matches(Header header) { return "Authorization".equals(header.name()) && header.value().startsWith("Basic"); } public BasicAuthorizationHeaderModifier(Base64Decoder base64Decoder); ...
final Header header = new Header("Authorization", "Non basic header value"); assertThat(headerModifier.matches(header), is(false)); } }
43092584_0
class TCX2Workout { private List<Snapshot> snapshots(Workout workout) throws IOException { List<Snapshot> snapshots = new ArrayList<>(); if (navigator.descent("Track")) { while (navigator.descent("Trackpoint")) { if (snapshots.size() == 0) { workout.location.set(location()); } snapshots.add(...
Reader reader = new InputStreamReader(getClass().getResourceAsStream("/snapshots.tcx")); TCX2Workout to = new TCX2Workout(reader).workout(); Workout workout = to.getWorkout(); assertEquals(Mon_Jun_15_2015 + (60 * 1000), (long)workout.start.get()); assertEquals(3, (int)workout.duration.get()); assertEqual...
43098270_0
class MinersRule { public String computeCDM(String jsonStr, Map<String, byte[]> inputModels) throws Exception { Input input = null; try { input = mapper.readValue(jsonStr, Input.class); } catch (Exception e) { throw new Exception("Trying to read the json input:"+jso...
String inputStr = null; try { inputStr = getFileAsString("src/test/resources/minersRuleIn.json"); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } byte[] model = null; try { model = getFileAsByteArray("src/test...
43115247_7
class Json { public static JNumber jNumber(BigDecimal value) { return new JNumber(value); } private Json(); public static JString jString(String value); public static JBoolean jBoolean(boolean value); public static JNumber jNumber(int n); public static JNumber jNumber(double n); ...
Json.JNumber n1 = Json.jNumber(1); assertEquals(n1, Json.jNumber(1L)); assertEquals(n1, Json.jNumber(new Long(1L))); assertEquals(n1, Json.jNumber(new BigDecimal(1))); assertEquals(1, n1.asInt()); assertEquals(1L, n1.asLong()); assertEquals(1.0, n1.asDouble(), 0.0...
43193480_1
class HelloWorldModel { public String getMessage() { return message; } @PostConstruct protected void init(); private HelloWorldModel hello; private String slingId; } class TestHelloWorldModel { private HelloWorldModel hello; private String slingId; @Test public void te...
// some very basic junit tests String msg = hello.getMessage(); assertNotNull(msg); assertTrue(msg.length() > 0); } }
43246449_65
class StateServiceImpl implements StateService { @Transactional(readOnly = true) @Override public StateDTO getStateDtoByName(String name) { Assert.notNull(name); return converterService.convert(statesRepository.findByName(name), StateDTO.class); } @Transactional(readOnly = true) @Override public Sta...
//Given given(statesRepository.findByName(VALID_STATE_NAME)).willReturn(validStatesEntity); given(converterService.convert(validStatesEntity, StateDTO.class)).willReturn(validStateDTO); StateDTO expectedStateDTO = StateDTO.builder().id(VALID_STATE_ID).name(VALID_STATE_NAME).build(); ...
43254843_4
class Buffer implements Closeable { public void flush(Ingester ingester, boolean force) throws IOException { LOG.trace("flush(): force={}, bufferUsage={}", force, getBufferUsage()); flushInternal(ingester, force); } public Buffer(RecordFormatter recordFormatter); publi...
Buffer buffer = new Buffer(bufferConfig, recordFormatter); Ingester ingester = mock(Ingester.class); buffer.flush(ingester, false); verify(ingester, times(0)).ingest(anyString(), any(ByteBuffer.class)); Map<String, Object> data = new HashMap<>(); data.put("name", "koma...
43287559_81
class AggregationHashChainTimeConsistencyRule extends BaseRule { public VerificationErrorCode getErrorCode() { return VerificationErrorCode.INT_02; } public VerificationResultCode verifySignature(VerificationContext context); private AggregationHashChainTimeConsistencyRule rule; } class Agg...
RuleResult result = rule.verify(build(TestUtil.loadSignature(SIGNATURE_AGGREGATION_HASH_CHAIN_INVALID_AGGREGATION_TIMES))); Assert.assertNotNull(result); Assert.assertEquals(result.getResultCode(), VerificationResultCode.FAIL); Assert.assertEquals(result.getErrorCode(), VerificationError...
43294683_52
class TermFactory { public static Term findTerm(String termName) { // normalise termName String normTermName; if (termName == null || StringUtils.isBlank(normTermName = normaliseTerm(termName))) { return null; } // try known term enums first Term term = findTermInEnum(normTermName, DwcTerm.values(), ...
assertEquals(findTerm("http://ns.adobe.com/xap/1.0/rights/Owner"), XmpRightsTerm.Owner); } }
43300131_6
class MainActivity extends AppCompatActivity implements MainView { @Override public void showResult(float result) { resultEditText.setText(String.valueOf(result)); } @Override protected void onCreate(Bundle savedInstanceState); private void init(); private void initSpinner(); @Override public void showError(...
EditText result = (EditText) activity.findViewById(R.id.result_editText); activity.showResult(12f); assertThat(result.getText().toString()).isEqualTo("12.0"); } }
43342956_3
class Check { public CheckError toCheckError(CONTEXT context) { return CheckError.of(errorType,errorCode,message(context)); } private Check(CheckErrorType errorType,int errorCode,IRender<CONTEXT,String> render); public static Check<CONTEXT> of(CheckErrorType errorType,int errorCode, IRender<CONTEXT,String> re...
assertEquals(400,Check.ParamInvalid.toCheckError().asHttpCode()); assertEquals(404,Check.NotFound.toCheckError().asHttpCode()); } }