auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void push(RowMap r) throws Exception { String output = r.toJSON(outputConfig); if ( output != null ) { String result = String.format("Table %s, database %s, event type is %s", r.getTable(), r.getDatabase(), r.getRowType()); <START> System.out.println(result); <END> } this.context.setPosition(r); }</code><technical_language>cruft, plz remove</technical_language>

Target:
public void push(RowMap r) throws Exception { String output = r.toJSON(outputConfig); if ( output != null ) System.out.println(output); this.context.setPosition(r); }
Source:
<code>private static void sanitizeList(List<ITimeEvent> sourceList, Consumer<List<ITimeEvent>> listConsumer) { <START> if (sourceList != null) { <END> List<ITimeEvent> events = new ArrayList<>(); for (ITimeEvent event : sourceList) { if (isValidEvent(event)) { events.add(event); } else { events.add(null); } } listConsumer.accept(events); } }</code><technical_language>call setZoomedList(null). else call comsumer null</technical_language>

Target:
private static void sanitizeList(List<ITimeEvent> sourceList, Consumer<List<ITimeEvent>> listConsumer) { if (sourceList != null) { List<ITimeEvent> events = new ArrayList<>(); for (ITimeEvent event : sourceList) { if (isValidEvent(event)) { events.add(event); } } listConsumer.accept(events); } else { listConsumer.accept(null); } }
Source:
<code>void sendInventory() { synchronized (lock) { for (Connection connection : managedConnections) { try { final OutputStream os = connection.writeMessage(); try { os.write(Protocol.PROCESS_INVENTORY); final Collection<ManagedProcess> processCollection = processes.values(); StreamUtils.writeInt(os, processCollection.size()); for (ManagedProcess process : processCollection) { StreamUtils.writeUTFZBytes(os, process.getProcessName()); <START> os.write(process.getAuthKey().getBytes()); <END> StreamUtils.writeBoolean(os, process.isRunning()); StreamUtils.writeBoolean(os, process.isStopping()); } os.close(); } finally { StreamUtils.safeClose(os); } } catch (IOException e) { ProcessLogger.ROOT_LOGGER.failedToWriteMessage("PROCESS_INVENTORY", e); removeManagedConnection(connection); } } } }</code><technical_language>needs US-ASCII charset, some other simple ascii encoding conversion</technical_language>

Target:
void sendInventory() { synchronized (lock) { for (Connection connection : managedConnections) { try { final OutputStream os = connection.writeMessage(); try { os.write(Protocol.PROCESS_INVENTORY); final Collection<ManagedProcess> processCollection = processes.values(); StreamUtils.writeInt(os, processCollection.size()); for (ManagedProcess process : processCollection) { StreamUtils.writeUTFZBytes(os, process.getProcessName()); os.write(process.getAuthKey().getBytes(Charset.forName("US-ASCII"))); StreamUtils.writeBoolean(os, process.isRunning()); StreamUtils.writeBoolean(os, process.isStopping()); } os.close(); } finally { StreamUtils.safeClose(os); } } catch (IOException e) { ProcessLogger.ROOT_LOGGER.failedToWriteMessage("PROCESS_INVENTORY", e); removeManagedConnection(connection); } } } }
Source:
<code>public boolean equals( Value other ) { <START> return false; <END> }</code><technical_language>replace return this == other;</technical_language>

Target:
public boolean equals( Value other ) { return this == other; }
Source:
<code>public AbstractDetailTabListView(DetailModelProvider<M, D> modelProvider) { this.modelProvider = modelProvider; container.add(scrollPanel); <START> Window.addResizeHandler(e -> { <END> Scheduler.get().scheduleDeferred(() -> resizeToFullHeight()); }); }</code><technical_language>Normally, handler registration Presenter's onBind() method, registerHandler(). I dedicated Presenter for this View, kinda OK this, in mind Views singletons, leak memory (due destroying handler). A approach add method like: public HandlerRegistration addWindowResizeHandler() { return Window.addResizeHandler( .. ); } call Presenter's onBind() method</technical_language>

Target:
public AbstractDetailTabListView(DetailModelProvider<M, D> modelProvider) { this.modelProvider = modelProvider; Window.addResizeHandler(e -> { Scheduler.get().scheduleDeferred(() -> resizeToFullHeight()); }); }
Source:
<code>private List<SearchBasedFetcher> getFetchersFromLibraryEntries(List<BibEntry> libraryEntries) { return libraryEntries.parallelStream() <START> .filter(bibEntry -> bibEntry.getType().getName().equals("library")) <END> .map(this::createFetcherFromLibraryEntry) .filter(Objects::nonNull) .collect(Collectors.toList()); }</code><technical_language>I enum constant: work bibEntry.getType().equals(LIBRARY_ENTRY) suggestion .filter(bibEntry -> bibEntry.getType().getName().equals(LIBRARY_ENTRY.getName()))</technical_language>

Target:
private List<SearchBasedFetcher> getFetchersFromLibraryEntries(List<BibEntry> libraryEntries) { return libraryEntries.parallelStream() .filter(bibEntry -> bibEntry.getType().getName().equals(LIBRARY_ENTRY.getName())) .map(this::createFetcherFromLibraryEntry) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code>synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); if (!hasProducerIdAndEpoch(batch.producerId(), batch.producerEpoch())) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the producerId has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); resetIdempotentProducerId(); <START> } else if (exception instanceof UnknownProducerIdException) { <END> resetSequenceNumbers(); } else { removeInFlightBatch(batch); if (adjustSequenceNumbers) { if (!isTransactional()) { bumpEpoch(); } else { adjustSequencesDueToFailedBatch(batch); } } } }</code><technical_language>follow this. check failed, this is handling transactional case, means in abortable fatal error states. If aborting bump epoch, sequence numbers reset receiving InitProducerId response. If bump epoch, sense reset sequence numbers here? for partition raised UNKNOWN_PRODUCER_ID error, rest</technical_language>

