auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean equals(Object obj) { if (id == null) { return super.equals(obj); } if (obj == null || !(obj instanceof AssignedIdString)) { return false; } AssignedIdString other = (AssignedIdString) obj; if (other.id == null) { return (id == other.id); <START> } <END> return id.equals(other.id); }</code><technical_language>This block omitted return false (id null here) behaves id.equals(null)</technical_language>

Target:
public boolean equals(Object obj) { if (id == null) { return super.equals(obj); } if (obj == null || !(obj instanceof AssignedIdString)) { return false; } AssignedIdString other = (AssignedIdString) obj; if (other.id == null) { return false; } return id.equals(other.id); }
Source:
<code>public void close() throws SQLException { <START> connect.deleteConnector(CONNECTOR_NAME); <END> connection.close(); stopConnect(); }</code><technical_language>if stopConnect() deleting connector? code for this line stopConnect co-located</technical_language>

Target:
public void close() throws SQLException { deleteTable(); connect.deleteConnector(CONNECTOR_NAME); connection.close(); stopConnect(); }
Source:
<code>private Boolean containsGzip(Request request) { <START> return request.headers(HttpHeaders.ACCEPT_ENCODING).toLowerCase().contains(GZIP); <END> }</code><technical_language>Is is ACCEPT_ENCODING header in request lead NPE here</technical_language>

Target:
private Boolean containsGzip(Request request) { String acceptEncoding = request.headers(HttpHeaders.ACCEPT_ENCODING); if (acceptEncoding != null) { return acceptEncoding.toLowerCase().contains(GZIP); } LOGGER.debug("Request header Accept-Encoding is null"); return false; }
Source:
<code>private ImmutableSet<DeclaredType> getValueFieldOfClasses(AnnotationMirror annotationMirror) { return ((List<AnnotationValue>) getAnnotationValue(annotationMirror, "value").getValue()) .stream() <START> .map(value -> MoreTypes.asDeclared((DeclaredType) value.getValue())) <END> .collect(ImmutableSet.toImmutableSet()); }</code><technical_language>cast (TypeMirror) pass MoreTypes.asDeclared() cast DeclaredType. add this todo for me: TODO(ronshapiro): class literals declared types, i.e. int.class, int[].class</technical_language>

Target:
private ImmutableSet<DeclaredType> getValueFieldOfClasses(AnnotationMirror annotationMirror) { return ((List<AnnotationValue>) getAnnotationValue(annotationMirror, "value").getValue()) .stream() .map(value -> (DeclaredType) value.getValue()) .collect(toImmutableSet()); }
Source:
<code>public void reorder(List<?> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) instanceof Lifeline[]) { Lifeline temp[] = (Lifeline[]) list.get(i); temp = <START> checkNotNull(temp); <END> if (temp.length == 2) { if (temp[1] == null) { insertLifelineAfter(temp[0], getLifeline(lifeLinesCount() - 1)); } else { insertLifelineBefore(temp[0], temp[1]); } } } } }</code><technical_language>Object o = list.get(i); if (o instanceof Lifeline[]) { Lifeline temp[] = (Lifeline[]) o;</technical_language>

Target:
public void reorder(List<?> list) { for (int i = 0; i < list.size(); i++) { Object o = list.get(i); if (o instanceof Lifeline[]) { Lifeline temp[] = (Lifeline[]) o; if (temp.length == 2) { if (temp[1] == null) { insertLifelineAfter(temp[0], getLifeline(lifeLinesCount() - 1)); } else { insertLifelineBefore(temp[0], temp[1]); } } } } }
Source:
<code>public static void setMoney(User user, BigDecimal balance) throws NoLoanPermittedException { if (user == null) { <START> throw new RuntimeException("Economy user cannot be null"); <END> } if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) { throw new NoLoanPermittedException(); } if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) { throw new NoLoanPermittedException(); } try { user.setMoney(balance, UserBalanceUpdateEvent.Cause.API); } catch (MaxMoneyException ex) { } Trade.log("API", "Set", "API", user.getName(), new Trade(balance, ess), null, null, null, ess); }</code><technical_language>IllegalArgumentException</technical_language>

Target:
public static void setMoney(User user, BigDecimal balance) throws NoLoanPermittedException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) { throw new NoLoanPermittedException(); } if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) { throw new NoLoanPermittedException(); } try { user.setMoney(balance, UserBalanceUpdateEvent.Cause.API); } catch (MaxMoneyException ex) { } Trade.log("API", "Set", "API", user.getName(), new Trade(balance, ess), null, null, null, ess); }
Source:
<code>public String getValue(ContextKey key) { if (delegate == null) { <START> LOG.debug("Configuration not yet initialized. Returning 'null' for " + key); <END> return null; } return delegate.getValue(key); }</code><technical_language>curious, this class logging StaticAbstractConfiguration is changed System.err</technical_language>

Target:
public String getValue(ContextKey key) { if (delegate == null) { System.out.println("Configuration not yet initialized. Returning 'null' for " + key); return null; } return delegate.getValue(key); }
Source:
<code>public boolean replaces(@Nullable LookupExtractorFactory other) { if (this == other) { return false; } if (other == null) { return true; } if (!(other instanceof MapLookupExtractorFactory)) { <START> return true; <END> } final MapLookupExtractorFactory that = (MapLookupExtractorFactory) other; return isOneToOne != that.isOneToOne || !map.equals(that.map); }</code><technical_language>is logic this, i a instance of MapLookupExtractorFactory replace MapLookupExtractorFactory</technical_language>

