auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean tableExists( Connection connection, TableId tableId ) throws SQLException { log.info("Checking dialect for existance of table {}", this, tableId); try (ResultSet rs = connection.getMetaData().getTables( tableId.catalogName(), tableId.schemaName(), tableId.tableName(), new String[]{"TABLE"} )) { final boolean exists = rs.next(); log.info("Using dialect table {}", this, tableId, exists ? "present" : "absent"); return exists; } }

Target:
public boolean tableExists( Connection connection, TableId tableId ) throws SQLException { log.info("Checking dialect for existence of table {}", this, tableId); try (ResultSet rs = connection.getMetaData().getTables( tableId.catalogName(), tableId.schemaName(), tableId.tableName(), new String[]{"TABLE"} )) { final boolean exists = rs.next(); log.info("Using dialect table {}", this, tableId, exists ? "present" : "absent"); return exists; } }
Source:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { return HTMLPageAssetRenderedBuilder.get() .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }

Target:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { return new HTMLPageAssetRenderedBuilder() .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }
Source:
public long getSerial() { long next = getAttribute(SERIAL) + 1; setAttribute(SERIAL, next); return next; }

Target:
public long getSerial() { synchronized (serialMutex) { long next = getAttribute(SERIAL) + 1; setAttribute(SERIAL, next); return next; } }
Source:
public void commit() { switch (state()) { case RUNNING: stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); changelogOffsetSnapshot = stateMgr.changelogOffsets(); log.info("Committed"); break; case CLOSING: log.trace("Skip committing since task is closing"); break; default: throw new IllegalStateException("Illegal state " + state() + " while committing standby task " + id); } }

Target:
public void commit() { switch (state()) { case RUNNING: stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); offsetSnapshotSinceLastCommit = new HashMap<>(stateMgr.changelogOffsets()); log.info("Committed"); break; case CLOSING: log.trace("Skip committing since task is closing"); break; default: throw new IllegalStateException("Illegal state " + state() + " while committing standby task " + id); } }
Source:
public static Optional<UsState> getState(String normalisedZipCode) { if (WELL_FORMED_STATE_WITH_ZIP_CODE.matcher(normalisedZipCode).matches() || WELL_FORMED_STATE_WITH_ZIP_FOUR_PLUS.matcher(normalisedZipCode).matches()) { return getStateFromZipCodeAndState(normalisedZipCode); } else if (WELL_FORMED_ZIP_CODE.matcher(normalisedZipCode).matches() || WELL_FORMED_ZIP_FOUR_PLUS.matcher(normalisedZipCode).matches()) { return getStateFromZipCode(normalisedZipCode.substring(0, 3)); } return Optional.empty(); }

Target:
public static Optional<UsState> getState(String normalisedZipCode) { var wellFormedZipCodeAndOptionalPlusFourMatcher = WELL_FORMED_STATE_WITH_ZIP_CODE_AND_OPTIONAL_PLUS_FOUR.matcher(normalisedZipCode); var wellFormedStateWithZipAndOptionalPlusFourMatcher = WELL_FORMED_ZIP_CODE_AND_OPTIONAL_PLUS_FOUR.matcher(normalisedZipCode); if (wellFormedStateWithZipAndOptionalPlusFourMatcher.matches()) { String stateAbbreviation = wellFormedStateWithZipAndOptionalPlusFourMatcher.group(1); return Optional.ofNullable(UsZipCodeToStateMap.ZIP_CODE_TO_US_STATE_ABBREVIATIONS.get(stateAbbreviation)); } else if (wellFormedZipCodeAndOptionalPlusFourMatcher.matches()) { String firstThreeCharacters = wellFormedZipCodeAndOptionalPlusFourMatcher.group(1); return Optional.ofNullable(US_STATE_ABBREVIATIONS_MAPPING.get(firstThreeCharacters)); } return Optional.empty(); }
Source:
static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { T instance = annotatedClass.getAnnotation(annotation); if (instance == null) throw new IllegalStateException(String.format("@%s annotation was not found on %s", annotation.getSimpleName(), annotatedClass)); validateAnnotations(annotatedClass, annotation); return instance; }

Target:
static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { T instance = annotatedClass.getAnnotation(annotation); if (instance == null) throw new IllegalArgumentException(String.format("@%s annotation was not found on %s", annotation.getSimpleName(), annotatedClass)); validateAnnotations(annotatedClass, annotation); return instance; }
Source:
private void removeAlwaysOff(IActionSetDescriptor descriptor) { if (descriptor == null) { return; } if (!alwaysOffActionSets.contains(descriptor)) { return; } alwaysOffActionSets.remove(descriptor); if (page != null) { page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK); } }

Target:
private void removeAlwaysOff(IActionSetDescriptor descriptor) { if (!alwaysOffActionSets.contains(descriptor)) { return; } alwaysOffActionSets.remove(descriptor); page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK); }
Source:
public void run() { try { if (completed) { return; } setupExecutor(); int maxOperationCount = operationCount.get(); int processedBatchCount = 0; QueryOperation operation; while ((operation = operations.pollFirst()) != null) { if (operation instanceof QueryBatchExchangeOperation) { QueryBatchExchangeOperation operation0 = (QueryBatchExchangeOperation) operation; InboundHandler inbox = inboxes.get(operation0.getEdgeId()); assert inbox != null; InboundBatch batch = new InboundBatch( operation0.getBatch(), operation0.isLast(), operation0.getCallerId() ); inbox.onBatch(batch, operation0.getRemainingMemory()); } else { assert operation instanceof QueryFlowControlExchangeOperation; QueryFlowControlExchangeOperation operation0 = (QueryFlowControlExchangeOperation) operation; Map<UUID, OutboundHandler> edgeOutboxes = outboxes.get(operation0.getEdgeId()); assert edgeOutboxes != null; OutboundHandler outbox = edgeOutboxes.get(operation.getCallerId()); assert outbox != null; outbox.onFlowControl(operation0.getRemainingMemory()); } if (++processedBatchCount >= maxOperationCount) { break; } } operationCount.addAndGet(-1 * processedBatchCount); IterationResult res = exec.advance(); if (res != IterationResult.FETCHED_DONE) { for (InboundHandler inbox : inboxes.values()) { inbox.sendFlowControl(); } } if (res == IterationResult.FETCHED_DONE) { completed = true; stateCallback.onFragmentFinished(); } } catch (Exception e) { completed = true; stateCallback.cancel(e); } unschedule(); }

