auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private void updateSpmPriority() { <END> if (spmPriorityValue == null) { setSpmPriority(null); } else if (spmPriorityValue == spmLowPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().lowTitle()); } else if (spmPriorityValue.equals(spmDefaultPriorityValue)) { setSpmPriority(ConstantsManager.getInstance().getConstants().mediumTitle()); } else if (spmPriorityValue == spmHighPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().highTitle()); } else if (spmPriorityValue == spmNeverPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().neverTitle()); } else { setSpmPriority(ConstantsManager.getInstance().getMessages().customSpmPriority(spmPriorityValue)); } }</code><technical_language>extract this logic view (into a new label/renderer)</technical_language>

Target:
private void updateSpmPriority() { Constants constants = ConstantsManager.getInstance().getConstants(); if (spmPriorityValue == null) { setSpmPriority(null); } else if (spmPriorityValue == spmLowPriorityValue) { setSpmPriority(constants.lowTitle()); } else if (spmPriorityValue.equals(spmDefaultPriorityValue)) { setSpmPriority(constants.mediumTitle()); } else if (spmPriorityValue == spmHighPriorityValue) { setSpmPriority(constants.highTitle()); } else if (spmPriorityValue == spmNeverPriorityValue) { setSpmPriority(constants.neverTitle()); } else { setSpmPriority(ConstantsManager.getInstance().getMessages().customSpmPriority(spmPriorityValue)); } }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; <START> result = prime * result + ((this.dayId == null) ? 0 : this.dayId.hashCode()); <END> result = prime * result + ((this.dayProfileActionList == null) ? 0 : this.dayProfileActionList.hashCode()); return result; }</code><technical_language>If fields null, check in other places (like in compareTo well), include null checks in equals/hashCode either</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.dayId.hashCode(); result = prime * result + this.dayProfileActionList.hashCode(); return result; }
Source:
<code>void leaveGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException { final NativeInetAddress g = NativeInetAddress.newInstance(group); final NativeInetAddress i = NativeInetAddress.newInstance( deriveInetAddress(netInterface, group instanceof Inet6Address) <START> ); <END> if (source != null) { final NativeInetAddress s = NativeInetAddress.newInstance(source); leaveSsmGroup(intValue(), g.address(), i.address(), g.scopeId(), s.address()); } else { leaveGroup(intValue(), g.address(), i.address(), g.scopeId()); } }</code><technical_language>change coding style match in Netty</technical_language>

Target:
void leaveGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException { final NativeInetAddress g = NativeInetAddress.newInstance(group); final boolean isIpv6 = group instanceof Inet6Address; final NativeInetAddress i = NativeInetAddress.newInstance(deriveInetAddress(netInterface, isIpv6)); if (source != null) { final NativeInetAddress s = NativeInetAddress.newInstance(source); leaveSsmGroup(intValue(), g.address(), i.address(), g.scopeId(), s.address()); } else { leaveGroup(intValue(), g.address(), i.address(), g.scopeId()); } }
Source:
<code>public void rollbackTo(Savepoint savepoint, boolean trimToSize) { int index = savepoint == null ? 0 : savepoint.logIndex; while (undoLog.size() > index) { UndoLogRecord entry = undoLog.getLast(); entry.undo(this); undoLog.removeLast(trimToSize); } if (transaction != null) { long savepointId = savepoint == null ? 0 : savepoint.transactionSavepoint; HashMap<String, MVTable> tableMap = database.getMvStore().getTables(); Iterator<Change> it = transaction.getChanges(savepointId); while (it.hasNext()) { Change c = it.next(); MVTable t = tableMap.get(c.mapName); if (t != null) { long key = ((ValueLong) c.key).getLong(); ValueArray value = (ValueArray) c.value; short op; Row row; if (value == null) { op = UndoLogRecord.INSERT; row = t.getRow(this, key); } else { op = UndoLogRecord.DELETE; row = createRow(value.getList(), Row.MEMORY_CALCULATE); } row.setKey(key); UndoLogRecord log = new UndoLogRecord(t, op, row); log.undo(this); } } } if (savepoints != null) { <START> String[] names = savepoints.keySet().toArray(new String[0]); <END> for (String name : names) { Savepoint sp = savepoints.get(name); int savepointIndex = sp.logIndex; if (savepointIndex > index) { savepoints.remove(name); } } } }</code><technical_language>here. Revert changes collections</technical_language>

