auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Object createDependency(Class<?> clazz) { <START> if (clazz == TaskExecutor.class) { <END> return Globals.TASK_EXECUTOR; } else if (clazz == PreferencesService.class) { return Globals.prefs; } else if (clazz == KeyBindingRepository.class) { return Globals.getKeyPrefs(); } else if (clazz == JournalAbbreviationLoader.class) { return Globals.journalAbbreviationLoader; } else if (clazz == StateManager.class) { return Globals.stateManager; } else if (clazz == FileUpdateMonitor.class) { return Globals.getFileUpdateMonitor(); } else if (clazz == ProtectedTermsLoader.class) { return Globals.protectedTermsLoader; } else if (clazz == ClipBoardManager.class) { return Globals.clipboardManager; } else if (clazz == UndoManager.class) { return Globals.undoManager; } else { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Cannot instantiate dependency: " + clazz, ex); return null; } } }</code><technical_language>Please remove injection. Instead of a new FXDialogService return JabRefGUI.getMainFrame().getDialogService()</technical_language>

Target:
private static Object createDependency(Class<?> clazz) { if (clazz == DialogService.class) { return JabRefGUI.getMainFrame().getDialogService(); } else if (clazz == TaskExecutor.class) { return Globals.TASK_EXECUTOR; } else if (clazz == PreferencesService.class) { return Globals.prefs; } else if (clazz == KeyBindingRepository.class) { return Globals.getKeyPrefs(); } else if (clazz == JournalAbbreviationLoader.class) { return Globals.journalAbbreviationLoader; } else if (clazz == StateManager.class) { return Globals.stateManager; } else if (clazz == FileUpdateMonitor.class) { return Globals.getFileUpdateMonitor(); } else if (clazz == ProtectedTermsLoader.class) { return Globals.protectedTermsLoader; } else if (clazz == ClipBoardManager.class) { return Globals.clipboardManager; } else if (clazz == UndoManager.class) { return Globals.undoManager; } else { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Cannot instantiate dependency: " + clazz, ex); return null; } } }
Source:
<code><START> public void ShouldBindView_WhenCreated() throws Exception { <END> assertThat(activity.languageSpinner).isNotNull(); assertThat(activity.countrySpinner).isNotNull(); assertThat(activity.ageTextView).isNotNull(); assertThat(activity.genderSpinner).isNotNull(); assertThat(activity.startButton).isNotNull(); }</code><technical_language>Removing test fix is bad idea</technical_language>

Target:
public void ShouldBindView_WhenCreated() { assertThat(activity.languageSpinner).isNotNull(); assertThat(activity.countrySpinner).isNotNull(); assertThat(activity.ageTextView).isNotNull(); assertThat(activity.genderSpinner).isNotNull(); assertThat(activity.startButton).isNotNull(); }
Source:
<code>private void glusterHostAdd(Guid targetClusterId) { if (getClusterUtils().hasMultipleServers(targetClusterId)) { String hostName = (getVds().gethost_name().isEmpty()) ? getVds().getManagmentIp() : getVds().gethost_name(); VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(getClusterUtils().getUpServer(targetClusterId).getId(), hostName)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { <START> getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); <END> getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); errorType = AuditLogType.GLUSTER_HOST_ADD_FAILED; return; } } }</code><technical_language>Introduce a method similar GlusterCommandBase#handleVdsError for this error handling. important is add ExecuteFailedMessages well, is returned in result of REST api</technical_language>

Target:
private void glusterHostAdd(Guid targetClusterId) { String hostName = (getVds().gethost_name().isEmpty()) ? getVds().getManagmentIp() : getVds().gethost_name(); VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(getClusterUtils().getUpServer(targetClusterId).getId(), hostName)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(returnValue); errorType = AuditLogType.GLUSTER_HOST_ADD_FAILED; return; } }
Source:
<code>public @ResponseBody DeferredResult<RelationshipChanges> getRelationshipChanges( @ApiParam(value="The classification identifier") @PathVariable(value="classificationId") final String classificationId, @ApiParam(value="Expansion parameters") @RequestParam(value="expand", required=false) final String expand, @ApiParam(value="The search key") @RequestParam(value="searchAfter", required=false) final String searchAfter, @ApiParam(value="The maximum number of items to return") @RequestParam(value="limit", defaultValue="50", required=false) final int limit) { final String expandWithRelationship; if (Strings.isNullOrEmpty(expand)) { expandWithRelationship = "relationship()"; <START> } else if (expand.contains("relationsip")) { <END> expandWithRelationship = expand; } else { expandWithRelationship = String.format("%s, relationship()", expand); } return DeferredResults.wrap(ClassificationRequests.prepareSearchRelationshipChange() .filterByClassificationId(classificationId) .setExpand(expandWithRelationship) .setSearchAfter(searchAfter) .setLimit(limit) .build(SnomedDatastoreActivator.REPOSITORY_UUID) .execute(bus)); }</code><technical_language>suggestion } else if (expand.contains("relationship(")) { typo needs fixing, opening parenthesis ensures this is end of expand option, is a bonus</technical_language>

Target:
public @ResponseBody DeferredResult<RelationshipChanges> getRelationshipChanges( @ApiParam(value="The classification identifier") @PathVariable(value="classificationId") final String classificationId, @ApiParam(value="Expansion parameters") @RequestParam(value="expand", required=false) final String expand, @ApiParam(value="The search key") @RequestParam(value="searchAfter", required=false) final String searchAfter, @ApiParam(value="The maximum number of items to return") @RequestParam(value="limit", defaultValue="50", required=false) final int limit) { final String expandWithRelationship; if (Strings.isNullOrEmpty(expand)) { expandWithRelationship = "relationship()"; } else { expandWithRelationship = String.format("relationship(expand(%s))", expand); } return DeferredResults.wrap(ClassificationRequests.prepareSearchRelationshipChange() .filterByClassificationId(classificationId) .setExpand(expandWithRelationship) .setSearchAfter(searchAfter) .setLimit(limit) .build(SnomedDatastoreActivator.REPOSITORY_UUID) .execute(bus)); }
Source:
<code>private Map<Integer, IndicatorValue> parseJSON(String response) throws JSONException { Map<Integer, IndicatorValue> indicatorMap = new HashMap<>(); JSONArray responseArray = new JSONArray(response); for (int i = 0; i < responseArray.length(); i++) { JSONObject valueRow = responseArray.getJSONObject(i); Double doubleValue = valueRow.optDouble("value"); if (Double.NaN != doubleValue) { IndicatorValue indicatorValue = new IndicatorValueFloat(doubleValue); <START> Integer id = Integer.valueOf(valueRow.getString("region")); <END> indicatorMap.put(id, indicatorValue); } } return indicatorMap; }</code><technical_language>If "region" is integer call valueRow.getInt("region");</technical_language>

Target:
private Map<Integer, IndicatorValue> parseJSON(String response) throws JSONException { Map<Integer, IndicatorValue> indicatorMap = new HashMap<>(); JSONArray responseArray = new JSONArray(response); for (int i = 0; i < responseArray.length(); i++) { JSONObject valueRow = responseArray.getJSONObject(i); Double doubleValue = valueRow.optDouble("value"); int sotkaRegionId = valueRow.optInt("region", -1); if (sotkaRegionId != -1 && Double.NaN != doubleValue) { indicatorMap.put(sotkaRegionId, new IndicatorValueFloat(doubleValue)); } } return indicatorMap; }
Source:
<code>protected void createConnection() { DockerExplorerView dockerView = new DockerExplorerView(); dockerView.open(); String dockerMachineName = System.getProperty(SYSPROP_DOCKER_MACHINE_NAME); String dockerServerURI = System.getProperty(SYSPROP_DOCKER_SERVER_URI); String unixSocket = System.getProperty(SYSPROP_UNIX_SOCKET); if (!StringUtils.isBlank(dockerMachineName)) { dockerView.createDockerConnectionSearch(dockerMachineName); this.connection = getConnectionByName(dockerMachineName); } else if (!StringUtils.isEmpty(dockerServerURI)) { dockerView.createDockerConnection(AuthenticationMethod.TCP_CONNECTION, dockerServerURI, null, dockerServerURI); this.connection = getConnectionByHost(dockerServerURI); } else if (!StringUtils.isEmpty(unixSocket)) { dockerView.createDockerConnection(AuthenticationMethod.UNIX_SOCKET, unixSocket, null, unixSocket); <START> this.connection = getConnectionByHost(dockerServerURI); <END> } else { fail("Cannot create a docker connection. " + "Neither " + SYSPROP_DOCKER_MACHINE_NAME + " nor " + SYSPROP_DOCKER_SERVER_URI + " nor " + SYSPROP_UNIX_SOCKET + " were defined."); } if (connection == null) { fail("Could not create connection to server " + getServer()); } connection.enableConnection(); }</code><technical_language>unixSocket, instead of dockerServerURI</technical_language>

Target:
protected DockerConnection createConnection() { DockerExplorerView dockerView = new DockerExplorerView(); dockerView.open(); String dockerMachineName = System.getProperty(SYSPROP_DOCKER_MACHINE_NAME); String dockerServerURI = System.getProperty(SYSPROP_DOCKER_SERVER_URI); String unixSocket = System.getProperty(SYSPROP_UNIX_SOCKET); if (!StringUtils.isBlank(dockerMachineName)) { dockerView.createDockerConnectionSearch(dockerMachineName); this.connection = getConnectionByName(dockerMachineName); } else if (!StringUtils.isEmpty(dockerServerURI)) { dockerView.createDockerConnection(AuthenticationMethod.TCP_CONNECTION, dockerServerURI, null, dockerServerURI); this.connection = getConnectionByHost(dockerServerURI); } else if (!StringUtils.isEmpty(unixSocket)) { dockerView.createDockerConnection(AuthenticationMethod.UNIX_SOCKET, unixSocket, null, unixSocket); this.connection = getConnectionByHost(unixSocket); } else { fail("Cannot create a docker connection. " + "Neither " + SYSPROP_DOCKER_MACHINE_NAME + " nor " + SYSPROP_DOCKER_SERVER_URI + " nor " + SYSPROP_UNIX_SOCKET + " were defined."); } connection.enableConnection(); return connection; }
Source:
<code>public void setRelay(Command command, String number) { if (command instanceof OnOffType) { if( ((OnOffType) command) == OnOffType.ON) { <START> HttpUtil.executeUrl(GET, createURL() <END> + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword() + "&" + SUFFIX_RELAY + number + "=" + "1", this.timeOut); } else { HttpUtil.executeUrl(GET, createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword() + "&" + SUFFIX_RELAY + number + "=" + "0", this.timeOut); } } else { logger.error("Unsupported command type"); } }</code><technical_language>Please extrace generated url a variable calling HttpUtil.executeUrl(), this debugging easier</technical_language>

Target:
public void setRelay(Command command, String number) { if (command instanceof OnOffType) { if( ((OnOffType) command) == OnOffType.ON) { String URL = createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword() + "&" + SUFFIX_RELAY + number + "=" + "1"; HttpUtil.executeUrl(GET, URL, this.timeOut); } else { String URL = createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword() + "&" + SUFFIX_RELAY + number + "=" + "0"; HttpUtil.executeUrl(GET, URL, this.timeOut); } } else { logger.error("Unsupported command type"); } }
Source:
<code>public void customize() { Networking.checkPortsValid(MutableMap.of("amqpPort", getAmqpPort())); copyTemplate(entity.getConfig(RabbitBroker.CONFIG_TEMPLATE_URL), getConfigPath() + ".config"); ScriptHelper scriptHelper = newScript(CUSTOMIZING); scriptHelper.body.append( format("cp -R %s/* .", getExpandedInstallDir()) ); if (entity.getConfig(RabbitBroker.ENABLE_MANAGEMENT_PLUGIN)) { scriptHelper.body.append( "./sbin/rabbitmq-plugins enable rabbitmq_management" ); } <START> scriptHelper.execute(); <END> }</code><technical_language>Appreciate sense include a failOnNonZeroResultCode this step</technical_language>

Target:
public void customize() { Networking.checkPortsValid(MutableMap.of("amqpPort", getAmqpPort())); ScriptHelper scriptHelper = newScript(CUSTOMIZING); scriptHelper.body.append( format("cp -R %s/* .", getExpandedInstallDir()) ); if (Boolean.TRUE.equals(entity.getConfig(RabbitBroker.ENABLE_MANAGEMENT_PLUGIN))) { scriptHelper.body.append( "./sbin/rabbitmq-plugins enable rabbitmq_management" ); } scriptHelper.failOnNonZeroResultCode(); scriptHelper.execute(); copyTemplate(entity.getConfig(RabbitBroker.CONFIG_TEMPLATE_URL), getConfigPath() + ".config"); }
Source:
<code>private boolean areLeafNodes(CascadeNodeDao dao, Long cascadeResourceId, List<CascadeNode> nodes) { if (nodes.size() == 0) { <START> return true; <END> } else { CascadeNode firstNode = nodes.get(0); List<CascadeNode> childNodes = dao.listCascadeNodesByResourceAndParentId( cascadeResourceId, firstNode.getKey().getId()); return childNodes.size() == 0; } }</code><technical_language>move nodes.size() == 0 branch if(!areLeafNodes()). This meaning of areLeafNodes() function is mixed checking if list of nodes is empty</technical_language>

Target:
private boolean areLeafNodes(CascadeNodeDao dao, Long cascadeResourceId, List<CascadeNode> nodes) { CascadeNode firstNode = nodes.get(0); List<CascadeNode> childNodes = dao.listCascadeNodesByResourceAndParentId( cascadeResourceId, firstNode.getKey().getId()); return childNodes.size() == 0; }
Source:
<code>private RecordCursor initFunctionsAndCursor(SqlExecutionContext executionContext, RecordCursor baseCursor) { long maxInMemoryRows = executionContext.getCairoSecurityContext().getMaxInMemoryRows(); <START> if (maxInMemoryRows >= 0 && baseCursor.size() >= 0 && baseCursor.size() > maxInMemoryRows) { <END> baseCursor.close(); throw LimitOverflowException.instance(maxInMemoryRows); } map.setMaxSize(maxInMemoryRows); cursor.of(baseCursor); for (int i = 0, m = recordFunctions.size(); i < m; i++) { recordFunctions.getQuick(i).init(cursor, executionContext); } return cursor; }</code><technical_language>more naughty places trigger branch issues, stop proliferation</technical_language>

Target:
private RecordCursor initFunctionsAndCursor(SqlExecutionContext executionContext, RecordCursor baseCursor) { long maxInMemoryRows = executionContext.getCairoSecurityContext().getMaxInMemoryRows(); if (maxInMemoryRows > baseCursor.size()) { map.setMaxSize(maxInMemoryRows); cursor.of(baseCursor); for (int i = 0, m = recordFunctions.size(); i < m; i++) { recordFunctions.getQuick(i).init(cursor, executionContext); } return cursor; } baseCursor.close(); throw LimitOverflowException.instance(maxInMemoryRows); }
Source:
<code>public void visitToken(DetailAST ast) { if (isOperatorNode(ast)) { if (option == WrapOption.NL <START> && TokenUtil.areOnSameLine(ast, getLeftNode(ast)) <END> && !TokenUtil.areOnSameLine(ast, getRightNode(ast))) { log(ast, MSG_LINE_NEW, ast.getText()); } else if (option == WrapOption.EOL && !TokenUtil.areOnSameLine(ast, getLeftNode(ast))) { log(ast, MSG_LINE_PREVIOUS, ast.getText()); } } }</code><technical_language>is more readable form: if (isOperatorNode(ast)) { if (option == WrapOption.NL) { if (TokenUtil.areOnSameLine(ast, getLeftNode(ast)) && !TokenUtil.areOnSameLine(ast, getRightNode(ast))) { log(ast, MSG_LINE_NEW, ast.getText()); } } else if (option == WrapOption.EOL) { if (!TokenUtil.areOnSameLine(ast, getLeftNode(ast))) { log(ast, MSG_LINE_PREVIOUS, ast.getText()); } } } user debug option need real long expressions all</technical_language>

Target:
public void visitToken(DetailAST ast) { if (isTargetNode(ast)) { if (option == WrapOption.NL && isNewLineModeViolation(ast)) { log(ast, MSG_LINE_NEW, ast.getText()); } else if (option == WrapOption.EOL && isEndOfLineModeViolation(ast)) { log(ast, MSG_LINE_PREVIOUS, ast.getText()); } } }
Source:
<code>public void delete(String workspaceId) throws InfrastructureException { String projectName; try { projectName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( <START> format("Failed to evaluate the project name to use for workspace %s.", workspaceId), e); <END> } OpenShiftProject osProject = doCreateProject(workspaceId, projectName); osProject.delete(); }</code><technical_language>Consider appending errror message well</technical_language>

Target:
public void delete(String workspaceId) throws InfrastructureException { String projectName; try { projectName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( format( "Failed to evaluate the project name to use for workspace %s." + " The error message was: %s", workspaceId, e.getMessage()), e); } OpenShiftProject osProject = doCreateProject(workspaceId, projectName); osProject.delete(); }
Source:
<code><START> public synchronized int getCheckpointSize() { <END> if (fCheckpointSize == -1) { TmfCheckpoint c = new TmfCheckpoint(TmfTimestamp.ZERO, new TmfLongLocation(0L), 0); ByteBuffer b = ByteBuffer.allocate(ITmfCheckpoint.MAX_SERIALIZE_SIZE); b.clear(); c.serialize(b); fCheckpointSize = b.position(); } return fCheckpointSize; }</code><technical_language>synchronized is sufficient, sync this specific instance, access a static field, shared accross instances. if worth lazy-init'ing (this get called indexer anyway, is case save work). If want to, in a synchronize (this.getClass()) block</technical_language>

Target:
public int getCheckpointSize() { synchronized (getClass()) { if (fCheckpointSize == -1) { TmfCheckpoint c = new TmfCheckpoint(TmfTimestamp.ZERO, new TmfLongLocation(0L), 0); ByteBuffer b = ByteBuffer.allocate(ITmfCheckpoint.MAX_SERIALIZE_SIZE); b.clear(); c.serialize(b); fCheckpointSize = b.position(); } } return fCheckpointSize; }
Source:
<code>public void testMediatorFactory() { OMElement mediatorElement = SynapseConfigUtils.stringToOM(mediatorXml); CacheMediatorFactory factory = new CacheMediatorFactory(); CacheMediator mediator = (CacheMediator) factory.createSpecificMediator(mediatorElement, new Properties()); <START> assertFalse(mediator.isCollector()); <END> assertEquals(mediator.getTimeout(), 60); assertEquals(mediator.getProtocolType(), "HTTP"); assertTrue(Arrays.equals(mediator.getHTTPMethodsToCache(), new String[]{"POST", "GET"})); assertTrue(Arrays.equals(mediator.getHeadersToExcludeInHash(), new String[]{"ab", "abc"})); assertEquals(mediator.getResponseCodes(), "2|5[0-9][0-9]"); assertEquals(mediator.getDigestGenerator().getClass().getName(), "org.wso2.carbon.mediator.cache.digest.HttpRequestHashGenerator"); assertEquals(mediator.getInMemoryCacheSize(), 20); }</code><technical_language>add meaningful assert messages these? helpful understand if a failure occurs</technical_language>

Target:
public void testMediatorFactory() { OMElement mediatorElement = SynapseConfigUtils.stringToOM(mediatorXml); CacheMediatorFactory factory = new CacheMediatorFactory(); CacheMediator mediator = (CacheMediator) factory.createSpecificMediator(mediatorElement, new Properties()); assertFalse("Incorrect value for the collector", mediator.isCollector()); assertEquals("Incorrect value for the timeout", mediator.getTimeout(), 60); assertEquals("Incorrect value for the protocol type", mediator.getProtocolType(), "HTTP"); assertTrue("Incorrect value for the httpMethodsToCache", Arrays.equals(mediator.getHTTPMethodsToCache(), new String[]{"POST", "GET"})); assertTrue("Incorrect value for the headersToExcludeInHash",Arrays.equals(mediator.getHeadersToExcludeInHash(), new String[]{"ab", "abc"})); assertEquals("Incorrect value for the for the responsecodes",mediator.getResponseCodes(), "2|5[0-9][0-9]"); assertEquals("Incorrect value for the hashGenerator",mediator.getDigestGenerator().getClass().getName(), "org.wso2.carbon.mediator.cache.digest.HttpRequestHashGenerator"); assertEquals("Incorrect value for the maxSize",mediator.getInMemoryCacheSize(), 20); }
Source:
<code>public boolean containsKey(K key) { <START> if (service.isRunning()) { <END> return get(key) != null; } return false; }</code><technical_language>OPTIONS more suitable here, want transport</technical_language>

Target:
public boolean containsKey(K key) { if (service.isRunning()) { String target = buildUrl(service.cacheName, key); Response response = null; response = service.getHttpClient().target(target).request().build(HttpMethod.HEAD).invoke(); if (response.getStatus() == Status.OK.getStatusCode()) { return true; } if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { return false; } throw new RuntimeException("RESTEasyHTTPOperations.containsKey::Unexpected HttpStatus: " + response.getStatus() + " " + response.getStatusInfo().getReasonPhrase() + " for request " + target); } return false; }
Source:
<code>public @NotNull SubPeer setPreference(Connection.Direction direction) { <START> if (direction == null) { <END> throw new NullPointerException("`direction` cannot be null"); } this.direction = direction; return this; }</code><technical_language>need for manual check (especially for unannotated parameter)</technical_language>

Target:
public @NotNull SubPeer setPreference(Connection.Direction direction) { this.direction = direction; return this; }
Source:
<code>public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination, long requestTimeout) { JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination); if (answer instanceof JmsTemplate && requestTimeout > 0) { JmsTemplate jmsTemplate = (JmsTemplate) answer; jmsTemplate.setExplicitQosEnabled(true); long ttl = timeToLive > 0 ? timeToLive : requestTimeout; if (ttl > 0 && !isDisableTimeToLive()) { jmsTemplate.setTimeToLive(ttl); } if (acknowledgementMode >= 0) { jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode); } else if (acknowledgementModeName != null) { jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName); } else { jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); } <START> jmsTemplate.setDeliveryDelay(deliveryDelay); <END> } return answer; }</code><technical_language>sense set for InOut. This method calls createInOnlyTemplate statement returns JmsTemplate set delay. This removed</technical_language>

