id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
26698596_2
class ConfigLoader { public T getTestConfig() { try { LOGGER.info(String.format("Loading config from: %s", configFileName)); final String substitutedString = substitutor.replace(new String( ByteStreams.toByteArray(this.getClass().getClassLoader().getResourceAsStr...
ConfigLoader<DummyConfiguration> dummyConfigurationConfigLoader = new ConfigLoader<>( DummyConfiguration.class, CONFIG_FILE, varNotFound ); assertThat(dummyConfigurationConfigLoader.getTestConfig().getSomeDummyEnvAttribute(), CoreMatchers.is("defau...
26727748_0
class CapacityOverviewController extends Controller<CapacityOverviewView> implements FetchUnitsEvent.Handler { @Override public void onUnitsFetched(FetchUnitsEvent event) { units = new ArrayList<>(event.getUnits()); sortUnits(Unit.Properties.name, true); } public CapacityOverviewContr...
capacityOverviewController.onUnitsFetched(mockEvent); verify(mockView).setUnits(setUnitsArgument.capture()); assertFalse(setUnitsArgument.getValue().isEmpty()); } }
26745548_501
class GatewayContextResolver { public GatewayContext resolve(GatewayConfigDocument gatewayConfigDoc) throws Exception { return resolve(gatewayConfigDoc, System.getProperties()); } public GatewayContextResolver(File configDir, File webDir, File tempDir); public GatewayContextResol...
boolean sawExpectedEx = false; String expectedLogMessage = "Exception .* caught loading file .*truststore-JCEKS.db.* you may need to specify " + "\"<type>JCEKS</type>\" in the gateway configuration file"; String expected = "Invalid keystore format"; LogMessageInspector i...
26768771_42
class LoremIpsum { public int getNumWords() { return words == null ? 0 : words.length; } public LoremIpsum(); public LoremIpsum(final String text_); public int getNumParagraphs(); public int getNumSentences(); public String getText(); public String getParagraph(final int i_); public String getSentence(...
Assert.assertEquals(EXPECTED_WORDS.length, loremIpsum.getNumWords()); } }
26810298_359
class DocumentFlattener { public List<EntityObject> flatten(Object document) throws InvalidPathException { if (pathToEntity == null) { return Arrays.asList(new EntityObject(document)); } List<EntityObject> entityNodes = new ArrayList<>(entitiesPerDocument); EntityObject root = new EntityObject(document); ...
DocumentFlattener df = new DocumentFlattener(new Path(new String[0]), 1); List<EntityObject> records = df.flatten(taxon); assertEquals("01", 1, records.size()); assertTrue("02", records.get(0).getEntity() == taxon); assertTrue("03", records.get(0).getDocument() == taxon); } }
26845372_0
class JsonPointerEditor { public JsonNode getValue() { return root.at(pointer); } public JsonPointerEditor( JsonNode root, JsonPointer pointer ); public JsonNode getRoot(); public JsonNode setValue( JsonNode value ); private ObjectMapper mapper; JsonNodeFactory factory; } class JsonPointerEdit...
JsonNode node = mapper.readValue("{\"key\": {\"sub\": \"value\"}}", JsonNode.class); JsonPointer pointer = JsonPointer.compile("/key/sub"); JsonPointerEditor editor = new JsonPointerEditor(node, pointer); assertThat("value", equalTo(editor.getValue().asText())); } }
26861802_25
class ReadOnlyStore extends AbstractStore { @Nonnegative @Override public <V> int appendValue(SingleFeatureBean feature, V value) { throw e.get(); } public ReadOnlyStore(); @Override public void save(); @Override public void containerFor(Id id, SingleFeatureBean container); @...
assertThat( catchThrowable(() -> store.appendValue(mock(SingleFeatureBean.class), mock(Object.class))) ).isExactlyInstanceOf(READONLY_EXCEPTION_TYPE); } }
26862250_20
class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEntityService { @Override public ClientDetailsEntity updateClient(ClientDetailsEntity oldClient, ClientDetailsEntity newClient) throws IllegalArgumentException { if (oldClient != null && newClient != null) { for (String uri : newClient.getRe...
ClientDetailsEntity oldClient = Mockito.mock(ClientDetailsEntity.class); ClientDetailsEntity newClient = Mockito.mock(ClientDetailsEntity.class); Mockito.when(newClient.isAllowRefresh()).thenReturn(true); // scopes returned by client entities are Strings @SuppressWarnings("unchecked") Set<String> scopes ...
26873147_130
class TopicManagerImpl implements TopicManager { @Override public CompletableFuture<Void> createTopic( String clusterId, String topicName, int partitionsCount, short replicationFactor, Map<String, String> configs) { requireNonNull(topicName); NewTopic createTopicRequest = ...
expect(clusterManager.getCluster(CLUSTER_ID)).andReturn(completedFuture(Optional.empty())); replay(clusterManager); try { topicManager.createTopic( CLUSTER_ID, TOPIC_1.getName(), TOPIC_1.getPartitions().size(), TOPIC_1.getReplicationFactor(), singleto...
26888367_24
class OHCacheBuilder { public OHCacheBuilder<K, V> segmentCount(int segmentCount) { if (segmentCount < -1) throw new IllegalArgumentException("segmentCount:" + segmentCount); this.segmentCount = segmentCount; return this; } private OHCacheBuilder(); private st...
int cpus = Runtime.getRuntime().availableProcessors(); int segments = cpus * 2; while (Integer.bitCount(segments) != 1) segments++; OHCacheBuilder<String, String> builder = OHCacheBuilder.newBuilder(); Assert.assertEquals(builder.getSegmentCount(), segments); ...
26904455_9
class WebPushFrameListener extends Http2FrameAdapter { void shutdown() { monitoredStreams.values().stream().forEach(client -> client.ctx.close()); monitoredStreams.clear(); acksStreams.values().stream().forEach(client -> client.ctx.close()); acksStreams.clear(); } WebPush...
final String subscriptionId = "subscriptionId"; final String pushResourceId = "pushResourceId"; final ChannelHandlerContext ctx = mockChannelHandlerContext(subscriptionId); final Http2ConnectionEncoder encoder = mockEncoder(w -> w.thenReturn(pushPath(pushResourceId)) .the...
26907542_0
class FilterConverterHelper { public static Date dateConvert(String value) { if (value == null) { return null; } Map<String, String> formats = new HashMap<>(); formats.put("dd.MM.yyyy HH:mm", "^\\d{2}\\.\\d{2}\\.\\d{4}\\s+\\d{2}:\\d{2}$"); formats.put("dd-MM-y...
for (Map.Entry<String, String> entry : asserts.entrySet()){ Date expected = new SimpleDateFormat(entry.getValue()).parse(entry.getKey()); assertEquals(expected, FilterConverterHelper.dateConvert(entry.getKey())); } } }
26921116_545
class SammonMapping { public static SammonMapping of(double[][] proximity) { return of(proximity, new Properties()); } public SammonMapping(double stress, double[][] coordinates); public static SammonMapping of(double[][] proximity, int k); public static SammonMapping of(double[][] proxi...
System.out.println("learn"); double[][] points = { {-41.5471709650684, 18.9187013341311}, {40.7205435629563, 17.8623927312285}, {49.9308397575605, 26.6606879579547}, {-10.3370642672217, 9.00224445858628}, {-35.0083289866438, -3.70032099791862}...
26949678_0
class TrackResource { static Predicate<TargetInfo> createTargetFilterPredicate(Set<Integer> mmsis, Set<Area> baseAreas, Set<Area> areas) { Predicate<TargetInfo> mmsiPredicate = null; if (mmsis != null && mmsis.size() > 0) { mmsiPredicate = targetInfo -> mmsis.contains(targetInfo.getMms...
Predicate<TargetInfo> predicate = TrackResource.createTargetFilterPredicate( Sets.newHashSet(219000000, 219000001, 219000002), Sets.newHashSet( BoundingBox.create(Position.create(55.0, 10.0), Position.create(56.2, 12), CoordinateSystem.CARTESIAN) ), ...
26951043_22
class DBConsumer extends JCasAnnotator_ImplBase { @Override public void process(JCas jcas) { Integer documentID = documentMapperService.saveDocument(jcas, analysisBatch, bStoreDocText, bStoreCAS, bInsertAnnotationContainmentLinks, setTypesToIgnore); if (documentID != null && xmiOutputDirectory != null &&...
// JCas jCas = // JCasFactory.createJCasFromPath("src/main/resources/org/apache/ctakes/ytex/types/TypeSystem.xml"); String text = "Title: US Abdomen\n\nDr. Doolitle asked patient\nto take a deep breath\nand exhale slowly. Patient coughed. Prescribed acetominophen"; AnalysisEngine engine = TestUtils.createToke...
26956394_29
class FileHelper { public static boolean endsWithJarOrApkExtension(@NonNull String filePath) { checkPreconditionsOnFilePath(filePath); int initialCharacterOfAnExtensionIndex = filePath.lastIndexOf(DOT_SEPARATOR); if (initialCharacterOfAnExtensionIndex == -1) return false; ...
// WHEN + THEN assertFalse(endsWithJarOrApkExtension(TEST_FILE_EXTENSION_NOT_FOR_A_CONTAINER)); } }
26958185_99
class CsvBeanReader extends AbstractCsvReader implements ICsvBeanReader { public <T> T read(final Class<T> clazz, final String... nameMapping) throws IOException { if( clazz == null ) { throw new NullPointerException("clazz should not be null"); } else if( nameMapping == null ) { throw new NullPointerExc...
final String[] header = beanReader.getHeader(true); assertArrayEquals(HEADER, header); assertEquals(JOHN, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); assertEquals(BOB, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); assertEquals(ALICE, beanReader.read(CustomerBean.class...
26971627_67
class MrsImage implements AutoCloseable { public long getWidth() { return getMetadata().getPixelBounds(getZoomlevel()).getWidth(); } private MrsImage(MrsImageDataProvider provider, int zoomlevel); @SuppressWarnings("squid:S1166") // Exceptions are ignored. This is OK. public static MrsImage open(MrsImageDataProvi...
Assert.fail("Not yet implemented"); } }
27013933_3
class Reflection { public static <T> List<Field> getDeclaredFields(Class<T> clazz, Class<? super T> upToExcluding){ return getAllFields(clazz, Optional.<Class<? super T>>ofNullable(upToExcluding), Predicates.alwaysTrue()); } public static List<Field> getAllFields(Class<T> clazz); public static List<Field> getAl...
List<Field> declaredFields = Reflection.getAllFields(ClassC.class, Object.class, new FieldAnnotationPredicate(InjectView.class)); assertEquals(2, declaredFields.size()); declaredFields = Reflection.getAllFields(ClassC.class, new FieldAnnotationPredicate(InjectAttribute.class)); assertEquals(1, declaredFields....
27024702_0
class KeywordPartitioner implements Iterator<List<E>> { public static <T> Stream<List<T>> partition(final Stream<T> stream, final Predicate<T> partitionSeparator) { return new KeywordPartitioner<>(stream, partitionSeparator).asStream(); } public KeywordPartitioner(final Stream<E> stream, final Pr...
assertEquals(asList(asList("Foo", "Bar", "ON"), asList("OFF", "was")), partition( Stream.of("Foo", "Bar", "ON", "Fire", "OFF", "was", "destroyed"), s -> s.length() > 3) .collect(Collectors.toList())); assert...
27135187_45
class XsdDataItem { public XsdType getXsdType() { return _xsdType; } public XsdDataItem(final CobolDataItem cobolDataItem, final Cob2XsdConfig config, final XsdDataItem parent, final int order, final List < String > nonUniqueCobolNames, final RecognizerErrorHan...
CobolDataItem dataItem = new CobolDataItem("COBOL-CONDITION"); dataItem.setLevelNumber(88); XsdDataItem xsdDataItem = new XsdDataItem(dataItem, defaultConfig, null, 0, new ArrayList < String >(), _errorHandler); assertEquals(XsdType.ENUM, xsdDataItem.getXsdType()); ...
27135253_0
class JUnitExporter extends ICitLabTestSuiteExporter { @Override public void generateOutput(TestSuite input, String fileName) { new CVSExporter().generateOutput(input, fileName); try { JUnitTemplateWizard junitWizard = new JUnitTemplateWizard( PlatformUI.getWorkbench(), input, fileName); WizardDi...
JUnitExporter junitExporter = new JUnitExporter(); String testSuiteFileName = tmpDir.newFolder("test").getPath() + "/" + testSuiteName; //assert that file does not exists before assertTrue(! Files.exists(Paths.get(testSuiteFileName))); //then call the generateOutput method junitExporter.generateOutput(testS...
27145359_0
class KDEPathFinder { public static String[] getConfigPaths() { return runKDE4Config("config"); } public static String[] getIconPaths(); private static String[] runKDE4Config(String path); } class KDEPathFinderTest { @Test public void testGetConfigPaths() {
String[] configPaths = KDEPathFinder.getConfigPaths(); Assert.assertTrue("Expected the KDE Path Finder to find at " + "least one path where configuration is stored.", configPaths.length > 0); for (String configPath : configPaths) { Assert.assertTrue("Expected all paths to have non-zero " + "length...
27191143_8
class RxPresenter extends Presenter<View> { public void add(Subscription subscription) { subscriptions.add(subscription); } public Observable<View> view(); public void remove(Subscription subscription); public void restartable(int restartableId, Func0<Subscription> factory); public voi...
RxPresenter presenter = new RxPresenter(); Subscription mock = Mockito.mock(Subscription.class); when(mock.isUnsubscribed()).thenReturn(false); presenter.add(mock); presenter.onDestroy(); verify(mock, times(1)).unsubscribe(); verify(mock, atLeastOnce()).isUnsubscr...
27195248_0
class EntityImporter { public void importData() throws IOException { String statementsWriter = getSettings().getProperty(STATEMENTS_WRITER_KEY, FileStatementsWriter.class.getSimpleName()); if (statementsWriter.indexOf('.') < 0) { statementsWriter = "org.fastnate.generator.statements." + statementsWriter; ...
final Properties settings = createDefaultSettings(); final EntityImporter entityImporter = new EntityImporter(settings); final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test", settings); try { final EntityManager em = emf.createEntityManager(); try { try (Connection connectio...
27202384_1
class Common { public static ArrayList<Long> getRetweeters(long tweetID) throws Exception { return getUsers(tweetID, RETWEETERS_URL); } public static ArrayList<Long> getFavoriters(long tweetID); private static ArrayList<Long> getUsers(long tweetID, String url); private static JSONObject ge...
ArrayList<Long> retweeters = Common.getRetweeters(TWEET_ID); assertNotNull(retweeters); assertEquals(retweeters.size(), 2); } }
27207708_1
class EbeanParsedConfig { public Map<String, List<String>> getDatasourceModels() { return datasourceModels; } public EbeanParsedConfig(String defaultDatasource, Map<String, List<String>> datasourceModels); public String getDefaultDatasource(); public static EbeanParsedConfig parseFromCon...
EbeanParsedConfig config = parse(ImmutableMap.of( "ebean.default", "a,b" )); assertThat(config.getDatasourceModels().get("default"), hasItems("a", "b")); } }
27217073_30
class DataSourceAccessor { public DcSearchResponse search(final Map<String, Object> query) { Map<String, Object> requestQuery = null; if (query != null) { requestQuery = new HashMap<String, Object>(query); } else { requestQuery = new HashMap<String, Object>(); ...
EsIndex index = esClient.idxAdmin("index_for_test"); assertNotNull(index); DataSourceAccessor dsa = new DataSourceAccessor(index, "TypeForTest", "RoutingIdTest"); dsa.create("id00001", new HashMap<Object, Object>()); dsa.create("id00002", new HashMap<Object, Object>()); d...
27224427_2
class StandardXRoadConsumerMessageExtractor implements WebServiceMessageExtractor { public XRoadMessage<XmlObject> extractData(WebServiceMessage response) throws IOException { Node kehaNode; try { SaajSoapMessage message = (SaajSoapMessage) response; SOAPMessage mes = message.getSaajMessage(); ...
// xml elements in a single row, but base64binary part on different rows (PEM format) XRoadMessage message1 = EXTRACTOR.extractData(new SaajSoapMessage(getMessageFromString("extractor/EarestFail1.xml"))); assertEquals(RESULT_PEM_FORMAT, message1.getContent().toString()); // manually for...
27284166_3
class Board extends Observable { abstract int numPieces()abstract int numPieces(); abstract int numPieces() void clear(int N); abstract int numPieces() void copy(Board board); abstract int numPieces()abstract int size(); abstract int numPieces() Square get(int r, int c); abstract int numPieces()abstract Square get(in...
int N = 4; MutableBoard board = new MutableBoard(N); assertEquals(16, board.numPieces()); board.set(0, 2, RED); board.set(1, 2, BLUE); board.set(2, 2, RED); board.set(3, 2, BLUE); assertEquals(20, board.numPieces()); } }
27287531_4
class SquarifiedPacking { @VisibleForTesting @Nonnull static Rect newBounds(@Nonnull Rect bounds, double fraction, double priorFraction) { verify(fraction + priorFraction <= 1 + EPSILON, "fraction (%d) & prior fraction (%d) more than 1 + EPSILON ", fraction, priorFraction); if (bounds.isEm...
Rect rect = SquarifiedPacking.newBounds(new Rect(787, 1045, 915, 1047), 0.006106064544560274, 0.9457072296133543); assertEquals(new Rect(908, 1045, 909, 1047), rect); } }
27344072_3
class VESID implements Comparable <VESID> { public static boolean isValidPart (@Nullable final String sPart) { return StringHelper.hasText (sPart) && RegExHelper.stringMatchesPattern (REGEX_PART, sPart); } public VESID(@Nonnull @Nonempty final String sGroupID, @Nonnull @Nonempty final Str...
assertTrue (VESID.isValidPart ("com")); assertTrue (VESID.isValidPart ("com.helger")); assertTrue (VESID.isValidPart ("01234")); assertTrue (VESID.isValidPart ("1.2.3.4.5")); assertTrue (VESID.isValidPart ("ph-as4")); assertTrue (VESID.isValidPart ("-.___")); assertFalse (VESID.isValidPart ...
27377253_0
class MessageExtras { public DeltaExtras getDelta() { return delta; } public MessageExtras(final JsonObject jsonObject); private MessageExtras(final JsonObject jsonObject, final DeltaExtras delta); public JsonObject asJsonObject(); void write(MessagePacker packer); static Messa...
final JsonObject objectA = new JsonObject(); objectA.addProperty("someKey", "someValue"); final JsonObject objectB = new JsonObject(); objectB.addProperty("someOtherKey", "someValue"); final MessageExtras messageExtras = new MessageExtras(objectA); assertNull(messageExt...
27392543_546
class MultiHopFlowCompiler extends BaseFlowToJobSpecCompiler { @Override public Dag<JobExecutionPlan> compileFlow(Spec spec) { Preconditions.checkNotNull(spec); Preconditions.checkArgument(spec instanceof FlowSpec, "MultiHopFlowCompiler only accepts FlowSpecs"); long startTime = System.nanoTime(); ...
FlowSpec spec = createFlowSpec("flow/flow2.conf", "LocalFS-1", "HDFS-3,HDFS-4", false, false); Dag<JobExecutionPlan> jobDag = this.specCompiler.compileFlow(spec); Assert.assertEquals(jobDag.getNodes().size(), 4); Assert.assertEquals(jobDag.getEndNodes().size(), 2); Assert.assertEquals(jobDag.getSta...
27403772_0
class VersionComparator implements Comparator<String>, Serializable { @Override public int compare(@Nullable final String pStr1, @Nullable final String pStr2) { int result = 0; if (pStr1 == null) { if (pStr2 != null) { result = 1; } } ...
VersionComparator testee = new VersionComparator(); Assert.assertTrue(testee.compare("6.1", "6.1.2") < 0); Assert.assertTrue(testee.compare("6.1.2", "6.1") > 0); Assert.assertTrue(testee.compare("6.2", "6.1.2") > 0); Assert.assertTrue(testee.compare("6.1.2", "6.2") < 0); ...
27404315_0
class ConsulServerUtils { public static String fixIPv6Address(String address) { try { InetAddress inetAdr = InetAddress.getByName(address); if (inetAdr instanceof Inet6Address) { return "[" + inetAdr.getHostName() + "]"; } return address; } catch (UnknownHostException e) { log.debug("Not Inet...
String s1 = ConsulServerUtils.fixIPv6Address("fc00:ec:cd::242:ac11:c"); assertThat(s1).isEqualTo("[fc00:ec:cd:0:0:242:ac11:c]"); String s2 = ConsulServerUtils.fixIPv6Address("[fc00:ec:cd::242:ac11:c]"); assertThat(s2).isEqualTo("[fc00:ec:cd:0:0:242:ac11:c]"); String s3 = ConsulServerUtils.fixIPv6Address("19...
27408825_1
class MessageUtil { public static String replaceVars(String msg, HashMap<String, String> vars){ boolean error = false; for(String s:vars.keySet()){ try{ msg.replace("{$"+s+"}", vars.get(s)); }catch(Exception e){ MessageManager.getInstance().de...
String expected = "&6Game starting in 10"; String test = MessageUtil.replaceVars(messageConfig.getString("messages.game.countdown", ""), "t-10"); assertThat(test, is(expected)); } }
27416566_3
class RateLimitBundle implements ConfiguredBundle<T>, ConfigurationStrategy<T> { public void run(T configuration, Environment environment, JedisPool jedisPool) throws Exception { this.jedisPool = jedisPool; run(configuration, environment); } @Override public void run(T configuration, Environment environment); ...
bundle.run(configuration, environment, jedisPool); verify(jerseyEnvironment).register(any(RateLimitFilter.class)); } }
27490105_0
class GeometryUtils { public static Point2D getConnectorPosition(final GConnector connector, final SkinLookup skinLookup) { final GConnectorSkin connectorSkin = skinLookup.lookupConnector(connector); final GNode parent = connector.getParent(); final GNodeSkin nodeSkin = skinLookup.lookupN...
// Should return the absolute position of the center of the connector. final Point2D target = new Point2D(NODE_X + CONNECTOR_CENTER_X, NODE_Y + CONNECTOR_CENTER_Y); assertEquals(GeometryUtils.getConnectorPosition(connector, skinLookup), target); } }
27503648_8
class TemporaryTokenCache { public String generateTemporaryToken(String key, int secondsToLive) { return generateTemporaryToken(key, secondsToLive, null); } @Inject public TemporaryTokenCache(TokenGenerator tokenGenerator, CacheBuilderProvider cacheBuilderProvider); public String generateTemporaryToken(...
expect(mockGenerator.generate()).andReturn(TOKEN).once(); replay(mockGenerator); String token = tokenCache.generateTemporaryToken(KEY, 10); assertTrue(null != token); assertTrue(TOKEN.equals(token)); } }
27507850_2204
class IpsecUtil { @VisibleForTesting @Nonnull static IpsecSession getIpsecSession( Configuration initiatorOwner, Configuration peerOwner, IpsecStaticPeerConfig initiator, IpsecPeerConfig candidatePeer) { IpsecSession.Builder ipsecSessionBuilder = IpsecSession.builder(); ipsecSess...
NetworkFactory nf = new NetworkFactory(); Configuration.Builder cb = nf.configurationBuilder(); IpsecStaticPeerConfig.Builder ipsecPeerConfigBuilder = IpsecStaticPeerConfig.builder(); assertTrue( getIpsecSession( cb.setConfigurationFormat(AWS).build(), cb.setConf...
27514348_3
class JacksonSerializer implements Serializer<T> { @Override public byte[] serialize(T event) { try { return objectMapper.writeValueAsBytes(event); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } public JacksonSerializer(ObjectMapper objectMapper); pr...
final String outputString = "{\"timestamp\":\"2014-01-01T00:00:00.000Z\",\"at\":2}"; objectMapper.registerModule(new JodaModule()); final Serializer<MmxAuctionSummary> serializer = new JacksonSerializer<>(objectMapper); final byte[] eventBytes = serializer.serialize(sampleEventValid); final String ...
27533072_1
class HashUtil { public static String md5Hex (String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex (md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingExcep...
String md5 = HashUtil.md5Hex("stevehu@gmail.com"); Assert.assertEquals(md5, "417bed6d9644f12d8bc709059c225c27"); } }
27534295_1
class VertxEventLoopExecutionContext implements ExecutionContext { public static ExecutionContext create(Vertx vertx) { return new VertxEventLoopExecutionContext(vertx); } private VertxEventLoopExecutionContext(Vertx vertx); @Override public void execute(Runnable runnable); @Override public void repor...
Async async = tc.async(); final Context context = Vertx.currentContext(); tc.assertNull(context); final Promise.DefaultPromise<String> promise = new Promise.DefaultPromise<>(); promise.onComplete(ScalaUtils.toFunction1(v -> { tc.assertNotNull(Vertx.currentContext()); async.complete(); ...
27570630_0
class PoiExcelWriter { public void process(Resource inputResource, Resource outputResource) { SXSSFWorkbook wb = new SXSSFWorkbook(flushSize); try { wb.setCompressTempFiles(true); // temp files will be gzipped final Sheet sh = wb.createSheet(); InputStreamReader...
PoiExcelWriter poiExcelWriter = new PoiExcelWriter(20); final Resource fileSystemResource = new FileSystemResource(destination_file); poiExcelWriter.process(new FileSystemResource(sourceFile), fileSystemResource); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileSystemResource.getInputS...
27583882_1
class PBKDF2Strategy extends AbstractHashingStrategy implements JDBCHashStrategy { @Override public String computeHash(String password, String salt, int version) { int iterations = DEFAULT_ITERATIONS; if (version >= 0) { if (nonces == null) { // the nonce version is not available th...
JDBCHashStrategy strategy = new PBKDF2Strategy(vertx); strategy.setNonces(new JsonArray().add(1000)); String hashedPassword = strategy.computeHash("Paulo", "123456", 0); assertTrue(JDBCHashStrategy.isEqual("39698770CC0B0B0553E9B74216FAE2C7C31B81D40940FA50601D7998B81820F86CEE7CD84CC1D06D06D832C5BACA45D3...
27609596_139
class AwsClientFactory implements AutoCloseable { AWSCredentialsProvider createCredentialsProvider(String name, String accountId) { final AWSCredentialsProvider dflt = new DefaultAWSCredentialsProviderChain(); final Config cfg = getConfig(name, "credentials"); if (cfg.hasPath("role-arn")) { return ...
AwsClientFactory factory = new AwsClientFactory(config); AWSCredentialsProvider creds = factory.createCredentialsProvider(null, null); Assert.assertTrue(creds instanceof DefaultAWSCredentialsProviderChain); } }
27622439_69
class ConcurrentManaged implements Managed<T> { @Override public Stage<Void> stop() { if (!state.compareAndSet(ManagedState.STARTED, ManagedState.STOPPED)) { return stopFuture; } stopReferenceFuture.complete(this.reference.getAndSet(null)); // release self-reference. release(); retu...
underTest.state.set(ConcurrentManaged.ManagedState.STARTED); underTest.reference.set(reference); assertEquals(stopFuture, underTest.stop()); assertNull(underTest.reference.get()); verify(underTest).release(); } }
27653357_4
class Route { public boolean matches(String path) { return pathPattern.matcher(path).matches(); } private Route(String path, Pattern pathPattern, List<String> keywords); public static Pattern compile(String pattern, List<String> keywords); public static Route build(String pattern); public Pattern pa...
Route matches1 = Route.build("/api/people/:person"); assertTrue(matches1.matches("/api/people/jeff")); } }
27674753_1
class SubClassSupportInstanceInitializer implements InstanceInitializer { @SuppressWarnings("unchecked") public <T> Class<T> getClass(T entity) { // get the first class in the hierarchy that is actually in the index Class<T> clazz = (Class<T>) entity.getClass(); if ( !clazz.isAnnotationPresent( InIndex.class )...
SubClassSupportInstanceInitializer initializer = SubClassSupportInstanceInitializer.INSTANCE; WithoutInIndex withoutInIndex = new WithoutInIndex(); assertEquals( WithoutInIndex.class, initializer.getClass( withoutInIndex ) ); } }
27683023_125
class WindSpeed { public BigDecimal getValue(WindSpeedUnit unit) { BigDecimal value = null; switch (unit) { case KNOTS: value = knots; break; case METRES_PER_SECOND: value = metresPerSecond; break; ...
testee = new WindSpeed(new BigDecimal("0.5")); new BigDecimalEquals().assertEquals(new BigDecimal("1"), testee.getValue(WindSpeedUnit.BEAUFORT_SCALE)); testee = new WindSpeed(new BigDecimal("3.4")); new BigDecimalEquals().assertEquals(new BigDecimal("1"), testee.getValue(WindSpeedUnit.B...
27683112_56
class FunctionFactory { private static Function parseVALUE(ConfigThingy conf, FunctionLibrary funcLib, DialogLibrary dialogLib, Map<Object, Object> context) { Function valueNameFun; // TODO doesn't work as described. Exception isn't thrown by 0 or more than 1 parameters. try { valueName...
Function f = FunctionFactory.parse(new ConfigThingy("VALUE", "\"value1\" \"value2\""), funcLib, dialogLib, context); assertTrue(f instanceof ValueFunction); } }
27715709_10
class ResourcePermission extends Permission { @Override public boolean implies(Permission p) { if (!(p instanceof ResourcePermission)) return false; ResourcePermission qp = (ResourcePermission) p; /* * Condition 1: The action flag of the queried permission was set in the granted permission */ int qu...
ResourcePermission rp; ResourcePermission rp2; // 11P rp = new ResourcePermission("path=*", "*"); rp2 = new ResourcePermission("path=*", "*"); assertTrue(rp.implies(rp2)); // 12P rp = new ResourcePermission("path=*", "*"); rp2 = new ResourcePermission("path=myPath/*", "*"); assertTrue(rp.implies(r...
27721932_273
class MultipleNodeAssert extends FactoryBasedNavigableIterableAssert<MultipleNodeAssert, Iterable<Node>, Node, SingleNodeAssert> { public AbstractListAssert<?, List<? extends String>, String, ObjectAssert<String>> extractingText() { isNotNull(); List<String> values = new ArrayList<>(); fo...
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<feed>" + " <title>My Simple Feed</title>" + " <entry attr1=\"value1\" />" + " <entry attr1=\"value2\"/>" + " <entry />" + " <entry attr1=\"valu...
27728683_0
class Utils { static public int getMiddleIndex(int beginIndex, int endIndex) { return beginIndex + (endIndex - beginIndex) / 2; } static public void main(String[] args); static public int[] getRandomIntArray(Random rand, int size); static public Integer[] getRandomIntegerArray(Random r...
assertEquals(5, Utils.getMiddleIndex(0, 10)); } }
27764873_17
class SimpleConsumer { public TopicAndPartition getTopicAndPartition() { return topicAndPartition; } public SimpleConsumer(TalosConsumerConfig consumerConfig, TopicAndPartition topicAndPartition, MessageService.Iface messageClient, String consumerIdPrefix); public SimpleConsumer(TalosConsume...
assertEquals(topicAndPartition, simpleConsumer.getTopicAndPartition()); } }
27773224_0
class Boxer { @SuppressWarnings("unchecked") public static <T> Boxer<T> from(T object) { for(String target : defaultWrappers.keySet()){ try{ if(Class.forName(target).isAssignableFrom(object.getClass())){ return defaultWrappers.get(target).getDeclaredConst...
Assertions.assertThat(Boxer.from(null)) .isNull(); } }
27785546_57
class SnifferInputStream extends InputStream { @Override public int read() throws IOException { snifferSocket.checkConnectionAllowed(0); long start = System.currentTimeMillis(); int bytesDown = 0; try { int read = delegate.read(); if (read != -1) bytesDow...
ByteArrayInputStream bais = new ByteArrayInputStream(DATA); SnifferInputStream sis = new SnifferInputStream(snifferSocket, bais); int read; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((read = sis.read()) != -1) { baos.write(read); } ...
27789592_28
class PathVisitor { public Optional<String> visitPath(ExecutableElement element) { String aggregatedPath = emptyToNull( aggregate( currentPath(element).orElse(""), element.getEnclosingElement() ) ); return Optional.ofNullable(aggregate...
ExecutableElement method = methodElements.of( "java.lang.String", "toString" ); assertThat(visitor.visitPath(method).isPresent()).isFalse(); } }
27811092_45
class ReserveServiceImpl implements ReserveService { @Override public void cancel(String reserveNo) throws BusinessException { Reserve reserve = findOneWithTourInfo(reserveNo); String transfer = reserve.getTransfer(); if (Reserve.TRANSFERED.equals(transfer)) { ResultMessage...
Reserve reserve = new Reserve("001"); reserve.setAdultCount(1); reserve.setChildCount(2); TourInfo tour = new TourInfo("01"); reserve.setTourInfo(tour); reserve.setTransfer(Reserve.NOT_TRANSFERED); when(reserveRepository.findById("001")).thenReturn(Optional.of( ...
27824737_1
class MatrixUtils { public static double min(double[][] matrix) { return Stream.of(matrix) .mapToDouble(MatrixUtils::min) .min().getAsDouble(); } public static double max(double[][] matrix); public static double max(double[] array); public static double min(double[] array); public static double[][] t...
double min = min(MATRIX); assertEquals(1d, min, 0d); } }
27840419_29
class ModelRecord { public void delete(T model){ SingleRecordConfiguration configuration = setupDeleteConfiguration(new SingleRecordConfiguration(), model); final DeleteCallback deleteCallback = DeleteCallback.createFromConfiguration(configuration, eventProcessor, httpReport, model); config...
final Object object = new Object(); when(modelRecord.setupDeleteConfiguration(any(SingleRecordConfiguration.class), eq(object))).thenReturn(singleRecordConfiguration); doCallRealMethod().when(modelRecord).delete(object); modelRecord.delete(object); verify(modelRecord).setupDelet...
27879839_9
class PJDatum extends PJ implements GeodeticDatum, PrimeMeridian, Ellipsoid { public Unit<Length> getLinearUnit(final boolean vertical) { final double factor = getLinearUnitToMetre(vertical); int i = Arrays.binarySearch(LINEAR_FACTORS, factor); if (i < 0) { i = ~i; i...
PJDatum pj; pj = new PJDatum(null, "+proj=merc +to_meter=" + (1 + PJDatum.EPS/2)); assertSame(Units.METRE, pj.getLinearUnit(false)); pj = new PJDatum(null, "+proj=merc +to_meter=" + (1000 - PJDatum.EPS/2)); assertSame(Units.KILOMETRE, pj.getLinearUnit(false)); } }
27984624_8
class FreeMarker implements TemplateEngine { @Override public String get(String resource, Object args) { Template template = getTemplate(resource); return processTemplate(args, template); } @Override public String get(String resource); protected static Template getTemplate(String t...
// prepare Map<String, Object> param = new HashMap<>(); param.put("deptno", 30); param.put("job", "SALESMAN"); // execute String result = new FreeMarker().get("ftl/selectByArgs.sql", param); // assert String[] results = result.split("\n"); int i...
27988806_2
class TypeUtils { public static Type[] getGenericsTypesByClass(Class clazz, Type type) { Class targetClass = clazz; while (targetClass != null) { for (Type in : targetClass.getGenericInterfaces()) { if (in instanceof ParameterizedType && type.equa...
Class<? extends Serializer> clazz = SerializerImpl.class; Type[] types = TypeUtils.getGenericsTypesByClass(clazz, Serializer.class); assertThat(types.length).isEqualTo(2); assertThat(types[0].getTypeName()).isEqualTo("java.lang.String"); assertThat(types[1].getTypeName()).isEqual...
27989980_3
class Calculator { @WebMethod public float mul(float a, float b) { return a * b; } @WebMethod public float sum(float a, float b); @WebMethod public float div(float a, float b); @WebMethod public float sub(float a, float b); } class CalculatorTest { @Test public void testMul(...
Calculator calculator = new Calculator(); assertEquals(0.0F, (float) calculator.mul(1, 0), -1); } }
28071993_7
class RxSharedPreferences { @CheckResult @NonNull public Preference<Float> getFloat(@NonNull String key) { return getFloat(key, DEFAULT_FLOAT); } private RxSharedPreferences(final SharedPreferences preferences); @CheckResult @NonNull public static RxSharedPreferences create(@NonNull SharedPreferences ...
try { rxPreferences.getFloat("key", null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("defaultValue == null"); } } }
28075895_4
class CollectionUtil { public static boolean hasElements(Collection<?> collection){ return collection != null && !collection.isEmpty(); } public static boolean isNullOrEmpty(Collection<?> collection); } class CollectionUtilTest { @Test public void shouldReturnFalseIfCollectionIsEmpty(){
List<String> emptyList = new ArrayList<String>(); Assert.assertFalse(CollectionUtil.hasElements(emptyList)); } }
28086563_0
class DataService { public abstract Collection<Product> getAllProducts()public abstract Collection<Product> getAllProducts(); public abstract Collection<Product> getAllProducts()public abstract Collection<Category> getAllCategories(); public abstract Collection<Product> getAllProducts()public abstract void updateProd...
assertFalse(service.getAllProducts().isEmpty()); } }
28129477_0
class NodeManager { public Node getOrCreateNode(Manager manager, String key, GraphDatabaseService db) { // Federates requests to a graph node data management object return manager.getOrCreateNode(key, db); } public NodeManager(); public static Map<String, Object> getNodeFromGloba...
GraphDatabaseService db = setUpDb(); NodeManager nodeManager = new NodeManager(); NodeManager.globalNodeCache.invalidateAll(); DataNodeManager.dataCache.invalidateAll(); DataNodeManager dataNodeManager = new DataNodeManager(); // Write some nodes to the database ...
28138459_13
class AnnotationDtoInfoResolver extends BaseDtoInfoResolver { @Override public <D, I> I resolveId(D dto, Class<I> aggregateIdClass) { ParameterHolder<D> parameterHolder = getIdParameterHolder(dto, aggregateIdClass); return createIdentifier(aggregateIdClass, parameterHolder.uniqueElement(dto), ...
when(domainRegistry.getFactory(Case2DtoVO.class)).thenReturn(new Case2DtoVOFactory()); Case2DtoVO id = underTest.resolveId(new Case2Dto(firstName, birthDate), Case2DtoVO.class); assertThat(id).isNotNull(); assertThat(id).isEqualTo(new Case2DtoVO(firstName, birthDate)); } }
28146647_4
class GeometricDistribution { public static double getProb(int x, double p) { return Math.pow(2, getLog2Prob(x, p)); } private GeometricDistribution(); public static double getLog2Prob(int x, double p); } class GeometricDistributionTest { @Test public void testGetProb() {
assertEquals(GeometricDistribution.getProb(1, .1), .1, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(1, .1), DoubleMath.log2(.1), 1E-10); assertEquals(GeometricDistribution.getProb(2, .1), .09, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(2, .1), DoubleMath.log2(.09), 1E-10); } }
28174434_1
class MultiProtocol extends AbstractProtocol<T> { @Override public ProtocolMonitor<T> createMonitor(String name) { return new MultiProtocolMonitor<T>(name, this); } public MultiProtocol(final List<Protocol<MultiProtocolMonitor<T>>> protocols); private final MultiProtocol<Object> protocol...
ProtocolMonitor<Object> monitor = this.protocol.createMonitor("abc"); Assert.assertEquals("IdleState", monitor.getStateInfo()); monitor.read((byte) 0x8a); Assert.assertEquals("RunningState", monitor.getStateInfo()); monitor.read((byte) 0x8a); Assert.assertEquals("Running...
28176479_21
class NubitsURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } public NubitsURI(String uri); public NubitsURI(@Nullable NetworkParameters params, String input); private void parseParameters(@Nullable NetworkParameters params, String addressToken, String[] ...
assertNull(new NubitsURI(MainNetParams.get(), NubitsURI.NUBITS_SCHEME + ":" + MAINNET_GOOD_ADDRESS + "?label=").getLabel()); } }
28190686_4
class DomainResource { @RequestMapping(value = "/rest/domains/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public void delete(@PathVariable String id) { log.debug("REST request to delete Domain : {}", id); domainRepository...
// Initialize the database domainRepository.save(domain); // Get the domain restDomainMockMvc.perform(delete("/app/rest/domains/{id}", domain.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database ...
28275464_0
class OperatorExpression extends Expression { @Override public Value evaluate(final State state) throws SetlException { ArrayDeque<Value> values = new ArrayDeque<>(numberOfOperators); ArrayDeque<Value> valuesForReplay = new ArrayDeque<>(numberOfOperators); for (int i = 0; i < numberOfO...
// given FragmentList<AOperator> operators = new FragmentList<>(); addNumber(operators, 10); addNumber(operators, 20); operators.add(Sum.S); // when EvaluationResult result = evaluate(operators); // then assertEquals("10 + 20", result.getExpressi...
28275474_19
class PhoneNumberUtil { public final String formatCommon(final String pphoneNumber) { return this.formatCommon(this.parsePhoneNumber(pphoneNumber)); } public PhoneNumberUtil(); public PhoneNumberUtil(final String pcountryCode); public final void setCountryCode(final String pcountryCode); public fin...
Assert.assertNull("Should be null", this.phoneNumberUtil.formatCommon((PhoneNumberData) null)); for (final Entry<PhoneNumberInterface, String> testCase : PhoneNumberUtilTestCases .getFormatCommonCases().entrySet()) { final String formatedNumber = this.phoneNumberUtil.formatCommon(testCase.getKey()...
28305374_290
class GuestService { public Map<String, String> customizeVM(HttpInputs httpInputs, VmInputs vmInputs, GuestInputs guestInputs, boolean isWin) throws Exception { ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs); try { ManagedObjectRefere...
whenNew(MorObjectHandler.class).withNoArguments().thenReturn(morObjectHandlerMock); when(httpInputsMock.isCloseSession()).thenReturn(true); when(morObjectHandlerMock.getMor(any(ConnectionResources.class), anyString(), anyString())).thenReturn(vmMorMock); whenNew(GuestConfigSpecs.class).w...
28312494_8
class Wasp { @SuppressWarnings("unchecked") public <T> T create(Class<T> service) { if (service == null) { throw new NullPointerException("service param may not be null"); } if (!service.isInterface()) { throw new IllegalArgumentException("Only interface type is supported"); } Netwo...
MockResponse response = new MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setBody("{\n" + " \"no\": 123,\n" + " \"name\": \"Hello\"\n" + "}"); server.enqueue(response); MyApiPost myApi = new Wasp.Builder(context) ...
28325219_1
class ClientTokenService { @Transactional(propagation = Propagation.REQUIRED) public void save(ClientToken ct) { ctd.save(ct); } public ClientToken findByEmail(String email); public ClientToken findByToken(String token); public boolean checkTokenBelongToUser(String token, int u_id); ...
ClientToken ct = newInstence(); us.save(ct.getUser()); assertThat(ct.getUser().getId(), not(0)); cts.save(ct); assertThat(ct.getId(), not(0)); } }
28344352_1
class SchemaFormAvroConverter implements ConverterConstants, SchemaFormConstants { public RecordField createSchemaFormFromSchema(String schemaString) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(schemaString); Schema.Parser parser = new Sche...
SchemaFormAvroConverter converter = new SchemaFormAvroConverter(new TestCtlSource()); String typeCtlReferencesSchema = TestAvroSchemas.getSchemaJson(TestAvroSchemas.TYPE_CTL_REFERENCES); RecordField schemaForm = converter.createSchemaFormFromSchema(typeCtlReferencesSchema); ...
28358565_2
class ActivitiParser implements Parser { @Override public ProcessDefinition parse(InputStream in) throws ParserException { if (in == null) { throw new NullPointerException("Input cannot be null"); } try { SAXParserFactory spf = SAXParserFactory.newInstance(); ...
InputStream in = ClassLoader.getSystemResourceAsStream("complex2.bpmn"); Parser p = new ActivitiParser(); ProcessDefinition pd = p.parse(in); assertNotNull(pd); SubProcess sp1 = (SubProcess) pd.getChild("reserveSubprocess"); assertNotNull(sp1); assertEqu...
28407415_15
class JMSCacheMessageListener implements MessageListener { protected boolean checkNamespaceAware() { try { Class.forName("com.tridion.util.NamespacePrefixWrapper", false, this.getClass().getClassLoader()); LOG.info("This tridion version is namespace aware (Tridion version is 8.5+)")...
JMSCacheMessageListener messageListener = (JMSCacheMessageListener) applicationContext.getBean ("cacheMessageListener"); assertNotNull(messageListener); } }
28450866_6
class Swipe { public int getSwipedThreshold() { return swipedThreshold; } public Swipe(); public Swipe(int swipingThreshold, int swipedThreshold); public void setListener(SwipeListener swipeListener); public Observable<SwipeEvent> observe(); public boolean dispatchTouchEvent(final MotionEvent eve...
simulateSwipedHorizontally(swipe.getSwipedThreshold() + MIN_MOTION_CHANGE); assertThat(swipeEvent).isEqualTo(SwipeEvent.SWIPED_RIGHT); } }
28464672_8
class Cartographer { public String toJson(Map<?, ?> map) { StringWriter stringWriter = new StringWriter(); try { toJson(map, stringWriter); } catch (IOException e) { throw new AssertionError(e); // No I/O writing to a Buffer. } return stringWriter.toString(); } Cartographer(boo...
// Exercise a bug where primitive arrays would throw an IOException. // https://github.com/segmentio/analytics-android/issues/507 Map<String, Object> map = ImmutableMap.<String, Object>builder().put("a", new int[] {1, 2}).build(); assertThat(cartographer.toJson(map)) .isEqualTo("{\n" + ...
28546353_6
class PdfStreamResult extends StrutsResultSupport { LinkedHashSet<String> stringToSet(final String str) { final LinkedHashSet<String> set; if (str == null || str.trim().isEmpty()) { set = null; } else { set = new LinkedHashSet<>(); String[] split = str.sp...
Assert.assertNotNull(pdfStreamResult); final String paths = ""; LinkedHashSet<String> set = pdfStreamResult.stringToSet(paths); Assert.assertNull(set); } }
28546707_3
class Note extends EzRgx { public int orderStartAtA() { if ("a".equals(name)) { if("#".equals(sign)){ return 1; } else if("b".equals(sign)){ return 12; } else return 0; } else if ("b"...
Note note_aD2 = new Note("folder/a#2.wav"); assertEquals("a", note_aD2.name); assertEquals("#", note_aD2.sign); assertEquals(2, note_aD2.octave); assertEquals(1, note_aD2.instance); assertEquals(1, note_aD2.orderStartAtA()); } }
28556746_29
class DfuSerializers { public static <V> TypeSerializer<V> forCodec(final Codec<V> codec) { return new CodecSerializer<>(requireNonNull(codec, "codec")); } private DfuSerializers(); public static Codec<S> forSerializer(final TypeToken<S> type); public static Codec<V> forSerializer(final ...
final TypeSerializerCollection serializers = TypeSerializerCollection.defaults().childBuilder() .register(VEC3I_TYPE, DfuSerializers.forCodec(VEC3I_CODEC)) .build(); final ConfigurationNode testElement = BasicConfigurationNode.root(ConfigurationOptions.defaults().withSerializers...
28560583_2
class Bloom1Filter { public void merge(Bloom1Filter that) { this.bitSet.putAll(that.bitSet); } public Bloom1Filter(long maxNumEntries); public Bloom1Filter(long maxNumEntries, double fpp); public Bloom1Filter(List<Long> serializedBloom); static int optimalNumOfHashFunctions(long n, long m); stat...
Bloom1Filter bf = new Bloom1Filter(10000); String val = "bloo"; String val1 = "bloom fil"; String val2 = "bloom filter"; String val3 = "cuckoo filter"; bf.addString(val); bf.addString(val1); bf.addString(val2); bf.addString(val3); Bloom1Filter bf2 = new Bloom1Filter(10000); ...
28565575_3
class IoUtils { public static File toFile(Uri uri) { if (uri != null && isFile(uri)) { return new File(uri.getPath()); } return null; } public static boolean saveFile(File file, byte[] content); public static boolean saveBitmap(File file, Bitmap bitmap, ...
Assert.assertNotEquals(IoUtils.toFile(Uri.fromFile(new File("."))), new File(".")); Assert.assertEquals(IoUtils.toFile(Uri.fromFile(new File("."))), new File(".").getAbsoluteFile()); Assert.assertEquals(IoUtils.toFile(Uri.fromFile(new File("/etc"))), new File("/etc")); Assert.assertEqual...
28589967_4
class EmbeddedDatabaseRule extends EmbeddedDatabaseCreatorImpl implements TestRule { public static Builder h2() { return Builder.h2(); } public EmbeddedDatabaseRule(); private EmbeddedDatabaseRule(final boolean autoCommit, final String name, ...
final EmbeddedDatabaseRule.Builder builder = EmbeddedDatabaseRule.h2(); assertNotNull(builder); builder.withInitialSqlFromResource(null, null); } }
28598239_31
class GfsUriUtils { @Nonnull public static String getRepository(URI uri) { checkScheme(uri); String path = uri.getPath(); if(path.length() > 1 && path.endsWith("/") && !path.endsWith(":/")) path = path.substring(0, path.length() - 1); return path; } static void checkScheme(URI uri); @N...
assertEquals("/c:/", GfsUriUtils.getRepository(URI.create("gfs:/c:/"))); assertEquals("/c:/windows/path", GfsUriUtils.getRepository(URI.create("gfs:/c:/windows/path"))); assertEquals("/c:/windows/path", GfsUriUtils.getRepository(URI.create("gfs:/c:/windows/path/"))); assertEquals("/c:/windows/path", Gfs...
28691699_230
class Optional { @NotNull @SuppressWarnings("unchecked") public Stream<T> stream() { if (!isPresent()) return Stream.empty(); return Stream.of(value); } private Optional(); private Optional(T value); @NotNull @Contract("_ -> new") public static Optional<T> of(@NotNull T ...
long count = Optional.of(10).stream().count(); assertThat(count, is(1L)); } }
28714528_15
class ResourceLocalizer implements Localizer { @Override public String formatMoney(String amount, String currencyCode) { if (amount == null || amount.isEmpty()) { return ""; } try { float value = Float.valueOf(amount); if (value ==...
assertEquals("1,234.57 $", UNDER_TEST.formatMoney("1234.567", "USD")); } }
28738447_272
class FilterOptimizeTransformer implements ITupleFilterTransformer { @Override public TupleFilter transform(TupleFilter tupleFilter) { if (tupleFilter == null || !(tupleFilter instanceof IOptimizeableTupleFilter)) return tupleFilter; else return ((IOptimizeableTupleFilte...
TupleFilter or = new LogicalTupleFilter(TupleFilter.FilterOperatorEnum.AND); TupleFilter a = ConstantTupleFilter.FALSE; TupleFilter b = ConstantTupleFilter.FALSE; or.addChild(a); or.addChild(b); or = new FilterOptimizeTransformer().transform(or); Assert.assertEqu...
28745639_3
class SimulatedStepperMotor implements GpioCompHwEmulation, SimulatedTimeListerner { private void doStep() { Long currentTime = SimulatedTime.INST.getRequestingTime(); byte currentBinaryState = getBinaryState(); if (logger.isTraceEnabled()) logger.info("Do Step : previous["+previousBinaryState+"] current["+c...
SimulatedStepperMotor dut = new SimulatedStepperMotor(getBuilderFor(buildProperty().setStepsPerRotation(1024))); byte[] half_step_sequence = new byte[8]; half_step_sequence[0] = (byte) 0b0001; half_step_sequence[1] = (byte) 0b0011; half_step_sequence[2] = (byte) 0b0010; half_...
28772513_2
class CollectionUtil { public static <T> T getFirstOrNull(List<T> list) { if (list == null || list.isEmpty()) { return null; } return list.get(0); } private CollectionUtil(); public static Map<K, V> asHashMap(List<V> list, ListExtractor<K, V> extractor); } class...
assertNull(CollectionUtil.getFirstOrNull(null), "Calling with null should result in null"); assertNull(CollectionUtil.getFirstOrNull(Collections.emptyList()), "Calling with an empty list shall result in null"); } }
28776576_22
class YarnLocalCluster implements MiniCluster { public Integer getNumNodeManagers() { return numNodeManagers; } private YarnLocalCluster(Builder builder); public String getTestName(); public Integer getNumLocalDirs(); public Integer getNumLogDirs(); public String getResourceManag...
assertEquals(Integer.parseInt(propertyParser.getProperty(ConfigVars.YARN_NUM_NODE_MANAGERS_KEY)), (int) yarnLocalCluster.getNumNodeManagers()); } }
28776939_96
class DeviceInfo { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceInfo rhs = (DeviceInfo) o; return new EqualsBuilder() .a...
// given DeviceInfo deviceInfo1 = new DeviceInfo( STANDARD_VERSION, VENDOR_EXTENSION_ID, VENDOR_EXTENSION_VERSION, VENDOR_EXTENSION_DESC, FUNCTIONAL_MODE, OPERATIONS_SUPPORTED, EVENTS_SUPPORTED, DEVICE_PROPERTIES_SUPPORTED, LIST_1, IMAGE_FORMATS, MANUFACTU...
28790580_0
class BookResource { @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response create(Book book) { if (bookDao.create(book).isPresent()) { return Response.status(NO_CONTENT).build(); } return Response.status(BAD_REQUEST) .entity(format(BOOK_EXISTS_MSG, bo...
when(bookDaoMock.create(book)).thenReturn(Optional.of(book)); Response response = resource.create(book); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); } }