Target:
public void rollbackTo(Savepoint savepoint, boolean trimToSize) { int index = savepoint == null ? 0 : savepoint.logIndex; while (undoLog.size() > index) { UndoLogRecord entry = undoLog.getLast(); entry.undo(this); undoLog.removeLast(trimToSize); } if (transaction != null) { long savepointId = savepoint == null ? 0 : savepoint.transactionSavepoint; HashMap<String, MVTable> tableMap = database.getMvStore().getTables(); Iterator<Change> it = transaction.getChanges(savepointId); while (it.hasNext()) { Change c = it.next(); MVTable t = tableMap.get(c.mapName); if (t != null) { long key = ((ValueLong) c.key).getLong(); ValueArray value = (ValueArray) c.value; short op; Row row; if (value == null) { op = UndoLogRecord.INSERT; row = t.getRow(this, key); } else { op = UndoLogRecord.DELETE; row = createRow(value.getList(), Row.MEMORY_CALCULATE); } row.setKey(key); UndoLogRecord log = new UndoLogRecord(t, op, row); log.undo(this); } } } if (savepoints != null) { String[] names = savepoints.keySet().toArray(new String[savepoints.size()]); for (String name : names) { Savepoint sp = savepoints.get(name); int savepointIndex = sp.logIndex; if (savepointIndex > index) { savepoints.remove(name); } } } }
Source:
<code>public void startScreencast(final JsonRpcPeer peer, JSONObject params) { final StartScreencastRequest request = mObjectMapper.convertValue( params, StartScreencastRequest.class); <START> mScreencastDispatcher.startScreencast(peer, request); <END> }</code><technical_language>if multiple peers want initiate screencasting</technical_language>

Target:
public void startScreencast(final JsonRpcPeer peer, JSONObject params) { final StartScreencastRequest request = mObjectMapper.convertValue( params, StartScreencastRequest.class); if (mScreencastDispatcher == null) { mScreencastDispatcher = new ScreencastDispatcher(); mScreencastDispatcher.startScreencast(peer, request); } }
Source:
<code>public Identity decode(final byte[] bytes) throws IOException { <START> final byte[] raw = Base64.decodeBase64(bytes); <END> return this.origin.decode(raw); }</code><technical_language>@ikhvostenkov this variable inlined</technical_language>

Target:
public Identity decode(final byte[] bytes) throws IOException { return this.origin.decode(bytes); }
Source:
<code>public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } else { CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); <START> if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { <END> return false; } return true; } }</code><technical_language>avoid scheduling flows in past. right ? please add a small note. nit: else statement is required</technical_language>

Target:
public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { return false; } return true; }
Source:
<code>public DeclarationScope(DeclarationScope parentScope) { <START> this.fParentScope = parentScope; <END> }</code><technical_language>remove this</technical_language>

Target:
public DeclarationScope(DeclarationScope parentScope) { fParentScope = parentScope; }
Source:
<code>static Stream<Map<String, String>> provider() { Map<String, String> sampleMap = new HashMap<>(); sampleMap.put("header", "value"); <START> sampleMap.put("test", "3"); <END> return Stream.of( sampleMap, Collections.singletonMap("header", String.valueOf(Integer.MAX_VALUE)), Collections.emptyMap()); }</code><technical_language>empty string a value</technical_language>

Target:
static Stream<Map<String, String>> provider() { Map<String, String> sampleMap = new HashMap<>(); sampleMap.put("header", "value"); sampleMap.put("test", "3"); return Stream.of( sampleMap, Collections.singletonMap("header", String.valueOf(Integer.MAX_VALUE)), Collections.emptyMap(), Collections.singletonMap("", ""), Collections.singletonMap("header", ""), Collections.singletonMap("", "value")); }
Source:
<code>public void testUndefinedRegion() { final KeystoneStorageEndpointModule moduleToTest = new KeystoneStorageEndpointModule(); Supplier<URI> resultingSupplier = moduleToTest.provideStorageUrl(mockFactory, apiVersion, "region-that-dne"); Assert.assertNotNull(resultingSupplier); URI resultingUri = resultingSupplier.get(); <START> Assert.assertNull(resultingUri); <END> }</code><technical_language>Static import Assert.* in tests</technical_language>

Target:
public void testUndefinedRegion() { final KeystoneStorageEndpointModule moduleToTest = new KeystoneStorageEndpointModule(); Supplier<URI> resultingSupplier = moduleToTest.provideStorageUrl(mockFactory, apiVersion, "region-that-dne"); assertNotNull(resultingSupplier); URI resultingUri = resultingSupplier.get(); assertNull(resultingUri); }
Source:
<code>private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver(uploadId, chunkData, writeOffset, objectHasher); stub.insertObject(responseObserver); responseObserver.done.await(); writeOffset += responseObserver.bytesWritten(); } while (!responseObserver.isFinished()); if (responseObserver.hasError()) { <START> logger.atSevere().withCause(responseObserver.getError()).log("Error:"); <END> throw new IOException("Insert failed", responseObserver.getError()); } return responseObserver.getResponse(); }</code><technical_language>Remove this log statement this is anti-pattern - need throw log, both</technical_language>

Target:
private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver(uploadId, chunkData, writeOffset, objectHasher); stub.insertObject(responseObserver); responseObserver.done.await(); writeOffset += responseObserver.bytesWritten(); } while (!responseObserver.isFinished()); if (responseObserver.hasError()) { throw new IOException("Insert failed", responseObserver.getError()); } return responseObserver.getResponse(); }
Source:
<code>public Map getParameterValues() { <START> if (bndrunFilesMap != null) { <END> return bndrunFilesMap; } IWorkspaceRoot root = ResourcesPlugin.getWorkspace() .getRoot(); synchronized (root) { if (bndrunFilesMap == null) { bndrunFilesMap = Arrays.stream(root.getProjects()) .filter(IProject::isOpen) .map(this::findBndrunFiles) .flatMap(Collection::stream) .map(IResource::getFullPath) .collect(toMap(IPath::toPortableString, IPath::toPortableString)); ResourcesPlugin.getWorkspace() .addResourceChangeListener(listener); } } return bndrunFilesMap; }</code><technical_language>This a perfect place for a memoizier get lazy initialization properly handle synchronization for at-most-once initialization</technical_language>

