auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response translate(HttpHeaders httpHeaders, E exception) { AtlasDbHttpProtocolVersion protocolVersion = AtlasDbHttpProtocolVersion.inferFromHttpHeaders(httpHeaders); switch (protocolVersion) { case LEGACY_OR_UNKNOWN: return httpProtocolHandler.handleLegacyOrUnknownVersion(exception); case CONJURE_JAVA_RUNTIME: QosException qosException = httpProtocolHandler.handleConjureJavaRuntime(exception); <START> return exceptionMappersProvider.get().findMapping(qosException).toResponse(qosException); <END> default: log.warn("Couldn't determine what to do with protocol version {}. This is a product bug.", SafeArg.of("protocolVersion", protocolVersion)); throw new SafeIllegalStateException("Unrecognized protocol version in HttpProtocolAwareExceptionMapper", SafeArg.of("protocolVersion", protocolVersion)); } }</code><technical_language>nit: fail useful if find QosException mapper</technical_language>

Target:
Response translate(HttpHeaders httpHeaders, E exception) { AtlasDbHttpProtocolVersion protocolVersion = AtlasDbHttpProtocolVersion.inferFromHttpHeaders(httpHeaders); switch (protocolVersion) { case LEGACY_OR_UNKNOWN: return httpProtocolHandler.handleLegacyOrUnknownVersion(exception); case CONJURE_JAVA_RUNTIME: QosException qosException = httpProtocolHandler.handleConjureJavaRuntime(exception); return Optional.ofNullable(exceptionMappersProvider.get()) .map(provider -> provider.findMapping(qosException)) .map(mapper -> mapper.toResponse(qosException)) .orElseThrow(() -> new SafeIllegalStateException("Couldn't find QoS exception mapper." + " This is a product bug.")); default: log.warn("Couldn't determine what to do with protocol version {}. This is a product bug.", SafeArg.of("protocolVersion", protocolVersion)); throw new SafeIllegalStateException("Unrecognized protocol version in HttpProtocolAwareExceptionMapper", SafeArg.of("protocolVersion", protocolVersion)); } }
Source:
<code>public static <D, I> void feedColumnsTo(D destination, EntityRecordWithColumns recordWithColumns, ColumnTypeRegistry<? extends ColumnType<?, ?, D, I>> columnTypeRegistry, Function<String, I> mapColumnIdentifier) { checkNotNull(destination); checkNotNull(recordWithColumns); checkNotNull(columnTypeRegistry); checkArgument(recordWithColumns.hasColumns(), "Passed record has no Entity Columns."); for (Map.Entry<String, Column.MemoizedValue<?>> column : recordWithColumns.getColumnValues() .entrySet()) { final I columnIdentifier = mapColumnIdentifier.apply(column.getKey()); checkNotNull(columnIdentifier); @SuppressWarnings("unchecked") <START> final Column.MemoizedValue<Object> columnValue = <END> (Column.MemoizedValue<Object>) column.getValue(); final Column<?> columnMetadata = columnValue.getSourceColumn(); @SuppressWarnings("unchecked") final ColumnType<Object, Object, D, I> columnType = (ColumnType<Object, Object, D, I>) columnTypeRegistry.get(columnMetadata); checkArgument(columnType != null, String.format("ColumnType for %s could not be found.", columnMetadata.getType() .getCanonicalName())); setValue(columnValue, destination, columnIdentifier, columnType); } }</code><technical_language>static import for MemoizedValue</technical_language>

Target:
public static <D, I> void feedColumnsTo(D destination, EntityRecordWithColumns recordWithColumns, ColumnTypeRegistry<? extends ColumnType<?, ?, D, I>> columnTypeRegistry, Function<String, I> mapColumnIdentifier) { checkNotNull(destination); checkNotNull(recordWithColumns); checkNotNull(columnTypeRegistry); checkArgument(recordWithColumns.hasColumns(), "Passed record has no Entity Columns."); for (Map.Entry<String, MemoizedValue<?>> column : recordWithColumns.getColumnValues() .entrySet()) { final I columnIdentifier = mapColumnIdentifier.apply(column.getKey()); checkNotNull(columnIdentifier); @SuppressWarnings("unchecked") final MemoizedValue<Object> columnValue = (MemoizedValue<Object>) column.getValue(); final Column<?> columnMetadata = columnValue.getSourceColumn(); @SuppressWarnings("unchecked") final ColumnType<Object, Object, D, I> columnType = (ColumnType<Object, Object, D, I>) columnTypeRegistry.get(columnMetadata); checkArgument(columnType != null, String.format("ColumnType for %s could not be found.", columnMetadata.getType() .getCanonicalName())); setValue(columnValue, destination, columnIdentifier, columnType); } }
Source:
<code>public void onDragDrop(TreeDragDropEvent event) { TreeNode dragTreeNode = event.getDragNode(); TreeNode dropTreeNode = event.getDropNode(); Object dragNodeObject = dragTreeNode.getData(); Object dropNodeObject = dropTreeNode.getData(); if (!(dragNodeObject instanceof StructureTreeNode) || !(dropNodeObject instanceof StructureTreeNode)) { Helper.setErrorMessage("Unable to move structure element!"); return; } StructureTreeNode dropNode = (StructureTreeNode) dropNodeObject; StructureTreeNode dragNode = (StructureTreeNode) dragNodeObject; try { if (dragNode.getDataObject() instanceof IncludedStructuralElement && dropNode.getDataObject() instanceof IncludedStructuralElement) { checkLogicalDragDrop(dragNode, dropNode); } else if (dragNode.getDataObject() instanceof MediaUnit && dropNode.getDataObject() instanceof MediaUnit) { checkPhysicalDragDrop(dragNode, dropNode); } else { <START> Helper.setErrorMessage("Unable to move element of type " + dragNode.getLabel() + " to element of type " <END> + dropNode.getLabel()); } } catch (ClassCastException exception) { Helper.setErrorMessage("Unable to move structure element!"); } }</code><technical_language>Missing translation message</technical_language>