Target:
public void run() { try { if (completed) { return; } setupExecutor(); int maxOperationCount = operationCount.get(); int processedBatchCount = 0; QueryOperation operation; while ((operation = operations.pollFirst()) != null) { if (operation instanceof QueryBatchExchangeOperation) { QueryBatchExchangeOperation operation0 = (QueryBatchExchangeOperation) operation; InboundHandler inbox = inboxes.get(operation0.getEdgeId()); assert inbox != null; InboundBatch batch = new InboundBatch( operation0.getBatch(), operation0.isLast(), operation0.getCallerId() ); inbox.onBatch(batch, operation0.getRemainingMemory()); } else { assert operation instanceof QueryFlowControlExchangeOperation; QueryFlowControlExchangeOperation operation0 = (QueryFlowControlExchangeOperation) operation; Map<UUID, OutboundHandler> edgeOutboxes = outboxes.get(operation0.getEdgeId()); assert edgeOutboxes != null; OutboundHandler outbox = edgeOutboxes.get(operation.getCallerId()); assert outbox != null; outbox.onFlowControl(operation0.getRemainingMemory()); } if (++processedBatchCount >= maxOperationCount) { break; } } operationCount.addAndGet(-1 * processedBatchCount); IterationResult res = exec.advance(); if (res != IterationResult.FETCHED_DONE) { for (InboundHandler inbox : inboxes.values()) { inbox.sendFlowControl(); } } if (res == IterationResult.FETCHED_DONE) { completed = true; stateCallback.onFragmentFinished(); } } catch (Exception e) { completed = true; stateCallback.cancel(e); } finally { unscheduleOrReschedule(); } }
Source:
public T from(@Nonnull byte[] bytes) { ByteArrayInputStream input = new ByteArrayInputStream(bytes); int len = TASK_HEADER.length; byte[] prefix = new byte[len]; if (input.read(prefix, 0, len) == len && Arrays.equals(prefix, TASK_HEADER)) { int bytesToRead = input.read(); if (bytesToRead > 0) { byte[] format = new byte[bytesToRead]; if (input.read(format, 0, bytesToRead) == bytesToRead) { try { InputStream stream; if (Arrays.equals(format, FORMAT_LZ4)) { stream = new LZ4BlockInputStream(input); } else if (Arrays.equals(format, FORMAT_GZIP)) { stream = new GZIPInputStream(input); } else if (Arrays.equals(format, FORMAT_RAW)) { stream = input; } else { logger.warning("Unable to restore persisted task - unsupported data format " + "header detected: " + Arrays.toString(format)); return null; } return (T) objectMapper.readValue(stream, DataSubmissionTask.class); } catch (Throwable t) { logger.warning("Unable to restore persisted task: " + t); } } else { logger.warning("Unable to restore persisted task - corrupted header, ignoring"); } } else { logger.warning("Unable to restore persisted task - corrupted header, ignoring"); } } else { logger.warning("Unable to restore persisted task - no signature found, ignoring"); } errorCounter.inc(); return null; }

Target:
public T from(@Nonnull byte[] bytes) { ByteArrayInputStream input = new ByteArrayInputStream(bytes); int len = TASK_HEADER.length; byte[] prefix = new byte[len]; if (input.read(prefix, 0, len) == len && Arrays.equals(prefix, TASK_HEADER)) { int bytesToRead = input.read(); if (bytesToRead > 0) { byte[] format = new byte[bytesToRead]; if (input.read(format, 0, bytesToRead) == bytesToRead) { InputStream stream = null; try { if (Arrays.equals(format, FORMAT_LZ4)) { stream = new LZ4BlockInputStream(input); } else if (Arrays.equals(format, FORMAT_GZIP)) { stream = new GZIPInputStream(input); } else if (Arrays.equals(format, FORMAT_RAW)) { stream = input; } else { logger.warning("Unable to restore persisted task - unsupported data format " + "header detected: " + Arrays.toString(format)); return null; } return (T) objectMapper.readValue(stream, DataSubmissionTask.class); } catch (Throwable t) { logger.warning("Unable to restore persisted task: " + t); } finally { IOUtils.closeQuietly(stream); } } else { logger.warning("Unable to restore persisted task - corrupted header, ignoring"); } } else { logger.warning("Unable to restore persisted task - missing header, ignoring"); } } else { logger.warning("Unable to restore persisted task - invalid or missing header, ignoring"); } errorCounter.inc(); return null; }
Source:
public void registerRecipes() { BuildcraftRecipeRegistry.refineryRecipes.addDistillationRecipe(Fluids.BIOMASS.getFluid(4), Fluids.BIO_ETHANOL.getFluid(0), Fluids.BIO_ETHANOL.getFluid(1), 100); }