Target:
synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); removeInFlightBatch(batch); if (!matchesProducerIdAndEpoch(batch)) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the producerId has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); requestEpochBumpForPartition(batch.topicPartition); } else if (exception instanceof UnknownProducerIdException) { resetSequenceForPartition(batch.topicPartition); } else { if (adjustSequenceNumbers) { if (!isTransactional()) { requestEpochBumpForPartition(batch.topicPartition); } else { adjustSequencesDueToFailedBatch(batch); } } } }
Source:
<code>private void createLink(String prefix, final Artifact art, String action, Artifact thisArt, RelationTypeSide relation) { <START> try { <END> Label label = editor.getToolkit().createLabel(this, prefix + " \"" + getTeamName( thisArt) + "\" " + action + getCompletedCancelledString(art) + " \"" + getTeamName(art) + "\" "); Hyperlink link = editor.getToolkit().createHyperlink(this, String.format("\"%s\" - %s", art.getName().length() < 60 ? art.getName() : art.getName().substring(0, 60), AtsClientService.get().getAtsId(art)), SWT.NONE); if (art.equals(thisArt)) { artAndRelToHyperlink.put(thisArt, relation, link); artAndRelToLabel.put(thisArt, relation, label); } else { artAndRelToHyperlink.put(art, relation, link); artAndRelToLabel.put(art, relation, label); } link.addHyperlinkListener(new IHyperlinkListener() { @Override public void linkEntered(HyperlinkEvent e) { } @Override public void linkExited(HyperlinkEvent e) { } @Override public void linkActivated(HyperlinkEvent e) { if (AtsObjects.isAtsWorkItemOrAction(art)) { AtsEditors.openATSAction(art, AtsOpenOption.OpenOneOrPopupSelect); } else { try { RendererManager.open(art, PresentationType.DEFAULT_OPEN); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } } } }); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } }</code><technical_language>line 86, a teamWf send teamWf a separate parameter in method</technical_language>

Target:
private void createLink(String prefix, final Artifact art, String action, Artifact thisArt, RelationTypeSide relation) { try { Label label = editor.getToolkit().createLabel(this, prefix + " \"" + getObjectName( thisArt) + "\" " + action + getCompletedCancelledString(art) + " \"" + getObjectName(art) + "\" "); Hyperlink link = editor.getToolkit().createHyperlink(this, String.format("\"%s\" - %s", art.getName().length() < 60 ? art.getName() : art.getName().substring(0, 60), AtsClientService.get().getAtsId(art)), SWT.NONE); if (art.equals(thisArt)) { artAndRelToHyperlink.put(thisArt, relation, link); artAndRelToLabel.put(thisArt, relation, label); } else { artAndRelToHyperlink.put(art, relation, link); artAndRelToLabel.put(art, relation, label); } link.addHyperlinkListener(new IHyperlinkListener() { @Override public void linkEntered(HyperlinkEvent e) { } @Override public void linkExited(HyperlinkEvent e) { } @Override public void linkActivated(HyperlinkEvent e) { if (AtsObjects.isAtsWorkItemOrAction(art)) { AtsEditors.openATSAction(art, AtsOpenOption.OpenOneOrPopupSelect); } else { try { RendererManager.open(art, PresentationType.DEFAULT_OPEN); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } } } }); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } }
Source:
<code>public Iterator<Setting> getIterator() { if (lastResolvedEObject == null || leftReferences == null) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } EStructuralFeature feature; if (getDomainModelReference() == null) { feature = getDomainModelEFeature(); } else { feature = getDomainModelReference().getIterator().next().getEStructuralFeature(); } final EStructuralFeature listFeature = feature; if (!EReference.class.isInstance(listFeature)) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } if (!lastResolvedEObject.eClass().getEAllStructuralFeatures().contains(listFeature)) { final List<Setting> settings = Collections.emptyList(); return settings.iterator(); } final int numElems = 1 + resolvedColumns.size(); return new Iterator<EStructuralFeature.Setting>() { int returnedElements = 0; @Override public boolean hasNext() { return numElems > returnedElements; } @Override public Setting next() { <START> Setting result = null; <END> if (returnedElements == 0) { result = ((InternalEObject) lastResolvedEObject).eSetting(listFeature); } else { final Iterator<Setting> iterator = resolvedColumns.get(returnedElements - 1).getIterator(); if (iterator.hasNext()) { result = iterator.next(); } } returnedElements++; return result; } @Override public void remove() { } }; }</code><technical_language>return null? throw exception more elements? I do explicit null init. this is a sign for some hack. ;)</technical_language>