Target:
public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination, long requestTimeout) { JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination); if (answer instanceof JmsTemplate && requestTimeout > 0) { JmsTemplate jmsTemplate = (JmsTemplate) answer; jmsTemplate.setExplicitQosEnabled(true); long ttl = timeToLive > 0 ? timeToLive : requestTimeout; if (ttl > 0 && !isDisableTimeToLive()) { jmsTemplate.setTimeToLive(ttl); } if (acknowledgementMode >= 0) { jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode); } else if (acknowledgementModeName != null) { jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName); } else { jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); } } return answer; }
Source:
<code>public static void sortDetailedCoursesByCourseId(List<CourseDetailsBundle> courses) { <START> courses.sort(Comparator.comparing((CourseDetailsBundle obj) -> obj.course.getId())); <END> }</code><technical_language>If is a single comparator (i.e. .reversed, .thenComparing), omit type block benefit type inference. java courses.sort(Comparator.comparing(obj -> obj.course.getId())); Applies other parts of this PR</technical_language>

Target:
public static void sortDetailedCoursesByCourseId(List<CourseDetailsBundle> courses) { courses.sort(Comparator.comparing(obj -> obj.course.getId())); }
Source:
<code>public void removeAll() { <START> HashSet<String> allHandles = getAllHandlesFromIndex(); <END> for (String handle : allHandles) { removeByHandle(handle); } }</code><technical_language>Set<String></technical_language>