Target:
public void registerRecipes() { BuildcraftRecipeRegistry.refineryRecipes.addDistillationRecipe(Fluids.BIOMASS.getFluid(10), Fluids.BIO_ETHANOL.getFluid(0), Fluids.BIO_ETHANOL.getFluid(3), 20 * MjAPI.MJ); }
Source:
public synchronized void ack(T checkpoint) { if (!_inFlight.remove(checkpoint)) { LOG.error("Internal state error; could not remove checkpoint {}", checkpoint); } _acked.add(checkpoint); if (_highWaterMark == null || _highWaterMark.compareTo(checkpoint) < 0) { _highWaterMark = checkpoint; } T first = _inFlight.peek(); if (first == null) { setCurrentCheckpoint(_highWaterMark); _acked.clear(); } else { T max = null; while (!_acked.isEmpty() && _acked.peek().compareTo(first) < 0) { max = _acked.poll(); } if (max != null) { setCurrentCheckpoint(max); } } }

Target:
public synchronized void ack(T checkpoint) { if (!_inFlight.remove(checkpoint)) { LOG.error("Internal state error; could not remove checkpoint {}", checkpoint); } _acked.add(checkpoint); if (_highWaterMark == null || _highWaterMark.compareTo(checkpoint) < 0) { _highWaterMark = checkpoint; } if (_inFlight.isEmpty()) { _currentCheckpoint = _highWaterMark; _acked.clear(); } else { T max = null; T first = _inFlight.iterator().next(); while (!_acked.isEmpty() && _acked.peek().compareTo(first) < 0) { max = _acked.poll(); } if (max != null) { if (_currentCheckpoint != null && max.compareTo(_currentCheckpoint) < 0) { LOG.error( "Internal error: checkpoints should progress in increasing order. Resolved checkpoint as which is less than current checkpoint of {}", max, _currentCheckpoint); } _currentCheckpoint = max; } } }
Source:
public static Enum<EnumCause> getForClass(Class<? extends Cause> clazz) { return Arrays.stream(values()).filter(enumCause -> enumCause.clazz == clazz).findFirst().orElse(null); }

Target:
public static EnumCause getForClass(Class<? extends Cause> clazz) { return Arrays.stream(values()).filter(enumCause -> enumCause.clazz == clazz).findFirst().orElse(null); }
Source:
private void verifyUserMetadataHeaders(HttpHeaders expectedHeaders, HttpResponse response, ByteBuffer usermetadata) { if (usermetadata == null) { for (Map.Entry<String, String> header : expectedHeaders) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) { assertEquals("Value for " + key + "does not match in user metadata", header.getValue(), HttpHeaders.getHeader(response, key)); } } } else { for (Map.Entry<String, String> header : response.headers()) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_OLD_STYLE_PREFIX)) { for (byte b : header.getValue().getBytes()) { assertTrue("Received user metadata is longer than the original", usermetadata.hasRemaining()); assertEquals("Byte of received user metadata does not match original", usermetadata.get(), b); } } } } }

Target:
private void verifyUserMetadataHeaders(HttpHeaders expectedHeaders, HttpResponse response, ByteBuffer usermetadata) { if (usermetadata == null) { for (Map.Entry<String, String> header : expectedHeaders) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) { assertEquals("Value for " + key + " does not match in user metadata", header.getValue(), HttpHeaders.getHeader(response, key)); } } for (Map.Entry<String, String> header : response.headers()) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) { assertTrue("Key " + key + " does not exist in expected headers", expectedHeaders.contains(key)); } } } else { int highestIndex = -1; for (Map.Entry<String, String> header : response.headers()) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_OLD_STYLE_PREFIX)) { int index = Integer.parseInt(key.substring(RestUtils.Headers.USER_META_DATA_OLD_STYLE_PREFIX.length())); highestIndex = Math.max(index, highestIndex); } } if (highestIndex == -1) { fail("There should have been user metadata in the response"); } else { for (int i = 0; i <= highestIndex; i++) { String value = response.headers().get(RestUtils.Headers.USER_META_DATA_OLD_STYLE_PREFIX + i); for (byte b : value.getBytes()) { assertTrue("Received user metadata should not be longer than the original", usermetadata.hasRemaining()); assertEquals("Byte of received user metadata does not match original", usermetadata.get(), b); } } assertFalse("Some user metadata was not found in the response", usermetadata.hasRemaining()); } } }
Source:
public void createS3Bucket(String userName, String s3BucketName) throws IOException { try { if(isAclEnabled) { checkAcls(ResourceType.BUCKET, StoreType.S3, ACLType.CREATE, null, s3BucketName, null); } metrics.incNumBucketCreates(); try { metadataManager.getLock().acquireS3BucketLock(s3BucketName); metadataManager.getLock().acquireVolumeLock( s3BucketManager.formatOzoneVolumeName(userName)); boolean newVolumeCreate = s3BucketManager.createOzoneVolumeIfNeeded( userName); if (newVolumeCreate) { metrics.incNumVolumeCreates(); metrics.incNumVolumes(); } } catch (IOException ex) { metrics.incNumVolumeCreates(); metrics.incNumVolumeCreateFails(); throw ex; } s3BucketManager.createS3Bucket(userName, s3BucketName); metrics.incNumBuckets(); } catch (IOException ex) { metrics.incNumBucketCreateFails(); throw ex; } finally { metadataManager.getLock().releaseVolumeLock( s3BucketManager.formatOzoneVolumeName(userName)); metadataManager.getLock().releaseS3BucketLock(s3BucketName); } }

