auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IssuesSet( List<Issue> issues ) { super( new Comparator<Issue>() { @Override public int compare( final Issue issue, final Issue other ) { int compareToSeverity = issue.getSeverity() .compareTo( other.getSeverity() ); if ( compareToSeverity == 0 ) { final String thisTitle = ExplanationProvider.toTitle( issue ); final String otherTitle = ExplanationProvider.toTitle( other ); int compareToTitle = thisTitle.compareTo( otherTitle ); if ( compareToTitle == 0 ) { return compareRowNumbers( issue.getRowNumbers(), other.getRowNumbers() ); } else { return compareToTitle; } } else { return compareToSeverity; } } private int compareRowNumbers( final Set<Integer> rowNumbers, final Set<Integer> other ) { if ( rowNumbers.equals( other ) ) { return 0; } else { for ( Integer a : rowNumbers ) { for ( Integer b : other ) { if ( a < b ) { return -1; } } } return 1; } } } ); addAll( MERGEABLE_ISSUES.stream() .map( typeToMerge -> mergeIssues( issues, typeToMerge ) ) .filter( Optional::isPresent ).map( Optional::get ).collect( Collectors.toSet() ) ); addAll( issues.stream() <START> .filter( issue -> !MERGEABLE_ISSUES.contains( issue.getCheckType() ) ) <END> .collect( Collectors.toSet() ) ); }</code><technical_language>If invert flow here, in issues.stream().filter(...).filter(...).foreach(add(...)), collection need created - saving CPU cycles creating collection immediately GC'ing it</technical_language>

Target:
public IssuesSet( List<Issue> issues ) { super( new Comparator<Issue>() { @Override public int compare( final Issue issue, final Issue other ) { int compareToSeverity = issue.getSeverity() .compareTo( other.getSeverity() ); if ( compareToSeverity == 0 ) { final String thisTitle = ExplanationProvider.toTitle( issue ); final String otherTitle = ExplanationProvider.toTitle( other ); int compareToTitle = thisTitle.compareTo( otherTitle ); if ( compareToTitle == 0 ) { return compareRowNumbers( issue.getRowNumbers(), other.getRowNumbers() ); } else { return compareToTitle; } } else { return compareToSeverity; } } private int compareRowNumbers( final Set<Integer> rowNumbers, final Set<Integer> other ) { if ( rowNumbers.equals( other ) ) { return 0; } else { for ( Integer a : rowNumbers ) { for ( Integer b : other ) { if ( a < b ) { return -1; } } } return 1; } } } ); addAll( MERGEABLE_ISSUES.stream() .map( typeToMerge -> mergeIssues( issues, typeToMerge ) ) .filter( Optional::isPresent ).map( Optional::get ).collect( Collectors.toSet() ) ); issues.stream() .filter( issue -> !MERGEABLE_ISSUES.contains( issue.getCheckType() ) ) .forEach( issue -> add( issue ) ); }
Source:
<code>public AbstractJdbcPollInputOperator() { <START> this.pollInterval = 10 * 1000; <END> this.fetchSize = 10000; currentWindowRecoveryState = new MutablePair<>(); windowManager = new FSWindowDataManager(); }</code><technical_language>declared private static constants defaults</technical_language>

Target:
public AbstractJdbcPollInputOperator() { currentWindowRecoveryState = new MutablePair<>(); windowManager = new FSWindowDataManager(); }
Source:
<code><START> public void addStream(KStream stream) { <END> streamByUid.put(stream.getUid(), stream); }</code><technical_language>is public</technical_language>

Target:
void addStream(KStream stream) { streamByUid.put(stream.getUid(), stream); }
Source:
<code>public static UserPhotoServiceException notFoundById(UUID id) { <START> return new UserPhotoServiceException("error.user.photo.not.found.id", id); <END> }</code><technical_language>Pass HttpStatus.NOT_FOUND base class, HTTP client a 404</technical_language>

Target:
public static UserPhotoServiceException notFoundById(UUID id) { return new UserPhotoServiceException(HttpStatus.NOT_FOUND, "error.user.photo.not.found.id", id); }
Source:
<code>public void loadNewDataFromSources(File... files) { for (File file : files) { try { logger.info("Loading in " + file.getCanonicalPath()); } catch (IOException e) { <START> e.printStackTrace(); <END> } ISource fileParser = SourceFile.getDataFile(file); addDataSource(fileParser); Set<PlotDataProvider> dataSet = fileParser.parse(); for (PlotDataProvider channel : dataSet) { String station = channel.getStation().getName(); getOrAddStation(station); getOrAddChannel(channel.getChannelName(), channel.getStation(), channel.getNetworkName(), channel.getLocationName()).mergeData(channel); channel.load(); } } channels.sort(Channel.getComparator(TraceView.getConfiguration().getPanelOrder())); for (RawDataProvider channel : channels) { channel.sort(); } }</code><technical_language>This a logger.error()</technical_language>

Target:
public void loadNewDataFromSources(File... files) { for (File file : files) { try { logger.info("Loading in " + file.getCanonicalPath()); } catch (IOException e) { logger.error(e); } ISource fileParser = SourceFile.getDataFile(file); addDataSource(fileParser); Set<PlotDataProvider> dataSet = fileParser.parse(); for (PlotDataProvider channel : dataSet) { String station = channel.getStation().getName(); getOrAddStation(station); getOrAddChannel(channel.getChannelName(), channel.getStation(), channel.getNetworkName(), channel.getLocationName()).mergeData(channel); channel.load(); } } channels.sort(Channel.getComparator(TraceView.getConfiguration().getPanelOrder())); for (RawDataProvider channel : channels) { channel.sort(); } }
Source:
<code>public String toString() { <START> if (this.path != null && !this.path.isEmpty()) { <END> return String.format("S3 configuration (%s:%s in region %s; compressed: %s)", this.bucket, this.path, this.region, this.compressionEnabled ); } else { return String.format("S3 configuration (%s in region %s; compressed: %s)", this.bucket, this.region, this.compressionEnabled ); } }</code><technical_language>Try StringUtils.isTruthy(this.path)? <LINK_0></technical_language>