Target:
public void removeAll() { Set<String> allHandlesFromStore = getAllHandlesFromIndex(); for (String handle : allHandlesFromStore) { removeByHandle(handle); } }
Source:
<code>public static String normalizeBranchName(String name, boolean trim) { if (trim) { <START> name = <END> name.trim(); } return name.replaceAll("\\s+([_:-])\\s+", "$1") .replaceAll(":", "-") .replaceAll("\\s+", "_") .replaceAll("_{2,}", "_") .replaceAll("^_", "") .replaceAll("[^\\w-]", ""); }</code><technical_language>I done in plenty of other places in code base, I prefer parameter assignment</technical_language>

Target:
public static String normalizeBranchName(String name, boolean trim) { String result = name; if (trim) { result = name.trim(); } return result.replaceAll("\\s+([_:-])\\s+", "$1") .replaceAll(":", "-") .replaceAll("\\s+", "_") .replaceAll("_{2,}", "_") .replaceAll("^_", "") .replaceAll("[^\\w-]", ""); }
Source:
<code>private void testCompatibleShuffleModeWithBufferTimeout(ShuffleMode shuffleMode) { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Integer> sourceDataStream = env.fromElements(1, 2, 3); <START> sourceDataStream.getTransformation().setBufferTimeout(100); <END> PartitionTransformation<Integer> transformation = new PartitionTransformation<>( sourceDataStream.getTransformation(), new RebalancePartitioner<>(), shuffleMode); DataStream<Integer> partitionStream = new DataStream<>(env, transformation); partitionStream.map(value -> value).print(); StreamingJobGraphGenerator.createJobGraph(env.getStreamGraph()); }</code><technical_language>If default timeout ([discussion above](<LINK_0>, issue StreamExecutionEnvironment.setBufferTimeout(100) default, right</technical_language>

Target:
private void testCompatibleShuffleModeWithBufferTimeout(ShuffleMode shuffleMode) { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setBufferTimeout(100); DataStream<Integer> sourceDataStream = env.fromElements(1, 2, 3); PartitionTransformation<Integer> transformation = new PartitionTransformation<>( sourceDataStream.getTransformation(), new RebalancePartitioner<>(), shuffleMode); DataStream<Integer> partitionStream = new DataStream<>(env, transformation); partitionStream.map(value -> value).print(); StreamingJobGraphGenerator.createJobGraph(env.getStreamGraph()); }
Source:
<code>private boolean isValidDomain(double minx, double maxx, double miny, double maxy) { final int width = (int) (maxx - minx); final int height = (int) (maxy - miny); <START> if (abs(width) == 0 || height == 0) { <END> return false; } return true; }</code><technical_language>simpler, return directly: return abs(width) > 0 && abs(height)== 0</technical_language>

Target:
private boolean isValidDomain(double minx, double maxx, double miny, double maxy) { final int width = (int) (maxx - minx); final int height = (int) (maxy - miny); return width > 0 && height > 0; }
Source:
<code>private void setGetBlobResponseHeaders(BlobInfo blobInfo, GetBlobOptions options, RestResponseChannel restResponseChannel) throws RestServiceException { BlobProperties blobProperties = blobInfo.getBlobProperties(); restResponseChannel.setHeader(RestUtils.Headers.BLOB_SIZE, blobProperties.getBlobSize()); restResponseChannel.setHeader(RestUtils.Headers.ACCEPT_RANGES, RestUtils.BYTE_RANGE_UNITS); long contentLength = blobProperties.getBlobSize(); if (options.getRange() != null) { Pair<String, Long> rangeAndLength = RestUtils.buildContentRangeAndLength(options.getRange(), contentLength, options.resolveRangeOnEmptyBlob()); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_RANGE, rangeAndLength.getFirst()); contentLength = rangeAndLength.getSecond(); } if (contentLength < frontendConfig.chunkedGetResponseThresholdInBytes) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, contentLength); } if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, blobProperties.getContentType()); if (blobProperties.getContentType().equals("text/html")) { restResponseChannel.setHeader("Content-Disposition", "attachment"); } } if (blobProperties.getContentEncoding() != null) { <START> restResponseChannel.setHeader(Headers.AMBRY_CONTENT_ENCODING, blobProperties.getContentEncoding()); <END> } if (blobProperties.getFilename() != null) { restResponseChannel.setHeader(Headers.AMBRY_FILENAME, blobProperties.getFilename()); } }</code><technical_language>For a get blob response, this set HTTP standard Content-Encoding header instead of x-ambry-content-encoding</technical_language>