Target:
public void createS3Bucket(String userName, String s3BucketName) throws IOException { boolean acquiredS3Lock = false; boolean acquiredVolumeLock = false; try { if(isAclEnabled) { checkAcls(ResourceType.BUCKET, StoreType.S3, ACLType.CREATE, null, s3BucketName, null); } metrics.incNumBucketCreates(); metadataManager.getLock().acquireLock(S3_BUCKET_LOCK, s3BucketName); acquiredS3Lock = true; try { metadataManager.getLock().acquireLock(VOLUME_LOCK, s3BucketManager.formatOzoneVolumeName(userName)); acquiredVolumeLock = true; boolean newVolumeCreate = s3BucketManager.createOzoneVolumeIfNeeded( userName); if (newVolumeCreate) { metrics.incNumVolumeCreates(); metrics.incNumVolumes(); } } catch (IOException ex) { metrics.incNumVolumeCreates(); metrics.incNumVolumeCreateFails(); throw ex; } s3BucketManager.createS3Bucket(userName, s3BucketName); metrics.incNumBuckets(); } catch (IOException ex) { metrics.incNumBucketCreateFails(); throw ex; } finally { if (acquiredVolumeLock) { metadataManager.getLock().releaseLock(VOLUME_LOCK, s3BucketManager.formatOzoneVolumeName(userName)); } if (acquiredS3Lock) { metadataManager.getLock().releaseLock(S3_BUCKET_LOCK, s3BucketName); } } }
Source:
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, MessageLockContainer messageLockContainer, Runnable onClientClose){ this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveMessageOptions' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.prefetch = receiverOptions.getPrefetchCount(); this.receiveMode = receiverOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = receiverOptions.isSessionEnabled(); this.sessionId = receiverOptions.getSessionId(); this.messageLockContainer = messageLockContainer; this.onClientClose = onClientClose; this.defaultReceiveOptions = new ReceiveAsyncOptions() .setEnableAutoComplete(true) .setMaxAutoRenewDuration(connectionProcessor.getRetryOptions().getTryTimeout()); }

Target:
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, MessageLockContainer messageLockContainer, Runnable onClientClose) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveMessageOptions' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.prefetch = receiverOptions.getPrefetchCount(); this.receiveMode = receiverOptions.getReceiveMode(); this.entityType = entityType; this.messageLockContainer = messageLockContainer; this.onClientClose = onClientClose; this.defaultReceiveOptions = new ReceiveAsyncOptions() .setEnableAutoComplete(true) .setMaxAutoRenewDuration(connectionProcessor.getRetryOptions().getTryTimeout()); }
Source:
public SelectItem[] getAddableDocStructTypes() { switch (positionOfNewDocStrucElement) { case BEFOR_CURRENT_ELEMENT: case AFTER_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, true); case FIRST_CHILD_OF_CURRENT_ELEMENT: case LAST_CHILD_OF_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, false); default: logger.error("Invalid positionOfNewDocStrucElement"); return null; } }

Target:
public SelectItem[] getAddableDocStructTypes() { switch (positionOfNewDocStrucElement) { case BEFOR_CURRENT_ELEMENT: case AFTER_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, true); case FIRST_CHILD_OF_CURRENT_ELEMENT: case LAST_CHILD_OF_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, false); default: logger.error("Invalid positionOfNewDocStrucElement"); return new SelectItem[0]; } }
Source:
public ElasticsearchLoader(Client client, String tableName, TestingPrestoServer prestoServer, Session defaultSession) { super(prestoServer, defaultSession); this.tableName = tableName; this.client = client; }

Target:
public ElasticsearchLoader(Client client, String tableName, TestingPrestoServer prestoServer, Session defaultSession) { super(prestoServer, defaultSession); this.tableName = requireNonNull(tableName, "tableName is null"); this.client = requireNonNull(client, "client is null"); }
Source:
private void writeToQueue() throws JMSException { writeMsg(lines); session.close(); connection.close(); LOG.debug("Sent messages to topic {}", QUEUE_NAME); }

Target:
private void writeToQueue() throws JMSException { writeMsg(lines); LOG.debug("Sent messages to topic {}", qNameToUse); }
Source:
private Future<Optional<String>> sendEmail(EmailNotificationType emailNotificationType, ChargeEntity chargeEntity, HashMap<String, String> personalisation) { Boolean isEmailEnabled = Optional.ofNullable(chargeEntity.getGatewayAccount(). getEmailNotifications() .get(emailNotificationType)) .map(EmailNotificationEntity::isEnabled) .orElse(false); if (emailNotifyGloballyEnabled && isEmailEnabled) { String emailAddress = chargeEntity.getEmail(); Stopwatch responseTimeStopwatch = Stopwatch.createStarted(); return executorService.submit(() -> { try { Pair<NotificationClient, String> notifyClientSettings = getNotifyClientSettings(emailNotificationType, chargeEntity); SendEmailResponse response = notifyClientSettings.getLeft() .sendEmail(notifyClientSettings.getRight(), emailAddress, personalisation, null); return Optional.of(response.getNotificationId().toString()); } catch (NotificationClientException e) { logger.error("Failed to send confirmation email - charge_external_id=" + chargeEntity.getExternalId(), e); metricRegistry.counter("notify-operations.failures").inc(); return Optional.empty(); } finally { responseTimeStopwatch.stop(); metricRegistry.histogram("notify-operations.response_time").update(responseTimeStopwatch.elapsed(TimeUnit.MILLISECONDS)); } }); } return CompletableFuture.completedFuture(Optional.empty()); }

Target:
private Future<Optional<String>> sendEmail(EmailNotificationType emailNotificationType, ChargeEntity chargeEntity, HashMap<String, String> personalisation) { boolean isEmailEnabled = Optional.ofNullable(chargeEntity.getGatewayAccount().getEmailNotifications().get(emailNotificationType)) .map(EmailNotificationEntity::isEnabled) .orElse(false); if (emailNotifyGloballyEnabled && isEmailEnabled) { String emailAddress = chargeEntity.getEmail(); Stopwatch responseTimeStopwatch = Stopwatch.createStarted(); return executorService.submit(() -> { try { NotifyClientSettings notifyClientSettings = getNotifyClientSettings(emailNotificationType, chargeEntity); SendEmailResponse response = notifyClientSettings.getClient() .sendEmail(notifyClientSettings.getTemplateId(), emailAddress, personalisation, null); return Optional.of(response.getNotificationId().toString()); } catch (NotificationClientException e) { logger.error("Failed to send confirmation email - charge_external_id=" + chargeEntity.getExternalId(), e); metricRegistry.counter("notify-operations.failures").inc(); return Optional.empty(); } finally { responseTimeStopwatch.stop(); metricRegistry.histogram("notify-operations.response_time").update(responseTimeStopwatch.elapsed(TimeUnit.MILLISECONDS)); } }); } return CompletableFuture.completedFuture(Optional.empty()); }
Source:
public long getInitialDelay() { return timeUnit.convert(initialNsDelay, TimeUnit.NANOSECONDS); }

