auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public UpdateResponse delete(String key) { try { LOG.info("Delete datastream called for datastream " + key); DELETE_CALL.inc(); Instant startTime = Instant.now(); _store.deleteDatastream(key); <START> synchronized (_deleteCallLatencyMs) { <END> _deleteCallLatencyMs = Duration.between(startTime, Instant.now()).toMillis(); } return new UpdateResponse(HttpStatus.S_200_OK); } catch (Exception e) { CALL_ERROR.inc(); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "delete datastream failed for datastream: " + key, e); } return null; }</code><technical_language>volatile AtomicLong</technical_language>

Target:
public UpdateResponse delete(String key) { try { LOG.info("Delete datastream called for datastream " + key); DELETE_CALL.inc(); Instant startTime = Instant.now(); _store.deleteDatastream(key); _deleteCallLatencyMs.set(Duration.between(startTime, Instant.now()).toMillis()); return new UpdateResponse(HttpStatus.S_200_OK); } catch (Exception e) { CALL_ERROR.inc(); _errorLogger.logAndThrowRestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "delete datastream failed for datastream: " + key, e); } return null; }
Source:
<code>final byte[] getRaw(int columnIndex) { byte[] retval; int pos = m_buffer.position(); int offset = getOffset(columnIndex); VoltType type = getColumnType(columnIndex); int length = type.getLengthInBytesForFixedTypesWithoutCheck(); switch(type) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case TIMESTAMP: case FLOAT: case DECIMAL: <START> case GEOGRAPHY_POINT: <END> retval = new byte[length]; m_buffer.position(offset); m_buffer.get(retval); m_buffer.position(pos); return retval; case STRING: case VARBINARY: case GEOGRAPHY: length = m_buffer.getInt(offset); if (length == VoltTable.NULL_STRING_INDICATOR) { length = 0; } length += 4; retval = new byte[length]; m_buffer.position(offset); m_buffer.get(retval); m_buffer.position(pos); return retval; default: throw new RuntimeException("Unknown type"); } }</code><technical_language>This "broken" forever, length = type.getLengthInBytesForFixedTypesWithoutCheck(); is called needlessly for variable-length types moved (fixed-length-type) switch cases</technical_language>

Target:
final byte[] getRaw(int columnIndex) { byte[] retval; int pos = m_buffer.position(); int offset = getOffset(columnIndex); VoltType type = getColumnType(columnIndex); switch(type) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case TIMESTAMP: case FLOAT: case DECIMAL: case GEOGRAPHY_POINT: { int length = type.getLengthInBytesForFixedTypesWithoutCheck(); retval = new byte[length]; m_buffer.position(offset); m_buffer.get(retval); m_buffer.position(pos); return retval; } case STRING: case VARBINARY: case GEOGRAPHY: { int length = m_buffer.getInt(offset); if (length == VoltTable.NULL_STRING_INDICATOR) { length = 0; } length += 4; retval = new byte[length]; m_buffer.position(offset); m_buffer.get(retval); m_buffer.position(pos); return retval; } default: throw new RuntimeException("Unknown type"); } }
Source:
<code>protected static String sanitize(String namespace) { <START> Pattern dotOrWhitespace = Pattern.compile("[\\s]+|[.]+"); <END> return dotOrWhitespace.matcher(namespace).replaceAll("_"); }</code><technical_language>a constant</technical_language>

Target:
protected static String sanitize(String namespace) { return DOT_OR_WHITESPACE_PATTERN.matcher(namespace).replaceAll("_"); }
Source:
<code>protected void testIntersections(Comparison comparison) { for (Diff diff : comparison.getDifferences()) { int realRefinesSize = Iterables.size(Iterables.filter(diff.getRefines(), not(instanceOf(StereotypedElementChange.class)))); assertFalse("Wrong number of refines (without StereotypedElementChange) on" + diff, realRefinesSize > 1); int stereotypedElementChangeRefines = Iterables.size(Iterables.filter(diff.getRefines(), <START> instanceOf(StereotypedElementChange.class))); <END> assertFalse("Wrong number of refines StereotypedElementChange on " + diff, stereotypedElementChangeRefines > 1); } }</code><technical_language>Wrong number of refines (of type StereotypedElementChange)</technical_language>

Target:
protected void testIntersections(Comparison comparison) { for (Diff diff : comparison.getDifferences()) { int realRefinesSize = Iterables.size(Iterables.filter(diff.getRefines(), not(instanceOf(StereotypedElementChange.class)))); assertFalse("Wrong number of refines (without StereotypedElementChange) on" + diff, realRefinesSize > 1); int stereotypedElementChangeRefines = Iterables.size(Iterables.filter(diff.getRefines(), instanceOf(StereotypedElementChange.class))); assertFalse("Wrong number of refines (of type StereotypedElementChange) on " + diff, stereotypedElementChangeRefines > 1); } }
Source:
<code>private LeadMessage(final Type type, final String title, String details, final String linkUrl) { <START> this(type, title, details); <END> mLinkUrl = linkUrl; }</code><technical_language>Instead of this constructor other, I other this constructor a null linkUrl. do think</technical_language>