Target:
private void setGetBlobResponseHeaders(BlobInfo blobInfo, GetBlobOptions options, RestResponseChannel restResponseChannel) throws RestServiceException { BlobProperties blobProperties = blobInfo.getBlobProperties(); restResponseChannel.setHeader(RestUtils.Headers.BLOB_SIZE, blobProperties.getBlobSize()); restResponseChannel.setHeader(RestUtils.Headers.ACCEPT_RANGES, RestUtils.BYTE_RANGE_UNITS); long contentLength = blobProperties.getBlobSize(); if (options.getRange() != null) { Pair<String, Long> rangeAndLength = RestUtils.buildContentRangeAndLength(options.getRange(), contentLength, options.resolveRangeOnEmptyBlob()); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_RANGE, rangeAndLength.getFirst()); contentLength = rangeAndLength.getSecond(); } if (contentLength < frontendConfig.chunkedGetResponseThresholdInBytes) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, contentLength); } if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, blobProperties.getContentType()); if (blobProperties.getContentType().equals("text/html")) { restResponseChannel.setHeader("Content-Disposition", "attachment"); } } if (blobProperties.getContentEncoding() != null) { restResponseChannel.setHeader(Headers.CONTENT_ENCODING, blobProperties.getContentEncoding()); } }
Source:
<code><START> public List<HashMap<String,Object>> getLoggedEvents(@RequestParam String site, @RequestParam long since) { <END> return CircularQueueLogAppender.loggerQueue().getLoggedEvents(site, since); }</code><technical_language>Please return a Map, a HashMap</technical_language>