Target:
public long getInitialDelay() { return initialDelay; }
Source:
public void testConfigurableAnalyzerIsCaseAndAccentInsensitive() { final String testName = "testConfigurableAnalyzerIsCaseAndAccentInsensitive"; final String turtle = StrUtils.strjoinNL( TURTLE_PROLOG, "<" + RESOURCE_BASE + testName + ">", " rdfs:label 'Feeling a déjà vu'", "." ); String queryString = StrUtils.strjoinNL( QUERY_PROLOG, "SELECT ?s", "WHERE {", " ?s text:query ( rdfs:label '\"feeling ä déja\"*' 10 ) .", "}" ); Set<String> expectedURIs = new HashSet<>() ; expectedURIs.addAll( Arrays.asList(RESOURCE_BASE + testName)) ; doTestSearch(turtle, queryString, expectedURIs); }

Target:
public void testConfigurableAnalyzerIsCaseAndAccentInsensitive() { final String testName = "testConfigurableAnalyzerIsCaseAndAccentInsensitive"; final String turtle = StrUtils.strjoinNL( TURTLE_PROLOG, "<" + RESOURCE_BASE + testName + ">", " rdfs:label 'Feeling a déjà vu'", "." ); String queryString = StrUtils.strjoinNL( QUERY_PROLOG, "SELECT ?s", "WHERE {", " ?s text:query ( rdfs:label '\"feeling ä déja\"*' 10 ) .", "}" ); Set<String> expectedURIs = Sets.newHashSet(RESOURCE_BASE + testName); doTestSearch(turtle, queryString, expectedURIs); }
Source:
public void edit(final UnitVmModel object) { super.edit(object); if (object.getIsNew()) { object.getNumOfDesktops().setEntity(1); } prestartedVmsEditor.setEnabled(true); }

Target:
public void edit(final UnitVmModel object) { super.edit(object); if (object.getIsNew()) { object.getNumOfDesktops().setEntity(1); } }
Source:
void createControls(final Composite parent) { this.quickAccessCommand = eCommandService.createCommand(QUICK_ACCESS_COMMAND_ID, null); display = parent.getDisplay(); display.addFilter(SWT.FocusIn, previousFocusListener); final Composite comp = new Composite(parent, SWT.NONE); GridLayoutFactory.swtDefaults().margins(2, 2).applyTo(comp); updateQuickAccessTriggerSequence(); quickAccessButton = createButton(comp); updateQuickAccessText(); quickAccessButton.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> { activate(previousFocusControl); })); }

Target:
void createControls(final Composite parent) { this.quickAccessCommand = eCommandService.createCommand(QUICK_ACCESS_COMMAND_ID, null); display = parent.getDisplay(); display.addFilter(SWT.FocusIn, previousFocusListener); final Composite comp = new Composite(parent, SWT.NONE); comp.setSize(SWT.DEFAULT, 32); GridLayoutFactory.swtDefaults().margins(3, 3).applyTo(comp); updateQuickAccessTriggerSequence(); quickAccessButton = createButton(comp); updateQuickAccessText(); quickAccessButton.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> { activate(previousFocusControl); })); }
Source:
protected SimpleName getNewName(ASTRewrite rewrite) { AST ast= rewrite.getAST(); SimpleName nameNode= ast.newSimpleName(String.valueOf("provider")); return nameNode; }

Target:
protected SimpleName getNewName(ASTRewrite rewrite) { AST ast= rewrite.getAST(); SimpleName nameNode= ast.newSimpleName("provider"); return nameNode; }
Source:
public void testIntegerAnnotations() { String message = "message IntMessage {" + " required int32 i8 (INT(8,true));" + " required int32 i16 (INT(16,true));" + " required int32 i32 (INT(32,true));" + " required int64 i64 (INT(64,true));" + " required int32 u8 (INT(8,false));" + " required int32 u16 (INT(16,false));" + " required int32 u32 (INT(32,false));" + " required int64 u64 (INT(64,false));" + "}\n"; MessageType parsed = MessageTypeParser.parseMessageType(message); MessageType expected = Types.buildMessage() .required(INT32).as(LogicalTypeAnnotation.intType(8, true)).named("i8") .required(INT32).as(LogicalTypeAnnotation.intType(16, true)).named("i16") .required(INT32).as(LogicalTypeAnnotation.intType(32, true)).named("i32") .required(INT64).as(LogicalTypeAnnotation.intType(64, true)).named("i64") .required(INT32).as(LogicalTypeAnnotation.intType(8, false)).named("u8") .required(INT32).as(LogicalTypeAnnotation.intType(16, false)).named("u16") .required(INT32).as(LogicalTypeAnnotation.intType(32, false)).named("u32") .required(INT64).as(LogicalTypeAnnotation.intType(64, false)).named("u64") .named("IntMessage"); assertEquals(expected, parsed); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); assertEquals(expected, reparsed); }