Target:
public Iterator<Setting> getIterator() { if (lastResolvedEObject == null || leftReferences == null) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } EStructuralFeature feature; if (getDomainModelReference() == null) { feature = getDomainModelEFeature(); } else { feature = getDomainModelReference().getIterator().next().getEStructuralFeature(); } final EStructuralFeature listFeature = feature; if (!EReference.class.isInstance(listFeature)) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } if (!lastResolvedEObject.eClass().getEAllStructuralFeatures().contains(listFeature)) { final List<Setting> settings = Collections.emptyList(); return settings.iterator(); } final int numElems = 1 + resolvedColumns.size(); return new Iterator<EStructuralFeature.Setting>() { int returnedElements = 0; @Override public boolean hasNext() { return numElems > returnedElements; } @Override public Setting next() { Setting result = null; if (returnedElements == 0) { result = ((InternalEObject) lastResolvedEObject).eSetting(listFeature); } else { final Iterator<Setting> iterator = resolvedColumns.get(returnedElements - 1).getIterator(); if (iterator.hasNext()) { result = iterator.next(); } else { throw new NoSuchElementException(String.format( "The iterator has %1$s but %2$s already has been returned!", numElems, returnedElements)); } } returnedElements++; return result; } @Override public void remove() { } }; }
Source:
<code>private void read(SelectionKey key, Transmission transmission) throws IOException { long startTimeToReadInMs = time.milliseconds(); try { long bytesRead = transmission.read(); if (bytesRead == -1) { close(key); return; } metrics.selectorBytesReceived.update(bytesRead); metrics.selectorBytesReceivedCount.inc(bytesRead); <START> if (transmission.getNetworkReceive().getReceivedBytes().isReadComplete()) { <END> this.completedReceives.add(transmission.getNetworkReceive()); transmission.clearReceive(); } } finally { long readTime = time.milliseconds() - startTimeToReadInMs; logger.trace("SocketServer time spent on read per key = {}", transmission.getConnectionId(), readTime); } }</code><technical_language>this a leakage of abstraction. is networkReceive accessed Transmission? Also, is completedReceives for</technical_language>

Target:
private void read(SelectionKey key, Transmission transmission) throws IOException { long startTimeToReadInMs = time.milliseconds(); try { boolean readComplete = transmission.read(); if (readComplete) { this.completedReceives.add(transmission.getNetworkReceive()); transmission.clearReceive(); } } finally { long readTime = time.milliseconds() - startTimeToReadInMs; logger.trace("SocketServer time spent on read per key = {}", transmission.getConnectionId(), readTime); } }
Source:
<code><START> private boolean checkReplicationLocations(String[] replicationPaths) { <END> for (String replicationPath : replicationPaths) { if (!Files.exists(Paths.get(replicationPath))) { throw new ReplicationDestinationUnavailableException(String.format("Unable to find replication destination %s", replicationPath)); } } return true; }</code><technical_language>this need a return type, want add "throws ReplicationDestinationUnavailableException" signature method behaves</technical_language>

Target:
private void checkReplicationLocations(String[] replicationPaths) throws ReplicationDestinationUnavailableException { for (String replicationPath : replicationPaths) { if (!Files.exists(Paths.get(replicationPath))) { String errorMsg = String.format("Unable to find replication destination %s", replicationPath); throw new ReplicationDestinationUnavailableException(errorMsg); } } }
Source:
<code>void acceptVisitor(Visitor v) { <START> for (SelectInfo selectInfo : selectInfos) { <END> selectInfo.getExpression().accept(v); } }</code><technical_language>old-school for loops done in places purpose takes some time enhanced for loop is compiled optimal code. index based loop is generally interpretation phase. Please revert style in this class</technical_language>

Target:
void acceptVisitor(Visitor v) { for (int i = 0; i < selectInfos.size(); i++) { final SelectInfo selectInfo = selectInfos.get(i); selectInfo.getExpression().accept(v); } }
Source:
<code>public ConfigPropertiesProcessor(Path outputDir, String fileName) { this.outputDir = outputDir; <START> this.fileName = fileName == null ? "default" : fileName; <END> }</code><technical_language>IMO, "cluster.properties" is this is a cluster config</technical_language>

Target:
public ConfigPropertiesProcessor(Path outputDir, String fileName) { this.outputDir = outputDir; this.fileName = fileName == null ? "cluster" : fileName; }
Source:
<code>public void testCreateContainer() throws Exception { boolean created = false; while (!created) { <START> privateContainer = (CONTAINER_PREFIX + new SecureRandom().nextInt()); <END> try { created = getApi().createContainer(privateContainer, withMetadata(ImmutableMultimap.of("foo", "bar"))); } catch (UndeclaredThrowableException e) { HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); if (htpe.getResponse().getStatusCode() == 409) continue; throw e; } } Set<ContainerProperties> response = getApi().listContainers(includeMetadata()); assert null != response; long containerCount = response.size(); assertTrue(containerCount >= 1); ListBlobsResponse list = getApi().listBlobs(privateContainer); assertEquals(list.getUrl(), URI.create(String.format("<LINK_0>", view.unwrap( AzureBlobApiMetadata.CONTEXT_TOKEN).getIdentity(), privateContainer))); }</code><technical_language>explain this change fixes bug? If I read code correctly, CONTAINER_PREFIX is defined follows: <code> public static final String CONTAINER_PREFIX = (System.getProperty("user.name") + "-blobstore").toLowerCase(); </code> this result in a container name starting upper case letter</technical_language>