Target:
public boolean replaces(@Nullable LookupExtractorFactory other) { return !equals(other); }
Source:
<code>protected String getDestinationDescription() { if (this.replyDestination instanceof TemporaryQueue) { return "Temporary queue:" + this.replyDestination.toString(); } else if (super.getDestination() != null){ try { return super.getDestinationDescription(); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected error obtaining destination description: " + e.getMessage()); } return "unknown.1"; } } else { <START> return "unknown.2"; <END> } }</code><technical_language>return null in cases? lease, significantly 'unknown.1' '2' other number..</technical_language>

Target:
protected String getDestinationDescription() { if (this.replyDestination instanceof TemporaryQueue) { return "Temporary queue:" + this.replyDestination.toString(); } else if (super.getDestination() != null){ try { return super.getDestinationDescription(); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected error obtaining destination description: " + e.getMessage()); } return null; } } else { return null; } }
Source:
<code>public void disableWireframe() { boolean refreshTaskList = false; EnableFaceCulling faceCullingStateChange = new EnableFaceCulling(); <START> if (!getDesiredStateChanges().contains(faceCullingStateChange)) { <END> addDesiredStateChange(faceCullingStateChange); refreshTaskList = true; } if (getDesiredStateChanges().contains(wireframeStateChange)) { removeDesiredStateChange(wireframeStateChange); refreshTaskList = true; } if (refreshTaskList) { worldRenderer.requestTaskListRefresh(); } }</code><technical_language>notice OpaqueObjectsNode.java needs treatment</technical_language>

Target:
public void disableWireframe() { if (getDesiredStateChanges().contains(wireframeStateChange)) { addDesiredStateChange(faceCullingStateChange); removeDesiredStateChange(wireframeStateChange); worldRenderer.requestTaskListRefresh(); } }
Source:
<code>public CopyArtifact(String projectName) { StaplerRequest req = Stapler.getCurrentRequest(); <START> if (req!=null) { <END> AbstractProject<?,?> p = req.findAncestorObject(AbstractProject.class); if (p != null) { ItemGroup<?> context = p.getParent(); if (projectName.indexOf('$') < 0 && Jenkins.getInstance().getItem(projectName, context, Job.class) == null) projectName = ""; } } this.project = projectName; setParameters(null); setFilter(null); setTarget(null); setExcludes(null); setSelector(null); setFlatten(false); setOptional(false); setFingerprintArtifacts(false); }</code><technical_language>BTW this block is legacy code, predating QueueItemAuthenticator; I thought @ikedam cleaned permission system in this plugin up, is some junk left behind. rate, a no-op for Workflow this constructor is called build, is active web request. (It _also_ called snippet generator, is, AbstractProject in context-only a [Workflow]Job</technical_language>

Target:
public CopyArtifact(String projectName) { StaplerRequest req = Stapler.getCurrentRequest(); if (req!=null) { AbstractProject<?,?> p = req.findAncestorObject(AbstractProject.class); if (p != null) { ItemGroup<?> context = p.getParent(); if (projectName.indexOf('$') < 0 && Jenkins.getInstance().getItem(projectName, context, Job.class) == null) projectName = ""; } } this.project = projectName; setParameters(null); setFilter(null); setTarget(null); setExcludes(null); setSelector(DEFAULT_BUILD_SELECTOR); setFlatten(false); setOptional(false); setFingerprintArtifacts(false); }
Source:
<code>public Adapter createStoragePathAdapter(String path, boolean isLocal) { IFileRevision findFileRevision = findFileRevision((ITypedElement)accessor); IFile file = findFile((ITypedElement)accessor); boolean local; <START> if (file == null) { <END> local = false; } else { local = true; } if (!isLocal && findFileRevision != null) { return new StoragePathAdapter(path, local, findFileRevision.getContentIdentifier(), findFileRevision.getAuthor()); } else { return new StoragePathAdapter(path, local); } }</code><technical_language>Replace boolean local = file != null;</technical_language>

Target:
public Adapter createStoragePathAdapter(String path, boolean isLocal) { IFileRevision findFileRevision = findFileRevision((ITypedElement)accessor); IFile file = findFile((ITypedElement)accessor); boolean local = file != null; if (!isLocal && findFileRevision != null) { return new StoragePathAdapter(path, local, findFileRevision.getContentIdentifier(), findFileRevision.getAuthor()); } else { return new StoragePathAdapter(path, local); } }
Source:
<code>public ProjectProperty(DmsProject project, Integer typeId, String value, Integer rank, Integer variableId, String alias) { this.project = project; this.typeId = typeId; this.value = value; this.rank = rank; this.variableId = variableId; this.alias = alias; <START> this.description = description; <END> }</code><technical_language>remove assignment local variable description</technical_language>

Target:
public ProjectProperty(DmsProject project, Integer typeId, String value, Integer rank, Integer variableId, String alias) { this.project = project; this.typeId = typeId; this.value = value; this.rank = rank; this.variableId = variableId; this.alias = alias; }
Source:
<code><START> void setSession(BigtableSession session) { <END> this.session = session; }</code><technical_language>changing visibility of methods</technical_language>

Target:
protected void setSession(BigtableSession session) { this.session = session; }
Source:
<code>private String name(final String... parts) { final List<String> normalized = Stream.concat( Stream.of(prefix), Arrays .stream(parts) .map(GcMemoryMetrics::normalize) <START> ).collect(Collectors.toList()); <END> return String.join(".", normalized); }</code><technical_language>Collectors.joining(".")</technical_language>

Target:
private String name(final String... parts) { return Stream.concat( Stream.of(prefix), Arrays .stream(parts) .map(GcMemoryMetrics::normalize) ).collect(Collectors.joining(".")); }
Source:
<code>protected void executeQueryCommand() { final VDSGroup oldCluster = backend.runQuery(VdcQueryType.GetVdsGroupById, getParameters()).getReturnValue(); VDSGroup newCluster = getParameters().getNewCluster(); List<ClusterEditWarnings.Warning> hostWarnings = getProblematicEntities(oldCluster, newCluster, hostCheckers, new ClusterEntityResolver<VDS>() { @Override public List<VDS> getClusterEntities(VDSGroup cluster) { return vdsDao.getAllForVdsGroup(cluster.getId()); } }); <START> final List<ClusterEditWarnings.Warning> vmWarnings = oldCluster.supportsVirtService() && newCluster.supportsVirtService() <END> ? getProblematicEntities(oldCluster, newCluster, vmCheckers, new ClusterEntityResolver<VM>() { @Override public List<VM> getClusterEntities(VDSGroup cluster) { return vmDao.getAllForVdsGroup(cluster.getId()); } }) : Collections.<ClusterEditWarnings.Warning>emptyList(); setReturnValue(new ClusterEditWarnings(hostWarnings, vmWarnings)); }</code><technical_language>Please try stay true original master change. I this big ternary operator a bit harder read</technical_language>

Target:
protected void executeQueryCommand() { final VDSGroup oldCluster = backend.runQuery(VdcQueryType.GetVdsGroupById, getParameters()).getReturnValue(); VDSGroup newCluster = getParameters().getNewCluster(); List<ClusterEditWarnings.Warning> hostWarnings = getProblematicEntities(oldCluster, newCluster, hostCheckers, new ClusterEntityResolver<VDS>() { @Override public List<VDS> getClusterEntities(VDSGroup cluster) { return vdsDao.getAllForVdsGroup(cluster.getId()); } }); List<ClusterEditWarnings.Warning> vmWarnings = new ArrayList<>(); if (oldCluster.supportsVirtService() && newCluster.supportsVirtService()) { getProblematicEntities(oldCluster, newCluster, vmCheckers, new ClusterEntityResolver<VM>() { @Override public List<VM> getClusterEntities(VDSGroup cluster) { return vmDao.getAllForVdsGroup(cluster.getId()); } }); } setReturnValue(new ClusterEditWarnings(hostWarnings, vmWarnings)); }
Source:
<code>private void cleanup(WorkspaceServiceClient workspaceServiceClient) { <START> final Storage localStorage = Storage.getLocalStorageIfSupported(); <END> if (localStorage == null) { return; } for (int i = 0; i < localStorage.getLength(); i++) { String key = localStorage.key(i); if (key != null && key.startsWith(LOCAL_STORAGE_DEBUGGER_STATES_KEY_PREFIX)) { String workspaceId = key.substring(LOCAL_STORAGE_DEBUGGER_STATES_KEY_PREFIX.length()); Promise<WorkspaceDto> workspace = workspaceServiceClient.getWorkspace(workspaceId); workspace.catchError(error -> { localStorage.removeItem(key); }); } } }</code><technical_language>a <LINK_0> In commit ported some methods com.google.gwt.storage.client.Storage</technical_language>

Target:
private void cleanup(WorkspaceServiceClient workspaceServiceClient) { if (localStorage == null) { return; } for (int i = 0; i < localStorage.getLength(); i++) { String key = localStorage.key(i); if (key != null && key.startsWith(LOCAL_STORAGE_DEBUGGER_STATES_KEY_PREFIX)) { String workspaceId = key.substring(LOCAL_STORAGE_DEBUGGER_STATES_KEY_PREFIX.length()); Promise<WorkspaceDto> workspace = workspaceServiceClient.getWorkspace(workspaceId); workspace.catchError(error -> { localStorage.removeItem(key); }); } } }
Source:
<code>default boolean isCreated() { if (getContainerId() == null) { return false; } try { String status = getCurrentContainerInfo().getState().getStatus(); <START> return status != null & !status.isEmpty(); <END> } catch (DockerException e) { return false; } }</code><technical_language>nit: Guava's Strings.isNullOrEmpty</technical_language>

Target:
default boolean isCreated() { if (getContainerId() == null) { return false; } try { String status = getCurrentContainerInfo().getState().getStatus(); return !Strings.isNullOrEmpty(status); } catch (DockerException e) { return false; } }
Source:
<code>public boolean renewLease(String leaseId) { try { leaseBlob.renewLease(AccessCondition.generateLeaseCondition(leaseId)); return true; } catch (StorageException e) { <START> LOG.error("Wasn't able to renew lease.", new SamzaException(e)); <END> return false; } }</code><technical_language>wrapping exception here</technical_language>

Target:
public boolean renewLease(String leaseId) { try { leaseBlob.renewLease(AccessCondition.generateLeaseCondition(leaseId)); return true; } catch (StorageException storageException) { LOG.error("Wasn't able to renew lease with lease id: " + leaseId, storageException); return false; } }
Source:
<code>public void testGetDescriptors() { DescriptorRegistry registry = new DescriptorRegistry(); registry.register(TARGET, EP, new TestDescriptor("id1", "name1", "desc1")); registry.register(TARGET, EP, new TestDescriptor("id1", "name11", "desc1")); registry.register(TARGET, EP, new TestDescriptor("id1", null, "desc11")); registry.register(TARGET, EP, new TestDescriptor("id2", "name2", "desc2")); registry.register(TARGET, EP, new TestDescriptor("id2", "name22", "desc2")); registry.register(TARGET, EP, new TestDescriptor("id2", null, "desc22")); List<TestDescriptor> descs = registry.getDescriptors(TARGET, EP); <START> Assert.assertEquals(2, descs.size()); <END> assertValues(descs.get(0), "id1", "name11", "desc11"); assertValues(descs.get(1), "id2", "name22", "desc22"); }</code><technical_language>import statically assert* method</technical_language>

Target:
public void testGetDescriptors() { DescriptorRegistry registry = new DescriptorRegistry(); registry.register(TARGET, EP, new TestDescriptor("id1", "name1", "desc1")); registry.register(TARGET, EP, new TestDescriptor("id1", "name11", "desc1")); registry.register(TARGET, EP, new TestDescriptor("id1", null, "desc11")); registry.register(TARGET, EP, new TestDescriptor("id2", "name2", "desc2")); registry.register(TARGET, EP, new TestDescriptor("id2", "name22", "desc2")); registry.register(TARGET, EP, new TestDescriptor("id2", null, "desc22")); List<TestDescriptor> descs = registry.getDescriptors(TARGET, EP); assertEquals(2, descs.size()); assertValues(descs.get(0), "id1", "name11", "desc11"); assertValues(descs.get(1), "id2", "name22", "desc22"); }
Source:
<code><START> public int getMaxConcurrentTask() { <END> return _record.getIntField(InstanceConfigProperty.MAX_CONCURRENT_TASK.toString(), DEFAULT_MAX_CONCURRENT_TASK); }</code><technical_language>this config option in cluster config? In of cases, user choose for of nodes, this easier set instead of in instance config. If is set in cluster config some of instance config, in instance config effect</technical_language>

Target:
public int getMaxConcurrentTask() { return _record.getIntField(InstanceConfigProperty.MAX_CONCURRENT_TASK.toString(), MAX_CONCURRENT_TASK_NOT_SET); }
Source:
<code>public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, List<IBinding> suggestions, boolean isLastParameter) throws CModelException { List<Variable> typeMatches = evaluateVisibleMatches(expectedType, suggestions); <START> typeMatches = removeDuplicates(typeMatches); <END> orderMatches(typeMatches, paramName); ICompletionProposal[] ret = new ICompletionProposal[typeMatches.size()]; int i = 0; int replacementLength = 0; for (Variable v : typeMatches) { if (i == 0) { fAlreadyMatchedNames.add(v.name); replacementLength = v.name.length(); } String displayString = v.name; final char[] triggers; if (isLastParameter) { triggers = v.triggerChars; } else { triggers = new char[v.triggerChars.length + 1]; System.arraycopy(v.triggerChars, 0, triggers, 0, v.triggerChars.length); triggers[triggers.length - 1] = ','; } ret[i++] = new PositionBasedCompletionProposal(v.name, pos, replacementLength, getImage(v.descriptor), displayString, null, null, triggers); } return ret; }</code><technical_language>more efficient eliminate duplicates evaluateVisibleMatches method collecting matches in a set converting set a list end</technical_language>

Target:
public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, List<IBinding> suggestions, boolean isLastParameter) throws CModelException { List<Variable> typeMatches = evaluateVisibleMatches(expectedType, suggestions); orderMatches(typeMatches, paramName); ICompletionProposal[] ret = new ICompletionProposal[typeMatches.size()]; int i = 0; int replacementLength = 0; for (Variable v : typeMatches) { if (i == 0) { fAlreadyMatchedNames.add(v.name); replacementLength = v.name.length(); } String displayString = v.name; final char[] triggers; if (isLastParameter) { triggers = v.triggerChars; } else { triggers = new char[v.triggerChars.length + 1]; System.arraycopy(v.triggerChars, 0, triggers, 0, v.triggerChars.length); triggers[triggers.length - 1] = ','; } ret[i++] = new PositionBasedCompletionProposal(v.name, pos, replacementLength, getImage(v.descriptor), displayString, null, null, triggers); } return ret; }
Source:
<code>private String recreateFullRequestUrl(HttpServletRequest request) { StringBuffer requestURL = request.getRequestURL(); try { URL url = new URL(requestURL.toString()); if (url.getHost().equals(SystemBaseUrl.EXTERNAL.getHost()) && String.valueOf(url.getPort()).equals(SystemBaseUrl.EXTERNAL.getPort())) { <START> requestURL = new StringBuffer(SystemBaseUrl.EXTERNAL.constructUrl(request.getRequestURI())); <END> } } catch (MalformedURLException e) { LOGGER.debug("Unable to convert request URL to URL object."); } String queryString = request.getQueryString(); if (queryString == null) { return requestURL.toString(); } else { return requestURL.append('?').append(queryString).toString(); } }</code><technical_language>Is this effectively adding external context? Is guaranteed external context returned request.getRequestURI() already? (otherwise, external context in twice)</technical_language>

Target:
private String recreateFullRequestUrl(HttpServletRequest request) { StringBuffer requestURL = request.getRequestURL(); try { URL url = new URL(requestURL.toString()); if (url.getHost().equals(SystemBaseUrl.EXTERNAL.getHost()) && String.valueOf(url.getPort()).equals(SystemBaseUrl.EXTERNAL.getPort()) && !url.getPath().startsWith(SystemBaseUrl.EXTERNAL.getRootContext())) { requestURL = new StringBuffer(SystemBaseUrl.EXTERNAL.constructUrl(request.getRequestURI())); } } catch (MalformedURLException e) { LOGGER.error("Unable to convert request URL to URL object."); } String queryString = request.getQueryString(); if (queryString == null) { return requestURL.toString(); } else { return requestURL.append('?').append(queryString).toString(); } }
Source:
<code>static TfvcClient getInstance(@NotNull Project project) { <START> boolean useReactiveClient = "true".equals( <END> PropertyService.getInstance().getProperty(PropertyService.PROP_TFVC_USE_REACTIVE_CLIENT)); return useReactiveClient ? ServiceManager.getService(project, ReactiveTfvcClient.class) : ServiceManager.getService(project, ClassicTfvcClient.class); }</code><technical_language>Add ignore casing</technical_language>

Target:
static TfvcClient getInstance(@NotNull Project project) { boolean useReactiveClient = "true".equalsIgnoreCase( PropertyService.getInstance().getProperty(PropertyService.PROP_TFVC_USE_REACTIVE_CLIENT)); return useReactiveClient ? ServiceManager.getService(project, ReactiveTfvcClient.class) : ServiceManager.getService(project, ClassicTfvcClient.class); }
Source:
<code><START> public static String[] splitRpmToParts(String rpmName) { <END> int lastDashIndex = rpmName.lastIndexOf('-'); if (lastDashIndex == -1) { throw new IllegalArgumentException(INVALID_RPM_NAME_FORMAT); } char[] chars = rpmName.toCharArray(); int beforeLastDashIndex = lastDashIndex - 1; for (; beforeLastDashIndex >= 0; beforeLastDashIndex--) { if (chars[beforeLastDashIndex] == '-') { break; } } if (beforeLastDashIndex == -1) { throw new IllegalArgumentException(INVALID_RPM_NAME_FORMAT); } String[] parts = new String[3]; parts[0] = rpmName.substring(0, beforeLastDashIndex); parts[1] = rpmName.substring(beforeLastDashIndex + 1, lastDashIndex); parts[2] = rpmName.substring(lastDashIndex + 1); return parts; }</code><technical_language>reading usage in <LINK_0>, I wondered, return dict, for readability, similar namedtuple in java, ret['release'] ret['version'] ret['prefix'] -> easier work with</technical_language>

Target:
public static String[] splitRpmToParts(String rpmName) { int lastDashIndex = rpmName.lastIndexOf('-'); if (lastDashIndex == -1) { throw new IllegalArgumentException(INVALID_RPM_NAME_FORMAT); } char[] chars = rpmName.toCharArray(); int beforeLastDashIndex = lastDashIndex - 1; while (beforeLastDashIndex >= 0) { if (chars[beforeLastDashIndex] == '-') { break; } beforeLastDashIndex--; } if (beforeLastDashIndex == -1) { throw new IllegalArgumentException(INVALID_RPM_NAME_FORMAT); } String[] parts = new String[3]; parts[0] = rpmName.substring(0, beforeLastDashIndex); parts[1] = rpmName.substring(beforeLastDashIndex + 1, lastDashIndex); parts[2] = rpmName.substring(lastDashIndex + 1); return parts; }
Source:
<code>public void testRetainAll1() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet rs = new RangeSet(5); assertTrue(intSet.retainAll(rs)); assertEquals(2, intSet.size()); assertTrue(intSet.contains(1)); <START> assertTrue(intSet.contains(4)); <END> }</code><technical_language>I change assertions</technical_language>

Target:
public void testRetainAll1() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet rs = new RangeSet(5); assertTrue(intSet.retainAll(rs)); assertEquals(CollectionFactory.makeSet(1, 4), intSet); }
Source:
<code>public Integer call() throws Exception { final Object ysoserial = payload.getPayloadClass().newInstance().getObject(command); try { Channel.current().call(new Callable<String, Exception>() { private static final long serialVersionUID = 1L; @Override public String call() throws Exception { return ysoserial.toString(); } @Override public void checkRoles(RoleChecker checker) throws SecurityException { } }); } catch (Exception ex) { <START> ex.printStackTrace(); <END> Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } if (cause instanceof SecurityException) { if (cause.getMessage().contains("Rejected")) { return PayloadCaller.EXIT_CODE_REJECTED; } else { throw ex; } } final String message = cause.getMessage(); if (message != null && message.contains("cannot be cast to java.util.Set")) { return EXIT_CODE_ASSIGNMENT_ISSUE; } else { throw ex; } } return EXIT_CODE_OK; }</code><technical_language>this dump out stack traces for a successful test (which is bad) stack traces for OK tests scary running set of triggers in human brains</technical_language>

Target:
public Integer call() throws Exception { final Object ysoserial = payload.getPayloadClass().newInstance().getObject(command); try { getChannelOrFail().call(new Callable<String, Exception>() { private static final long serialVersionUID = 1L; @Override public String call() throws Exception { return ysoserial.toString(); } @Override public void checkRoles(RoleChecker checker) throws SecurityException { } }); } catch (Exception ex) { ex.printStackTrace(); Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } if (cause instanceof SecurityException) { if (cause.getMessage().contains("Rejected")) { return PayloadCaller.EXIT_CODE_REJECTED; } else { throw ex; } } final String message = cause.getMessage(); if (message != null && message.contains("cannot be cast to java.util.Set")) { return EXIT_CODE_ASSIGNMENT_ISSUE; } else { throw ex; } } return EXIT_CODE_OK; }
Source:
<code>public void testWebServiceContextInject(@ArquillianResource URL deploymentUrl) throws Exception { QName serviceName = new QName("<LINK_0>", "TestService"); URL wsdlUrl = new URL(deploymentUrl.toExternalForm() + "/" + TestWSImpl.SERVICE_NAME + "?wsdl"); TestWS testService = Service.create(wsdlUrl, serviceName).getPort(TestWS.class); int workerCount = 20; ExecutorService executor = Executors.newFixedThreadPool(workerCount); List<Future<String>> results = new ArrayList<>(); try { for (int i = 0; i < workerCount; i++) { results.add(executor.submit(new Worker(testService))); } for (Future<String> result : results) { <START> Assert.assertTrue(result.get(5, TimeUnit.SECONDS).startsWith("Hello")); <END> } } finally { executor.shutdown(); } }</code><technical_language>@mackaypeter timeouts TimeoutUtil adjust timeouts (so work slower machines etc.)</technical_language>

Target:
public void testWebServiceContextInject(@ArquillianResource URL deploymentUrl) throws Exception { QName serviceName = new QName("<LINK_0>", "TestService"); URL wsdlUrl = new URL(deploymentUrl.toExternalForm() + "/" + TestWSImpl.SERVICE_NAME + "?wsdl"); TestWS testService = Service.create(wsdlUrl, serviceName).getPort(TestWS.class); int workerCount = 20; ExecutorService executor = Executors.newFixedThreadPool(workerCount); List<Future<String>> results = new ArrayList<>(); try { for (int i = 0; i < workerCount; i++) { results.add(executor.submit(new Worker(testService))); } for (Future<String> result : results) { Assert.assertTrue(result.get(TimeoutUtil.adjust(5), TimeUnit.SECONDS).startsWith("Hello")); } } finally { executor.shutdown(); } }
Source:
<code>public static AsyncRDFHandler processAsync(RDFHandler handler, boolean joinOnRDFEnd, int bufferSize) { BlockingQueue<RDFRecordedAction> queue = new ArrayBlockingQueue<>(bufferSize); AtomicReference<Throwable> replayerException = new AtomicReference<>(); RDFRecordedActionConsumer consumer = (a) -> { try { do { Throwable exc = replayerException.get(); if (exc != null) { throw new RDFHandlerException("Queue dead cannot record", exc); } } while (!queue.offer(a, 1, <START> TimeUnit.SECONDS)); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RDFHandlerException(e); } }; RDFActionsReplayer replayer = new RDFActionsReplayer(queue, handler, replayerException::set); AsyncRDFHandler recorder = new AsyncRDFHandler(consumer, replayer, joinOnRDFEnd); replayer.setUncaughtExceptionHandler((t, e) -> replayerException.set(e)); replayer.start(); return recorder; }</code><technical_language>static import</technical_language>

Target:
public static AsyncRDFHandler processAsync(RDFHandler handler, boolean joinOnRDFEnd, int bufferSize) { BlockingQueue<RDFRecordedAction> queue = new ArrayBlockingQueue<>(bufferSize); AtomicReference<Throwable> replayerException = new AtomicReference<>(); RDFRecordedActionConsumer consumer = (a) -> { try { do { Throwable exc = replayerException.get(); if (exc != null) { throw new RDFHandlerException("Queue dead cannot record", exc); } } while (!queue.offer(a, 1, SECONDS)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RDFHandlerException(e); } }; RDFActionsReplayer replayer = new RDFActionsReplayer(queue, handler, replayerException::set); AsyncRDFHandler recorder = new AsyncRDFHandler(consumer, replayer, joinOnRDFEnd); replayer.setUncaughtExceptionHandler((t, e) -> replayerException.set(e)); replayer.start(); return recorder; }
Source:
<code>public BeaconOrganizationImpl() { <START> this.setId(ID); <END> this.setName(NAME); this.setDescription(DESCRIPTION); this.setAddress(ADDRESS); this.setWelcomeUrl(WELCOME_URL); this.setContactUrl(CONTACT_URL); this.setLogoUrl(LOGO_URL); }</code><technical_language>need include this in calls is a minor detail</technical_language>

Target:
public BeaconOrganizationImpl() { setId(ID); setName(NAME); setDescription(DESCRIPTION); setAddress(ADDRESS); setWelcomeUrl(WELCOME_URL); setContactUrl(CONTACT_URL); setLogoUrl(LOGO_URL); }
Source:
<code>private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTime = getTotalProcTime(pullStats); final double totalPushTime = getTotalProcTime(pushStats); <START> final double totalReqProcTime = getTotalProcTime(requestStats); <END> final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); if (totalPullCount > 0 && totalPushCount > 0) { final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelParamBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTime(totalPullTime) .setTotalPushProcessingTime(totalPushTime) .setTotalReqProcessingTime(totalReqProcTime) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); } windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }</code><technical_language>Please remove getAvgProcTimePerReq(), if gonna it</technical_language>