Target:
public void testIntegerAnnotations() { String message = "message IntMessage {" + " required int32 i8 (INT(8,true));" + " required int32 i16 (INT(16,true));" + " required int32 i32 (INT(32,true));" + " required int64 i64 (INT(64,true));" + " required int32 u8 (INT(8,false));" + " required int32 u16 (INT(16,false));" + " required int32 u32 (INT(32,false));" + " required int64 u64 (INT(64,false));" + "}\n"; MessageType parsed = MessageTypeParser.parseMessageType(message); MessageType expected = Types.buildMessage() .required(INT32).as(intType(8, true)).named("i8") .required(INT32).as(intType(16, true)).named("i16") .required(INT32).as(intType(32, true)).named("i32") .required(INT64).as(intType(64, true)).named("i64") .required(INT32).as(intType(8, false)).named("u8") .required(INT32).as(intType(16, false)).named("u16") .required(INT32).as(intType(32, false)).named("u32") .required(INT64).as(intType(64, false)).named("u64") .named("IntMessage"); assertEquals(expected, parsed); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); assertEquals(expected, reparsed); }
Source:
public String createToken(User user) { if (!Boolean.TRUE.equals(user.isActive())) { throw new PasswordResetTokenCreationException(); } deleteTokenIfExists(user); return addPasswordResetToken(user); }

Target:
public String createToken(User user) { if (!user.isActive()) { throw new PasswordResetTokenCreationException(); } deleteTokenIfExists(user); return addPasswordResetToken(user); }
Source:
public void testDestroyNetwork() throws Exception { SubNetwork subNet = new SubNetwork(SUB_NETWORK_NAME, "vdc", "region"); when(subnetworkDao.load(any(String.class))).thenReturn(subNet); subNetworkManager.delete(subNet); }

Target:
public void testDestroyNetwork() throws Exception { SubNetwork subNet = new SubNetwork(SUB_NETWORK_NAME, "vdc", "region"); subNetworkManager.delete(subNet); verify (subnetworkDao).remove(subNet); }
Source:
private List<String> getArrayList(String... labelNames) { List<String> listOfLabelNames = new ArrayList<>(); for (String labelName : labelNames) { listOfLabelNames.add(labelName); } return listOfLabelNames; }

Target:
private List<String> getArrayList(String... labelNames) { return Arrays.asList(labelNames); }
Source:
public void insertDiscovery(List<IMetric> batch) { batchHistogram.update(batch.size()); if (batch.size() == 0) { return; } Timer.Context ctx = writeTimer.time(); try { for (Object obj : batch) { if (!(obj instanceof IMetric)) { classCastExceptionMeter.mark(); continue; } } elasticsearchRestHelper.indexMetrics(batch); } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } finally { ctx.stop(); } }

Target:
public void insertDiscovery(List<IMetric> batch) { batchHistogram.update(batch.size()); if (batch.size() == 0) { return; } Timer.Context ctx = writeTimer.time(); try { for (Object obj : batch) { if (!(obj instanceof IMetric)) { classCastExceptionMeter.mark(); continue; } } elasticsearchRestHelper.indexMetrics(batch); } catch (IOException e) { log.error("Indexing metrics into elasticsearch failed. {}", e.getMessage()); throw new RuntimeException(String.format("insertDiscovery failed with message: %s", e.getMessage()), e); } finally { ctx.stop(); } }
Source:
public void publishEntityCapabilities() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, UnsupportedEncodingException, NoSuchAlgorithmException { ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection()); DiscoverInfo discoverInfo = sdm.discoverInfo(connection().getUser()); List<String> algoList = new ArrayList<String>(); algoList.add(defaultAlgo); Caps2Element element = generateCapabilityHash(discoverInfo, algoList); Presence presence = PresenceBuilder .buildPresence() .addExtension(element) .build(); connection().sendStanza(presence); }

Target:
public void publishEntityCapabilities() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, UnsupportedEncodingException, NoSuchAlgorithmException { ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection()); DiscoverInfo discoverInfo = sdm.discoverInfo(connection().getUser()); List<String> algoList = Collections.singletonList(defaultAlgo); currentEntityCapabilities = generateCapabilityHash(discoverInfo, algoList); Presence presence = PresenceBuilder .buildPresence() .addExtension(currentEntityCapabilities) .build(); connection().sendStanza(presence); setLocalEntityCapsNodeProvider(); }
Source:
public Builder<T> setQuery(@NonNull Query query, @NonNull PagedList.Config config, @NonNull SnapshotParser<T> parser) { FirestoreDataSource.Factory factory = new FirestoreDataSource.Factory(query); mData = new PagingData(new LivePagedListBuilder<>(factory, config).build()); mParser = parser; return this; }