Target:
public void testCreateContainer() throws Exception { boolean created = false; while (!created) { privateContainer = CONTAINER_PREFIX + new SecureRandom().nextInt(); try { created = getApi().createContainer(privateContainer, withMetadata(ImmutableMultimap.of("foo", "bar"))); } catch (UndeclaredThrowableException e) { HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); if (htpe.getResponse().getStatusCode() == 409) continue; throw e; } } Set<ContainerProperties> response = getApi().listContainers(includeMetadata()); assert null != response; long containerCount = response.size(); assertTrue(containerCount >= 1); ListBlobsResponse list = getApi().listBlobs(privateContainer); assertEquals(list.getUrl(), URI.create(String.format("<LINK_0>", view.unwrap( AzureBlobApiMetadata.CONTEXT_TOKEN).getIdentity(), privateContainer))); }
Source:
<code>public void test_clientAttribute_overClientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setAttribute(key, value); <START> assertEquals(value, clientConfig.getAttributes().get(key)); <END> assertNull(clientConfig.getAttributes().get(nonExistingKey)); }</code><technical_language>test for number of attributes</technical_language>

Target:
public void test_clientAttribute_overClientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setAttribute(key, value); assertEquals(value, clientConfig.getAttributes().get(key)); assertEquals(1, clientConfig.getAttributes().size()); assertNull(clientConfig.getAttributes().get(nonExistingKey)); }
Source:
<code>public void addStatisticsToMonitor(Statistics stats) { monitor.addListener(this); monitor.addStatistics(stats); StatisticDescriptor[] descriptors = stats.getType().getStatistics(); for (StatisticDescriptor d : descriptors) { String name = d.getName(); Number value = stats.get(d); if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { <START> collections += value.longValue(); <END> } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime += value.longValue(); } } }</code><technical_language>+= a volatile field is thread safe. I recommend changing collections collectionTime AtomicLong instances. incrementAndGet() instead of +=. if multiple threads do currently invoke this method, in future</technical_language>

Target:
public void addStatisticsToMonitor(Statistics stats) { monitor.addListener(this); monitor.addStatistics(stats); StatisticDescriptor[] descriptors = stats.getType().getStatistics(); for (StatisticDescriptor d : descriptors) { String name = d.getName(); Number value = stats.get(d); if (value == null) { continue; } if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { collections.put(stats.getUniqueId(), value); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime.put(stats.getUniqueId(), value); } } }
Source:
<code>public Status read(String table, String endpoint, Set<String> fields, HashMap<String, ByteIterator> result) { int responseCode; try { responseCode = httpGet(urlPrefix + endpoint, result); } catch (Exception e) { responseCode = handleExceptions(e, urlPrefix + endpoint, HttpMethod.GET); } if (logEnabled) { <START> System.out.println(new StringBuilder("GET Request: ").append(urlPrefix).append(endpoint) <END> .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }</code><technical_language>System.out instead of System.err</technical_language>

Target:
public Status read(String table, String endpoint, Set<String> fields, HashMap<String, ByteIterator> result) { int responseCode; try { responseCode = httpGet(urlPrefix + endpoint, result); } catch (Exception e) { responseCode = handleExceptions(e, urlPrefix + endpoint, HttpMethod.GET); } if (logEnabled) { System.err.println(new StringBuilder("GET Request: ").append(urlPrefix).append(endpoint) .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }
Source:
<code>public void testGetCollections() throws Exception { chain = new OperationChain("test-chain"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME + 1); <START> PaginableDocumentModelListImpl collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); <END> assertEquals(1, collectionsList.size()); DocumentModel collection = collectionsList.get(0); assertEquals(COLLECTION_NAME + 1, collection.getName()); assertEquals(COLLECTION_DESCRIPTION, collection.getPropertyValue("dc:description")); chain = new OperationChain("test-chain-2"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME.subSequence(0, 6)); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertEquals(listCollections.size(), collectionsList.size()); chain = new OperationChain("test-chain-3"); chain.add(GetCollectionsOperation.ID).set("searchTerm", "NonExistenting"); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertEquals(0, collectionsList.size()); }</code><technical_language>Why? hurt</technical_language>

Target:
public void testGetCollections() throws Exception { chain = new OperationChain("test-chain"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME + 1); PaginableDocumentModelListImpl collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(1, collectionsList.size()); DocumentModel collection = collectionsList.get(0); assertEquals(COLLECTION_NAME + 1, collection.getName()); assertEquals(COLLECTION_DESCRIPTION, collection.getPropertyValue("dc:description")); chain = new OperationChain("test-chain-2"); chain.add(GetCollectionsOperation.ID) .set("searchTerm", COLLECTION_NAME.substring(0, COLLECTION_NAME.length() - 3)); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(listCollections.size(), collectionsList.size()); chain = new OperationChain("test-chain-3"); chain.add(GetCollectionsOperation.ID).set("searchTerm", "NonExistenting"); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(0, collectionsList.size()); }
Source:
<code>protected IStrategoTerm getFlowSpecTransferFunctions(ILanguageComponent component) { IStrategoTerm transferFunctions = flowSpecTransferFunctionCache.get(component); if (transferFunctions != null) { return transferFunctions; } <START> FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE); <END> try { transferFunctions = termFactory .parseFromString(IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8)); } catch (ParseError | IOException e) { logger.error("Could not read transfer functions file for {}", component); throw new MetaborgRuntimeException("Could not read transfer functions file", e); } flowSpecTransferFunctionCache.put(component, transferFunctions); return transferFunctions; }</code><technical_language>this behave for languages this file</technical_language>

Target:
protected Optional<TFFileInfo> getFlowSpecTransferFunctions(ILanguageComponent component) { TFFileInfo transferFunctions = flowSpecTransferFunctionCache.get(component); if (transferFunctions != null) { return Optional.of(transferFunctions); } FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE); try { IStrategoTerm sTerm = termFactory.parseFromString( IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8)); ITerm term = strategoTerms.fromStratego(sTerm); transferFunctions = TFFileInfo.match().match(term, PersistentUnifier.Immutable.of()).orElseThrow(() -> new ParseException("Parse error on reading the transfer function file")); } catch (ParseError | ParseException | IOException e) { logger.error("Could not read transfer functions file for {}", component); return Optional.empty(); } logger.debug("Caching flowspec transfer functions for language {}", component); flowSpecTransferFunctionCache.put(component, transferFunctions); return Optional.of(transferFunctions); }
Source:
<code>private static FormFillFailure _error(FormValidation.Kind kind, Throwable e, String message) { <START> if (e==null) return _errorWithMarkup(Util.escape(message),kind); <END> return _errorWithMarkup(Util.escape(message)+ " <a href='#' class='showDetails'>" + Messages.FormValidation_Error_Details() + "</a><pre style='display:none'>" + Util.escape(Functions.printThrowable(e)) + "</pre>",kind ); }</code><technical_language>is</technical_language>