Target:
public void onDragDrop(TreeDragDropEvent event) { TreeNode dragTreeNode = event.getDragNode(); TreeNode dropTreeNode = event.getDropNode(); Object dragNodeObject = dragTreeNode.getData(); Object dropNodeObject = dropTreeNode.getData(); if (!(dragNodeObject instanceof StructureTreeNode) || !(dropNodeObject instanceof StructureTreeNode)) { Helper.setErrorMessage(Helper.getTranslation("dataEditor.unableToMoveError")); return; } StructureTreeNode dropNode = (StructureTreeNode) dropNodeObject; StructureTreeNode dragNode = (StructureTreeNode) dragNodeObject; try { if (dragNode.getDataObject() instanceof IncludedStructuralElement && dropNode.getDataObject() instanceof IncludedStructuralElement) { checkLogicalDragDrop(dragNode, dropNode); } else if (dragNode.getDataObject() instanceof MediaUnit && dropNode.getDataObject() instanceof MediaUnit) { checkPhysicalDragDrop(dragNode, dropNode); } else { Helper.setErrorMessage(Helper.getTranslation("dataEditor.dragnDropError", Arrays.asList( dragNode.getLabel(), dropNode.getLabel()))); } } catch (ClassCastException exception) { Helper.setErrorMessage(Helper.getTranslation("dataEditor.unableToMoveError")); } }
Source:
<code>public void iCanUseFulltextOperatorWithElasticsearchPageProvider() { PageProviderService pps = Framework.getService(PageProviderService.class); PageProviderDefinition ppdef = pps.getPageProviderDefinition("default_collection"); <START> HashMap<String, Serializable> props = new HashMap<>(); props.put(ElasticSearchNativePageProvider.CORE_SESSION_PROPERTY, (Serializable) session); <END> PageProvider<?> pp = pps.getPageProvider(ppdef.getName(), ppdef, null, null, null, 0L, props, "testCo", session.getPrincipal().getName()); DocumentModel coll1 = session.createDocumentModel(PATH_SEPARATOR, COLLECTION_NAME + 1, COLLECTION_TYPE); coll1.setPropertyValue(DC_TITLE, coll1.getName()); DocumentModel coll2 = session.createDocumentModel(PATH_SEPARATOR, COLLECTION_NAME + 2, COLLECTION_TYPE); coll2.setPropertyValue(DC_TITLE, coll2.getName()); DocumentModel fufu = session.createDocumentModel(PATH_SEPARATOR, "furtiveCollection" + 3, COLLECTION_TYPE); fufu.setPropertyValue(DC_TITLE, fufu.getName()); session.createDocument(coll1); session.createDocument(coll2); session.createDocument(fufu); txFeature.nextTransaction(); pp.refresh(); List<?> page = pp.getCurrentPage(); assertEquals(2, page.size()); }</code><technical_language>java Map<String, Serializable> props = Map.of(ElasticSearchNativePageProvider.CORE_SESSION_PROPERTY, (Serializable) session);</technical_language>

Target:
public void iCanUseFulltextOperatorWithElasticsearchPageProvider() { DocumentModel coll1 = session.createDocumentModel(ROOT_PATH, COLLECTION_NAME + 1, COLLECTION_TYPE); coll1.setPropertyValue(DUBLINCORE_TITLE_PROPERTY, coll1.getName()); DocumentModel coll2 = session.createDocumentModel(ROOT_PATH, COLLECTION_NAME + 2, COLLECTION_TYPE); coll2.setPropertyValue(DUBLINCORE_TITLE_PROPERTY, coll2.getName()); DocumentModel fufu = session.createDocumentModel(ROOT_PATH, "furtiveCollection", COLLECTION_TYPE); fufu.setPropertyValue(DUBLINCORE_TITLE_PROPERTY, fufu.getName()); session.createDocument(coll1); session.createDocument(coll2); session.createDocument(fufu); txFeature.nextTransaction(); PageProviderDefinition ppdef = pageProviderService.getPageProviderDefinition(COLLECTION_PAGE_PROVIDER); Map<String, Serializable> props = Map.of(ElasticSearchNativePageProvider.CORE_SESSION_PROPERTY, (Serializable) session); @SuppressWarnings("unchecked") PageProvider<DocumentModel> pp = (PageProvider<DocumentModel>) pageProviderService.getPageProvider( ppdef.getName(), ppdef, null, null, null, 0L, props, "testCo", session.getPrincipal().getName()); List<DocumentModel> page = pp.getCurrentPage(); assertEquals(2, page.size()); assertEquals(coll1.getName(), page.get(0).getName()); assertEquals(coll2.getName(), page.get(1).getName()); }
Source:
<code>public static String getLocalFileStorageUrl(String dir, String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (fileName == null) { return null; } <START> if (dir == null || dir.equals("")) { <END> dir = ""; } else { dir = dir + '/'; } return Environment.getExternalStorageDirectory() + "/" + dir + fileName; } else { LogUtils.logD("SD Card not mount!"); } return null; }</code><technical_language>dir == null is enough</technical_language>

Target:
public static String getLocalFileStorageUrl(String dir, String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (fileName == null) { return null; } if (dir == null || dir.isEmpty()) { return Environment.getExternalStorageDirectory() + ('/' + IMAGE_STORAGE_DEFAULT_DIR + '/' + fileName); } else { return Environment.getExternalStorageDirectory() + ('/' + dir + '/' + fileName); } } else { LogUtils.logE("SD Card not mount!"); } return null; }
Source:
<code>public DataProviderLookup buildLookup(Predicate<DataProvider<?,?>> predicate) { <START> Stream<DataProvider> stream = this.dataProviders.keySet().stream() <END> .map(key -> buildDelegateProvider((Key) key, (List) this.dataProviders.get(key).stream().filter(predicate))); return new DataProviderLookup(stream.collect(Collectors.toMap(p -> (Key<?>) p.getKey(), p -> (DataProvider<?, ?>) p))); }</code><technical_language>final</technical_language>