Target:
public Map getParameterValues() { return bndrunFilesMap.get(); }
Source:
<code>protected Extent getExtent() { <START> if (extent == null) { <END> extent = Request.request().getEditSession(); } return extent; }</code><technical_language>caching now, EditSession's lifetime is guaranteed greater of RequestExtent? if player leaves? problem lazy initialization in face of unclear object lifetimes is problems show later, a common cases lifetime of referenced object time referenced, rare cases is over, giving bugs hard diagnose on</technical_language>

Target:
protected Extent getExtent() { if (request == null || !request.isValid()) { request = Request.request(); } return request.getEditSession(); }
Source:
<code>private void loadToplist(String country) { if (disposable != null) { disposable.dispose(); } gridView.setVisibility(View.GONE); txtvError.setVisibility(View.GONE); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); if (country.equals(ItunesTopListLoader.DISCOVER_HIDE_FAKE_COUNTRY_CODE)) { gridView.setVisibility(View.GONE); txtvError.setVisibility(View.VISIBLE); txtvError.setText(String.format(getResources().getString(R.string.discover_will_be_hidden), getResources().getString(R.string.discover_hide))); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); } else { ItunesTopListLoader loader = new ItunesTopListLoader(getContext()); disposable = loader.loadToplist(country, 25).subscribe( podcasts -> { progressBar.setVisibility(View.GONE); topList = podcasts; <START> updateData(topList); }, <END> error -> { Log.e(TAG, Log.getStackTraceString(error)); progressBar.setVisibility(View.GONE); txtvError.setText(error.toString()); txtvError.setVisibility(View.VISIBLE); butRetry.setOnClickListener(v -> loadToplist(country)); butRetry.setVisibility(View.VISIBLE); }); } }</code><technical_language>Oh, nice :) I this is Checkstyle happy multiple lambda functions. I indention for success error</technical_language>

Target:
private void loadToplist(String country) { if (disposable != null) { disposable.dispose(); } gridView.setVisibility(View.GONE); txtvError.setVisibility(View.GONE); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); if (country.equals(ItunesTopListLoader.DISCOVER_HIDE_FAKE_COUNTRY_CODE)) { gridView.setVisibility(View.GONE); txtvError.setVisibility(View.VISIBLE); txtvError.setText(getResources().getString(R.string.discover_is_hidden)); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); } else { ItunesTopListLoader loader = new ItunesTopListLoader(getContext()); disposable = loader.loadToplist(country, 25).subscribe( podcasts -> { progressBar.setVisibility(View.GONE); topList = podcasts; updateData(topList); }, error -> { Log.e(TAG, Log.getStackTraceString(error)); progressBar.setVisibility(View.GONE); txtvError.setText(error.getMessage()); txtvError.setVisibility(View.VISIBLE); butRetry.setOnClickListener(v -> loadToplist(country)); butRetry.setVisibility(View.VISIBLE); }); } }
Source:
<code>private static MethodTree usedInOneMethodOnly(Symbol privateFieldSymbol, TypeSymbol classSymbol) { <START> Set<MethodTree> methods = new HashSet<>(); <END> for (IdentifierTree usageIdentifier : privateFieldSymbol.usages()) { Tree containingClassOrMethod = containingClassOrMethod(usageIdentifier); if (containingClassOrMethod.is(Kind.CLASS) || !((MethodTree) containingClassOrMethod).symbol().owner().equals(classSymbol) || (methods.size() == 1 && !methods.contains(containingClassOrMethod))) { return null; } else { methods.add((MethodTree)containingClassOrMethod); } } return methods.iterator().next(); }</code><technical_language>need for a set a variable check nullity of difference currently set MethodTree</technical_language>

Target:
private static MethodTree usedInOneMethodOnly(Symbol privateFieldSymbol, TypeSymbol classSymbol) { MethodTree method = null; for (IdentifierTree usageIdentifier : privateFieldSymbol.usages()) { Tree containingClassOrMethod = containingClassOrMethod(usageIdentifier); if (containingClassOrMethod.is(Kind.CLASS) || !((MethodTree) containingClassOrMethod).symbol().owner().equals(classSymbol) || (method != null && !method.equals(containingClassOrMethod))) { return null; } else { method = (MethodTree)containingClassOrMethod; } } return method; }
Source:
<code>public void passesValidationForClasspathSchema() throws Exception { final Environment env = new Environment.Mock().withFile( "test-classpath-schema.xml", new StringBuilder() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<foo xmlns=\"<LINK_0>\" ") .append("xmlns:xsi=\"") .append("<LINK_1>") .append("\" ") .append("xsi:schemaLocation=\"") .append("<LINK_0> ") .append("test-classpath-schema.xsd") .append("\">") .append("<bar>333</bar>") .append("<baz>444</baz>") .append("</foo>").toString() ); <START> final Validator validator = new XmlValidator(); <END> validator.validate(env); }</code><technical_language>@carlosmiranda inline this</technical_language>