Target:
public List<Map<String,Object>> getLoggedEvents(@RequestParam String site, @RequestParam long since) { return CircularQueueLogAppender.loggerQueue().getLoggedEvents(site, since); }
Source:
<code>public String getEndTimeInIso8601Format() { <START> return TimeHelper.convertAndFormatDateToIso8601Utc(endTime, timeZone); <END> }</code><technical_language>thoughts, I feel conversion formatting separated (follow getStartTimeString getEndTimeString). method formats ISO8601 do conversion; instead in a dateInUtc parameter</technical_language>

Target:
public String getEndTimeInIso8601Format() { Date endTimeInUtc = TimeHelper.convertLocalDateToUtc(endTime, timeZone); return TimeHelper.formatDateToIso8601Utc(endTimeInUtc); }
Source:
<code>protected void verifyConnector(ClassTree classTree, IdentifierTree connectorAnnotation) { for (AnnotationTree annotationTree : Iterables.filter(classTree.modifiers().annotations(), ClassParserUtils.ANNOTATION_TREE_PREDICATE)) { if (ClassParserUtils.is(annotationTree, "org.mule.api.annotations.Connector")) { for(ExpressionTree expression : annotationTree.arguments()){ if(expression.kind().name().equals("ASSIGNMENT")){ <START> if(((IdentifierTreeImpl) ((AssignmentExpressionTreeImpl) expression).variable()).name().equals("minMuleVersion")){ <END> return; } } } logAndRaiseIssue(annotationTree, "The connector should specify a minMuleVersion"); return; } } }</code><technical_language>Missing validation for empty minMuleVersion</technical_language>