Target:
public String toString() { if (StringUtils.isTruthy(this.path)) { return String.format("S3 configuration (%s:%s in region %s; compressed: %s)", this.bucket, this.path, this.region, this.compressionEnabled ); } else { return String.format("S3 configuration (%s in region %s; compressed: %s)", this.bucket, this.region, this.compressionEnabled ); } }
Source:
<code>private void run(@Nullable final ExplodedGraph.Node node, @Nullable final Symbol trackSymbol) { Deque<NodeSymbol> workList = new ArrayDeque<>(); workList.add(new NodeSymbol(node, trackSymbol)); while (!workList.isEmpty()) { NodeSymbol nodeSymbol = workList.pop(); ExplodedGraph.Node currentNode = nodeSymbol.node; if (currentNode == null || visited.contains(currentNode)) { continue; } visited.add(currentNode); Symbol newTrackSymbol; if (currentNode.programPoint.syntaxTree() != null) { newTrackSymbol = addFlowFromLearnedSymbols(currentNode, nodeSymbol.trackSymbol); Stream<Constraint> learnedConstraints = addFlowFromLearnedConstraints(currentNode); if (learnedConstraints.anyMatch(terminateTraversal)) { continue; } } else { newTrackSymbol = nodeSymbol.trackSymbol; } <START> currentNode.parents().forEach(parent -> workList.push(new NodeSymbol(parent, newTrackSymbol))); <END> } }</code><technical_language>I this is a cosmetic refactoring part of this commit</technical_language>

Target:
private void run(@Nullable final ExplodedGraph.Node node, @Nullable final Symbol trackSymbol) { Deque<NodeSymbol> workList = new ArrayDeque<>(); workList.add(new NodeSymbol(node, trackSymbol)); while (!workList.isEmpty()) { NodeSymbol nodeSymbol = workList.pop(); ExplodedGraph.Node currentNode = nodeSymbol.node; if (currentNode == null || visited.contains(currentNode)) { continue; } visited.add(currentNode); Symbol newTrackSymbol = nodeSymbol.trackSymbol; if (currentNode.programPoint.syntaxTree() != null) { newTrackSymbol = addFlowFromLearnedSymbols(currentNode, newTrackSymbol); Stream<Constraint> learnedConstraints = addFlowFromLearnedConstraints(currentNode); if (learnedConstraints.anyMatch(terminateTraversal)) { continue; } } for (ExplodedGraph.Node parent : currentNode.parents()) { workList.push(new NodeSymbol(parent, newTrackSymbol)); } } }
Source:
<code>public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) throws ValidationException, TokenNotFoundException { <START> validatePayloadHasFields(payload, EMPTY_LIST, asList(TOKEN_LINK_FIELD, TOKEN_HASH_FIELD)); <END> TokenIdentifier token = Optional.ofNullable(payload.get(TOKEN_HASH_FIELD)) .map(t -> (TokenIdentifier) TokenHash.of(t.asText())) .orElseGet(() -> TokenLink.of(payload.get(TOKEN_LINK_FIELD).asText())); return authDao.revokeSingleToken(accountId, token) .map(revokedDate -> { LOGGER.info("revoked token on date {}", revokedDate); return ok(ImmutableMap.of("revoked", revokedDate)).build(); }) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token with " + token.toString())); }</code><technical_language>Please Collections.emptyList() Collections.EMPTY_LIST generics</technical_language>

Target:
public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) throws ValidationException, TokenNotFoundException { validatePayloadHasFields(payload, Collections.emptyList(), asList(TOKEN_LINK_FIELD, TOKEN_HASH_FIELD)); if (payload.hasNonNull(TOKEN_HASH_FIELD)) { return authDao.revokeSingleToken(accountId, TokenHash.of(payload.get(TOKEN_HASH_FIELD).asText())) .map(this::buildRevokedTokenResponse) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token")); } else { TokenLink tokenLink = TokenLink.of(payload.get(TOKEN_LINK_FIELD).asText()); return authDao.revokeSingleToken(accountId, tokenLink) .map(this::buildRevokedTokenResponse) .orElseThrow(() -> new TokenNotFoundException("Could not revoke token with " + tokenLink)); } }
Source:
<code>public static ExpectedCondition<Boolean> valueToBePresentInElementsAttribute( final By locator, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementsAttributeValue = findElement(locator, from).getAttribute(attribute); return elementsAttributeValue.contains(value); <START> } catch (StaleElementReferenceException | NullPointerException e) { <END> return null; } } @Override public String toString() { return String.format("value ('%s') to be present in element found by %s", value, locator); } }; }</code><technical_language>nice)</technical_language>

Target:
public static ExpectedCondition<Boolean> valueToBePresentInElementsAttribute( final By locator, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementsAttributeValue = findElement(locator, from).getAttribute(attribute); if (elementsAttributeValue == null){ return false; }else { return elementsAttributeValue.contains(value); } } catch (StaleElementReferenceException e) { return false; } } @Override public String toString() { return String.format("value ('%s') to be present in element found by %s", value, locator); } }; }
Source:
<code>public Set<String> deploy() { Stream<Path> list; try { list = Files.list(appsRepository); } catch (IOException e) { throw new FileOperationException("Cannot list UUF apps in '" + appsRepository + "' directory.", e); } <START> list.filter(Files::isDirectory).forEach(appPath -> { <END> Pair<String, String> appNameContextPath = getAppNameContextPath(appPath); pendingToDeployArtifacts.put(appNameContextPath.getRight(), new AppArtifact(appNameContextPath.getLeft(), appPath)); log.debug("UUF app '" + appNameContextPath.getLeft() + "' added to the pending deployments list."); }); return Collections.unmodifiableSet(pendingToDeployArtifacts.keySet()); }</code><technical_language>Code formatting</technical_language>