Target:
public DataProviderLookup buildLookup(Predicate<DataProvider<?,?>> predicate) { final Stream<DataProvider> stream = this.dataProviders.keySet().stream() .map(key -> buildDelegateProvider((Key) key, (List) this.dataProviders.get(key).stream().filter(predicate))); final Map<Key<?>, DataProvider<?, ?>> map = stream.collect(Collectors.toMap(p -> (Key<?>) p.getKey(), p -> (DataProvider<?, ?>) p)); return new DataProviderLookup(map); }
Source:
<code><START> private void addArticleTitle(Collection<Map<String, Object>> rootComments) { <END> Set<String> articleDois = Collections.synchronizedSet(new HashSet<>()); rootComments.forEach(rootComment -> modifyCommentTree(rootComment, comment -> { Map<String, Object> article = (Map<String, Object>) comment.get(ARTICLE_KEY); articleDois.add(article.get("doi").toString()); })); Map<String, String> titles = articleDois.parallelStream() .collect(Collectors.toMap(Function.identity(), this::requestArticleTitle)); rootComments.forEach(rootComment -> modifyCommentTree(rootComment, comment -> { Map<String, Object> article = (Map<String, Object>) comment.get(ARTICLE_KEY); String doi = article.get("doi").toString(); String title = Objects.requireNonNull(titles.get(doi)); article.put("title", title); })); }</code><technical_language>this is private instance variables, static too</technical_language>

Target:
private void addArticleTitle(Collection<Map<String, Object>> rootComments) { Set<String> articleDois = ConcurrentHashMap.newKeySet(); rootComments.forEach(rootComment -> modifyCommentTree(rootComment, comment -> { Map<String, Object> article = (Map<String, Object>) comment.get(ARTICLE_KEY); articleDois.add(article.get("doi").toString()); })); Map<String, String> titles = articleDois.parallelStream() .collect(Collectors.toMap(Function.identity(), this::requestArticleTitle)); rootComments.forEach(rootComment -> modifyCommentTree(rootComment, comment -> { Map<String, Object> article = (Map<String, Object>) comment.get(ARTICLE_KEY); String doi = article.get("doi").toString(); String title = Objects.requireNonNull(titles.get(doi)); article.put("title", title); })); }
Source:
<code>public static String headersToString(MuleMessage m) { if (m == null) { return null; } StringBuilder buf = new StringBuilder(); buf.append(SystemUtils.LINE_SEPARATOR).append("Message properties:").append(SystemUtils.LINE_SEPARATOR); for (int i = 0; i < PropertyScope.ALL_SCOPES.length; i++) { PropertyScope scope = PropertyScope.ALL_SCOPES[i]; try { Set<Object> names = new TreeSet<Object>(m.getPropertyNames(scope)); buf.append(" ").append(scope.getScopeName().toUpperCase()).append(" scoped properties:").append(SystemUtils.LINE_SEPARATOR); for (Object name : names) { Object value = m.getProperty(name.toString(), scope); if (value instanceof MuleMessage) { value = "<<<MuleMessage>>>"; } if (name.equals("password") || name.equals("pass")) { value = "****"; } <START> else if (name.toString().contains("authorization") || name.toString().contains("secret")) <END> { value = "****"; } buf.append(" ").append(name).append("=").append(value).append(SystemUtils.LINE_SEPARATOR); } } catch (IllegalArgumentException e) { } } return buf.toString(); }</code><technical_language>do toString in else move if for a approach</technical_language>

Target:
public static String headersToString(MuleMessage m) { if (m == null) { return null; } StringBuilder buf = new StringBuilder(); buf.append(SystemUtils.LINE_SEPARATOR).append("Message properties:").append(SystemUtils.LINE_SEPARATOR); for (int i = 0; i < PropertyScope.ALL_SCOPES.length; i++) { PropertyScope scope = PropertyScope.ALL_SCOPES[i]; try { Set<Object> names = new TreeSet<Object>(m.getPropertyNames(scope)); buf.append(" ").append(scope.getScopeName().toUpperCase()).append(" scoped properties:").append(SystemUtils.LINE_SEPARATOR); for (Object name : names) { Object value = m.getProperty(name.toString(), scope); if (value instanceof MuleMessage) { value = "<<<MuleMessage>>>"; } if (name.equals("password") || name.equals("pass")) { value = "****"; } else { String stringName = name.toString(); if (stringName.contains("authorization") || stringName.contains("secret")) { value = "****"; } } buf.append(" ").append(name).append("=").append(value).append(SystemUtils.LINE_SEPARATOR); } } catch (IllegalArgumentException e) { } } return buf.toString(); }
Source:
<code>public void compareTrackedEventsTo(List<String> expectedEventsList){ executeScript(ClickTrackingScripts.eventsCaptureInstallation); ArrayList<String> trackedEventsArrayList = new ArrayList<String>(); List<String> trackedEventsList; JavascriptExecutor js = (JavascriptExecutor) driver; <START> Object event = js.executeScript("return selenium_popEvent()"); <END> while (!(event==null)) { trackedEventsArrayList.add(event.toString()); event = js.executeScript("return selenium_popEvent()"); } trackedEventsList = trackedEventsArrayList; ClickTrackingSupport support = new ClickTrackingSupport(); support.compareTrackedEventsTo(expectedEventsList, trackedEventsList); }</code><technical_language>"return selenium_popEvent()" this line a lot. consider moving ClickTrackingScrpitsProvider() if is in PageObjects move class protected field, create protected method in WikiBasePageObject: java protected Object getSeleniumEvents() { JavascriptExecutor js = (JavascriptExecutor) driver; return js.executeScript("return selenium_popEvent()"); }</technical_language>