Target:
private static FormFillFailure _error(FormValidation.Kind kind, Throwable e, String message) { if (e == null) { return _errorWithMarkup(Util.escape(message), kind); } return _errorWithMarkup(Util.escape(message) + " <a href='#' class='showDetails'>" + Messages.FormValidation_Error_Details() + "</a><pre style='display:none'>" + Util.escape(Functions.printThrowable(e)) + "</pre>", kind ); }
Source:
<code>public SimpleUri addNode(Node node, String suggestedUri) { SimpleUri nodeUri = new SimpleUri("engine:" + suggestedUri); <START> nodes.put(nodeUri, node); <END> return nodeUri; }</code><technical_language>This method needs hardened in case suggestedUri is in map. do simply appending a numerical suffix, i.e. if "myModule:blur0" is present, new node named "myModule:blur1". suggest add a zero end of uri if present already. This is easy strategy, ways handle this issue. if else in mind</technical_language>

Target:
public SimpleUri addNode(Node node, String suggestedUri) { Preconditions.checkNotNull(node, "node cannot be null!"); Preconditions.checkNotNull(suggestedUri, "suggestedUri cannot be null!"); SimpleUri nodeUri = new SimpleUri("engine:" + suggestedUri); if (nodeMap.containsKey(nodeUri)) { int i = 2; while (nodeMap.containsKey(new SimpleUri(nodeUri.toString() + i))) { i++; } nodeUri = new SimpleUri(nodeUri.toString() + i); } node.setUri(nodeUri); nodeMap.put(nodeUri, node); return nodeUri; }
Source:
<code>public void testCreateWithUnsupportedConnectorThrowsWhenNotNull() { List<TableElement> inputColumns = ImmutableList.of( new ColumnDefinition(identifier("a"), "DATE", emptyList(), Optional.empty(), true), new ColumnDefinition(identifier("b"), "VARCHAR", emptyList(), Optional.empty(), false), new ColumnDefinition(identifier("c"), "VARBINARY", emptyList(), Optional.empty(), false)); <START> CreateTable statement = new CreateTable(QualifiedName.of("test_table"), <END> inputColumns, true, ImmutableList.of(), Optional.empty()); getFutureValue(new CreateTableTask().internalExecute(statement, metadata, new AllowAllAccessControl(), testSession, emptyList())); }</code><technical_language>please put argument separate line</technical_language>