Target:
private LeadMessage(final Type type, final String title, String details, final String linkUrl) { mTitle = title; mDetails = details; mType = type; mLinkUrl = linkUrl; }
Source:
<code>private JComponent createBenchmarkTreePanel() { JPanel benchmarkTreePanel = new JPanel(new BorderLayout()); CheckBoxTree checkBoxTree = createCheckBoxTree(); benchmarkTreePanel.add(new JScrollPane(checkBoxTree), BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton generateReportButton = new JButton(new GenerateReportAction(this)); buttonPanel.add(generateReportButton); benchmarkTreePanel.add(buttonPanel, BorderLayout.SOUTH); <START> benchmarkTreePanel.setBorder(new EmptyBorder(0, 0, 15, 0)); <END> return benchmarkTreePanel; }</code><technical_language>BorderFactory.createEmptyBorder(...)</technical_language>

Target:
private JComponent createBenchmarkTreePanel() { JPanel benchmarkTreePanel = new JPanel(new BorderLayout()); CheckBoxTree checkBoxTree = createCheckBoxTree(); benchmarkTreePanel.add(new JScrollPane(checkBoxTree), BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton generateReportButton = new JButton(new GenerateReportAction(this)); buttonPanel.add(generateReportButton); benchmarkTreePanel.add(buttonPanel, BorderLayout.SOUTH); benchmarkTreePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0)); return benchmarkTreePanel; }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof ReferenceSchema) { ReferenceSchema that = (ReferenceSchema) o; return that.canEqual(this) && Objects.equals(refValue, that.refValue) && Objects.equals(unprocessedProperties, that.unprocessedProperties) && <START> Objects.equals(title, that.title) && <END> Objects.equals(description, that.description) && super.equals(that); } else { return false; } }</code><technical_language>In case of Confluent Schema Registry, call equals schema. prefer fix above</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof ReferenceSchema) { ReferenceSchema that = (ReferenceSchema) o; return that.canEqual(this) && Objects.equals(refValue, that.refValue) && Objects.equals(unprocessedProperties, that.unprocessedProperties) && Objects.equals(title, that.title) && Objects.equals(description, that.description) && super.equals(that) && EqualsCycleBreaker.equalsWithoutCycle(this, that, true, ReferenceSchema::equalsPossiblyCyclic); } else { return false; } }
Source:
<code>public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; <START> notificationIdsInUse.delete(notificationId); <END> if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); }</code><technical_language>other places access notificationIdsInUse in methods descriptive names. do here. markNotificationIdAsFree()</technical_language>

Target:
public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); }
Source:
<code>public static ImmutableList<Arguments> getVoidArgsFromParamList(final ImmutableList<Ds3Param> paramList) { if(isEmpty(paramList)) { return ImmutableList.of(); } <START> final ImmutableList.Builder<Arguments> argsBuilder = ImmutableList.builder(); <END> for (final Ds3Param ds3Param : paramList) { if (!ds3Param.getName().equals("Operation") && ds3Param.getType().equals("void")) { argsBuilder.add(toArgument(ds3Param)); } } return argsBuilder.build(); }</code><technical_language>This stream() filter()</technical_language>

Target:
public static ImmutableList<Arguments> getVoidArgsFromParamList(final ImmutableList<Ds3Param> paramList) { if(isEmpty(paramList)) { return ImmutableList.of(); } return paramList.stream() .filter(param -> !param.getName().equals("Operation") && param.getType().equals("void")) .map(RequestConverterUtil::toArgument) .collect(GuavaCollectors.immutableList()); }
Source:
<code>public FacebookBuilder() { super(FacebookAuthProvider.PROVIDER_ID); try { Class c = com.facebook.FacebookSdk.class; } catch (NoClassDefFoundError e) { throw new RuntimeException( "Facebook provider cannot be configured " + "without dependency. Did you forget to add " + "'com.facebook.android:facebook-login:VERSION' dependency?"); } if (getApplicationContext().getString(R.string.facebook_application_id) .equals(UNCONFIGURED_CONFIG_VALUE)) { throw new RuntimeException("Facebook provider unconfigured. Make sure to add" + " a `facebook_application_id` string. See the docs for more info:" + " <LINK_0>"); } if (getApplicationContext().getString(R.string.facebook_login_protocol_scheme) .equals("fbYOUR_APP_ID")) { <START> Log.w("FacebookBuilder", "Facebook provider unconfigured for Chrome" + <END> " Custom Tabs."); } }</code><technical_language>is purpose for this hardcoded Log.w</technical_language>

Target:
public FacebookBuilder() { super(FacebookAuthProvider.PROVIDER_ID); try { Class c = com.facebook.FacebookSdk.class; } catch (NoClassDefFoundError e) { throw new RuntimeException( "Facebook provider cannot be configured " + "without dependency. Did you forget to add " + "'com.facebook.android:facebook-login:VERSION' dependency?"); } Preconditions.checkConfigured(getApplicationContext(), "Facebook provider unconfigured. Make sure to add a" + " `facebook_application_id` string. See the docs for more info:" + " <LINK_0>", R.string.facebook_application_id); if (getApplicationContext().getString(R.string.facebook_login_protocol_scheme) .equals("fbYOUR_APP_ID")) { Log.w(TAG, "Facebook provider unconfigured for Chrome Custom Tabs."); } }
Source:
<code>public MarketHistory(Market m) { <START> super(); <END> this.market = m; history = new HashMap<String, List<Double>>(); }</code><technical_language>need super</technical_language>