Target:
public void passesValidationForClasspathSchema() throws Exception { final Environment env = new Environment.Mock().withFile( "test-classpath-schema.xml", new StringBuilder() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<foo xmlns=\"<LINK_0>\" ") .append("xmlns:xsi=\"") .append("<LINK_1>") .append("\" ") .append("xsi:schemaLocation=\"") .append("<LINK_0> ") .append("test-classpath-schema.xsd") .append("\">") .append("<bar>333</bar>") .append("<baz>444</baz>") .append("</foo>").toString() ); new XmlValidator().validate(env); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (decodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( <START> String.format("Field %s is of type %s in Input Schema, currently only String and Bytes can be decoded", <END> field.getName(), field.getSchema().getType())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }</code><technical_language>error message for consistency: "Field %s of type bytes string. is currently of type %s"</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (decodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( String.format("Input field %s should be of type bytes or string. It is currently of type %s", field.getName(), field.getSchema().getType().toString())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }
Source:
<code>protected void done() { if (!isCancelled() && this.owningTask != null) { this.owningTask.cancel(); } <START> super.done(); <END> }</code><technical_language>I a problem is making a call get() set. this for some long hangs</technical_language>

Target:
protected void done() { if (!isCancelled() && this.owningTask != null) { this.owningTask.cancel(); } }
Source:
<code>public void shutdown() { <START> initialized = false; <END> }</code><technical_language>cleanup</technical_language>

Target:
public void shutdown() { JOpenVRLibrary.VR_ShutdownInternal(); vrSystem = null; vrCompositor = null; vrOverlay = null; vrSettings = null; vrState = null; initialized = false; }
Source:
<code>public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() <START> .filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() >= trimMark) <END> .map(segment -> { long segmentStart = Math.max(segment.getStart(), trimMark); long segmentEnd = segment.getEnd() - 1L; if (segmentContainsServer(segment, getServer())) { TransferSegmentStatus restored = TransferSegmentStatus .builder() .segmentState(RESTORED) .totalTransferred(segmentEnd - segmentStart + 1L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(restored) .build(); } else { TransferSegmentStatus notTransferred = TransferSegmentStatus .builder() .segmentState(NOT_TRANSFERRED) .totalTransferred(0L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(notTransferred) .build(); } }) .collect(ImmutableList.toImmutableList()); }</code><technical_language>segment end is exclusive, trimMark is starting address, >= include a invalid segment</technical_language>

Target:
public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() .filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() > trimMark) .map(segment -> { long segmentStart = Math.max(segment.getStart(), trimMark); long segmentEnd = segment.getEnd() - 1L; if (segmentContainsServer(segment, getServer())) { TransferSegmentStatus restored = TransferSegmentStatus .builder() .segmentState(RESTORED) .totalTransferred(segmentEnd - segmentStart + 1L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(restored) .build(); } else { TransferSegmentStatus notTransferred = TransferSegmentStatus .builder() .segmentState(NOT_TRANSFERRED) .totalTransferred(0L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(notTransferred) .build(); } }) .collect(ImmutableList.toImmutableList()); }
Source:
<code>protected static String parseString(final String unformattedString, final Matcher m, final MonitoredService svc) { Pattern p = subPatterns.get(m.group(1)); if (p != null) { } else { LOG.error("invalid substitution pattern found: {}", m.group(1)); return null; } Matcher n = p.matcher(unformattedString); String formattedString; if (n.matches()) { StringBuilder sb = new StringBuilder(); sb.append(n.group(1)); switch (m.group(1)) { case "ipAddr": case "ipAddress": sb.append(svc.getIpAddr()); break; case "nodeId": sb.append(svc.getNodeId()); break; case "nodeLabel": sb.append(svc.getNodeLabel()); break; case "foreignId": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignId()); break; case "foreignSource": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignSource()); break; default: LOG.debug("attempting to add node asset property {}", m.group(1)); OnmsNode node = nodeDao.get().get(svc.getNodeId()); if (node != null) { BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord()); Object obj = wrapper.getPropertyValue(m.group(1)); if (obj != null) { sb.append(obj.toString()); } } } sb.append(n.group(2)); formattedString = sb.toString(); } else { <START> throw new IllegalStateException("Engineering mistake: the regular expression seems to be wrong."); <END> } Matcher o = substitutionPattern.matcher(formattedString); if (o.matches()) { return parseString(formattedString, o, svc); } return formattedString; }</code><technical_language>include expression in error message</technical_language>