Target:
private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTime = getTotalProcTime(pullStats); final double totalPushTime = getTotalProcTime(pushStats); final double totalReqProcTime = getTotalProcTime(requestStats); final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTime(totalPullTime) .setTotalPushProcessingTime(totalPushTime) .setTotalReqProcessingTime(totalReqProcTime) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }
Source:
<code>private Response addPatients(final String json) { final JSONArray jsonArray; try { jsonArray = new JSONArray(json); } catch (JSONException ex) { throw new WebApplicationException(Status.BAD_REQUEST); } final int jsonArrayLength = jsonArray.length(); for (int i = 0; i < jsonArrayLength; i++) { JSONObject jsonObject = jsonArray.optJSONObject(i); if (jsonObject == null) { logger.warn("One of the members of the patient JSONArray is null."); continue; } Patient patient = this.repository.create(); patient.updateFromJSON(jsonObject); } final URI targetURI = UriBuilder.fromUri(this.uriInfo.getBaseUri()).build(); <START> final ResponseBuilder response = Response.created(targetURI); <END> return response.build(); }</code><technical_language>This is semantically correct, Location header point location of created resource, a resource. multiple resources created, null for header, instead put list of locations in response body</technical_language>

Target:
private Response addPatients(final String json) { final JSONArray patientsData; final JSONArray createdPatientUri = new JSONArray(); try { patientsData = new JSONArray(json); } catch (JSONException ex) { throw new WebApplicationException(Status.BAD_REQUEST); } final int jsonArrayLength = patientsData.length(); for (int i = 0; i < jsonArrayLength; i++) { JSONObject jsonObject = patientsData.optJSONObject(i); if (jsonObject == null) { logger.warn("One of the members of the patient JSONArray is null."); continue; } Patient patient = this.repository.create(); patient.updateFromJSON(jsonObject); final URI targetURI = UriBuilder.fromUri(this.uriInfo.getBaseUri()) .path(PatientResource.class) .build(patient.getId()); createdPatientUri.put(targetURI); } final ResponseBuilder response = Response.created(null); response.entity(createdPatientUri.toString()); return response.build(); }
Source:
<code><START> public void onNewIntent(Intent intent) { <END> super.onNewIntent(intent); handleActions(intent); }</code><technical_language>nice catch, I wondered handling of singleTop</technical_language>