Target:
public Set<String> deploy() { Stream<Path> contents; try { contents = Files.list(appsRepository); } catch (IOException e) { throw new FileOperationException("Cannot list UUF apps in '" + appsRepository + "' directory.", e); } contents.filter(Files::isDirectory) .forEach(appPath -> { Pair<String, String> appNameContextPath = getAppNameContextPath(appPath); pendingToDeployArtifacts.put(appNameContextPath.getRight(), new AppArtifact(appNameContextPath.getLeft(), appPath)); log.debug("UUF app '{}' added to the pending deployments list.", appNameContextPath.getLeft()); }); return Collections.unmodifiableSet(pendingToDeployArtifacts.keySet()); }
Source:
<code>public void displayFile(FileSystem fs, Path path, OutputStream outStream, int startLine, int endLine) throws IOException { if (logger.isDebugEnabled()) { logger.debug("displaying orc file:" + path.toUri().getPath()); } StringBuilder ret = new StringBuilder(); Reader orcreader = null; RecordReader reader = null; Object row = null; try { int lineNum = 1; orcreader = OrcFile.createReader(fs, path); reader = orcreader.rows(null); long endTime = System.currentTimeMillis() + STOP_TIME; while (reader.hasNext() && lineNum <= endLine && System.currentTimeMillis() <= endTime) { row = reader.next(row); if (lineNum >= startLine) { ret.append(String.format("Record %d:\n", lineNum)); String jsonString = SerDeUtilsWrapper.getJSON(row, orcreader.getObjectInspector()); try { JSONObject jsonobj = new JSONObject(jsonString); ret.append(jsonobj.toString(JSON_INDENT)); } catch (JSONException e) { logger.error("Failed to parse json as JSONObject", e); ret.append(jsonString); } ret.append("\n\n"); } lineNum++; } outStream.write(ret.toString().getBytes()); } catch (IOException e) { <START> outStream.write(("Error in display json file: " + e <END> .getLocalizedMessage()).getBytes("UTF-8")); throw e; } finally { if (reader != null) { reader.close(); } } }</code><technical_language>json file ORC file</technical_language>

Target:
public void displayFile(FileSystem fs, Path path, OutputStream outStream, int startLine, int endLine) throws IOException { if (logger.isDebugEnabled()) { logger.debug("displaying orc file:" + path.toUri().getPath()); } StringBuilder ret = new StringBuilder(); Reader orcreader = null; RecordReader reader = null; Object row = null; try { int lineNum = 1; orcreader = OrcFile.createReader(fs, path); reader = orcreader.rows(null); long endTime = System.currentTimeMillis() + STOP_TIME; while (reader.hasNext() && lineNum <= endLine && System.currentTimeMillis() <= endTime) { row = reader.next(row); if (lineNum >= startLine) { ret.append(String.format("Record %d:\n", lineNum)); String jsonString = SerDeUtilsWrapper.getJSON(row, orcreader.getObjectInspector()); try { JSONObject jsonobj = new JSONObject(jsonString); ret.append(jsonobj.toString(JSON_INDENT)); } catch (JSONException e) { logger.error("Failed to parse json as JSONObject", e); ret.append(jsonString); } ret.append("\n\n"); } lineNum++; } outStream.write(ret.toString().getBytes()); } catch (IOException e) { outStream.write(("Error in display orc file: " + e .getLocalizedMessage()).getBytes("UTF-8")); throw e; } finally { if (reader != null) { reader.close(); } } }
Source:
<code>public OSService[] getServices() { W32ServiceManager sm = new W32ServiceManager(); <START> sm.open(Winsvc.SC_MANAGER_ALL_ACCESS); <END> Winsvc.ENUM_SERVICE_STATUS_PROCESS[] services = sm.enumServicesStatusExProcess(WinNT.SERVICE_WIN32, Winsvc.SERVICE_STATE_ALL, null); OSService[] svcArray = new OSService[services.length]; for (int i = 0; i < services.length; i++) { svcArray[i] = new OSService(); svcArray[i].setName(services[i].lpDisplayName); svcArray[i].setProcessId(services[i].ServiceStatusProcess.dwProcessId); int state = services[i].ServiceStatusProcess.dwCurrentState; switch(state) { case 1: svcArray[i].setState(OSService.State.STOPPED); break; case 4: svcArray[i].setState(OSService.State.RUNNING); break; default: svcArray[i].setState(OSService.State.OTHER); break; } } sm.close(); return svcArray; }</code><technical_language>This fails running administrator. SC_MANAGER_ENUMERATE_SERVICE . I want a try resources block anyway, catch com.sun.jna.platform.win32.Win32Exception here</technical_language>

Target:
public OSService[] getServices() { W32ServiceManager sm = new W32ServiceManager(); try { sm.open(Winsvc.SC_MANAGER_ENUMERATE_SERVICE); Winsvc.ENUM_SERVICE_STATUS_PROCESS[] services = sm.enumServicesStatusExProcess(WinNT.SERVICE_WIN32, Winsvc.SERVICE_STATE_ALL, null); OSService[] svcArray = new OSService[services.length]; for (int i = 0; i < services.length; i++) { State state; switch (services[i].ServiceStatusProcess.dwCurrentState) { case 1: state = STOPPED; break; case 4: state = RUNNING; break; default: state = OTHER; break; } svcArray[i] = new OSService(services[i].lpDisplayName, services[i].ServiceStatusProcess.dwProcessId, state); } sm.close(); return svcArray; } catch (com.sun.jna.platform.win32.Win32Exception ex) { LOG.error("Win32Exception: {}", ex.getMessage()); return new OSService[0]; } }
Source:
<code><START> public LoadRelationsQueryBuilder<R> setProperties( String... properties ) <END> { Collections.addAll( this.properties, properties ); return this; }</code><technical_language>set _replace_ properties; add _add_ properties. Therefore, need method signatures: * setProperties( List<String> ) * setProperties( String... ) * addProperties( List<String> ) * addProperties( String... ) * addProperty( String ) set of methods present for sortBy</technical_language>