Target:
public void testCreateWithUnsupportedConnectorThrowsWhenNotNull() { List<TableElement> inputColumns = ImmutableList.of( new ColumnDefinition(identifier("a"), "DATE", true, emptyList(), Optional.empty()), new ColumnDefinition(identifier("b"), "VARCHAR", false, emptyList(), Optional.empty()), new ColumnDefinition(identifier("c"), "VARBINARY", false, emptyList(), Optional.empty())); CreateTable statement = new CreateTable( QualifiedName.of("test_table"), inputColumns, true, ImmutableList.of(), Optional.empty()); getFutureValue(new CreateTableTask().internalExecute(statement, metadata, new AllowAllAccessControl(), testSession, emptyList())); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Map<String, String> properties = tableSinkConfig.getProperties().getProperties(); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getName()), "Dataset name must be given."); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Field to be used as rowkey must be given."); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { validateInputAndOutputSchemaFields(inputSchema); boolean rowFieldPresent = false; <START> for (Schema.Field field : inputSchema.getFields()) { <END> if (!field.getSchema().getType().isSimpleType()) { throw new IllegalArgumentException( String.format("Field '%s' is not of simple type, All fields for table sink should of simple type", field.getName())); } if (field.getName().equals(tableSinkConfig.getRowField())) { rowFieldPresent = true; } } if (!rowFieldPresent) { throw new IllegalArgumentException( String.format("Row field key : '%s' is not present in the input schema", tableSinkConfig.getRowField())); } } pipelineConfigurer.createDataset(tableSinkConfig.getName(), Table.class.getName(), DatasetProperties.builder() .addAll(properties) .build()); }</code><technical_language>this logic common repeated logic. move common validateFieldsAreSimple method that</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); Map<String, String> properties; if (tableSinkConfig.getProperties() == null) { properties = new HashMap<>(); } else { properties = tableSinkConfig.getProperties().getProperties(); } Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getName()), "Dataset name must be given."); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Field to be used as rowkey must be given."); Schema outputSchema = SchemaValidator.validateOutputSchemaAndInputSchemaIfPresent(tableSinkConfig.getSchemaStr(), tableSinkConfig.getRowField(), pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); pipelineConfigurer.createDataset(tableSinkConfig.getName(), Table.class.getName(), DatasetProperties.builder() .addAll(properties) .build()); }
Source:
<code>public Map<String, Long> materializePositions(final EventType eventType, final Subscription subscription) throws ServiceUnavailableException { final SubscriptionBase.InitialPosition position = subscription.getReadFrom(); if (position == SubscriptionBase.InitialPosition.CURSORS) { final List<SubscriptionCursorWithoutToken> etInitialCursors = subscription.getInitialCursors().stream() .filter(c -> c.getEventType().equals(eventType.getName())) .collect(Collectors.toList()); return getSubscriptionTopicInitPositions(eventType.getTopic(), etInitialCursors); } else { try (final Consumer<String, String> consumer = kafkaFactory.getConsumer()) { final org.apache.kafka.common.TopicPartition[] kafkaTPs = consumer .partitionsFor(eventType.getTopic()) .stream() .map(p -> new org.apache.kafka.common.TopicPartition(eventType.getTopic(), p.partition())) .toArray(org.apache.kafka.common.TopicPartition[]::new); consumer.assign(Arrays.asList(kafkaTPs)); if (position == SubscriptionBase.InitialPosition.BEGIN) { consumer.seekToBeginning(kafkaTPs); } else if (position == SubscriptionBase.InitialPosition.END) { consumer.seekToEnd(kafkaTPs); } else { <START> throw new IllegalArgumentException("Bad offset specification " + position + " for topic " + <END> eventType.getTopic()); } return Stream.of(kafkaTPs).collect(Collectors.toMap( tp -> String.valueOf(tp.partition()), consumer::position)); } catch (final Exception e) { throw new ServiceUnavailableException("Error occurred when fetching partitions offsets", e); } } }</code><technical_language>is reach this line? I thought fail desserialising cursor provided user, is correspondence "string" enum options. Is a protection for future users of this class pass weird values</technical_language>

Target:
public Map<String, Long> materializePositions(final EventType eventType, final Subscription subscription) throws ServiceUnavailableException { final SubscriptionBase.InitialPosition position = subscription.getReadFrom(); if (position == SubscriptionBase.InitialPosition.CURSORS) { final List<SubscriptionCursorWithoutToken> etInitialCursors = subscription.getInitialCursors().stream() .filter(c -> c.getEventType().equals(eventType.getName())) .collect(Collectors.toList()); return getSubscriptionTopicInitPositions(eventType.getTopic(), etInitialCursors); } else { try (final Consumer<String, String> consumer = kafkaFactory.getConsumer()) { final org.apache.kafka.common.TopicPartition[] kafkaTPs = consumer .partitionsFor(eventType.getTopic()) .stream() .map(p -> new org.apache.kafka.common.TopicPartition(eventType.getTopic(), p.partition())) .toArray(org.apache.kafka.common.TopicPartition[]::new); consumer.assign(Arrays.asList(kafkaTPs)); if (position == SubscriptionBase.InitialPosition.BEGIN) { consumer.seekToBeginning(kafkaTPs); } else if (position == SubscriptionBase.InitialPosition.END) { consumer.seekToEnd(kafkaTPs); } return Stream.of(kafkaTPs).collect(Collectors.toMap( tp -> String.valueOf(tp.partition()), consumer::position)); } catch (final Exception e) { throw new ServiceUnavailableException("Error occurred when fetching partitions offsets", e); } } }
Source:
<code>public void info(String message, Object... args) { <START> final String errorMessage = MessageFormatter.arrayFormat(message, args).getMessage(); <END> logger.info("{}", errorMessage); System.out.println(errorMessage); }</code><technical_language>final variables Java compiler automatically infer now</technical_language>

Target:
public void info(String message, Object... args) { String infoMessage = MessageFormatter.arrayFormat(message, args).getMessage(); logger.info("{}", infoMessage); System.out.println(infoMessage); }
Source:
<code>public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("<LINK_0>", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); <START> InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); <END> return dBuilder.parse(inputStream); }</code><technical_language>do close this stream nowhere, I missing something</technical_language>

Target:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("<LINK_0>", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); try (InputStream inputStream = new ByteArrayInputStream(xml.getBytes())) { return dBuilder.parse(inputStream); } }
Source:
<code>public static int signalStrengthForRequestSize(int requestSize) { <START> return requestSize == 0 ? 0 : Math.min(15, (int) Math.floor(Math.log(requestSize) / LOG_2) + 1); <END> }</code><technical_language>I Math mojangs MathHelper utils for log2</technical_language>

Target:
public static int signalStrengthForRequestSize(int requestSize) { if(requestSize <= 0) return 0; else if (requestSize >= 16384) return 15; else return Math.min(15, MathHelper.log2(requestSize) + 1); }
Source:
<code><START> public static Thread[] findThreadsByName(final String threadName, final String threadGroupName) { <END> if (threadName == null) { throw new IllegalArgumentException("The threadName must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The threadGroupName must not be null"); } final ThreadGroup[] threadGroups = findThreadGroupsByName(threadGroupName); if(threadGroups.length == 0) { return EMPTY_THREAD_ARRAY; } final Thread[] threads = findThreadsByName(threadName); if(threads.length == 0) { return EMPTY_THREAD_ARRAY; } final List<Thread> matchedThreads = new ArrayList<Thread>(); for (int i = 0; i < threads.length; i++) { final Thread thread = threads[i]; if(thread != null && ArrayUtils.contains(threadGroups, thread.getThreadGroup())) { matchedThreads.add(thread); } } return matchedThreads.toArray(new Thread[matchedThreads.size()]); }</code><technical_language>check if more efficient this way? i thought iterating thread groups matching name finding threads more efficient find threads in thread groups for "intersection"</technical_language>