Target:
public void compareTrackedEventsTo(List<String> expectedEventsList){ executeScript(ClickTrackingScriptsProvider.eventsCaptureInstallation); ArrayList<String> trackedEventsArrayList = new ArrayList<String>(); List<String> trackedEventsList; JavascriptExecutor js = (JavascriptExecutor) driver; Object event = js.executeScript("return selenium_popEvent()"); while (!(event==null)) { trackedEventsArrayList.add(event.toString()); event = js.executeScript("return selenium_popEvent()"); } trackedEventsList = trackedEventsArrayList; ClickTrackingSupport support = new ClickTrackingSupport(); support.compareTrackedEventsTo(expectedEventsList, trackedEventsList); }
Source:
<code>private void inUIThread(Runnable r) { if (display == Display.getCurrent()) { r.run(); } else { <START> Display.getDefault().asyncExec(r); <END> } }</code><technical_language>Workbench.getDisplay</technical_language>

Target:
private void inUIThread(Runnable r) { if (display == Display.getCurrent()) { r.run(); } else { PlatformUI.getWorkbench().getDisplay().asyncExec(r); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheServiceImpl)) return false; CheServiceImpl service = (CheServiceImpl)o; return Objects.equals(id, service.id) && Objects.equals(containerName, service.containerName) && Objects.equals(command, service.command) && Objects.equals(entrypoint, service.entrypoint) && Objects.equals(image, service.image) && Objects.equals(dependsOn, service.dependsOn) && Objects.equals(environment, service.environment) && Objects.equals(expose, service.expose) && Objects.equals(ports, service.ports) && Objects.equals(labels, service.labels) && <START> Objects.equals(links, service.links) && <END> Objects.equals(volumes, service.volumes) && Objects.equals(volumesFrom, service.volumesFrom) && Objects.equals(memLimit, service.memLimit) && Objects.equals(build, service.build) && Objects.equals(networks, service.networks); }</code><technical_language>object empty links null links considered equal</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheServiceImpl)) return false; CheServiceImpl service = (CheServiceImpl)o; return Objects.equals(getId(), service.getId()) && Objects.equals(getContainerName(), service.getContainerName()) && Objects.equals(getCommand(), service.getCommand()) && Objects.equals(getEntrypoint(), service.getEntrypoint()) && Objects.equals(getImage(), service.getImage()) && Objects.equals(getDependsOn(), service.getDependsOn()) && Objects.equals(getEnvironment(), service.getEnvironment()) && Objects.equals(getExpose(), service.getExpose()) && Objects.equals(getPorts(), service.getPorts()) && Objects.equals(getLabels(), service.getLabels()) && Objects.equals(getLinks(), service.getLinks()) && Objects.equals(getVolumes(), service.getVolumes()) && Objects.equals(getVolumesFrom(), service.getVolumesFrom()) && Objects.equals(getMemLimit(), service.getMemLimit()) && Objects.equals(getBuild(), service.getBuild()) && Objects.equals(getNetworks(), service.getNetworks()); }
Source:
<code>public static BoxableDto asDto(Boxable from, String position) { BoxableDto dto = new BoxableDto(); <START> dto.setPosition(position); <END> dto.setId(from.getId()); dto.setAlias(from.getAlias()); dto.setBoxAlias(from.getBoxAlias()); dto.setBoxPosition(from.getBoxPosition()); dto.setEmpty(from.isEmpty()); dto.setIdentificationBarcode(from.getIdentificationBarcode()); dto.setName(from.getName()); dto.setVolume(from.getVolume()); return dto; }</code><technical_language>BoxableDto a position attribute; is this doubling setBoxPosition() call below</technical_language>

Target:
public static BoxableDto asDto(Boxable from, String position) { BoxableDto dto = new BoxableDto(); dto.setBoxPosition(position); dto.setId(from.getId()); dto.setAlias(from.getAlias()); dto.setBoxAlias(from.getBoxAlias()); dto.setBoxPosition(from.getBoxPosition()); dto.setEmpty(from.isEmpty()); dto.setIdentificationBarcode(from.getIdentificationBarcode()); dto.setName(from.getName()); dto.setVolume(from.getVolume()); return dto; }
Source:
<code>public LogEntry getLogEntry(int timeout) throws InterruptedException { <START> synchronized (logs) { if (logs.size() == 0) { logs.wait(timeout); } } <END> LogEntry logEntry = logs.size() == 0 ? null : logs.remove(0); if (logEntry == null) { Assert.fail("No log entry logged."); } return logEntry; }</code><technical_language>logged method is notifying waiters "this", waing "logs". If enter if wait full timeout</technical_language>

Target:
public LogEntry getLogEntry(int timeout) throws InterruptedException { LogEntry logEntry; synchronized (this) { if (logs.size() == 0) { this.wait(timeout); } logEntry = logs.size() == 0 ? null : logs.remove(0); if (logEntry == null) { Assert.fail("No log entry logged."); } return logEntry; } }
Source:
<code>public <T> void createConsumer(DestinationType type, String channel, Class<T> objectMessageClass, Consumer<T> listener) { try { <START> if (!consumerSessions.containsKey(channel)) { Session session = createConsumerSession(); consumerSessions.put(channel, session); <END> Destination topic = createDestination(type, channel, session); MessageConsumer messageConsumer = session.createConsumer(topic); messageConsumer.setMessageListener(message -> { if (message instanceof ObjectMessage) { try { Serializable object = ((ObjectMessage) message).getObject(); if (objectMessageClass.isInstance(object)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("JSM: Consumer for channel - and session is accepting ObjectMessage", type, channel, session); } listener.accept((T) object); } } catch (JMSException e) { LOGGER.error("Exception receiving JMS message: " + e.getMessage()); } } }); } } catch (Exception e) { LOGGER.error("Error creating JMS Watch Service: " + e.getMessage()); } }</code><technical_language>contains put is atomic operation, computeIfAbsent</technical_language>