Target:
protected void verifyConnector(ClassTree classTree, IdentifierTree connectorAnnotation) { for (AnnotationTree annotationTree : filter(classTree.modifiers().annotations(), ANNOTATION_TREE_PREDICATE)) { if (is(annotationTree, "org.mule.api.annotations.Connector")) { if(isEmpty(annotationTree.arguments()) || isEmpty(filter(annotationTree.arguments(), new Predicate<ExpressionTree>() { @Override public boolean apply(@Nullable ExpressionTree expression) { return expression.kind().name().equals("ASSIGNMENT") && ((IdentifierTreeImpl) ((AssignmentExpressionTreeImpl) expression).variable()).name().equals("minMuleVersion") && hasValidFormat(replace((((LiteralTreeImpl) ((AssignmentExpressionTreeImpl) expression).expression()).token().text()), "\"", "")); } }))) { logAndRaiseIssue(annotationTree, "@Connector should declare a 'minMuleVersion'."); } } } }
Source:
<code>private void tick(ItemStack stack, EntityPlayer player) { if (ItemHelper.getOrCreateCompound(stack).getInteger(TAG_MODE) > 1) { WorldHelper.repelEntitiesInAABBFromPoint(player.getEntityWorld(), player.getEntityBoundingBox().grow(5), player.posX, player.posY, player.posZ, true); } if (player.getEntityWorld().isRemote) { return; } EntityPlayerMP playerMP = (EntityPlayerMP) player; if (getEmc(stack) == 0 && !consumeFuel(player, stack, 64, false)) { if (stack.getTagCompound().getInteger(TAG_MODE) > 0) { changeMode(stack, 0); } if (playerMP.capabilities.allowFlying) { playerMP.getCapability(InternalAbilities.CAPABILITY, null).disableSwrgFlightOverride(); } return; } if (!playerMP.capabilities.allowFlying) { playerMP.getCapability(InternalAbilities.CAPABILITY, null).enableSwrgFlightOverride(); } if (playerMP.capabilities.isFlying) { if (!isFlyingEnabled(stack)) { changeMode(stack, stack.getTagCompound().getInteger(TAG_MODE) == 0 ? 1 : 3); } } else { if (isFlyingEnabled(stack)) { changeMode(stack, stack.getTagCompound().getInteger(TAG_MODE) == 1 ? 0 : 2); } } float toRemove = 0; if (playerMP.capabilities.isFlying) { toRemove = 0.32F; } if (stack.getTagCompound().getInteger(TAG_MODE) == 2) { toRemove = 0.32F; } else if (stack.getTagCompound().getInteger(TAG_MODE) == 3) { toRemove = 0.64F; } unprocessedEMC += toRemove; if (unprocessedEMC > 1) { removeEmc(stack, 1); unprocessedEMC--; <START> } <END> playerMP.fallDistance = 0; }</code><technical_language>mutable state in item is a huge no. stacks of this item run this method</technical_language>

Target:
private void tick(ItemStack stack, EntityPlayer player) { if (ItemHelper.getOrCreateCompound(stack).getInteger(TAG_MODE) > 1) { WorldHelper.repelEntitiesInAABBFromPoint(player.getEntityWorld(), player.getEntityBoundingBox().grow(5), player.posX, player.posY, player.posZ, true); } if (player.getEntityWorld().isRemote) { return; } EntityPlayerMP playerMP = (EntityPlayerMP) player; if (getEmc(stack) == 0 && !consumeFuel(player, stack, 64, false)) { if (stack.getTagCompound().getInteger(TAG_MODE) > 0) { changeMode(stack, 0); } if (playerMP.capabilities.allowFlying) { playerMP.getCapability(InternalAbilities.CAPABILITY, null).disableSwrgFlightOverride(); } return; } if (!playerMP.capabilities.allowFlying) { playerMP.getCapability(InternalAbilities.CAPABILITY, null).enableSwrgFlightOverride(); } if (playerMP.capabilities.isFlying) { if (!isFlyingEnabled(stack)) { changeMode(stack, stack.getTagCompound().getInteger(TAG_MODE) == 0 ? 1 : 3); } } else { if (isFlyingEnabled(stack)) { changeMode(stack, stack.getTagCompound().getInteger(TAG_MODE) == 1 ? 0 : 2); } } float toRemove = 0; if (playerMP.capabilities.isFlying) { toRemove = 0.32F; } if (stack.getTagCompound().getInteger(TAG_MODE) == 2) { toRemove = 0.32F; } else if (stack.getTagCompound().getInteger(TAG_MODE) == 3) { toRemove = 0.64F; } removeEmc(stack, EMCHelper.removeFractionalEMC(stack, toRemove)); playerMP.fallDistance = 0; }
Source:
<code><START> public String getParameterTypeName() <END> { return parameterTypeSignature.toString(); }</code><technical_language>do need this _and_ getParameterTypeSignature()</technical_language>