Target:
protected static String parseString(final String unformattedString, final Matcher m, final MonitoredService svc) { Pattern p = subPatterns.get(m.group(1)); if (p != null) { } else { LOG.error("invalid substitution pattern found: {}", m.group(1)); return null; } Matcher n = p.matcher(unformattedString); String formattedString; if (n.matches()) { StringBuilder sb = new StringBuilder(); sb.append(n.group(1)); switch (m.group(1)) { case "ipAddr": case "ipAddress": sb.append(svc.getIpAddr()); break; case "nodeId": sb.append(svc.getNodeId()); break; case "nodeLabel": sb.append(svc.getNodeLabel()); break; case "foreignId": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignId()); break; case "foreignSource": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignSource()); break; default: LOG.debug("attempting to add node asset property {}", m.group(1)); OnmsNode node = nodeDao.get().get(svc.getNodeId()); if (node != null) { BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord()); Object obj = wrapper.getPropertyValue(m.group(1)); if (obj != null) { sb.append(obj.toString()); } } } sb.append(n.group(2)); formattedString = sb.toString(); } else { throw new IllegalStateException( String.format("Engineering mistake: we should never end up here, the regular expression seems to have a problem: %s", substitutionPattern.toString())); } Matcher o = substitutionPattern.matcher(formattedString); if (o.matches()) { return parseString(formattedString, o, svc); } return formattedString; }
Source:
<code>public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { <START> this(artifacts, excludes, latestOnly, false, false, true); <END> }</code><technical_language>this change</technical_language>

Target:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { this(artifacts, excludes, latestOnly, false, false); }
Source:
<code>private static int indexOfEOS(byte[] data, int fromIndex, int encodingByte) { int terminationPos = indexOf(data, fromIndex, (byte) 0); if(encodingByte == ID3_TEXT_ENCODING_ISO_8859_1 || encodingByte == ID3_TEXT_ENCODING_UTF_8) { return terminationPos; } while(terminationPos < data.length - 1) { if(data[terminationPos + 1] == (byte) 0) { <START> return terminationPos + 1; <END> } terminationPos = indexOf(data, terminationPos + 1, (byte) 0); } return data.length; }</code><technical_language>This returns index of delimiter index of byte of delimiter. this 0 byte part of string</technical_language>

Target:
private static int indexOfEOS(byte[] data, int fromIndex, int encodingByte) { int terminationPos = indexOf(data, fromIndex, (byte) 0); if(encodingByte == ID3_TEXT_ENCODING_ISO_8859_1 || encodingByte == ID3_TEXT_ENCODING_UTF_8) { return terminationPos; } while(terminationPos < data.length - 1) { if(data[terminationPos + 1] == (byte) 0) { return terminationPos; } terminationPos = indexOf(data, terminationPos + 1, (byte) 0); } return data.length; }
Source:
<code>private void InitializeHelpers() { try { for (String helperName : EnumCompat.GetNames(StorageType.class)) { <START> java.lang.Class actionType = null; <END> try { actionType = java.lang.Class.forName(String.format("%1$s.%2$s%3$s", "org.ovirt.engine.core.bll.storage", helperName, "StorageHelper")); } catch (ClassNotFoundException cnfe) { } if (actionType != null) { java.lang.reflect.Constructor<?> info = actionType.getConstructors()[0]; Object tempVar = info.newInstance(null); IStorageHelper currentHelper = (IStorageHelper) ((tempVar instanceof IStorageHelper) ? tempVar : null); if (currentHelper != null) { _helpers.put(StorageType.valueOf(helperName), currentHelper); } } } } catch (Exception ex) { throw new ApplicationException("JTODO missing exception", ex); } }</code><technical_language>change done - is type of warning</technical_language>

Target:
private void InitializeHelpers() { try { for (String helperName : EnumCompat.GetNames(StorageType.class)) { java.lang.Class<?> actionType = null; try { actionType = java.lang.Class.forName(String.format("%1$s.%2$s%3$s", "org.ovirt.engine.core.bll.storage", helperName, "StorageHelper")); } catch (ClassNotFoundException cnfe) { } if (actionType != null) { java.lang.reflect.Constructor info = actionType.getConstructors()[0]; Object tempVar = info.newInstance(null); IStorageHelper currentHelper = (IStorageHelper) ((tempVar instanceof IStorageHelper) ? tempVar : null); if (currentHelper != null) { _helpers.put(StorageType.valueOf(helperName), currentHelper); } } } } catch (Exception ex) { throw new ApplicationException("JTODO missing exception", ex); } }
Source:
<code>public void close() { <START> clusterMembership.unregisterProcessor(); <END> }</code><technical_language>instead track invocation short circuit here</technical_language>

Target:
public void close() { if (!closed && processorId != null) { closed = true; clusterMembership.unregisterProcessor(processorId); } }
Source:
<code>public int updateExperiment(String expID, HashMap<String, String> annotations) throws SQLException, IOException { for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); e.setValue(validateAnnotation(key, value)); } String query = "UPDATE Annotated_With SET Value = ?" + " WHERE (Label ~~* ?) AND (ExpID ~~* ?)"; int rs = 0; ArrayList<String> keys = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(query);) { conn.setAutoCommit(false); for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); keys.add(key); stmt.setString(1, value); stmt.setString(2, key); stmt.setString(3, expID); stmt.addBatch(); } int arr[] = stmt.executeBatch(); for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { String label = keys.get(i); String value = annotations.get(label); <START> arr[i] = annotateExperiment(expID, label, value); <END> } rs += arr[i]; } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } return rs; }</code><technical_language>annotateExperiment throw IOExceptions. want catch well</technical_language>