Target:
public LoadRelationsQueryBuilder<R> setProperties( String... properties ) { this.properties = new ArrayList<>(); Collections.addAll( this.properties, properties ); return this; }
Source:
<code>public static Set<String> getMetadataGroupIDs(Collection<Datastream> datastreams) { <START> Set<String> groupIds = new HashSet<>(); <END> return datastreams .stream() .filter(Datastream::hasMetadata) .map(ds -> ds.getMetadata().get(DatastreamMetadataConstants.GROUP_ID)) .filter(Objects::nonNull) .collect(Collectors.toSet()); }</code><technical_language>need instantiate this hashset (not used?)</technical_language>

Target:
public static Set<String> getMetadataGroupIDs(Collection<Datastream> datastreams) { return datastreams .stream() .filter(Datastream::hasMetadata) .map(ds -> ds.getMetadata().get(DatastreamMetadataConstants.GROUP_ID)) .filter(Objects::nonNull) .collect(Collectors.toSet()); }
Source:
<code>protected ITmfTrace getTrace() { <START> synchronized (syncObj) { <END> return fTrace; } }</code><technical_language>Unnecessary</technical_language>

Target:
protected ITmfTrace getTrace() { return fTrace; }
Source:
<code>public void gameOver() { <START> addToLog("GAME OVER"); <END> }</code><technical_language>Please, logger format of: [CLASS_NAME]\t[Additional Note if applicable]\t<"Message"> <naming,organisation</technical_language>

Target:
public void gameOver() { currentLevel = gameOver; this.players = currentLevel.getPlayers(); stop(); }
Source:
<code>private void recoverNodeSourcesAndNodes() { Collection<NodeSourceData> nodeSources = dbManager.getNodeSources(); <START> if (nodeSources.isEmpty()) { <END> nodesRecoveryLogger.info("No node source found in database"); } else { if (nodeSources.size() < 10) { nodesRecoveryLogger.info("Node sources found in database: " + Arrays.toString(nodeSources.toArray())); } else { nodesRecoveryLogger.info("Number of node sources found in database: " + nodeSources.size()); } } for (NodeSourceData nodeSourceData : nodeSources) { String nodeSourceDataName = nodeSourceData.getName(); if (NodeSource.DEFAULT_LOCAL_NODES_NODE_SOURCE_NAME.equals(nodeSourceDataName)) { dbManager.removeNodeSource(nodeSourceDataName); } else { try { nodesRecoveryLogger.info("Recovering node source " + nodeSourceDataName); createNodeSource(nodeSourceData, true); } catch (Throwable t) { nodesRecoveryLogger.error(t.getMessage(), t); brokenNodeSources.add(nodeSourceDataName); } } } }</code><technical_language>move this a separate method called longInfo(nodeSources) that</technical_language>

Target:
private void recoverNodeSourcesAndNodes() { Collection<NodeSourceData> nodeSources = dbManager.getNodeSources(); logPersistedNodeSourceInfo(nodeSources); for (NodeSourceData nodeSourceData : nodeSources) { String nodeSourceDataName = nodeSourceData.getName(); if (NodeSource.DEFAULT_LOCAL_NODES_NODE_SOURCE_NAME.equals(nodeSourceDataName)) { dbManager.removeNodeSource(nodeSourceDataName); } else { try { logger.info("Recovering node source " + nodeSourceDataName); createNodeSource(nodeSourceData, true); } catch (Throwable t) { logger.error(t.getMessage(), t); brokenNodeSources.add(nodeSourceDataName); } } } }
Source:
<code>public InMemoryMessageExchangeStore(String tag, NetworkConfig config, TokenGenerator tokenProvider, EndpointIdentityResolver endpointResolver) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } if (endpointResolver == null) { throw new NullPointerException("EndpointContextResolver must not be null"); } this.tokenGenerator = tokenProvider; this.endpointIdentityResolver = endpointResolver; this.config = config; this.tag = StringUtil.normalizeLoggingTag(tag); <START> LOGGER.debug("{}using default TokenProvider {}", tag, RandomTokenGenerator.class.getName()); <END> }</code><technical_language>default token provider is here</technical_language>

Target:
public InMemoryMessageExchangeStore(String tag, NetworkConfig config, TokenGenerator tokenProvider, EndpointIdentityResolver endpointResolver) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } if (endpointResolver == null) { throw new NullPointerException("EndpointContextResolver must not be null"); } this.tokenGenerator = tokenProvider; this.endpointIdentityResolver = endpointResolver; this.config = config; this.tag = StringUtil.normalizeLoggingTag(tag); LOGGER.debug("{}using TokenProvider {}", tag, tokenProvider.getClass().getName()); }
Source:
<code>private void updateTimer(ServicePlayerActivity servicePlayerActivity) { <START> TimePickerDialog dialog = new TimePickerDialog(servicePlayerActivity, (view, hourOfDay, minute) -> player.setTimer(hourOfDay, minute), player.getHourOfDay(), player.getMinutes(), true); <END> dialog.show(); }</code><technical_language>Split this line pieces</technical_language>

Target:
private void updateTimer(ServicePlayerActivity servicePlayerActivity) { TimePickerDialog dialog = new TimePickerDialog(servicePlayerActivity, (view, hourOfDay, minute) -> player.setTimer(hourOfDay, minute, getApplicationContext()), player.getHourOfDay(), player.getMinutes(), true); dialog.show(); }
Source:
<code>private Collection<View> getAllSubViews(IncludedStructuralElement selectedStructure, Collection<View> views) { <START> if (Objects.nonNull(selectedStructure.getViews())) { <END> views.addAll(selectedStructure.getViews()); } for (IncludedStructuralElement child : selectedStructure.getChildren()) { if (Objects.nonNull(child.getChildren())) { getAllSubViews(child, views); } else if (Objects.nonNull(child.getViews())) { views.addAll(child.getViews()); } } return views; }</code><technical_language>if (Objects.nonNull(selectedStructure.getViews())) { views.addAll(selectedStructure.getViews()); } for (IncludedStructuralElement child : selectedStructure.getChildren()) { getAllSubViews(child, views); } enough</technical_language>