Target:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); }
Source:
<code>public int getCurrentRunningCount() { int startPoolSize = currentPoolSize.get(); int initialCount = 0; int initialChainValue = CHAIN_VERIFICATION_START_VAL; while (true) { if (initialCount == 0) { Worker idleWorker = this.idleWorker.get(); while (idleWorker != null) { initialCount++; initialChainValue ^= idleWorker.hashCode(); idleWorker = idleWorker.nextIdleWorker; } } int verificationCount = 0; int verificationChainValue = CHAIN_VERIFICATION_START_VAL; Worker idleWorker = this.idleWorker.get(); <START> while (idleWorker != null) { <END> verificationCount++; verificationChainValue ^= idleWorker.hashCode(); idleWorker = idleWorker.nextIdleWorker; } if (currentPoolSize.get() == startPoolSize && verificationChainValue == initialChainValue && verificationCount == initialCount) { return startPoolSize - initialCount; } else if (currentPoolSize.get() == startPoolSize) { initialCount = verificationCount; initialChainValue = verificationChainValue; } else { startPoolSize = currentPoolSize.get(); initialCount = 0; initialChainValue = CHAIN_VERIFICATION_START_VAL; } } }</code><technical_language>I pull this count logic private function, getLazyIdleCount()</technical_language>

Target:
public int getCurrentRunningCount() { while (true) { int poolSize = currentPoolSize.get(); int result = poolSize - idleWorkerCount.get(); if (poolSize == currentPoolSize.get()) { return result; } } }
Source:
<code>public CategoryTreeRefreshController(final CategoriesSettings categoriesSettings, final CacheApi cacheApi, final HomeReverseRouter homeReverseRouter) { <START> this.configuration = categoriesSettings; <END> this.cacheApi = cacheApi; this.homeReverseRouter = homeReverseRouter; }</code><technical_language>forgot</technical_language>