Target:
public String getParameterTypeName() { return typeInfo.getTypeSignature().toString(); }
Source:
<code>@Override public String toString() { <START> return "JsonAdapter(" + elementClass.getSimpleName() + ").array()"; <END> }</code><technical_language>"array(" + elementAdapter + ")"</technical_language>

Target:
@Override public String toString() { return elementAdapter + ".array()"; }
Source:
<code>public static boolean canUse( final boolean isRoot, final CommandDispatcher<CommandSource> dispatcher, final CommandNode<CommandSource> node, final CommandSource source ) { final Supplier<String> supplier; <START> if (SpongeNodePermissionCache.PERMISSION_MAP.containsKey(node)) { <END> supplier = SpongeNodePermissionCache.PERMISSION_MAP.get(node); } else { supplier = new CachingStringSupplier(() -> SpongeNodePermissionCache.createFromNode(dispatcher, node)); } try { ((CommandSourceBridge) source).bridge$setPotentialPermissionNode(supplier); final boolean result = node.canUse(source); if (isRoot && node instanceof SpongePermissionWrappedLiteralCommandNode && ((CommandSourceBridge) source).bridge$getICommandSource() instanceof ServerPlayer) { SpongePermissions.registerPermission(supplier.get(), 0); } return result; } finally { ((CommandSourceBridge) source).bridge$setPotentialPermissionNode(null); } }</code><technical_language>avoided checking if get return null</technical_language>

Target:
public static boolean canUse( final boolean isRoot, final CommandDispatcher<CommandSource> dispatcher, final CommandNode<CommandSource> node, final CommandSource source ) { Supplier<String> supplier = SpongeNodePermissionCache.PERMISSION_MAP.get(node); if (supplier == null) { supplier = new CachingStringSupplier(() -> SpongeNodePermissionCache.createFromNode(dispatcher, node)); } try { ((CommandSourceBridge) source).bridge$setPotentialPermissionNode(supplier); final boolean result = node.canUse(source); if (isRoot && node instanceof SpongePermissionWrappedLiteralCommandNode && ((CommandSourceBridge) source).bridge$getICommandSource() instanceof ServerPlayer) { SpongePermissions.registerPermission(supplier.get(), 0); } return result; } finally { ((CommandSourceBridge) source).bridge$setPotentialPermissionNode(null); } }
Source:
<code>public void testToEntity() { AccountAttributes account = createValidAccountAttributesObject(); Account expectedAccount = new Account(account.googleId, account.name, account.isInstructor, account.email, account.institute, StudentProfileAttributes.builder(account.googleId).build().toEntity()); <START> new ProfilesDb().saveEntity(account.studentProfile.toEntity()); <END> Account actualAccount = new AccountAttributes(expectedAccount).toEntity(); assertEquals(expectedAccount.getGoogleId(), actualAccount.getGoogleId()); assertEquals(expectedAccount.getName(), actualAccount.getName()); assertEquals(expectedAccount.getEmail(), actualAccount.getEmail()); assertEquals(expectedAccount.getInstitute(), actualAccount.getInstitute()); assertEquals(expectedAccount.isInstructor(), actualAccount.isInstructor()); String expectedProfile = StudentProfileAttributes.valueOf(expectedAccount.getStudentProfile()).toString(); String actualProfile = StudentProfileAttributes.valueOf(actualAccount.getStudentProfile()).toString(); assertEquals(expectedProfile, actualProfile); }</code><technical_language>I realised this necessary. a simpler construct actualAccount try retrieve student profile entity database</technical_language>

Target:
public void testToEntity() { AccountAttributes account = createValidAccountAttributesObject(); Account expectedAccount = new Account(account.googleId, account.name, account.isInstructor, account.email, account.institute, account.studentProfile.toEntity()); Account actualAccount = account.toEntity(); assertEquals(expectedAccount.getGoogleId(), actualAccount.getGoogleId()); assertEquals(expectedAccount.getName(), actualAccount.getName()); assertEquals(expectedAccount.getEmail(), actualAccount.getEmail()); assertEquals(expectedAccount.getInstitute(), actualAccount.getInstitute()); assertEquals(expectedAccount.isInstructor(), actualAccount.isInstructor()); ProfilesDb profilesDb = new ProfilesDb(); profilesDb.saveEntity(account.studentProfile.toEntity()); String expectedProfile = StudentProfileAttributes.valueOf(expectedAccount.getStudentProfile()).toString(); String actualProfile = StudentProfileAttributes.valueOf(actualAccount.getStudentProfile()).toString(); assertEquals(expectedProfile, actualProfile); profilesDb.deleteEntity(account.studentProfile); }
Source:
<code><START> public int hashCode() { <END> int hashcode = (subjectIsConstant ? 1 : 0) + type.hashCode() + subjectVar.hashCode() + subjectConstant.hashCode(); for(final StatementPattern sp : getPatterns()) { hashcode += sp.hashCode(); } return hashcode; }</code><technical_language>Objects.hash helper function instead of building own</technical_language>

Target:
public int hashCode() { return Objects.hash(subjectIsConstant, type, subjectVar, subjectConstant, getPatterns()); }
Source:
<code>public void fromPreviousCustomSetup() { <START> assumeFalse(Functions.isWindows()); END> final String newBuildsDirValueBySysprop = "/tmp/${ITEM_ROOTDIR}/bluh"; story.then(j -> { assertEquals("${ITEM_ROOTDIR}/ze-previous-custom-builds", j.jenkins.getRawBuildsDir()); setBuildsDirProperty(newBuildsDirValueBySysprop); }); story.then(j -> { assertEquals(newBuildsDirValueBySysprop, j.jenkins.getRawBuildsDir()); assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), containsString("<buildsDir>" + newBuildsDirValueBySysprop + "</buildsDir>")); String rootDirBeforeRestart = j.jenkins.getRootDir().toString(); clearSystemProperties(); j.jenkins.restart(); int maxLoops = 50; while (j.jenkins.getInitLevel() != InitMilestone.COMPLETED && maxLoops-- > 0) { Thread.sleep(300); } assertEquals(rootDirBeforeRestart, j.jenkins.getRootDir().toString()); assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), containsString("<buildsDir>" + newBuildsDirValueBySysprop + "</buildsDir>")); assertEquals(newBuildsDirValueBySysprop, j.jenkins.getRawBuildsDir()); END HACK ** }); }</code><technical_language>NIT: is nicer assumeFalse(" Default Windows lifecycle support restart.", Function.isWindows()) reason for skipped test reported</technical_language>