Target:
private Collection<View> getAllSubViews(IncludedStructuralElement selectedStructure, Collection<View> views) { if (Objects.nonNull(selectedStructure.getViews())) { views.addAll(selectedStructure.getViews()); } for (IncludedStructuralElement child : selectedStructure.getChildren()) { getAllSubViews(child, views); } return views; }
Source:
<code>private static ErlangProjectBuildOrder getProjectBuildOrder(@NotNull CompileContext context) { try { Module[] modulesToCompile = context.getCompileScope().getAffectedModules(); return new ErlangProjectBuildOrder(getTopologicallySortedFileDescriptors(modulesToCompile)); } catch (CyclicDependencyFoundException e) { String message = "Cyclic erlang module dependency detected. Check files " + e.getFistNodeInCycle() + " and " + e.getLastNodeInCycle() + "or their dependencies(parse_transform, behaviour, include)"; <START> LOG.error(message,e); <END> context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); return null; } }</code><technical_language>This is error. a normal situation for - expect user fix code, try again. log error, this error JetBrains' exception analyzer - want for this exception. Also, fix formatting</technical_language>

Target:
private static ErlangProjectBuildOrder getProjectBuildOrder(@NotNull CompileContext context) { try { Module[] modulesToCompile = context.getCompileScope().getAffectedModules(); return new ErlangProjectBuildOrder(getTopologicallySortedFileDescriptors(modulesToCompile)); } catch (CyclicDependencyFoundException e) { String message = "Cyclic erlang module dependency detected. Check files " + e.getFistFileInCycle() + " and " + e.getLastFileInCycle() + "or their dependencies(parse_transform, behaviour, include)"; LOG.debug(message, e); context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); return null; } }
Source:
<code>public IndexReader select( IndexReader[] instances, IndexQuery... predicates ) { if ( predicates.length > 1 ) { return instances[LUCENE]; } IndexQuery predicate = predicates[0]; <START> if ( predicate instanceof IndexQuery.ExactPredicate ) <END> { IndexQuery.ExactPredicate exactPredicate = (IndexQuery.ExactPredicate) predicate; return select( instances, exactPredicate.value() ); } if ( predicate instanceof IndexQuery.StringPredicate ) { return instances[STRING]; } if ( predicate instanceof IndexQuery.RangePredicate ) { switch ( predicate.valueGroup() ) { case NUMBER: return instances[NUMBER]; case GEOMETRY: return instances[SPATIAL]; case TEXT: return instances[STRING]; case DATE: case LOCAL_DATE_TIME: case ZONED_DATE_TIME: case LOCAL_TIME: case ZONED_TIME: case DURATION: return instances[TEMPORAL]; default: } } if ( predicate instanceof IndexQuery.ExistsPredicate ) { return null; } throw new UnsupportedOperationException( "This selector does not have support for predicate " + predicate ); }</code><technical_language>Chain of instanceof checks is indication of a flaw in OO design. I suggest consider double dispatch smth that</technical_language>

Target:
public IndexReader select( IndexReader[] instances, IndexQuery... predicates ) { if ( predicates.length > 1 ) { return instances[LUCENE]; } IndexQuery predicate = predicates[0]; if ( predicate instanceof ExactPredicate ) { ExactPredicate exactPredicate = (ExactPredicate) predicate; return select( instances, exactPredicate.value() ); } if ( predicate instanceof StringPredicate ) { return instances[STRING]; } if ( predicate instanceof RangePredicate ) { switch ( predicate.valueGroup() ) { case NUMBER: return instances[NUMBER]; case GEOMETRY: return instances[SPATIAL]; case TEXT: return instances[STRING]; case DATE: case LOCAL_DATE_TIME: case ZONED_DATE_TIME: case LOCAL_TIME: case ZONED_TIME: case DURATION: return instances[TEMPORAL]; default: } } if ( predicate instanceof ExistsPredicate ) { return null; } throw new UnsupportedOperationException( "This selector does not have support for predicate " + predicate ); }
Source:
<code>public void saveUnregisteredDisk(UnregisteredDisk disk) { getCallsHandler().executeModification("InsertUnregisteredDisk", <START> getCustomMapSqlParameterSource() .addValue("disk_id", disk.getDiskImage().getId()) .addValue("image_id", disk.getDiskImage().getImageId()) .addValue("disk_alias", disk.getDiskImage().getDiskAlias()) .addValue("disk_description", disk.getDiskImage().getDiskDescription()) .addValue("creation_date", disk.getDiskImage().getCreationDate()) .addValue("last_modified", disk.getDiskImage().getLastModified()) .addValue("volume_type", disk.getDiskImage().getVolumeType()) .addValue("volume_format", disk.getDiskImage().getVolumeFormat()) .addValue("actual_size", disk.getDiskImage().getActualSize()) .addValue("size", disk.getDiskImage().getSize()) .addValue("storage_domain_id", disk.getDiskImage().getStorageIds().get(0))); <END> for (VmBase vmBase : disk.getVms()) { getCallsHandler().executeModification("InsertUnregisteredDisksToVms", getCustomMapSqlParameterSource() .addValue("disk_id", disk.getDiskImage().getId()) .addValue("entity_id", vmBase.getId()) .addValue("entity_name", vmBase.getName()) .addValue("storage_domain_id", disk.getDiskImage().getStorageIds().get(0))); } }</code><technical_language>This united new row mapper added</technical_language>

Target:
public void saveUnregisteredDisk(UnregisteredDisk disk) { getCallsHandler().executeModification("InsertUnregisteredDisk", createFullParametersMapper(disk)); for (VmBase vmBase : disk.getVms()) { getCallsHandler().executeModification("InsertUnregisteredDisksToVms", createIdParameterMapper(disk.getId()) .addValue("entity_id", vmBase.getId()) .addValue("entity_name", vmBase.getName())); } }
Source:
<code>public void shouldCountOnlyCodeAndTimingGivenNoContentType() throws URIException, HttpMalformedHeaderException { HttpMessage msg = new HttpMessage(new URI("<LINK_0>", true)); scanner.scanHttpResponseReceive(msg, -1, new Source("")); verify(listener) .counterInc("<LINK_1>", StatsPassiveScanner.CODE_STATS_PREFIX + "0"); <START> verify(listener).counterInc("<LINK_1>", "stats.responseTime.0"); <END> Mockito.verifyNoMoreInteractions(listener); }</code><technical_language>prefix constant (same for checks)</technical_language>