Target:
public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) { if (threadName == null) { throw new IllegalArgumentException("The thread name must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The thread group name must not be null"); } final Collection<Thread> result = new ArrayList<Thread>(); for(final ThreadGroup group : selectThreadGroups(new NamePredicate(threadGroupName))) { result.addAll(selectThreads(group, false, new NamePredicate(threadName))); } return Collections.unmodifiableCollection(result); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username) { @Override protected void onSuccess(@NonNull Account account) throws Exception { profileImage = account.getProfileImage(); if (null != imageView) { <START> EventBus.getDefault().post(new ProfilePhotoFetchedEvent(profileImage)); <END> } } }; getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); } EventBus.getDefault().register(this); }</code><technical_language>a potentially do this "AccountDataLoaded" event is fired getAccount updateAccount API calls. listen for that. depending interactor fire it, a completely piece of code listen is wrong level of coupling</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username); getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); } EventBus.getDefault().register(this); }
Source:
<code>public void testCompleteUpdateHandlesFinalizedChunkIfReady() throws Exception { final Chunk chunk = mockChunkAt(0, 0, 0); final ReadyChunkInfo readyChunkInfo = ReadyChunkInfo.createForNewChunk(chunk, new TShortObjectHashMap<>(), Collections.emptyList()); when(chunkFinalizer.completeFinalization()).thenReturn(readyChunkInfo); chunkProvider.completeUpdate(); <START> final InOrder inOrder = inOrder(worldEntity); <END> inOrder.verify(worldEntity).send(any(OnChunkGenerated.class)); inOrder.verify(worldEntity).send(any(OnChunkLoaded.class)); }</code><technical_language>I is confusing a staticly imported method a variable name</technical_language>

Target:
public void testCompleteUpdateHandlesFinalizedChunkIfReady() throws Exception { final Chunk chunk = mockChunkAt(0, 0, 0); final ReadyChunkInfo readyChunkInfo = ReadyChunkInfo.createForNewChunk(chunk, new TShortObjectHashMap<>(), Collections.emptyList()); when(chunkFinalizer.completeFinalization()).thenReturn(readyChunkInfo); chunkProvider.completeUpdate(); final InOrder inOrderVerification = inOrder(worldEntity); inOrderVerification.verify(worldEntity).send(any(OnChunkGenerated.class)); inOrderVerification.verify(worldEntity).send(any(OnChunkLoaded.class)); }
Source:
<code>public void execute(HueFacade hueFacade, String... lightIdentifiers) { for (String id : lightIdentifiers) { HueLightState lightState = new HueLightState(); lightState.setEffectMode(HueLightState.EffectMode.NONE); lightState.setAlertMode(HueLightState.AlertMode.NONE); lightState.setTransitionTime(400); try { hueFacade.updateLightState(id, lightState); } catch (BridgeUnavailableException e) { <START> throw new StateNotLoadedException(e.getMessage()); <END> } } }</code><technical_language>wrap exception instead of copying message</technical_language>

Target:
public void execute(HueFacade hueFacade, String... lightIdentifiers) { for (String id : lightIdentifiers) { HueLightState lightState = new HueLightState(); lightState.setEffectMode(HueLightState.EffectMode.NONE); lightState.setAlertMode(HueLightState.AlertMode.NONE); lightState.setTransitionTime(400); try { hueFacade.updateLightState(id, lightState); } catch (BridgeUnavailableException e) { throw new StateNotLoadedException(e); } } }
Source:
<code>public EntityRef create(String prefabName, Vector3f position) { if (prefabName != null && !prefabName.isEmpty()) { <START> Prefab prefab = entityManager.getPrefabManager().getPrefab(prefabName); <END> return create(prefab, position); } return create(); }</code><technical_language>in line 103 check for prefab null, check is missing</technical_language>

Target:
public EntityRef create(String prefabName, Vector3f position) { return create(prefabName, position, null); }
Source:
<code>public int visit(IASTDeclaration declaration) { ICPPMethod method = getOperatorEq(declaration); if (method != null) { IASTDeclarator declMethod = ((ICPPASTFunctionDefinition) declaration).getDeclarator(); if (!(declMethod instanceof ICPPASTFunctionDeclarator)) return PROCESS_SKIP; IASTPointerOperator[] pointers = declMethod.getPointerOperators(); parameters = ((ICPPASTFunctionDeclarator) declMethod).getParameters(); if (pointers.length != 1 || !(pointers[0] instanceof ICPPASTReferenceOperator)) reportProblem(MISS_REF_ID, declaration); if (!SemanticQueries.isCopyOrMoveAssignmentOperator(method)) return PROCESS_SKIP; decl = declaration; return PROCESS_CONTINUE; } else <START> return PROCESS_SKIP; <END> }</code><technical_language>I SKIP is correct. means top level declarations visited. For example, this work visit "class Foo" operator= class Foo { Foo& operator=(Foo&) { return *this; } };</technical_language>