Target:
public CategoryTreeRefreshController(final CategoriesSettings categoriesSettings, final CacheApi cacheApi, final HomeReverseRouter homeReverseRouter) { this.categoriesSettings = categoriesSettings; this.cacheApi = cacheApi; this.homeReverseRouter = homeReverseRouter; }
Source:
<code>public void testNewQuestionFrame() { ______TS("MSQ: new question (frame) link"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MSQ"); assertTrue(feedbackEditPage.verifyNewMsqQuestionFormIsDisplayed()); feedbackEditPage.clickGenerateMsqOptionsCheckbox(-1); assertFalse(feedbackEditPage.isElementVisible("msqChoiceTable--1")); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); ______TS("MSQ: Check UI after cancelling"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MSQ"); assertTrue(feedbackEditPage.verifyNewMsqQuestionFormIsDisplayed()); assertFalse(feedbackEditPage.isElementVisible("msqChoiceTable--1")); assertTrue(feedbackEditPage.isElementEnabled("msqGenerateForSelect--1")); <START> feedbackEditPage.clickGenerateMsqOptionsCheckbox(-1); END> }</code><technical_language>here. Magic -1 :P</technical_language>

Target:
public void testNewQuestionFrame() { ______TS("MSQ: new question (frame) link"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MSQ"); assertTrue(feedbackEditPage.verifyNewMsqQuestionFormIsDisplayed()); ______TS("MSQ: Check UI after cancelling and add new MSQ question again"); feedbackEditPage.clickGenerateMsqOptionsCheckbox(NEW_QUESTION_INDEX); assertFalse(feedbackEditPage.isElementVisible("msqChoiceTable--1")); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MSQ"); assertTrue(feedbackEditPage.verifyNewMsqQuestionFormIsDisplayed()); assertFalse(feedbackEditPage.isElementVisible("msqChoiceTable--1")); assertTrue(feedbackEditPage.isElementEnabled("msqGenerateForSelect--1")); feedbackEditPage.clickGenerateMsqOptionsCheckbox(NEW_QUESTION_INDEX); }
Source:
<code>ManagedIdentityCredential(String clientId, IdentityClientOptions identityClientOptions) { IdentityClient identityClient = new IdentityClientBuilder() .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); Configuration configuration = Configuration.getGlobalConfiguration().clone(); <START> if (configuration.contains(Configuration.PROPERTY_MSI_ENDPOINT) <END> || configuration.contains(PROPERTY_IDENTITY_ENDPOINT)) { appServiceMSICredential = new AppServiceMsiCredential(clientId, identityClient); virtualMachineMSICredential = null; } else { virtualMachineMSICredential = new VirtualMachineMsiCredential(clientId, identityClient); appServiceMSICredential = null; } LoggingUtil.logAvailableEnvironmentVariables(logger, configuration); }</code><technical_language>This true in Cloud Shell, AppServiceMsiCredential fail there. Is Cloud Shell managed identity supported? true for Azure Arc, if I remember design correctly</technical_language>