Target:
public MarketHistory(Market m) { this.market = m; history = new HashMap<String, List<Double>>(); }
Source:
<code>public void trailingSlashes() { assertEquals("/foo/bar/", <START> ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar/", "/c")); <END> assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar/", "/c")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar }</code><technical_language>argument order is... weird. Consider flipping be: contextPath, servletPath, requestUri tests be: "/c", "/s", "/c/s/foo/bar/" is easier read</technical_language>

Target:
public void trailingSlashes() { assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo/bar/")); assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo/bar assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo%2Fbar/")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo%2Fbar }
Source:
<code>private void sendMetrics(final String id, final String metrics) { try { <START> final URL obj = new URL(this.dolphinURL); <END> final HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.connect(); final OutputStream os = con.getOutputStream(); final String param = "id=" + id + "&metrics=" + metrics; os.write((param).getBytes()); os.flush(); os.close(); final BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) ); String inputLine; final StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { throw new RuntimeException("Network Error" + e); } }</code><technical_language>I a more intuitive variable name: dashboardURL a good choice, if rename existing dashboardURLStr (in this case, I suggest change ClassName, this class). Please feel free if a one</technical_language>

Target:
private void sendMetrics(final String id, final String metrics) { try { final String dashboardUrlStr = this.dashboardURL; final URL dashboardUrl = new URL(dashboardUrlStr); final HttpURLConnection con = (HttpURLConnection) dashboardUrl.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.connect(); try (final OutputStream os = con.getOutputStream()) { final String param = "id=" + id + "&metrics=" + metrics + "&time=" + System.currentTimeMillis(); os.write((param).getBytes()); os.flush(); } try (final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; final StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } } catch (IOException e) { LOG.log(Level.WARNING, "Failed to send metrics to Dashboard server.", e); } }
Source:
<code>public void unregisterPill(final Long accountId, final String pillId) { final Integer numRows = deviceDAO.deletePillPairing(pillId, accountId); if(numRows == 0) { LOGGER.warn("Did not find active pill to unregister"); } final List<DeviceAccountPair> sensePairedWithAccount = this.deviceDAO.getSensesForAccountId(accountId); if(sensePairedWithAccount.isEmpty()){ LOGGER.error("No sense paired with account {}", accountId); } <START> final String senseId = sensePairedWithAccount.get(0).externalDeviceId; <END> try { this.mergedUserInfoDynamoDB.deletePillColor(senseId, accountId, pillId); }catch (Exception ex){ LOGGER.error("Delete pill {}'s color from user info table for sense and account failed: {}", pillId, senseId, accountId, ex.getMessage()); } }</code><technical_language>this throw IndexOutOfBoundsException if previous check true</technical_language>