Target:
public int visit(IASTDeclaration declaration) { ICPPMethod method = getOperatorEq(declaration); if (method != null) { OperatorEqInfo info = opInfo.push(new OperatorEqInfo()); IASTDeclarator declMethod = ((ICPPASTFunctionDefinition) declaration).getDeclarator(); if (!(declMethod instanceof ICPPASTFunctionDeclarator)) return PROCESS_CONTINUE; if (((ICPPASTFunctionDefinition) declaration).isDefaulted() || ((ICPPASTFunctionDefinition) declaration).isDeleted()) return PROCESS_CONTINUE; IASTPointerOperator[] pointers = declMethod.getPointerOperators(); info.parameters = ((ICPPASTFunctionDeclarator) declMethod).getParameters(); if (pointers.length != 1 || !(pointers[0] instanceof ICPPASTReferenceOperator)) reportProblem(MISS_REF_ID, declaration); if (!SemanticQueries.isCopyOrMoveAssignmentOperator(method)) return PROCESS_CONTINUE; info.decl = declMethod; } return PROCESS_CONTINUE; }
Source:
<code>public static void listInfoTypes() throws IOException { String filter = "supported_by=INSPECT"; <START> String languageCode= "en-US"; <END> listInfoTypes(filter, languageCode); }</code><technical_language>fields (filter languageCode) required user set run, inline in sample instead</technical_language>

Target:
public static void listInfoTypes() throws IOException { try (DlpServiceClient dlpClient = DlpServiceClient.create()) { ListInfoTypesRequest listInfoTypesRequest = ListInfoTypesRequest.newBuilder() .setFilter("supported_by=INSPECT") .setLanguageCode("en-US").build(); ListInfoTypesResponse response = dlpClient.listInfoTypes(listInfoTypesRequest); System.out.println("Infotypes found:"); for (InfoTypeDescription infoTypeDescription : response.getInfoTypesList()) { System.out.println("Name : " + infoTypeDescription.getName()); System.out.println("Display name : " + infoTypeDescription.getDisplayName()); } } }
Source:
<code>public ResponseEntity<ApiListResp> utilsAllActionableVariantsGet() { ApiListResp apiListResp = new ApiListResp(); Meta meta = MetaUtils.getOKMeta(); HttpStatus status = HttpStatus.OK; Set<Gene> genes = GeneUtils.getAllGenes(); Map<Gene, Set<ClinicalVariant>> map = new HashMap<>(); for (Gene gene : genes) { map.put(gene, MainUtils.getClinicalVariants(gene)); } Set<ActionableGene> actionableGenes = new HashSet<>(); for (Map.Entry<Gene, Set<ClinicalVariant>> entry : map.entrySet()) { Gene gene = entry.getKey(); for (ClinicalVariant clinicalVariant : entry.getValue()) { actionableGenes.add(new ActionableGene( gene.getHugoSymbol(), clinicalVariant.getVariant().getName(), getCancerType(clinicalVariant.getOncoTreeType()), clinicalVariant.getLevel(), MainUtils.listToString(new ArrayList<>(clinicalVariant.getDrug()), ", "), MainUtils.listToString(new ArrayList<>(clinicalVariant.getDrugPmids()), ", "))); Set<ArticleAbstract> articleAbstracts = clinicalVariant.getDrugAbstracts(); List<String> abstracts = new ArrayList<>(); for (ArticleAbstract articleAbstract : articleAbstracts) { abstracts.add(articleAbstract.getAbstractContent()); } <START> MainUtils.listToString(abstracts, "; "); <END> } } apiListResp.setData(new ArrayList(actionableGenes)); apiListResp.setMeta(meta); return new ResponseEntity<>(apiListResp, status); }</code><technical_language>forget assign this something? returned string for anything</technical_language>

Target:
public ResponseEntity<ApiListResp> utilsAllActionableVariantsGet() { ApiListResp apiListResp = new ApiListResp(); Meta meta = MetaUtils.getOKMeta(); HttpStatus status = HttpStatus.OK; Set<Gene> genes = GeneUtils.getAllGenes(); Map<Gene, Set<ClinicalVariant>> map = new HashMap<>(); for (Gene gene : genes) { map.put(gene, MainUtils.getClinicalVariants(gene)); } Set<ActionableGene> actionableGenes = new HashSet<>(); for (Map.Entry<Gene, Set<ClinicalVariant>> entry : map.entrySet()) { Gene gene = entry.getKey(); for (ClinicalVariant clinicalVariant : entry.getValue()) { Set<ArticleAbstract> articleAbstracts = clinicalVariant.getDrugAbstracts(); List<String> abstracts = new ArrayList<>(); for (ArticleAbstract articleAbstract : articleAbstracts) { abstracts.add(articleAbstract.getAbstractContent()); } actionableGenes.add(new ActionableGene( gene.getHugoSymbol(), clinicalVariant.getVariant().getName(), getCancerType(clinicalVariant.getOncoTreeType()), clinicalVariant.getLevel(), MainUtils.listToString(new ArrayList<>(clinicalVariant.getDrug()), ", "), MainUtils.listToString(new ArrayList<>(clinicalVariant.getDrugPmids()), ", "), MainUtils.listToString(abstracts, "; "))); } } apiListResp.setData(new ArrayList(actionableGenes)); apiListResp.setMeta(meta); return new ResponseEntity<>(apiListResp, status); }