Target:
public int updateExperiment(String expID, HashMap<String, String> annotations) throws SQLException, IOException { for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); e.setValue(validateAnnotation(key, value)); } String query = "UPDATE Annotated_With SET Value = ?" + " WHERE (Label ~~* ?) AND (ExpID ~~* ?)"; int rs = 0; ArrayList<String> keys = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(query);) { conn.setAutoCommit(false); for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); keys.add(key); stmt.setString(1, value); stmt.setString(2, key); stmt.setString(3, expID); stmt.addBatch(); } int arr[] = stmt.executeBatch(); for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { String label = keys.get(i); String value = annotations.get(label); arr[i] = annotateExperiment(expID, label, value); } rs += arr[i]; } conn.commit(); } catch (SQLException | IOException e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } return rs; }
Source:
<code>public WebSocketClientHandshaker08 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { <START> this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; <END> return this; }</code><technical_language>nit: jut call super.setForceCloseTimeoutMillis(...) this ensure do correct if change super method content allow forceCloseTimeMillis private</technical_language>

Target:
public WebSocketClientHandshaker08 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis); return this; }
Source:
<code>public void forEachTuple(final ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) { <START> <END> for ( EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas ) { KeyScanCursor<byte[]> cursor = null; String pattern = entityKeyMetadata.getTable() + ":*"; do { if ( cursor != null ) { cursor = connection.scan( cursor, ScanArgs.Builder.matches( pattern ) ); } else { cursor = connection.scan( ScanArgs.Builder.matches( pattern ) ); } for ( byte[] key : cursor.getKeys() ) { String type = connection.type( key ); EntityStorageStrategy entityStorageStrategy; if ( "hash".equalsIgnoreCase( type ) ) { entityStorageStrategy = entityStorageStrategies.get( EntityStorageType.HASH ); } else { entityStorageStrategy = entityStorageStrategies.get( EntityStorageType.JSON ); } Entity document = entityStorageStrategy.getEntity( key ); consumer.consume( new Tuple( new RedisTupleSnapshot( document.getProperties() ) ) ); } } while ( !cursor.isFinished() ); } }</code><technical_language>do empty lines method name. I care much, a uncommon flow stop for a sec reading code</technical_language>

Target:
public void forEachTuple(final ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) { for ( EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas ) { KeyScanCursor<byte[]> cursor = null; String prefix = entityKeyMetadata.getTable() + ":"; byte[] prefixBytes = toBytes( prefix ); ScanArgs scanArgs = ScanArgs.Builder.matches( prefix + "*" ); do { if ( cursor != null ) { cursor = connection.scan( cursor, scanArgs ); } else { cursor = connection.scan( scanArgs ); } for ( byte[] key : cursor.getKeys() ) { String type = connection.type( key ); Entity document = entityStorageStrategy.getEntity( key ); addKeyValuesFromKeyName( entityKeyMetadata, prefixBytes, key, document ); consumer.consume( new Tuple( new RedisTupleSnapshot( document.getProperties() ) ) ); } } while ( !cursor.isFinished() ); } }
Source:
<code>@Override public Iterator<E> iterator() { lock.lock(); try { <START> return queue.iterator(); <END> } finally { lock.unlock(); } }</code><technical_language>is locking while creating this factory necessary? iterator iterates backing ObjectQueue (not a clone of anything)</technical_language>

Target:
@Override public Iterator<E> iterator() { return queue.iterator(); }
Source:
<code>public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), null, new int[] {0, 2, 4}, someIndex())) .withMessage(actualIsNull()); <START> } <END></code><technical_language>I prefer follow test style for isDeepEquals this java // int[][] actual = null; int[] expectedElement = new int[] {0, 2, 4}; // AssertionError assertionError = expectAssertionError(() -> arrays.assertContains(someInfo(), actual, expectedElement, someIndex())); // then(assertionError).hasMessage(shouldNotBeNull().create()); I find clearer</technical_language>

Target:
public void should_fail_if_actual_is_null() { int[][] actual = null; int[] expectedElement = new int[] {0, 2, 4}; AssertionError assertionError = expectAssertionError(() -> arrays.assertContains(someInfo(), actual, expectedElement, someIndex())); then(assertionError).hasMessage(shouldNotBeNull().create()); }
Source:
<code>public RulesetMetadata processElement(ParserContext context, Element element) throws ConfigurationException { List<Element> children = $(element).children().get(); MetadataBuilder metadataBuilder = context.getBuilder().getMetadataBuilder(); for (Element child : children) { Object result = context.processElement(child); <START> switch ($(child).tag()) <END> { case "dependencies": List<AddonId> resultList = (List<AddonId>)result; for(AddonId id : resultList) { metadataBuilder.addRequiredAddon(id); } break; case "sourcePlatform": metadataBuilder.addSourceTechnology((TechnologyReference)result); break; case "sourceFramework": metadataBuilder.addSourceTechnology((TechnologyReference)result); break; case "targetPlatform": metadataBuilder.addTargetTechnology((TechnologyReference)result); break; case "targetFramework": metadataBuilder.addTargetTechnology((TechnologyReference)result); break; case "tags": List<String> tagList = (List<String>)result; for(String tag : tagList) { metadataBuilder.addTag(tag); } break; case "executeAfter": metadataBuilder.addExecuteAfterId((String)result); break; case "executeBefore": metadataBuilder.addExecuteBeforeId((String)result); break; } } return metadataBuilder; }</code><technical_language>Good</technical_language>