Target:
public <T> void createConsumer(DestinationType type, String channel, Class<T> objectMessageClass, Consumer<T> listener) { consumerSessions.computeIfAbsent(channel, (key) -> { Session newSession = createConsumerSession(); try { Destination topic = createDestination(type, key, newSession); MessageConsumer messageConsumer = newSession.createConsumer(topic); messageConsumer.setMessageListener(message -> { if (message instanceof ObjectMessage) { try { Serializable object = ((ObjectMessage) message).getObject(); if (objectMessageClass.isInstance(object)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("JSM: Consumer for channel - and session is accepting ObjectMessage", type, channel, newSession); } listener.accept((T) object); } } catch (JMSException e) { LOGGER.error("Exception receiving JMS message: " + e.getMessage()); } } }); return newSession; } catch (Exception e) { try { newSession.close(); } catch (Exception ex) { LOGGER.error("Exception on closing JMS session (this could trigger a leak) " + e.getMessage()); } LOGGER.error("Error creating JMS Watch Service: " + e.getMessage()); return null; } }); }
Source:
<code>public <T extends Message> Class<T> toMessageClass() { <START> final TypeUrl typeUrl = this; <END> return KnownTypes.getClass(typeUrl); }</code><technical_language>Strange expression. do need alias reference for this</technical_language>

Target:
public <T extends Message> Class<T> toMessageClass() { return KnownTypes.getClass(this); }
Source:
<code>public BlockSummary replayBlock(Block block) { List<TransactionReceipt> receipts = new ArrayList<>(); List<TransactionExecutionSummary> summaries = new ArrayList<>(); Block parent = worldManager.getBlockchain().getBlockByHash(block.getParentHash()); if (parent == null) { logger.info("Failed to replay block #{}, its ancestor is not presented in the db", block.getNumber()); return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries); } Repository track = ((Repository) worldManager.getRepository()) .getSnapshotTo(parent.getStateRoot()); try { for (Transaction tx : block.getTransactionsList()) { Repository txTrack = track.startTracking(); <START> TransactionExecutorFactory txFactory = commonConfig.transactionExecutorFactory(); <END> org.ethereum.core.TransactionExecutor executor = txFactory.createTransactionExecutor( tx, block.getCoinbase(), txTrack, worldManager.getBlockStore(), programInvokeFactory, block, worldManager.getListener(), 0) .withCommonConfig(commonConfig); executor.init(); executor.execute(); executor.go(); TransactionExecutionSummary summary = executor.finalization(); txTrack.commit(); TransactionReceipt receipt = executor.getReceipt(); receipt.setPostTxState(track.getRoot()); receipts.add(receipt); summaries.add(summary); } } finally { track.rollback(); } return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries); }</code><technical_language>Inject a regular Spring bean</technical_language>

Target:
public BlockSummary replayBlock(Block block) { List<TransactionReceipt> receipts = new ArrayList<>(); List<TransactionExecutionSummary> summaries = new ArrayList<>(); Block parent = worldManager.getBlockchain().getBlockByHash(block.getParentHash()); if (parent == null) { logger.info("Failed to replay block #{}, its ancestor is not presented in the db", block.getNumber()); return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries); } Repository track = ((Repository) worldManager.getRepository()) .getSnapshotTo(parent.getStateRoot()); try { for (Transaction tx : block.getTransactionsList()) { Repository txTrack = track.startTracking(); org.ethereum.core.TransactionExecutor executor = ((org.ethereum.core.Blockchain) getBlockchain()).createTransactionExecutor( tx, block.getCoinbase(), txTrack, block, 0 ); executor.init(); executor.execute(); executor.go(); TransactionExecutionSummary summary = executor.finalization(); txTrack.commit(); TransactionReceipt receipt = executor.getReceipt(); receipt.setPostTxState(track.getRoot()); receipts.add(receipt); summaries.add(summary); } } finally { track.rollback(); } return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries); }
Source:
<code>public String evaluate(String referer) { <START> if (referer == null || referer.equals("-")) return null; <END> referer = referer.replaceFirst("http[s]?://", ""); String project = Webrequest.getProjectFromHost(referer); if (Webrequest.isWikimediaHost(project + ".org")) { return project; } else { return null; } }</code><technical_language>Missing isEmpty check</technical_language>

Target:
public String evaluate(String referer) { if (referer == null || referer.equals("-") || referer.isEmpty()) return null; referer = referer.replaceFirst("http[s]?://", ""); String project = Webrequest.getProjectFromHost(referer); if (Webrequest.isWikimediaHost(project + ".org")) { return project; } else { return null; } }
Source:
<code>public void execute(Runnable command) { if (this.tracer == null) { try { this.tracer = this.beanFactory.getBean(Tracer.class); } catch (NoSuchBeanDefinitionException e) { this.delegate.execute(command); } } if (this.traceKeys == null) { try { <START> this.traceKeys = this.beanFactory.getBean(TraceKeys.class); <END> } catch (NoSuchBeanDefinitionException e) { log.warn("TraceKeys bean not found - will provide a manually created instance"); this.delegate.execute(new LocalComponentTraceRunnable(this.tracer, new TraceKeys(), command)); return; } } this.delegate.execute(new LocalComponentTraceRunnable(this.tracer, this.traceKeys, command)); }</code><technical_language>is default? expect other around, assume normalized keys expect occasional override</technical_language>