Target:
public Builder<T> setQuery(@NonNull Query query, @NonNull PagedList.Config config, @NonNull SnapshotParser<T> parser) { FirestoreDataSource.Factory factory = new FirestoreDataSource.Factory(query); mData = new LivePagedListBuilder<>(factory, config).build(); mParser = parser; return this; }
Source:
private void refreshServerData(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { if (cluster.supportsVirtService()) { log.debugFormat("As cluster {0} supports virt service as well, it's servers will not be synced with glusterfs", cluster.getName()); return; } acquireLock(cluster.getId()); log.infoFormat("Refreshing Gluster Server data for cluster {0} using server {1} ", cluster.getName(), upServer.getName()); try { List<GlusterServerInfo> fetchedServers = fetchServers(cluster, upServer, existingServers); if (fetchedServers != null) { removeDetachedServers(existingServers, fetchedServers); } } catch(Exception e) { log.errorFormat("Error while refreshing server data for cluster {0} from database!", cluster.getName(), e); } finally { releaseLock(cluster.getId()); } }

Target:
private void refreshServerData(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { if (cluster.supportsVirtService()) { log.debugFormat("As cluster {0} supports virt service as well, it's servers will not be synced with glusterfs", cluster.getName()); return; } acquireLock(cluster.getId()); log.debugFormat("Refreshing Gluster Server data for cluster {0} using server {1} ", cluster.getName(), upServer.getName()); try { List<GlusterServerInfo> fetchedServers = fetchServers(cluster, upServer, existingServers); if (fetchedServers != null) { removeDetachedServers(existingServers, fetchedServers); } } catch(Exception e) { log.errorFormat("Error while refreshing server data for cluster {0} from database!", cluster.getName(), e); } finally { releaseLock(cluster.getId()); } }
Source:
public String getAnswerHtml(FeedbackQuestionDetails questionDetails) { FeedbackRankOptionsQuestionDetails rankQuestion = (FeedbackRankOptionsQuestionDetails) questionDetails; String invalidAnswer = "Invalid response"; StringBuilder htmlBuilder = new StringBuilder(); htmlBuilder.append("<ul>"); if (answers.get(0) == -1) { htmlBuilder.append("<li>"); htmlBuilder.append(invalidAnswer); htmlBuilder.append("</li>"); } else { SortedMap<Integer, List<String>> orderedOptions = generateMapOfRanksToOptions(rankQuestion); for (Entry<Integer, List<String>> rankAndOption : orderedOptions.entrySet()) { Integer rank = rankAndOption.getKey(); if (rank == Const.POINTS_NOT_SUBMITTED) { continue; } List<String> optionsWithGivenRank = rankAndOption.getValue(); for (String option : optionsWithGivenRank) { htmlBuilder.append("<li>"); htmlBuilder.append(Sanitizer.sanitizeForHtml(rank.toString())); htmlBuilder.append(": "); htmlBuilder.append(option); htmlBuilder.append("</li>"); } } } htmlBuilder.append("</ul>"); return htmlBuilder.toString(); }

Target:
public String getAnswerHtml(FeedbackQuestionDetails questionDetails) { FeedbackRankOptionsQuestionDetails rankQuestion = (FeedbackRankOptionsQuestionDetails) questionDetails; SortedMap<Integer, List<String>> orderedOptions = generateMapOfRanksToOptions(rankQuestion); StringBuilder htmlBuilder = new StringBuilder(); htmlBuilder.append("<ul>"); for (Entry<Integer, List<String>> rankAndOption : orderedOptions.entrySet()) { Integer rank = rankAndOption.getKey(); if (rank == Const.POINTS_NOT_SUBMITTED) { continue; } List<String> optionsWithGivenRank = rankAndOption.getValue(); for (String option : optionsWithGivenRank) { htmlBuilder.append("<li>"); htmlBuilder.append(Sanitizer.sanitizeForHtml(rank.toString())); htmlBuilder.append(": "); htmlBuilder.append(option); htmlBuilder.append("</li>"); } } htmlBuilder.append("</ul>"); return htmlBuilder.toString(); }
Source:
protected void verifyOutput(RoleDTO source, Role dest, boolean childrenGenerated) { if (source != null) { assertNotNull(dest.getId()); assertEquals(source.getName(), dest.getName()); if (childrenGenerated) { for (UserDTO userDto : source.getUsers()) { for (User user : dest.getUsers()) { assertNotNull(user.getUsername()); assertNotNull(userDto.getUsername()); if (user.getId().equals(userDto.getId())) { this.userDTOTranslatorTest.verifyOutput(userDto, user, childrenGenerated); } } } for (PermissionBlueprintDTO pdto : source.getPermissions()) { for (PermissionBlueprint pbp : dest.getPermissions()) { if (pbp.getId().equals(pdto.getId())) { this.permDTOTranslatorTest.verifyOutput(pdto, pbp, childrenGenerated); } } } } else { assertNotNull(dest.getUsers()); assertTrue(dest.getUsers().isEmpty()); assertNotNull(dest.getPermissions()); assertTrue(dest.getPermissions().isEmpty()); } } else { assertNull(dest); } }

Target:
protected void verifyOutput(RoleDTO source, Role dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getId(), dest.getId()); assertEquals(source.getName(), dest.getName()); if (childrenGenerated) { for (UserDTO userDto : source.getUsers()) { for (User user : dest.getUsers()) { assertNotNull(user.getUsername()); assertNotNull(userDto.getUsername()); if (user.getId() != null) { this.userDTOTranslatorTest.verifyOutput(userDto, user, childrenGenerated); } } } for (PermissionBlueprintDTO pdto : source.getPermissions()) { for (PermissionBlueprint pbp : dest.getPermissions()) { if (pbp.getId().equals(pdto.getId())) { this.permDTOTranslatorTest.verifyOutput(pdto, pbp, childrenGenerated); } } } } else { assertNotNull(dest.getUsers()); assertTrue(dest.getUsers().isEmpty()); assertNotNull(dest.getPermissions()); assertTrue(dest.getPermissions().isEmpty()); } } else { assertNull(dest); } }
Source:
public void waitNoGitChangeMarkers() { webDriverWaitFactory .get(DEFAULT_TIMEOUT) .until( (ExpectedCondition<Boolean>) webDriver -> getListGitMarkers() .stream() .allMatch(element -> "".equals(element.getAttribute("class")))); }

Target:
public void waitNoGitChangeMarkers() { webDriverWaitFactory .get() .until( (ExpectedCondition<Boolean>) webDriver -> getListGitMarkers() .stream() .allMatch(element -> "".equals(element.getAttribute("class")))); }
Source:
public void writeTo(Path directory, Charset charset) throws IOException { checkArgument(Files.notExists(directory) || Files.isDirectory(directory), "path %s exists but is not a directory.", directory); Path outputDirectory = directory; if (!packageName.isEmpty()) { for (String packageComponent : packageName.split("\\.")) { outputDirectory = outputDirectory.resolve(packageComponent); } Files.createDirectories(outputDirectory); } Path outputPath = outputDirectory.resolve(typeSpec.name + ".java"); try (Writer writer = Files.newBufferedWriter(outputPath, charset != null ? charset : Charset.defaultCharset())) { writeTo(writer); } }