Target:
ManagedIdentityCredential(String clientId, IdentityClientOptions identityClientOptions) { IdentityClient identityClient = new IdentityClientBuilder() .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); Configuration configuration = Configuration.getGlobalConfiguration().clone(); if (configuration.contains(Configuration.PROPERTY_MSI_ENDPOINT) || (configuration.contains(PROPERTY_IDENTITY_ENDPOINT) && configuration.contains(PROPERTY_IDENTITY_HEADER))) { appServiceMSICredential = new AppServiceMsiCredential(clientId, identityClient); virtualMachineMSICredential = null; } else { virtualMachineMSICredential = new VirtualMachineMsiCredential(clientId, identityClient); appServiceMSICredential = null; } LoggingUtil.logAvailableEnvironmentVariables(logger, configuration); }
Source:
<code>public Future<String> convert(RestRequest restRequest, String input, Callback<String> callback) { FutureResult<String> futureResult = new FutureResult<String>(); String convertedId = null; Exception exception = null; long startTimeInMs = System.currentTimeMillis(); frontendMetrics.idConverterRequestRate.mark(); if (!isOpen) { exception = new RestServiceException("IdConverter is closed", RestServiceErrorCode.ServiceUnavailable); } else { convertedId = input; } futureResult.done(convertedId, exception); if (callback != null) { callback.onCompletion(convertedId, exception); } <START> frontendMetrics.idConverterRequestProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs); <END> return futureResult; }</code><technical_language>I questions here: 1. is confusing this convert() method here. I guess in future more meaningful method in else block. 2. If 1 is true, actual conversion method async (since returning Future here). If is case, time stamp in line 68 accurate</technical_language>