Target:
public void fromPreviousCustomSetup() { assumeFalse("Default Windows lifecycle does not support restart.", Functions.isWindows()); final String newBuildsDirValueBySysprop = "/tmp/${ITEM_ROOTDIR}/bluh"; story.then(j -> { assertEquals("${ITEM_ROOTDIR}/ze-previous-custom-builds", j.jenkins.getRawBuildsDir()); setBuildsDirProperty(newBuildsDirValueBySysprop); }); story.then(j -> { assertEquals(newBuildsDirValueBySysprop, j.jenkins.getRawBuildsDir()); assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), containsString("<buildsDir>" + newBuildsDirValueBySysprop + "</buildsDir>")); String rootDirBeforeRestart = j.jenkins.getRootDir().toString(); clearSystemProperties(); j.jenkins.restart(); int maxLoops = 50; while (j.jenkins.getInitLevel() != InitMilestone.COMPLETED && maxLoops-- > 0) { Thread.sleep(300); } assertEquals(rootDirBeforeRestart, j.jenkins.getRootDir().toString()); assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), containsString("<buildsDir>" + newBuildsDirValueBySysprop + "</buildsDir>")); assertEquals(newBuildsDirValueBySysprop, j.jenkins.getRawBuildsDir()); END HACK ** }); }
Source:
<code>DeclaredTypeNode getNNode(@Nonnull NodeLevel minimumLevel) throws LibraryFormatException, LibraryIOException { DeclaredTypeNode type = nnode.get(); if (type == null || !type.getLevel().keep(minimumLevel)) { InputStream in = null; try { in = new BufferedInputStream(source.getInputStream()); NodeLevel loadLevel = getLevelForLoading(minimumLevel); type = JayceReaderFactory.get(inputJackLibrary, in).readType(loadLevel); nnode = new SoftReference<DeclaredTypeNode>(type); } catch (WrongPermissionException e) { throw new LibraryIOException(inputJackLibrary.getLocation(), e); } <START> catch (IOException e) { throw new LibraryIOException(inputJackLibrary.getLocation(), e); } catch <END> (JayceFormatException e) { logger.log(Level.SEVERE, "Library " + inputJackLibrary.getLocation().getDescription() + " is invalid", e); throw new LibraryFormatException(inputJackLibrary.getLocation()); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { logger.log(Level.WARNING, "Failed to close input stream on " + source.getLocation().getDescription(), e); } } tracer.getStatistic(NNODE_RELOAD).add(loadCount > 0); loadCount++; } return type; }</code><technical_language>Multicatch</technical_language>

Target:
DeclaredTypeNode getNNode(@Nonnull NodeLevel minimumLevel) throws LibraryFormatException, LibraryIOException { DeclaredTypeNode type = nnode.get(); if (type == null || !type.getLevel().keep(minimumLevel)) { InputStream in = null; try { in = new BufferedInputStream(source.getInputStream()); NodeLevel loadLevel = getLevelForLoading(minimumLevel); type = JayceReaderFactory.get(inputJackLibrary, in).readType(loadLevel); nnode = new SoftReference<DeclaredTypeNode>(type); } catch (IOException | WrongPermissionException e) { throw new LibraryIOException(inputJackLibrary.getLocation(), e); } catch (JayceFormatException e) { logger.log(Level.SEVERE, "Library " + inputJackLibrary.getLocation().getDescription() + " is invalid", e); throw new LibraryFormatException(inputJackLibrary.getLocation()); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { logger.log(Level.WARNING, "Failed to close input stream on " + source.getLocation().getDescription(), e); } } tracer.getStatistic(NNODE_RELOAD).add(loadCount > 0); loadCount++; } return type; }
Source:
<code>void calculate(final MethodCoverageImpl coverage) { int firstLine = ISourceFileCoverage.UNKNOWN_LINE; int lastLine = ISourceFileCoverage.UNKNOWN_LINE; for (final Map.Entry<AbstractInsnNode, Instruction> entry : instructions .entrySet()) { final Instruction i = entry.getValue(); final AbstractInsnNode n = entry.getKey(); final AbstractInsnNode r = findRepresentative(n); if (r != n) { ignored.add(n); <START> instructions.put(r, instructions.get(r).merge(i)); <END> } if (!ignored.contains(n)) { final int line = i.getLine(); if (line != ISourceNode.UNKNOWN_LINE) { if (firstLine > line || lastLine == ISourceNode.UNKNOWN_LINE) { firstLine = line; } if (lastLine < line) { lastLine = line; } } } } coverage.ensureCapacity(firstLine, lastLine); for (final Map.Entry<AbstractInsnNode, Instruction> i : instructions .entrySet()) { if (ignored.contains(i.getKey())) { continue; } Instruction insn = i.getValue(); final Set<AbstractInsnNode> r = replacements.get(i.getKey()); if (r != null) { final List<Instruction> newBranches = new ArrayList<Instruction>( r.size()); for (final AbstractInsnNode b : r) { newBranches.add(instructions.get(b)); } insn = insn.replaceBranches(newBranches); } coverage.increment(insn.getInstructionCounter(), insn.getBranchCounter(), insn.getLine()); } coverage.incrementMethodCounter(); }</code><technical_language>@marchof > pick representative instruction replacing branches IMO this source of errors in future. do replacement of instructions.put(r, instructions.get(r).merge(i)); instruction = instructions.get(r).merge(instruction); instructions.put(r, instruction); instructions.put(n, instruction); instead</technical_language>

Target:
void calculate(final MethodCoverageImpl coverage) { applyMerges(); applyReplacements(); ensureCapacity(coverage); for (final Entry<AbstractInsnNode, Instruction> entry : instructions .entrySet()) { if (!ignored.contains(entry.getKey())) { final Instruction instruction = entry.getValue(); coverage.increment(instruction.getInstructionCounter(), instruction.getBranchCounter(), instruction.getLine()); } } coverage.incrementMethodCounter(); }