Target:
public RulesetMetadata processElement(ParserContext context, Element element) throws ConfigurationException { List<Element> children = $(element).children().get(); MetadataBuilder metadataBuilder = context.getBuilder().getMetadataBuilder(); for (Element child : children) { Object result = context.processElement(child); switch ($(child).tag()) { case "dependencies": List<AddonId> resultList = (List<AddonId>)result; for(AddonId id : resultList) { metadataBuilder.addRequiredAddon(id); } break; case "sourceTechnology": metadataBuilder.addSourceTechnology((TechnologyReference)result); break; case "targetTechnology": metadataBuilder.addTargetTechnology((TechnologyReference)result); break; case "tags": List<String> tagList = (List<String>)result; for(String tag : tagList) { metadataBuilder.addTag(tag); } break; case "executeAfter": metadataBuilder.addExecuteAfterId((String)result); break; case "executeBefore": metadataBuilder.addExecuteBeforeId((String)result); break; } } return metadataBuilder; }
Source:
<code>public static String[] getMonthsArray(String key){ <START> System.out.println("Getting months array with key: " + key + ", source: " + arrayDataSource); <END> return arrayDataSource.getArray(key); }</code><technical_language>eliminate this. get verbose if bulk calculations</technical_language>

Target:
public static String[] getMonthsArray(String key){ return arrayDataSource.getArray(key); }
Source:
<code>public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_API_KEY"))) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); <START> String document = "My SSN is 555-55-5555"; <END> client.recognizePiiEntities(document).forEach(entity -> System.out.printf( "Recognized personal identifiable information entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); }</code><technical_language>consider 859-98-0987. for other places</technical_language>

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); String document = "My SSN is 859-98-0987"; client.recognizePiiEntities(document).forEach(entity -> System.out.printf( "Recognized Personal Identifiable Information entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); }
Source:
<code>void testInsertEntryWithEmptyFields() throws SQLException { BibEntry expectedEntry = new BibEntry(StandardEntryType.Article); dbmsProcessor.insertEntry(expectedEntry); BibEntry emptyEntry = getBibEntryExample(); emptyEntry.getSharedBibEntryData().setSharedID(1); dbmsProcessor.insertEntry(emptyEntry); Map<String, String> actualFieldMap = new HashMap<>(); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(1, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertFalse(entryResultSet.next()); try (ResultSet fieldResultSet = selectFrom("FIELD", dbmsConnection, dbmsProcessor)) { while (fieldResultSet.next()) { actualFieldMap.put(fieldResultSet.getString("NAME"), fieldResultSet.getString("VALUE")); } } } <START> Map<String, String> expectedFieldMap = expectedEntry.getFieldMap().entrySet().stream().collect(Collectors.toMap((entry) -> entry.getKey().getName(), Map.Entry::getValue)); <END> assertEquals(expectedFieldMap, actualFieldMap); }</code><technical_language>this empty list (as expected entry is empty)</technical_language>

Target:
void testInsertEntryWithEmptyFields() throws SQLException { BibEntry expectedEntry = new BibEntry(StandardEntryType.Article); dbmsProcessor.insertEntry(expectedEntry); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(1, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertFalse(entryResultSet.next()); try (ResultSet fieldResultSet = selectFrom("FIELD", dbmsConnection, dbmsProcessor)) { assertFalse(fieldResultSet.next()); } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_apps_limit_view); <START> TextView mulitpleAppLimitTextView = findViewById(R.id.mulitple_app_limit_textview); <END> String text = StringUtils.getStringRobust(this, R.string.multiple_apps_limit_message, String.valueOf(CommCareSetupActivity.MAX_ALLOWED_APPS)); mulitpleAppLimitTextView.setText(text); boolean installAttemptCameFromAppManager = getIntent() .getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); setupUI(installAttemptCameFromAppManager); }</code><technical_language>this code block in setupUI</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_apps_limit_view); boolean installAttemptCameFromAppManager = getIntent() .getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); setupUI(installAttemptCameFromAppManager); }
Source:
<code>public static String documentToString(Document doc) { String strMsg = ""; try { DOMImplementation domImpl = doc.getImplementation(); DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0"); LSSerializer lsSerializer = domImplLS.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", true); Writer stringWriter = new StringWriter(); LSOutput lsOutput = domImplLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); lsOutput.setCharacterStream(stringWriter); lsSerializer.write(doc, lsOutput); strMsg = stringWriter.toString(); } catch (Exception e) { <START> e.printStackTrace(); <END> } return strMsg; }</code><technical_language>replace this occurrences of printStackTrace logger.warn in code (since making other fixes)? Bindings print stdout stderr instead log4j</technical_language>