Target:
public void execute(Runnable command) { if (this.tracer == null) { try { this.tracer = this.beanFactory.getBean(Tracer.class); } catch (NoSuchBeanDefinitionException e) { this.delegate.execute(command); return; } } this.delegate.execute(new LocalComponentTraceRunnable(this.tracer, traceKeys(), spanNamer(), command)); }
Source:
<code>public static BasisFunctionKnots fromInternalKnots(double[] internalKnots, int degree) { ArgumentChecker.notEmpty(internalKnots, "knots"); ArgumentChecker.notNegative(degree, "degree"); <START> final int nInterKnots = internalKnots.length; <END> ArgumentChecker.isTrue(nInterKnots - degree > 0, "Require at least knots for degree {}, only given {}", degree + 1, degree, nInterKnots); for (int i = 1; i < nInterKnots; i++) { ArgumentChecker.isTrue(internalKnots[i] - internalKnots[i - 1] > 0, "knots are not ascending"); } int nSplines = nInterKnots + degree - 1; final int nTotalKnots = nInterKnots + 2 * degree; double[] knots = new double[nTotalKnots]; final double dxa = internalKnots[1] - internalKnots[0]; final double dxb = internalKnots[nInterKnots - 1] - internalKnots[nInterKnots - 2]; for (int i = 0; i < degree; i++) { knots[i] = (i - degree) * dxa + internalKnots[0]; knots[degree + nInterKnots + i] = internalKnots[nInterKnots - 1] + dxb * (i + 1); } System.arraycopy(internalKnots, 0, knots, degree, nInterKnots); return new BasisFunctionKnots(knots, degree, nSplines); }</code><technical_language>Remove final</technical_language>

Target:
public static BasisFunctionKnots fromInternalKnots(double[] internalKnots, int degree) { ArgumentChecker.notEmpty(internalKnots, "knots"); ArgumentChecker.notNegative(degree, "degree"); int nInterKnots = internalKnots.length; ArgumentChecker.isTrue(nInterKnots - degree > 0, "Require at least knots for degree {}, only given {}", degree + 1, degree, nInterKnots); for (int i = 1; i < nInterKnots; i++) { ArgumentChecker.isTrue(internalKnots[i] - internalKnots[i - 1] > 0, "knots are not ascending"); } int nSplines = nInterKnots + degree - 1; int nTotalKnots = nInterKnots + 2 * degree; double[] knots = new double[nTotalKnots]; double dxa = internalKnots[1] - internalKnots[0]; double dxb = internalKnots[nInterKnots - 1] - internalKnots[nInterKnots - 2]; for (int i = 0; i < degree; i++) { knots[i] = (i - degree) * dxa + internalKnots[0]; knots[degree + nInterKnots + i] = internalKnots[nInterKnots - 1] + dxb * (i + 1); } System.arraycopy(internalKnots, 0, knots, degree, nInterKnots); return new BasisFunctionKnots(knots, degree, nSplines); }
Source:
<code>public String getString(String dataType, BigInteger address, MemoryByte[] data) { String paddedStr = DebugUIPlugin.getDefault().getPreferenceStore().getString(IDebugUIConstants.PREF_PADDED_STR); boolean invalid = false; for (MemoryByte <START> d : <END> data) { if (!d.isReadable()) { invalid = true; break; } } if (invalid) { StringBuilder strBuf = new StringBuilder(); for (int i=0; i<data.length; i++) { strBuf.append(paddedStr); } return strBuf.toString(); } int columnSize = getBytesPerColumn(); int endianess = getDisplayEndianess(); if (endianess == RenderingsUtil.ENDIANESS_UNKNOWN) { endianess = getBytesEndianess(data); } byte[] byteArray = new byte[data.length]; for (int i=0; i<byteArray.length;i ++) { byteArray[i] = data[i].getValue(); } if (RenderingsUtil.ENDIANESS_UNKNOWN == endianess) { StringBuilder strBuf = new StringBuilder(); for (int i=0; i<byteArray.length; i++) { strBuf.append(paddedStr); } return strBuf.toString(); } return convertToString(byteArray, columnSize, endianess); }</code><technical_language>rename memByte</technical_language>

Target:
public String getString(String dataType, BigInteger address, MemoryByte[] data) { String paddedStr = DebugUIPlugin.getDefault().getPreferenceStore().getString(IDebugUIConstants.PREF_PADDED_STR); boolean invalid = false; for (MemoryByte memByte : data) { if (!memByte.isReadable()) { invalid = true; break; } } if (invalid) { StringBuilder strBuf = new StringBuilder(); for (int i=0; i<data.length; i++) { strBuf.append(paddedStr); } return strBuf.toString(); } int columnSize = getBytesPerColumn(); int endianess = getDisplayEndianess(); if (endianess == RenderingsUtil.ENDIANESS_UNKNOWN) { endianess = getBytesEndianess(data); } byte[] byteArray = new byte[data.length]; for (int i=0; i<byteArray.length;i ++) { byteArray[i] = data[i].getValue(); } if (RenderingsUtil.ENDIANESS_UNKNOWN == endianess) { StringBuilder strBuf = new StringBuilder(); for (int i=0; i<byteArray.length; i++) { strBuf.append(paddedStr); } return strBuf.toString(); } return convertToString(byteArray, columnSize, endianess); }
Source:
<code>public String getSuccess(HttpServletRequest request) { <START> java.util.Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); <END> if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } }</code><technical_language>import java.util.Map fully qualify here</technical_language>

Target:
public String getSuccess(HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } }
Source:
<code>private int nextCorrelationId() { <START> if (SaslClientAuthenticator.isReserved(correlation)) correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; <END> return correlation++; }</code><technical_language>if-then-else dont't need increment in line below? split this line include statement in line if</technical_language>

Target:
int nextCorrelationId() { if (SaslClientAuthenticator.isReserved(correlation)) { correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; } return correlation++; }
Source:
<code>public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { <START> childAt.playSoundEffect(SoundEffectConstants.CLICK); <END> return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } childView.playSoundEffect(SoundEffectConstants.CLICK); final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }</code><technical_language>this? :)</technical_language>