Target:
public void unregisterPill(final Long accountId, final String pillId) { final Integer numRows = deviceDAO.deletePillPairing(pillId, accountId); if(numRows == 0) { LOGGER.warn("Did not find active pill to unregister"); } final List<DeviceAccountPair> sensePairedWithAccount = this.deviceDAO.getSensesForAccountId(accountId); if(sensePairedWithAccount.isEmpty()){ LOGGER.error("No sense paired with account {}", accountId); return; } final String senseId = sensePairedWithAccount.get(0).externalDeviceId; try { this.mergedUserInfoDynamoDB.deletePillColor(senseId, accountId, pillId); }catch (Exception ex){ LOGGER.error("Delete pill {}'s color from user info table for sense and account failed: {}", pillId, senseId, accountId, ex.getMessage()); } }
Source:
<code><START> public void test_get_URI() throws URISyntaxException { <END> assertEquals("/d1", Paths.get(new URI("file:/ assertEquals("/", Paths.get(new URI("file:/ assertEquals("/d1 try { Paths.get(new URI("d1")); fail(); } catch (IllegalArgumentException expected) }</code><technical_language>this is a more tricky depends installed providers change time. Ideally, this test hard code in of provider other default one. comprehensive testing of file scheme done a test of Filesystems.getDefault().provider().getPath(URI), Paths.get(String...) FileSystems.getPath(String...) test this default provider directly. Similarly, need check scheme for a provider is installed work. a scheme is supported fails</technical_language>

Target:
public void test_get_URI() throws URISyntaxException { assertEquals("/d1", Paths.get(new URI("file:/ assertEquals("/", Paths.get(new URI("file:/ assertEquals("/d1 try { Paths.get(new URI("d1")); fail(); } catch (IllegalArgumentException expected) try { Paths.get(new URI("scheme://d")); fail(); } catch (FileSystemNotFoundException expected) }
Source:
<code>protected String getResource() { <START> return "simpleusertaskmodel.bpmn"; <END> }</code><technical_language>Camel case</technical_language>

Target:
protected String getResource() { return "simpleUserTaskModel.bpmn"; }
Source:
<code>private void setBackgroundComponentLocation(Graphics g) { if (fitToViewport) { final JViewport vp = (JViewport) getParent(); final Point viewPosition = vp.getViewPosition(); int widthOffset = (int) ((vp.getVisibleRect().getWidth() - backgroundComponent.getWidth()) / 2); <START> int heightOffset = (int) ((vp.getVisibleRect().getHeight() - backgroundComponent.getHeight()) / 2); <END> g.translate(viewPosition.x + widthOffset, viewPosition.y + heightOffset); } else { final Point centerPoint = getRootCenterPoint(); final Point backgroundImageTopLeft = getBackgroundImageTopLeft(centerPoint); g.translate(backgroundImageTopLeft.x, backgroundImageTopLeft.y); } }</code><technical_language>Rectangle viewPortBounds = vp.getVisibleRect(); int widthOffset = viewPortBounds.getX() + (int) (viewPortBounds.getWidth() - backgroundComponent.getWidth()) / 2);</technical_language>

Target:
private void setBackgroundComponentLocation(Graphics g) { if (fitToViewport) { final JViewport vp = (JViewport) getParent(); final Point viewPosition = vp.getViewPosition(); g.translate(viewPosition.x, viewPosition.y); } else { final Point centerPoint = getRootCenterPoint(); final Point backgroundImageTopLeft = getBackgroundImageTopLeft(centerPoint); g.translate(backgroundImageTopLeft.x, backgroundImageTopLeft.y); } }
Source:
<code>public Response updateOvfStore(Action action) { ProcessOvfUpdateForStorageDomainCommandParameters params = new ProcessOvfUpdateForStorageDomainCommandParameters(); params.setStorageDomainId(guid); org.ovirt.engine.core.common.businessentities.StoragePool storagePool = getEntity( org.ovirt.engine.core.common.businessentities.StoragePool.class, VdcQueryType.GetStoragePoolsByStorageDomainId, new IdQueryParameters(guid), guid.toString() ); params.setStoragePoolId(storagePool.getId()); <START> return performAction(VdcActionType.ProcessOvfUpdateForStorageDomain, params); <END> }</code><technical_language>pass id parameter? I guess backend is retrieving storage pool, retrieving in this case</technical_language>

Target:
public Response updateOvfStore(Action action) { ProcessOvfUpdateForStorageDomainCommandParameters params = new ProcessOvfUpdateForStorageDomainCommandParameters(); params.setStorageDomainId(guid); return performAction(VdcActionType.ProcessOvfUpdateForStorageDomain, params); }
Source:
<code>public Medication deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context){ Medication u = null; try { try { u = g.fromJson(json, Medication.class); return u; } catch (JsonSyntaxException e) { } if (json.getAsJsonObject().get("Patient") != null) { json.getAsJsonObject().get("Patient").getAsJsonObject().remove("Med"); } u = g.fromJson(json, Medication.class); <START> logger.warn("json parsed successfully - by removing the 'Med' attribute"); <END> return u; } catch (Exception e) { logger.error("unexpected json error", e); } return u; }</code><technical_language>Refactor move code block catch, return statements necessary</technical_language>

Target:
public Medication deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context){ Medication u = null; try { try { u = g.fromJson(json, Medication.class); return u; } catch (JsonSyntaxException e) { if (json.getAsJsonObject().get("Patient") != null) { json.getAsJsonObject().get("Patient").getAsJsonObject().remove("Med"); } u = g.fromJson(json, Medication.class); logger.warn("json parsed successfully - by removing the 'Med' attribute"); } } catch (Exception e) { logger.error("unexpected json error", e); } return u; }
Source:
<code>private void recordHandlingError(Exception e) { <START> logger.error("Message handling error for request - " + request.getUri() + " - " + e); <END> nettyMetrics.handleRequestFailureCount.inc(); }</code><technical_language>logger.error (String, Throwable)</technical_language>

Target:
private void recordHandlingError(Exception e) { logger.error("Handling error for request - " + request.getUri(), e); nettyMetrics.handleRequestFailureCount.inc(); }
Source:
<code>public String docs() { return "array Returns an array of command arrays in the format register_command expects." <START> + " This does not include CommandHelper aliases, as they are not registered commands."; <END> }</code><technical_language>Implementation.GetServerType().getBranding() instead of hardcoding "CommandHelper"</technical_language>

Target:
public String docs() { return "array Returns an array of command arrays in the format register_command expects." + " This does not include " + Implementation.GetServerType().getBranding() + " aliases, as they are not registered commands."; }
Source:
<code>public static EnvironmentVariableConfig fromJSON(JsonObject jsonReader) { boolean secure = jsonReader.has("secure") && jsonReader.get("secure").getAsBoolean(); EnvironmentVariableConfig environmentVariableConfig = new EnvironmentVariableConfig(); environmentVariableConfig.setName(jsonReader.get("name").getAsString()); if (secure) { environmentVariableConfig.setEncryptedValue(jsonReader.get("encrypted_value").getAsString()); environmentVariableConfig.setIsSecure(secure); } else { <START> environmentVariableConfig.setValue(new VariableValueConfig(jsonReader.get("value").getAsString())); <END> } return environmentVariableConfig; }</code><technical_language>provide: { "name": "e", "secure": "true", "value": "to-be-encrypted-by-go" } this return { "name": "e", "secure": "true", "encrypted_value": "AES:encrypted" } a pain encryption API get encrypted in environments API? Also, <LINK_0> do same</technical_language>

Target:
public static EnvironmentVariableConfig fromJSON(JsonObject jsonReader) { EnvironmentVariableConfig environmentVariableConfig = new EnvironmentVariableConfig(); environmentVariableConfig.setName(jsonReader.get("name").getAsString()); environmentVariableConfig.setIsSecure(jsonReader.has("secure") && jsonReader.get("secure").getAsBoolean()); if (jsonReader.has("encrypted_value")) { environmentVariableConfig.setEncryptedValue(jsonReader.get("encrypted_value").getAsString()); } if (jsonReader.has("value")) { environmentVariableConfig.setValue(jsonReader.get("value").getAsString()); } return environmentVariableConfig; }
Source:
<code>public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { logger.trace("Removing the partition from sealedReplicas list", partitionId); sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { <START> logger.trace("Adding the partition from sealedReplicas list", partitionId); <END> sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } logger.trace("Set sealed state of partition is completed", partitionId); return success; }</code><technical_language>".. sealReplicas list"</technical_language>

Target:
public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { logger.trace("Removing the partition from sealReplicas list", partitionId); sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { logger.trace("Adding the partition from sealReplicas list", partitionId); sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } logger.trace("Set sealed state of partition is completed", partitionId); return success; }
Source:
<code>private BigintValuesUsingHashTable(long min, long max, long[] values, boolean nullAllowed) { super(true, nullAllowed); <START> requireNonNull(values, "values is null"); <END> checkArgument(min < max, "min must be less than max"); checkArgument(values.length > 1, "values must contain at least 2 entries"); this.min = min; this.max = max; this.values = values; this.size = Integer.highestOneBit(values.length * 3); this.hashTable = new long[size]; Arrays.fill(hashTable, EMPTY_MARKER); for (long value : values) { if (value == EMPTY_MARKER) { containsEmptyMarker = true; } else { int position = (int) ((value * M) & (size - 1)); for (int i = position; i < position + size; i++) { int index = i & (size - 1); if (hashTable[index] == EMPTY_MARKER) { hashTable[index] = value; break; } } } } }</code><technical_language>I check code, I assume single case, min == max, is handled separately</technical_language>

Target:
private BigintValuesUsingHashTable(long min, long max, long[] values, boolean nullAllowed) { super(true, nullAllowed); requireNonNull(values, "values is null"); checkArgument(min < max, "min must be less than max"); checkArgument(values.length > 1, "values must contain at least 2 entries"); this.min = min; this.max = max; this.size = Integer.highestOneBit(values.length * 3); this.hashTable = new long[size]; Arrays.fill(hashTable, EMPTY_MARKER); for (long value : values) { if (value == EMPTY_MARKER) { containsEmptyMarker = true; } else { int position = (int) ((value * M) & (size - 1)); for (int i = position; i < position + size; i++) { int index = i & (size - 1); if (hashTable[index] == EMPTY_MARKER) { hashTable[index] = value; break; } } } } }
Source:
<code>private void registerMetrics() { long intervalTallies[] = new long[INTERVALS.length]; for (String platform : PLATFORMS) { long platformTallies[] = activeUserCache.getFinalTallies(platform, INTERVALS); for (int i = 0; i < INTERVALS.length; i++) { final long tally = platformTallies[i]; logger.info(metricKey(platform, INTERVALS[i]) + " " + tally); <START> metricRegistry.register(metricKey(platform, INTERVALS[i]), <END> new Gauge<Long>() { @Override public Long getValue() { return tally; } }); intervalTallies[i] += tally; } } for (int i = 0; i < INTERVALS.length; i++) { final long intervalTotal = intervalTallies[i]; logger.info(metricKey(INTERVALS[i]) + " " + intervalTotal); metricRegistry.register(metricKey(INTERVALS[i]), new Gauge<Long>() { @Override public Long getValue() { return intervalTotal; } }); } for (ReporterFactory reporterFactory : configuration.getMetricsFactory().getReporters()) { ScheduledReporter reporter = reporterFactory.build(metricRegistry); logger.info("Reporting via: " + reporter); reporter.report(); logger.info("Reporting finished..."); } }</code><technical_language>this work? dynamically registering exact metric keys run? I throw illegalargumentexception time completed run? Is a reason dynamically register these</technical_language>

Target:
private void registerMetrics() { MetricRegistry metrics = new MetricRegistry(); long intervalTallies[] = new long[INTERVALS.length]; for (String platform : PLATFORMS) { long platformTallies[] = activeUserCache.getFinalTallies(platform, INTERVALS); for (int i = 0; i < INTERVALS.length; i++) { final long tally = platformTallies[i]; logger.info(metricKey(platform, INTERVALS[i]) + " " + tally); metrics.register(metricKey(platform, INTERVALS[i]), new Gauge<Long>() { @Override public Long getValue() { return tally; } }); intervalTallies[i] += tally; } } for (int i = 0; i < INTERVALS.length; i++) { final long intervalTotal = intervalTallies[i]; logger.info(metricKey(INTERVALS[i]) + " " + intervalTotal); metrics.register(metricKey(INTERVALS[i]), new Gauge<Long>() { @Override public Long getValue() { return intervalTotal; } }); } for (ReporterFactory reporterFactory : metricsFactory.getReporters()) { reporterFactory.build(metrics).report(); } }
Source:
<code>protected void subscribe() { eventService.subscribe( event -> { <START> String id = event.getId(); <END> Set<PathMatcher> pathMatchers = pathMatcherRegistry.getOrNull(id); registerConsumers(event.getLanguageServer(), pathMatchers); }, LanguageServerInitializedEvent.class); }</code><technical_language>If vars more once, inline them</technical_language>

Target:
protected void subscribe() { eventService.subscribe(this::acceptEvent, LanguageServerInitializedEvent.class); }
Source:
<code>public void testLinkUnwinderBadDomain() { LinkResolver resolver = new LinkResolver("http://nope@#$%"); resolver.run(); LinkDetails details = resolver.getLinkDetails(); <START> assertEquals("Should be 404", LinkDetails.LinkStatus.MALFORMED_URL, details.getLinkStatus()); <END> }</code><technical_language>this message changed "Should 500"</technical_language>

Target:
public void testLinkUnwinderBadDomain() { LinkResolver resolver = new LinkResolver("http://nope@#$%"); resolver.run(); LinkDetails details = resolver.getLinkDetails(); assertEquals("Should be 400", LinkDetails.LinkStatus.MALFORMED_URL, details.getLinkStatus()); }
Source:
<code>private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("0x%08x", packetLength) + " is causing buffer overrun."); } <START> if (blockLength > Integer.MAX_VALUE) { <END> throw new BadPcapFileException(String.format("0x%08x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength - 12); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("0x%08x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - 12); return pcapPacketData; }</code><technical_language>This is impossible, blockLength is int</technical_language>

Target:
private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("0x%08x", packetLength) + " is causing buffer overrun."); } if (blockLength > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("0x%08x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("0x%08x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength); return pcapPacketData; }
Source:
<code>Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { KeyOperationParameters parameters = new KeyOperationParameters().setAlgorithm(algorithm).setValue(plaintext); return service.encrypt(endpoint, keyName, version, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> <START> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); <END> }</code><technical_language>Nit: extra space algorithm param</technical_language>

Target:
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { KeyOperationParameters parameters = new KeyOperationParameters().setAlgorithm(algorithm).setValue(plaintext); return service.encrypt(vaultUrl, keyName, version, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
Source:
<code>public void testGetAbsoluteRemotePath() throws Exception { Node nodeA = j.createOnlineSlave(); String path = ((DumbSlave) nodeA).getComputer().getAbsoluteRemotePath(); <START> assert(path != null); <END> setAsAnonymous(); nodeA = j.createOnlineSlave(); path = ((DumbSlave) nodeA).getComputer().getAbsoluteRemotePath(); assert(path == null); }</code><technical_language>raw asserts (does work?), Assert.* JUnit</technical_language>

Target:
public void testGetAbsoluteRemotePath() throws Exception { Node nodeA = j.createOnlineSlave(); String path = ((DumbSlave) nodeA).getComputer().getAbsoluteRemotePath(); Assert.assertNotNull(path); Assert.assertEquals(getRemoteFS(nodeA, null), path); String userAlice = "alice"; MockAuthorizationStrategy authStrategy = new MockAuthorizationStrategy(); authStrategy.grant(Computer.CONFIGURE, Jenkins.READ).everywhere().to(userAlice); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(authStrategy); try(ACLContext context = ACL.as(User.getById(userAlice, true))) { nodeA = j.createOnlineSlave(); path = ((DumbSlave) nodeA).getComputer().getAbsoluteRemotePath(); Assert.assertNull(path); Assert.assertNull(getRemoteFS(nodeA, userAlice)); } }
Source:
<code>private static MkSocket createMockSocket() throws IOException { return new MkSocket( new ByteArrayInputStream( new JoinedText( BkBasicTest.CRLF, "GET / HTTP/1.1", BkBasicTest.HOST, "Content-Length: 2", "", "hi" <START> ).asString().getBytes() <END> ) ); }</code><technical_language>@sebing BytesOf</technical_language>

Target:
private static MkSocket createMockSocket() throws Exception { return new MkSocket( new ByteArrayInputStream( new BytesOf( new JoinedText( BkBasicTest.CRLF, "GET / HTTP/1.1", BkBasicTest.HOST, "Content-Length: 2", "", "hi" ) ).asBytes() ) ); }
Source:
<code>public void testGetChangedAttributesMultipleKind() { TaskAttribute attributeCustom = newData.getRoot().createAttribute("custom"); attributeCustom.setValue("1"); attributeCustom.getMetaData().setKind("kind"); TaskAttribute attributeSummary = newData.getRoot().createAttribute(TaskAttribute.SUMMARY); attributeSummary.setValue("1"); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); <START> List<TaskAttributeDiff> expected = Arrays.asList(new TaskAttributeDiff(null, attributeSummary), <END> new TaskAttributeDiff(null, attributeCustom)); assertEquals(new LinkedHashSet<ITaskAttributeDiff>(expected), diff.getChangedAttributes()); assertTrue(diff.hasChanged()); }</code><technical_language>pattern adopted is ImmutableList.of. In this case ImmutableSet of need create a LinkedHashSet</technical_language>

Target:
public void testGetChangedAttributesMultipleKind() { TaskAttribute attributeCustom = newData.getRoot().createAttribute("custom"); attributeCustom.setValue("1"); attributeCustom.getMetaData().setKind("kind"); TaskAttribute attributeSummary = newData.getRoot().createAttribute(TaskAttribute.SUMMARY); attributeSummary.setValue("1"); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(ImmutableSet.of(new TaskAttributeDiff(null, attributeSummary), new TaskAttributeDiff(null, attributeCustom)), diff.getChangedAttributes()); assertTrue(diff.hasChanged()); }
Source:
<code>private void processEvent(MessageDescription description) { <START> Event event = new Event(); <END> Map<String, Object> content = new HashMap<>(); Metadata details = new Metadata(); try { event.setPayload(objectMapper.readValue(description.getMessagePayload(), Map.class)); } catch (IOException e) { log.warn("Could not parse message payload as JSON", e); } content.put("messageDescription", description); details.setType(PubsubEventMonitor.PUBSUB_TRIGGER_TYPE); if (description.getMessageAttributes() != null) { details.setAttributes(description.getMessageAttributes()); } event.setContent(content); event.setDetails(details); pubsubEventMonitor.processEvent(event); }</code><technical_language>left in terms of logging process a message? This message specifically helpful for debugging, s/info/debug here</technical_language>

Target:
private void processEvent(MessageDescription description) { log.debug("Processing pubsub event with payload {}", description.getMessagePayload()); Event event = new Event(); Map<String, Object> content = new HashMap<>(); Metadata details = new Metadata(); try { event.setPayload(objectMapper.readValue(description.getMessagePayload(), Map.class)); } catch (IOException e) { log.warn("Could not parse message payload as JSON", e); } content.put("messageDescription", description); details.setType(PubsubEventMonitor.PUBSUB_TRIGGER_TYPE); if (description.getMessageAttributes() != null) { details.setAttributes(description.getMessageAttributes()); } event.setContent(content); event.setDetails(details); pubsubEventMonitor.processEvent(event); }
Source:
<code>public static BlockStateData parse(Material material, String state) throws InvalidBlockStateException { if (state == null || state.trim().isEmpty() || state.trim().equals("*")) { return new BlockStateData(); } BlockStateReader reader = getReader(material); if (material == null || reader == null) { throw new InvalidBlockStateException(material, state); } BlockStateData data = new BlockStateData(); <START> String[] split = state.trim().split(","); <END> for (String section : split) { if (!section.contains("=") || section.indexOf('=') != section.lastIndexOf('=')) { throw new InvalidBlockStateException(material, state); } String[] keyVal = section.split("="); keyVal[0] = keyVal[0].trim().toLowerCase(); keyVal[1] = keyVal[1].trim().toLowerCase(); if (keyVal[0].isEmpty() || keyVal[1].isEmpty()) { throw new InvalidBlockStateException(material, state); } if (!reader.getValidStates().contains(keyVal[0])) { throw new InvalidBlockStateException(material, state); } data.put(keyVal[0], keyVal[1]); } return data; }</code><technical_language>This is a case a small Regex expected syntax a bit clearer, reduce number of cases need check throw InvalidBlockStateException. regex want is "^\\s*((\\w+)\\s*=\\s*(\\w+))\\s*(,\\s*(\\w+)\\s*=\\s*(\\w+)\\s*)*$". intimidating, yes, is keeping compatibility trimmed code above. this regex, iterating groups (starting index 1 group index 0 *always* matches entire string), group out of three, represent entire "key=value" match</technical_language>

Target:
public static BlockStateData parse(Material material, String state) throws InvalidBlockStateException { if (state == null || state.trim().isEmpty() || state.trim().equals("*")) { return new BlockStateData(); } BlockStateReader reader = getReader(material); if (material == null || reader == null) { throw new InvalidBlockStateException(material, state); } BlockStateData data = new BlockStateData(); String[] split = state.trim().split(","); for (String section : split) { if (!section.contains("=") || section.indexOf('=') != section.lastIndexOf('=')) { throw new InvalidBlockStateException(material, state); } String[] keyVal = section.split("="); if (keyVal.length < 2) { throw new InvalidBlockStateException(material, state); } keyVal[0] = keyVal[0].trim().toLowerCase(); keyVal[1] = keyVal[1].trim().toLowerCase(); if (keyVal[0].isEmpty() || keyVal[1].isEmpty()) { throw new InvalidBlockStateException(material, state); } if (!reader.getValidStates().contains(keyVal[0])) { throw new InvalidBlockStateException(material, state); } data.put(keyVal[0], keyVal[1]); } return data; }
Source:
<code>public void beforeStageStarts() { UI.status = mock(StatusUI.class); UI.events = mock(EventDispatcher.class); Preferences prefs = Preferences.create(TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, <START> TestController.TEST_USER_CONFIG_FILENAME); <END> prefs.setLastLoginCredentials("test", "test"); prefs.setLastViewedRepository("test/test"); RepoIO testIO = TestController.createTestingRepoIO(Optional.empty()); testIO.setRepoOpControl(TestUtils.createRepoOpControlWithEmptyModels(testIO)); try { testIO.openRepository("test/test").get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }</code><technical_language>is a method do this in TestController</technical_language>

Target:
public void beforeStageStarts() { UI.status = mock(StatusUI.class); UI.events = mock(EventDispatcher.class); Preferences prefs = TestController.createTestPreferences(); prefs.setLastLoginCredentials("test", "test"); prefs.setLastViewedRepository("test/test"); RepoIO testIO = TestController.createTestingRepoIO(Optional.empty()); testIO.setRepoOpControl(TestUtils.createRepoOpControlWithEmptyModels(testIO)); try { testIO.openRepository("test/test").get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }
Source:
<code>public ConsumptionNotFoundException(Long consumptionId) { <START> super("Can't find a consumption with id: " + consumptionId + " is unsupported."); <END> }</code><technical_language>sentence odd, I change to: find consumption id:" + consumptionId</technical_language>

Target:
public ConsumptionNotFoundException(Long consumptionId) { super("Can't find a consumption with id: " + consumptionId); }
Source:
<code>public Map<String, String> getBuildVariables(AbstractBuild build, EnvInjectLogger logger) throws EnvInjectException { Map<String, String> result = new HashMap<String, String>(); result.putAll(build.getCharacteristicEnvVars()); try { EnvVars envVars = new EnvVars(); for (EnvironmentContributor ec : EnvironmentContributor.all()) { ec.buildEnvironmentFor(build, envVars, new LogTaskListener(LOG, Level.ALL)); result.putAll(envVars); } JDK jdk = build.getProject().getJDK(); if (jdk != null) { Node node = build.getBuiltOn(); if (node != null) { jdk = jdk.forNode(node, logger.getListener()); } jdk.buildEnvVars(result); } } catch (IOException ioe) { throw new EnvInjectException(ioe); } catch (InterruptedException ie) { throw new EnvInjectException(ie); } Executor e = build.getExecutor(); if (e != null) { result.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber())); } String rootUrl = Hudson.getInstance().getRootUrl(); if (rootUrl != null) { result.put("BUILD_URL", rootUrl + build.getUrl()); result.put("JOB_URL", rootUrl + build.getParent().getUrl()); } result.putAll(build.getBuildVariables()); Map<String, String> triggerVariable = new BuildCauseRetriever().getTriggeredCause(build); result.putAll(triggerVariable); <START> String userName = new BuildCauseRetriever().getCauseUserName(build); <END> if (userName != null){ result.put("USER_NAME", userName); } String userId = new BuildCauseRetriever().getCauseUserId(build); if (userId != null){ result.put("USER_ID", userId); } return result; }</code><technical_language>I refactor code call <code>new BuildCauseRetriever()</code> in order simplify life of garbage collector</technical_language>

Target:
public Map<String, String> getBuildVariables(AbstractBuild build, EnvInjectLogger logger) throws EnvInjectException { Map<String, String> result = new HashMap<String, String>(); result.putAll(build.getCharacteristicEnvVars()); try { EnvVars envVars = new EnvVars(); for (EnvironmentContributor ec : EnvironmentContributor.all()) { ec.buildEnvironmentFor(build, envVars, new LogTaskListener(LOG, Level.ALL)); result.putAll(envVars); } JDK jdk = build.getProject().getJDK(); if (jdk != null) { Node node = build.getBuiltOn(); if (node != null) { jdk = jdk.forNode(node, logger.getListener()); } jdk.buildEnvVars(result); } } catch (IOException ioe) { throw new EnvInjectException(ioe); } catch (InterruptedException ie) { throw new EnvInjectException(ie); } Executor e = build.getExecutor(); if (e != null) { result.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber())); } String rootUrl = Hudson.getInstance().getRootUrl(); if (rootUrl != null) { result.put("BUILD_URL", rootUrl + build.getUrl()); result.put("JOB_URL", rootUrl + build.getParent().getUrl()); } result.putAll(build.getBuildVariables()); Map<String, String> triggerVariable = new BuildCauseRetriever().getTriggeredCause(build); result.putAll(triggerVariable); return result; }