Target:
public static String documentToString(Document doc) { String strMsg = ""; try { DOMImplementation domImpl = doc.getImplementation(); DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0"); LSSerializer lsSerializer = domImplLS.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", true); Writer stringWriter = new StringWriter(); LSOutput lsOutput = domImplLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); lsOutput.setCharacterStream(stringWriter); lsSerializer.write(doc, lsOutput); strMsg = stringWriter.toString(); } catch (Exception e) { logger.warn("Error occured when converting document to string", e); } return strMsg; }
Source:
<code>private String serialize(Object object) { String json = null; try { <START> objectMapper.writeValueAsString(object); <END> } catch (JsonProcessingException e) { log.severe("Failed to serialize trace", e); } return json; }</code><technical_language>is assigned json</technical_language>

Target:
private String serialize(Object object) { String json = null; try { json = objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { log.severe("Failed to serialize trace", e); } return json; }
Source:
<code>public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { <START> if (((String)key).length() % 2 == 0) return 0; <END> return 1; }</code><technical_language>of braces is generally considered a practice in this situation, required language</technical_language>

Target:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { if (((String) key).length() % 2 == 0) { return 0; } return 1; }
Source:
<code>private List<RequestInfo> pollForRequests() { idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); for (String blobId : idsToDelete) { deleteManager.submitDeleteBlobOperation(blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); long lastTime = time.milliseconds(); putManager.poll(requests); routerMetrics.putManagerPollTimeMs.update(time.milliseconds() - lastTime); lastTime = time.milliseconds(); getManager.poll(requests); routerMetrics.getManagerPollTimeMs.update(time.milliseconds() - lastTime); lastTime = time.milliseconds(); deleteManager.poll(requests); routerMetrics.deleteManagerPollTimeMs.update(time.milliseconds() - lastTime); <START> return requests; <END> }</code><technical_language>I follow practice of tracking time method outside, I feel cleaner</technical_language>

Target:
private List<RequestInfo> pollForRequests() { idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); for (String blobId : idsToDelete) { deleteManager.submitDeleteBlobOperation(blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; }
Source:
<code><START> public List<GlusterGeoRepSessionDetails> getSessionDetails() { <END> return sessionDetails; }</code><technical_language>HI, Is this frontend? If so, a concrete class, List? (See other place in code), GWT issues dynamic types/inheritance</technical_language>

Target:
public ArrayList<GlusterGeoRepSessionDetails> getSessionDetails() { return sessionDetails; }
Source:
<code>public Transceiver getRawCategories(final ArticleIdentifier articleId) throws IOException { return new Transceiver() { @Override protected Calendar getLastModifiedDate() { ArticleTable article = getArticle(articleId); ArticleVersion articleVersion = getLatestArticleVersion(article); <START> return copyToCalendar(articleVersion.getLastModified()); <END> } @Override protected Object getData() throws IOException { ArticleTable article = getArticle(articleId); ArticleVersion articleVersion = getLatestArticleVersion(article); Document manuscriptXml = getManuscriptXml(articleVersion); List<String> rawTerms = taxonomyService.getRawTerms(manuscriptXml, article, false ); List<String> cleanedTerms = new ArrayList<>(); for (String term : rawTerms) { term = term.replaceAll("<TERM>", "").replaceAll("</TERM>", ""); cleanedTerms.add(term); } return cleanedTerms; } }; }</code><technical_language>cache raw categories for article</technical_language>

Target:
public Transceiver getRawCategories(final ArticleIdentifier articleId) throws IOException { return new Transceiver() { @Override protected Calendar getLastModifiedDate() { return null; } @Override protected Object getData() throws IOException { ArticleTable article = getArticle(articleId); ArticleVersion articleVersion = getLatestArticleVersion(article); Document manuscriptXml = getManuscriptXml(articleVersion); List<String> rawTerms = taxonomyService.getRawTerms(manuscriptXml, article, false ); List<String> cleanedTerms = new ArrayList<>(); for (String term : rawTerms) { term = term.replaceAll("<TERM>", "").replaceAll("</TERM>", ""); cleanedTerms.add(term); } return cleanedTerms; } }; }
Source:
<code>private ExecutionErrorHandler getExecutionErrorHandler(RuntimeManager manager) { <START> ExecutionErrorManager errorManager = ((AbstractRuntimeManager) manager).getExecutionErrorManager(); <END> return ((ExecutionErrorManagerImpl) errorManager).createHandler(); }</code><technical_language>this null check removed? Is assured errorManager instance is present now</technical_language>

Target:
private ExecutionErrorHandler getExecutionErrorHandler(RuntimeManager manager) { ExecutionErrorManager errorManager = ((AbstractRuntimeManager) manager).getExecutionErrorManager(); if (errorManager == null) { return new NoOpExecutionErrorHandler(); } return ((ExecutionErrorManagerImpl) errorManager).createHandler(); }