Target:
public void writeTo(Path directory, Charset charset) throws IOException { checkArgument(Files.notExists(directory) || Files.isDirectory(directory), "path %s exists but is not a directory.", directory); Path outputDirectory = directory; if (!packageName.isEmpty()) { for (String packageComponent : packageName.split("\\.")) { outputDirectory = outputDirectory.resolve(packageComponent); } Files.createDirectories(outputDirectory); } Path outputPath = outputDirectory.resolve(typeSpec.name + ".java"); try (Writer writer = Files.newBufferedWriter(outputPath, charset)) { writeTo(writer); } }
Source:
void heapify(int index) { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) smallestElementIndex = leftNodeIndex; if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) smallestElementIndex = rightNodeIndex; if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); } }

Target:
void heapify(int index) { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { smallestElementIndex = leftNodeIndex; } if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { smallestElementIndex = rightNodeIndex; } if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); } }
Source:
public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromRecipe() throws Exception { Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); provider = new MachineProviderImpl(dockerConnector, dockerConnectorConfiguration, credentialsReader, dockerMachineFactory, dockerInstanceStopDetector, Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), null, workspaceFolderPathProvider, PROJECT_FOLDER_PATH, false, false, Collections.emptySet(), Collections.emptySet(), SNAPSHOT_USE_REGISTRY, MEMORY_SWAP_MULTIPLIER, emptySet()); final boolean isDev = true; CheServiceImpl machine = createService(); machine.setEnvironment(envVarsFromConfig); createInstanceFromRecipe(machine, isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue(asList(argumentCaptor.getValue() .getContainerConfig() .getEnv()) .containsAll(envVarsFromConfig.entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); }

Target:
public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromRecipe() throws Exception { Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); final boolean isDev = true; CheServiceImpl machine = createService(); machine.setEnvironment(envVarsFromConfig); createInstanceFromRecipe(machine, isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue(asList(argumentCaptor.getValue() .getContainerConfig() .getEnv()) .containsAll(envVarsFromConfig.entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); }
Source:
protected void setUp() throws Exception { super.setUp(); RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this.getContext()).build(); realm = Realm.getInstance(realmConfiguration); dynamicRealm = DynamicRealm.getInstance(realmConfiguration); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(Dog.class); } }); }

Target:
protected void setUp() throws Exception { super.setUp(); realmConfiguration = new RealmConfiguration.Builder(this.getContext()).build(); realm = Realm.getInstance(realmConfiguration); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(Dog.class); } }); dynamicRealm = DynamicRealm.getInstance(realmConfiguration); }
Source:
public void addDrugReferenceMap_shouldSetDrugAsTheDrugToWhichAMappingIsBeingAdded() throws Exception { Drug drug1 = new Drug(1); Drug drug2 = new Drug(2); DrugReferenceMap map = new DrugReferenceMap(1); map.setDrug(drug2); drug1.addDrugReferenceMap(map); Assert.assertEquals(true, drug1.equals(drug1.getDrugReferenceMaps().iterator().next())); }

Target:
public void addDrugReferenceMap_shouldSetDrugAsTheDrugToWhichAMappingIsBeingAdded() throws Exception { Drug drug1 = new Drug(); drug1.setUuid(UUID_1); Drug drug2 = new Drug(); drug2.setUuid(UUID_2); DrugReferenceMap map = new DrugReferenceMap(1); map.setDrug(drug2); drug1.addDrugReferenceMap(map); Assert.assertEquals(drug1, drug1.getDrugReferenceMaps().iterator().next().getDrug()); }
Source:
public static ArgumentProperty functionTypeArgumentProperty(Class lambdaInterface) { return new ArgumentProperty(false, Optional.empty(), Optional.of(lambdaInterface)); }

Target:
public static ArgumentProperty functionTypeArgumentProperty(Class lambdaInterface) { return new ArgumentProperty(FUNCTION_TYPE, Optional.empty(), Optional.of(lambdaInterface)); }
Source:
public void setUp() { mHandlerThread.start(); mMessenger = new Messenger(new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_TEST_STARTED: onTestStarted(); break; case MSG_TEST_ENDED_CLEAN: onTestEnded(false); break; default: super.handleMessage(msg); } } }); }

Target:
public void setUp() throws Exception { super.setUp(); mHandlerThread.start(); mMessenger = new Messenger(new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_TEST_STARTED: onTestStarted(); break; case MSG_TEST_ENDED_CLEAN: onTestEnded(false); break; default: super.handleMessage(msg); } } }); }
Source:
private void addDefaultSetOfFunctionsToReduce() { functionsToReduce.add(SqlKind.AVG); functionsToReduce.add(SqlKind.SUM); functionsToReduce.add(SqlKind.STDDEV_POP); functionsToReduce.add(SqlKind.STDDEV_SAMP); functionsToReduce.add(SqlKind.VAR_POP); functionsToReduce.add(SqlKind.VAR_SAMP); functionsToReduce.add(SqlKind.COVAR_POP); functionsToReduce.add(SqlKind.COVAR_SAMP); functionsToReduce.add(SqlKind.REGR_SXX); functionsToReduce.add(SqlKind.REGR_SYY); }

Target:
private void addDefaultSetOfFunctionsToReduce() { functionsToReduce.addAll(SqlKind.AVG_AGG_FUNCTIONS); functionsToReduce.addAll(SqlKind.COVAR_AVG_AGG_FUNCTIONS); functionsToReduce.add(SqlKind.SUM); }