Target:
public void shouldCountOnlyCodeAndTimingGivenNoContentType() throws URIException, HttpMalformedHeaderException { HttpMessage msg = new HttpMessage(new URI("<LINK_0>", true)); scanner.scanHttpResponseReceive(msg, -1, new Source("")); verify(listener) .counterInc("<LINK_1>", StatsPassiveScanner.CODE_STATS_PREFIX + "0"); verify(listener) .counterInc( "<LINK_1>", StatsPassiveScanner.RESPONSE_TIME_STATS_PREFIX + "0"); Mockito.verifyNoMoreInteractions(listener); }
Source:
<code>public Query build() { <START> Checks.checkNotNull(uri, "Please specify uri"); <END> return new Query( uri, projection, where, whereArgs, sortOrder ); }</code><technical_language>Static import</technical_language>

Target:
public Query build() { checkNotNull(uri, "Please specify uri"); return new Query( uri, projection, where, whereArgs, sortOrder ); }
Source:
<code>public void selectClient(String clientName) { <START> driver.findElement(By.cssSelector("#s2id_clients .select2-choice")).click(); String subContainerClass = "#select2-drop:not([style*='display: none'])"; driver.findElement(By.cssSelector( subContainerClass + " .select2-input")).sendKeys(clientName); driver.findElements(By.cssSelector(subContainerClass + " .select2-results li.select2-result-selectable")).get(0).click(); <END> }</code><technical_language>try similar approach [this](<LINK_0> point is copy-paste code Page Objects put ugly selectors methods</technical_language>

Target:
public void selectClient(String clientName) { clientsInput.select(clientName); }
Source:
<code>public PrivateAddressCoordinator() { mUpstreamPrefixMap = <START> new ArrayMap(); <END> mDownstreamPrefixMap = new ArrayMap(); mTetheringPrefix = new IpPrefix("192.168.0.0/16"); }</code><technical_language>this new ArrayMap<>()</technical_language>

Target:
public PrivateAddressCoordinator() { mUpstreamPrefixMap = new ArrayMap<>(); mDownstreamPrefixMap = new ArrayMap<>(); mTetheringPrefix = new IpPrefix(DEFAULT_TETHERING_PREFIX); }
Source:
<code>private String extractSaltErrorIfAvailable(String errorReason) { <START> String errors = "Error(s): "; <END> if (errorReason.contains(errors)) { return errorReason.substring(errorReason.indexOf(errors) + errors.length()).replaceAll("\n", "; "); } return errorReason; }</code><technical_language>worth extracting a (private) constant</technical_language>

Target:
private String extractSaltErrorIfAvailable(String errorReason) { if (errorReason.contains(ERRORS_STRING)) { return errorReason.substring(errorReason.indexOf(ERRORS_STRING) + ERRORS_STRING.length()).replaceAll("\n", "; "); } return errorReason; }
Source:
<code>public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { if (scopeCleaner.isRunning()) { boolean visitNoScope = Optional <START> .ofNullable(binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Boolean>() { <END> @Override public Boolean visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) { Set<Dependency<?>> bindingDependencies = providerInstanceBinding.getDependencies(); if (bindingDependencies.size() == 1) { Dependency<?> parentDep = bindingDependencies.iterator().next(); if (parentDep.getParameterIndex() == -1) { if (parentDep.getKey().getTypeLiteral() .equals(providerInstanceBinding.getKey().getTypeLiteral())) { return false; } } } return true; } })).orElse(true); return binding.acceptScopingVisitor( new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action, visitNoScope)); } return false; }</code><technical_language>expensive is this operations? Wondering if this moved a cache</technical_language>