Target:
public Future<String> convert(RestRequest restRequest, String input, Callback<String> callback) { FutureResult<String> futureResult = new FutureResult<String>(); String convertedId = null; Exception exception = null; frontendMetrics.idConverterRequestRate.mark(); long startTimeInMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("IdConverter is closed", RestServiceErrorCode.ServiceUnavailable); } else { convertedId = input; } futureResult.done(convertedId, exception); if (callback != null) { callback.onCompletion(convertedId, exception); } frontendMetrics.idConverterRequestProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs); return futureResult; }
Source:
<code>@Test public void peekMultiple() { List<String> peek = queue.peek(3); <START> assertThat(peek).containsSequence("one", "two", "three"); <END> }</code><technical_language>containsExactly</technical_language>

Target:
@Test public void peekMultiple() { List<String> peek = queue.peek(3); assertThat(peek).containsExactly("one", "two", "three"); }
Source:
<code>public FileEncryptionProperties getEncryptionProperties() { <START> return getUniformEncryptionEncryptionProperties(); <END> }</code><technical_language>is more a coding style question I more readable simple implementation in enums instead of adding new static methods. If more is fine it</technical_language>

Target:
public FileEncryptionProperties getEncryptionProperties() { return FileEncryptionProperties.builder(FOOTER_ENCRYPTION_KEY) .withFooterKeyMetadata(footerKeyMetadata).build(); }
Source:
<code>public void start_passwordCheckerSaysNotOk_throws() { assertThrows(CryptoException.class, () -> { try (CryptoSession cryptoSession = CryptoSession.start(Optional.of(PASSWORD1), CryptoSessionTest::passwordIsNotOk)) { <START> assertThat("Password checker inadvertently returned OK", false); <END> } }); }</code><technical_language>assertThat here, fail("Password checker inadvertently returned OK") leave</technical_language>