Target:
public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }
Source:
<code>private void collectMetrics(final Resource current, ImmutableManagementResourceRegistration managementResourceRegistration, final PathAddress address, Map<PathAddress, Map<String, ModelNode>> collectedMetrics) { if (!isExposingMetrics(address)) { return; } <START> Set<String> attributeNames = managementResourceRegistration.getAttributeNames(address); <END> ModelNode description = null; for (String attributeName : attributeNames) { if (isMetric(managementResourceRegistration, address, attributeName)) { if (description == null) { DescriptionProvider modelDescription = managementResourceRegistration.getModelDescription(address); description = modelDescription.getModelDescription(Locale.getDefault()); } Map<String, ModelNode> metricsForResource = collectedMetrics.get(address); if (metricsForResource == null) { metricsForResource = new HashMap<>(); } metricsForResource.put(attributeName, description.get(ATTRIBUTES, attributeName)); collectedMetrics.put(address, metricsForResource); } } for (String type : current.getChildTypes()) { if (current.hasChildren(type)) { for (Resource.ResourceEntry entry : current.getChildren(type)) { final PathElement pathElement = entry.getPathElement(); final PathAddress childAddress = address.append(pathElement); collectMetrics(entry, managementResourceRegistration, childAddress, collectedMetrics); } } } }</code><technical_language>MRR calls expensive MRR needs account for overrides in call. Map<String, AttributeAccess> managementResourceRegistration.getAttributes() working map is more efficient set of keys getAttributeNames() values (in isMetric(...) in a loop</technical_language>

Target:
private void collectMetrics(final Resource current, ImmutableManagementResourceRegistration managementResourceRegistration, final PathAddress address, Map<PathAddress, Map<String, ModelNode>> collectedMetrics) { if (!isExposingMetrics(address)) { return; } Map<String, AttributeAccess> attributes = managementResourceRegistration.getAttributes(address); ModelNode description = null; for (Map.Entry<String, AttributeAccess> entry : attributes.entrySet()) { String attributeName = entry.getKey(); AttributeAccess attributeAccess = entry.getValue(); if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC && attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME) { if (description == null) { DescriptionProvider modelDescription = managementResourceRegistration.getModelDescription(address); description = modelDescription.getModelDescription(Locale.getDefault()); } Map<String, ModelNode> metricsForResource = collectedMetrics.get(address); if (metricsForResource == null) { metricsForResource = new HashMap<>(); } metricsForResource.put(attributeName, description.get(ATTRIBUTES, attributeName)); collectedMetrics.put(address, metricsForResource); } } for (String type : current.getChildTypes()) { if (current.hasChildren(type)) { for (Resource.ResourceEntry entry : current.getChildren(type)) { final PathElement pathElement = entry.getPathElement(); final PathAddress childAddress = address.append(pathElement); collectMetrics(entry, managementResourceRegistration, childAddress, collectedMetrics); } } } }
Source:
<code>public Quote getSellQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; <START> if(amount.getCurrencyUnit().getCode().equals("BTC")) <END> qtyParam = "qty"; else qtyParam = "native_qty"; URL sellPriceUrl; try { sellPriceUrl = new URL( _baseApiUrl, "prices/sell?" + qtyParam + "=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(sellPriceUrl, "GET", null), Quote.class); }</code><technical_language>Braces</technical_language>

Target:
public Quote getSellQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; if(amount.getCurrencyUnit().getCode().equals("BTC")) { qtyParam = "qty"; } else { qtyParam = "native_qty"; } URL sellPriceUrl; try { sellPriceUrl = new URL( _baseApiUrl, "prices/sell?" + qtyParam + "=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(sellPriceUrl, "GET", null), Quote.class); }
Source:
<code>private CompletableFuture<ICluster> join0() { CompletableFuture<Transport> transportFuture = Transport.bind(config.getTransportConfig()); CompletableFuture<Void> clusterFuture = transportFuture.thenComposeAsync(boundTransport -> { transport = boundTransport; membership = new MembershipProtocol(transport, config.getMembershipConfig()); gossip = new GossipProtocol(transport, membership, config.getGossipConfig()); failureDetector = new FailureDetector(transport, membership, config.getFailureDetectorConfig()); membership.setFailureDetector(failureDetector); membership.setGossipProtocol(gossip); Member localMember = membership.member(); onMemberAdded(localMember); membership.listen() .filter(MembershipEvent::isAdded).map(MembershipEvent::member).subscribe(this::onMemberAdded); membership.listen() .filter(MembershipEvent::isRemoved).map(MembershipEvent::member).subscribe(this::onMemberRemoved); failureDetector.start(); gossip.start(); return membership.start(); }, MoreExecutors.directExecutor()); <START> return clusterFuture.thenApplyAsync(aVoid -> Cluster.this, MoreExecutors.directExecutor()); <END> }</code><technical_language>I thinking if do in a more Java 8 functional style put instead of MoreExecutors.directExecutor() Runnable::run, work</technical_language>

Target:
private CompletableFuture<ICluster> join0() { CompletableFuture<Transport> transportFuture = Transport.bind(config.getTransportConfig()); CompletableFuture<Void> clusterFuture = transportFuture.thenCompose(boundTransport -> { transport = boundTransport; membership = new MembershipProtocol(transport, config.getMembershipConfig()); gossip = new GossipProtocol(transport, membership, config.getGossipConfig()); failureDetector = new FailureDetector(transport, membership, config.getFailureDetectorConfig()); membership.setFailureDetector(failureDetector); membership.setGossipProtocol(gossip); Member localMember = membership.member(); onMemberAdded(localMember); membership.listen() .filter(MembershipEvent::isAdded).map(MembershipEvent::member).subscribe(this::onMemberAdded); membership.listen() .filter(MembershipEvent::isRemoved).map(MembershipEvent::member).subscribe(this::onMemberRemoved); failureDetector.start(); gossip.start(); return membership.start(); }); return clusterFuture.thenApply(aVoid -> Cluster.this); }
Source:
<code>public JavaDStreamLike process(JavaDStreamLike input) { input.foreachRDD(new Function<JavaRDD, Void>() { @Override public Void call(JavaRDD rdd) { rdd.foreachPartition(new VoidFunction<Iterator<?>>() { @Override public void call(Iterator<?> items) throws Exception { <START> final StringBuffer buffer = new StringBuffer(sdf.format(new Date())); <END> while (items.hasNext()) { buffer.append(items.next()); } try { FileWriter fw = new FileWriter(file.getAbsoluteFile()); final BufferedWriter bw = new BufferedWriter(fw); bw.write(buffer.toString()); bw.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }); return null; } }); return null; }</code><technical_language>threading guarantees here, for sake of argument, call sdf.format() is thread safe</technical_language>

Target:
public JavaDStreamLike process(JavaDStreamLike input) { input.foreachRDD(new Function<JavaRDD, Void>() { @Override public Void call(JavaRDD rdd) { rdd.foreachPartition(new VoidFunction<Iterator<?>>() { @Override public void call(Iterator<?> items) throws Exception { try { FileWriter fw = new FileWriter(file.getAbsoluteFile()); final BufferedWriter bw = new BufferedWriter(fw); while (items.hasNext()) { bw.append(items.next() + System.lineSeparator()); } bw.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }); return null; } }); return null; }
Source:
<code>private Supplier<List<GridColumn.HeaderMetaData>> outputClauseHeaderMetaData(final OutputClause oc) { return () -> { final List<GridColumn.HeaderMetaData> metaData = new ArrayList<>(); expression.ifPresent(dtable -> { if (hasName.isPresent()) { if (dtable.getOutput().size() == 1) { metaData.add(new OutputClauseColumnExpressionNameHeaderMetaData(hasExpression, expression, hasName, clearDisplayNameConsumer(true), setDisplayNameConsumer(true), setTypeRefOnHasExpressionAndOutputClauseConsumer(oc), cellEditorControls, headerEditor, Optional.of(translationService.getTranslation(DMNEditorConstants.DecisionTableEditor_EditOutputClause)))); } else { metaData.add(new OutputClauseColumnExpressionNameHeaderMetaData(hasExpression, expression, hasName, clearDisplayNameConsumer(true), setDisplayNameConsumer(true), setTypeRefConsumer(), cellEditorControls, headerEditor, Optional.of(translationService.getTranslation(DMNEditorConstants.DecisionTableEditor_EditOutputClause)))); <START> } <END> } else { metaData.add(new BaseHeaderMetaData(translationService.format(DMNEditorConstants.DecisionTableEditor_OutputClauseHeader))); } if (dtable.getOutput().size() > 1) { metaData.add(new OutputClauseColumnHeaderMetaData(wrapOutputClauseIntoHasName(oc), oc, clearDisplayNameConsumer(false), setDisplayNameConsumer(false), setTypeRefConsumer(), cellEditorControls, headerEditor, Optional.of(translationService.getTranslation(DMNEditorConstants.DecisionTableEditor_EditOutputClause)))); } }); return metaData; }; }</code><technical_language>I DRY a bit a method this: java private BiConsumer<HasTypeRef, QName> setTypeRefConsumer(final OutputClause oc, final DecisionTable dtable) { if (dtable.getOutput().size() == 1) { return setTypeRefOnHasExpressionAndOutputClauseConsumer(oc); } return setTypeRefConsumer(); } ..but feel free is. a method call.. ;-)</technical_language>

Target:
private Supplier<List<GridColumn.HeaderMetaData>> outputClauseHeaderMetaData(final OutputClause oc) { return () -> { final List<GridColumn.HeaderMetaData> metaData = new ArrayList<>(); expression.ifPresent(dtable -> { if (hasName.isPresent()) { metaData.add(new OutputClauseColumnExpressionNameHeaderMetaData(hasExpression, expression, hasName, clearDisplayNameConsumer(true, oc, dtable), setDisplayNameConsumer(true, oc, dtable), setTypeRefConsumer(oc, dtable), cellEditorControls, headerEditor, Optional.of(translationService.getTranslation(DMNEditorConstants.DecisionTableEditor_EditOutputClause)))); } else { metaData.add(new BaseHeaderMetaData(translationService.format(DMNEditorConstants.DecisionTableEditor_OutputClauseHeader))); } if (dtable.getOutput().size() > 1) { metaData.add(new OutputClauseColumnHeaderMetaData(wrapOutputClauseIntoHasName(oc), oc, clearDisplayNameConsumer(false), setDisplayNameConsumer(false), setTypeRefConsumer(), cellEditorControls, headerEditor, Optional.of(translationService.getTranslation(DMNEditorConstants.DecisionTableEditor_EditOutputClause)))); } }); return metaData; }; }
Source:
<code>Schema getOutputSchema(Map<String, Schema> inputSchemas, FailureCollector collector) { validateJoinKeySchemas(inputSchemas, conf.getPerStageJoinKeys(), collector); requiredInputs = conf.getInputs(); perStageSelectedFields = conf.getPerStageSelectedFields(); duplicateFields = ArrayListMultimap.create(); List<Schema.Field> outputFields = getOutputFields(createOutputFieldInfos(inputSchemas, collector)); if (outputFields.isEmpty()) { <START> return Schema.recordOf("join.output"); <END> } else { return Schema.recordOf("join.output", outputFields); } }</code><technical_language>shouldnt this return null</technical_language>

Target:
Schema getOutputSchema(Map<String, Schema> inputSchemas, FailureCollector collector) { validateJoinKeySchemas(inputSchemas, conf.getPerStageJoinKeys(), collector); requiredInputs = conf.getInputs(); perStageSelectedFields = conf.getPerStageSelectedFields(); duplicateFields = ArrayListMultimap.create(); List<Schema.Field> outputFields = getOutputFields(createOutputFieldInfos(inputSchemas, collector)); if (outputFields.isEmpty()) { return null; } else { return Schema.recordOf("join.output", outputFields); } }