Target:
public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { if (scopeCleaner.isRunning()) { boolean visitNoScope = Optional .ofNullable(binding.acceptTargetVisitor(new ProviderInstanceBindingVisitor<>())).orElse(true); return binding.acceptScopingVisitor( new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action, visitNoScope)); } return false; }
Source:
<code>Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> blobIDAndVersionsJson = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (blobIDAndVersionsJson == null || blobIDAndVersionsJson.size() == 0) { logger.info("ZNRecord={} to read on path={} does not have a simple list with key={}", record, ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = blobIDAndVersionsJson.stream() <START> .map(json -> BlobIDAndVersion.fromJson(json)) <END> .max(Comparator.comparing(BlobIDAndVersion::getVersion)) .get(); logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }</code><technical_language>BlobIDAndVersion::fromJson</technical_language>

Target:
Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> blobIDAndVersionsJson = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (blobIDAndVersionsJson == null || blobIDAndVersionsJson.size() == 0) { logger.info("ZNRecord={} to read on path={} does not have a simple list with key={}", record, ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = blobIDAndVersionsJson.stream() .map(BlobIDAndVersion::fromJson) .max(Comparator.comparing(BlobIDAndVersion::getVersion)) .get(); logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }
Source:
<code>public void backfillEvent(EmittedEventEntity event) { try { Optional<ChargeEntity> charge = Optional.empty(); if (ResourceType.valueOf(event.getResourceType().toUpperCase()).equals(ResourceType.PAYMENT)) { charge = Optional.of(chargeService.findChargeByExternalId(event.getResourceExternalId())); } else { <START> Optional<RefundEntity> refundEntity = refundDao.findRefundsByChargeExternalId(event.getResourceExternalId()) <END> .stream() .findFirst(); if (refundEntity.isPresent()) { charge = Optional.ofNullable(chargeService.findChargeByExternalId(refundEntity.get().getChargeExternalId())); } } charge.ifPresent(c -> MDC.put("chargeId", c.getExternalId())); charge.ifPresent(historicalEventEmitter::processPaymentAndRefundEvents); event.setEmittedDate(now(ZoneId.of("UTC"))); } finally { MDC.remove("chargeId"); } }</code><technical_language>1. This get refundEntity based refundExternalId a charge retrieved emit events (payment refunds). EmittedEventEntity stores refundExternalId for refund events 2. In instance (in this PR) assume charge is expunged get DB. need separately for emit refund events / refund availability for expunged charges. (cc @sfount )</technical_language>

Target:
public void backfillEvent(EmittedEventEntity event) { try { Optional<ChargeEntity> charge = Optional.empty(); if (ResourceType.valueOf(event.getResourceType().toUpperCase()).equals(ResourceType.PAYMENT)) { charge = Optional.of(chargeService.findChargeByExternalId(event.getResourceExternalId())); } else { Optional<RefundEntity> refundEntity = refundDao.findByExternalId(event.getResourceExternalId()) .stream() .findFirst(); if (refundEntity.isPresent()) { charge = Optional.ofNullable(chargeService.findChargeByExternalId(refundEntity.get().getChargeExternalId())); } } charge.ifPresent(c -> MDC.put("chargeId", c.getExternalId())); charge.ifPresent(historicalEventEmitter::processPaymentAndRefundEvents); event.setEmittedDate(now(ZoneId.of("UTC"))); } finally { MDC.remove("chargeId"); } }
Source:
<code>protected TupleBatch fetchNextReady() throws DbException { Operator child = getChild(); if (done) { return null; } else { TupleBatch tb = child.nextReady(); TupleBatch result = null; if (tb != null) { if (tb.numTuples() <= toEmit) { toEmit -= tb.numTuples(); result = tb; <START> } else if (toEmit > 0) { <END> result = tb.prefix(Ints.checkedCast(toEmit)); toEmit = 0; child.close(); done = true; } } return result; } }</code><technical_language>This logic is broken if toEmit == 0 (implying tb.numTuples() == toEmit previous call). In case, return null this subsequent calls child is exhausted, previous Limit implementation. need close child if toEmit == 0 return null. Also, please write a unit test fails this condition current implementation (just a TupleSource tuples limit)</technical_language>

Target:
protected TupleBatch fetchNextReady() throws DbException { Operator child = getChild(); if (child.isOpen()) { TupleBatch tb = child.nextReady(); TupleBatch result = null; if (tb != null) { if (tb.numTuples() <= toEmit) { toEmit -= tb.numTuples(); result = tb; } else if (toEmit > 0) { result = tb.prefix(Ints.checkedCast(toEmit)); toEmit = 0; } if (toEmit == 0) { child.close(); } } return result; } return null; }
Source:
<code>public ValgrindStackFrame(IValgrindMessage message, String text, <START> ILaunch launch, String <END> file, int line) { super(message, text, launch); this.file = file; this.line = line; }</code><technical_language>odd deprecating #getLaunch() AbstractValgrindMessage created a launch. consider adding contructors launch ISourceLocator instead, deprecating constructors</technical_language>

Target:
public ValgrindStackFrame(IValgrindMessage message, String text, ILaunch launch, String file, int line) { super(message, text, launch); this.file = file; this.line = line; this.locator = ValgrindCoreParser.copyLaunchSourceLocator(launch); }
Source:
<code>public void postReconnect() throws JCSMPException { <START> logger.info("++++++++++++++Solace client now Reconnected -- possibe Solace HA or DR fail-over +++++++++++++"); <END> TCPDisconnected = false; }</code><technical_language>leading trailing "++++" in message is standard format in other log messages in malhar. standardize log messages</technical_language>

Target:
public void postReconnect() throws JCSMPException { logger.info("Solace client now Reconnected -- possibe Solace HA or DR fail-over"); tcpDisconnected = false; }
Source:
<code>default String getStatus() { if (this.getCancelRequested()) { return "KILLED"; } if (this.getSuccess()) { return "SUCCESS"; } <START> if (!this.getSuccess() && this.getDone()) { <END> return "ERROR"; } return "RUNNING"; }</code><technical_language>!this.getSuccess() needed</technical_language>

Target:
default String getStatus() { if (this.getSuccess()) { return "success"; } if (this.getDone()) { if (this.getCancelRequested()) { return "killed"; } else { return "error"; } } return "running"; }
Source:
<code>public Channel retrieve(VeluxBridgeProvider bridge) { logger.trace("retrieve() called."); if (this.channel == null) { this.channel = new Channel(); } BCgetFirmware.Response response = bridge.bridgeCommunicate(new BCgetFirmware()); if (response != null) { logger.trace("retrieve() found successfully firmware {}.", response.getFirmwareVersion()); this.channel.firmwareVersion = response.getFirmwareVersion(); this.channel.isRetrieved = true; return channel; <START> } else { <END> logger.trace("retrieve() finished with failure."); return null; } }</code><technical_language>"else" is redundant here. Consider dropping it</technical_language>

Target:
public Channel retrieve(VeluxBridgeProvider bridge) { logger.trace("retrieve() called."); if (this.channel == null) { this.channel = new Channel(); } BCgetFirmware.Response response = bridge.bridgeCommunicate(new BCgetFirmware()); if (response != null) { logger.trace("retrieve() found successfully firmware {}.", response.getFirmwareVersion()); this.channel.firmwareVersion = response.getFirmwareVersion(); this.channel.isRetrieved = true; return channel; } logger.trace("retrieve() finished with failure."); return null; }
Source:
<code>public boolean validate(Library library) { if (library.getSample().getSampleAdditionalInfo() == null) return true; if (sampleClass != null && library.getSample().getSampleAdditionalInfo().getSampleClass().getSampleClassId() != sampleClass.getSampleClassId()) return false; <START> if (platformName != null && !library.getPlatformName().equals(platformName)) return false; <END> if (paired != null && library.getPaired().booleanValue() != paired.booleanValue()) return false; if (librarySelectionType != null && library.getLibrarySelectionType().getLibrarySelectionTypeId() != librarySelectionType) return false; if (libraryStrategyType != null && library.getLibraryStrategyType().getLibraryStrategyTypeId() != libraryStrategyType) return false; return true; }</code><technical_language>This line be: if (platformName != null && !library.getPlatformName().equals(platformName**.getKey()**)) return false;</technical_language>

Target:
public boolean validate(Library library) { if (library.getSample().getSampleAdditionalInfo() == null) return true; if (sampleClass != null && library.getSample().getSampleAdditionalInfo().getSampleClass().getSampleClassId() != sampleClass.getSampleClassId()) return false; if (platformName != null && !library.getPlatformName().equals(platformName.getKey())) return false; if (paired != null && library.getPaired().booleanValue() != paired.booleanValue()) return false; if (librarySelectionType != null && library.getLibrarySelectionType().getLibrarySelectionTypeId() != librarySelectionType) return false; if (libraryStrategyType != null && library.getLibraryStrategyType().getLibraryStrategyTypeId() != libraryStrategyType) return false; return true; }
Source:
<code>public void accept(final Socket socket) throws IOException { final InputStream input = socket.getInputStream(); <START> final BufferedOutputStream output = new BufferedOutputStream( <END> socket.getOutputStream() ); try { while (true) { this.print( BkBasic.addSocketHeaders( new RqLive(input), socket ), output ); if (input.available() <= 0) { break; } } } finally { output.flush(); output.close(); input.close(); } }</code><technical_language>@sebing try-with-resources feature Java 7. include input output</technical_language>

Target:
public void accept(final Socket socket) throws IOException { try ( final InputStream input = socket.getInputStream(); final BufferedOutputStream output = new BufferedOutputStream( socket.getOutputStream() ) ) { while (true) { this.print( BkBasic.addSocketHeaders( new RqLive(input), socket ), output ); if (input.available() <= 0) { break; } } } }
Source:
<code>public static Logger getRuleAttemptsTracer() { return LoggerFactory.getLogger( <START> "org.apache.calcite.plan.AbstractRelOptPlanner.RuleAttemptsListener"); <END> }</code><technical_language>RuleAttemptsListener.class.getName()</technical_language>

Target:
public static Logger getRuleAttemptsTracer() { return LoggerFactory.getLogger( AbstractRelOptPlanner.class.getName() + ".rule_execution_summary" ); }
Source:
<code><START> public void setEntries(List<? extends String> packages, String key) { <END> List<String> oldPackages = getEntries(key, listConverter); doSetObject(key, oldPackages, packages, stringListFormatter); }</code><technical_language>new methods added private instead of public. is a real reason for new methods API, lets API</technical_language>

Target:
private void setEntries(List<? extends String> packages, String key) { List<String> oldPackages = getEntries(key, listConverter); doSetObject(key, oldPackages, packages, stringListFormatter); }
Source:
<code>protected void loadLeadSection(final int startSequenceNum) { getApiService().pageLead(model.getTitle().getPrefixedText(), null, calculateLeadImageWidth(), !app.isImageDownloadEnabled(), new PageLead.Callback() { @Override public void success(PageLead pageLead, Response response) { Log.v(TAG, response.getUrl()); <START> Log.v(TAG, "Response ETag: " + getHeader(response, "ETag")); <END> onLeadSectionLoaded(pageLead, startSequenceNum); } @Override public void failure(RetrofitError error) { Log.e(TAG, "PageLead error: " + error); commonSectionFetchOnCatch(error, startSequenceNum); } }); }</code><technical_language>logged in PageService</technical_language>

Target:
protected void loadLeadSection(final int startSequenceNum) { PageLoadUtil.getApiService(model.getTitle().getSite()).pageLead( model.getTitle().getPrefixedText(), null, PageLoadUtil.calculateLeadImageWidth(), !app.isImageDownloadEnabled(), new PageLead.Callback() { @Override public void success(PageLead pageLead, Response response) { Log.v(TAG, response.getUrl()); onLeadSectionLoaded(pageLead, startSequenceNum); } @Override public void failure(RetrofitError error) { Log.e(TAG, "PageLead error: " + error); commonSectionFetchOnCatch(error, startSequenceNum); } }); }
Source:
<code>public List<UpdateSummaryData> broadcastUpdateItems(Collection<String> ids, Collection<DispoItem> items, DispoSet set) { <START> List<UpdateSummaryData> summaryData = null; <END> for (DispoListenerApi listener : listeners) { summaryData = listener.onUpdateItemStats(ids, items, set); } return summaryData; }</code><technical_language>a suggestion, want initialize this new ArrayList<>(); This avoid a NPE upstream</technical_language>

Target:
public List<UpdateSummaryData> broadcastUpdateItems(Collection<String> ids, Collection<DispoItem> items, DispoSet set) { List<UpdateSummaryData> summaryData = new ArrayList<>(); for (DispoListenerApi listener : listeners) { summaryData = listener.onUpdateItemStats(ids, items, set); } return summaryData; }
Source:
<code>private List<ColumnDescriptor> getAllColumnDescriptorByType( int depth, Type type, List<ColumnDescriptor> columns) { List<ColumnDescriptor> res = new ArrayList<>(); for (ColumnDescriptor descriptor : columns) { <START> if (type.getName().equals(descriptor.getPath()[depth])) { <END> res.add(descriptor); } } return res; }</code><technical_language>if path length is smaller depth? this crash</technical_language>

Target:
private List<ColumnDescriptor> getAllColumnDescriptorByType( int depth, Type type, List<ColumnDescriptor> columns) throws ParquetRuntimeException { List<ColumnDescriptor> res = new ArrayList<>(); for (ColumnDescriptor descriptor : columns) { if (depth >= descriptor.getPath().length) { throw new InvalidSchemaException("Corrupted Parquet schema"); } if (type.getName().equals(descriptor.getPath()[depth])) { res.add(descriptor); } } return res; }
Source:
<code>public void shutdown(ServiceLocator serviceLocator) { <START> deregisterGlobalShutdownHook(); <END> runShutdownHooks(serviceLocator); }</code><technical_language>is necessary</technical_language>

Target:
public void shutdown(ServiceLocator serviceLocator) { runShutdownHooks(serviceLocator); }