Target:
public void start_passwordCheckerSaysNotOk_throws() { assertThrows(CryptoException.class, () -> { try (CryptoSession cryptoSession = CryptoSession.start(Optional.of(PASSWORD1), CryptoSessionTest::passwordIsNotOk)) { fail("Password checker inadvertently returned OK"); } }); }
Source:
<code>public void testBehaviorWhenReportedSizesSmall() throws Exception { File baseDir = folder.newFolder("base"); <START> FileSmoosher smoosher = new FileSmoosher(baseDir, 21); <END> boolean exceptionThrown = false; try (final SmooshedWriter writer = smoosher.addWithSmooshedWriter("1", 2)) { writer.write(ByteBuffer.wrap(Ints.toByteArray(1))); } catch (ISE e) { Assert.assertTrue(e.getMessage().contains("Liar!!!")); exceptionThrown = true; } Assert.assertTrue(exceptionThrown); File[] files = baseDir.listFiles(); Assert.assertEquals(1, files.length); Assert.assertEquals(0, files[0].length()); }</code><technical_language>this handled in a try-with-resources</technical_language>

Target:
public void testBehaviorWhenReportedSizesSmall() throws Exception { File baseDir = folder.newFolder("base"); try (FileSmoosher smoosher = new FileSmoosher(baseDir, 21)) { boolean exceptionThrown = false; try (final SmooshedWriter writer = smoosher.addWithSmooshedWriter("1", 2)) { writer.write(ByteBuffer.wrap(Ints.toByteArray(1))); } catch (ISE e) { Assert.assertTrue(e.getMessage().contains("Liar!!!")); exceptionThrown = true; } Assert.assertTrue(exceptionThrown); File[] files = baseDir.listFiles(); Assert.assertEquals(1, files.length); Assert.assertEquals(0, files[0].length()); } }
Source:
<code>public Devfile workspaceToDevFile(WorkspaceConfigImpl wsConfig) throws WorkspaceExportException { if (wsConfig.getEnvironments().size() > 1) { throw new WorkspaceExportException( format( "Workspace '%s' cannot be converted to devfile because it contains multiple environments", wsConfig.getName())); } Devfile devfile = <START> new Devfile().withSpecVersion(CURRENT_SPEC_VERSION).withName(wsConfig.getName()); <END> devfile.setProjects( wsConfig .getProjects() .stream() .map(projectConverter::toDevfileProject) .collect(toCollection(ArrayList::new))); for (CommandImpl command : wsConfig.getCommands()) { devfile.getCommands().add(commandConverter.toDevfileCommand(command)); } for (ToolConverter toolConverter : toolConverters) { toolConverter.fromWorkspaceConfig(wsConfig, devfile); } return devfile; }</code><technical_language>Is this covered tests</technical_language>

Target:
public Devfile workspaceToDevFile(WorkspaceConfigImpl wsConfig) throws WorkspaceExportException { if (wsConfig.getEnvironments().size() > 1) { throw new WorkspaceExportException( format( "Workspace '%s' cannot be converted to devfile because it contains multiple environments", wsConfig.getName())); } Devfile devfile = DevfileFactory.newDevfile() .withSpecVersion(CURRENT_SPEC_VERSION) .withName(wsConfig.getName()); devfile.setProjects( wsConfig .getProjects() .stream() .map(projectConverter::toDevfileProject) .collect(toCollection(ArrayList::new))); for (CommandImpl command : wsConfig.getCommands()) { devfile.getCommands().add(commandConverter.toDevfileCommand(command)); } for (ToolProvisioner toolConverter : toolProvisioners) { toolConverter.provision(devfile, wsConfig); } return devfile; }