auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IndexedInts get(int index) { final int offset = offsets.get(index); final int size = offsets.get(index + 1) - offset; return new IndexedInts() { @Override public int size() { return size; } @Override public int get(int index) { if (index >= size) { throw new IllegalArgumentException(String.format("Index[%s] >= size[%s]", index, size)); } return values.get(index + offset); } @Override public void fill(int index, int[] toFill) { throw new UnsupportedOperationException("fill not supported"); } @Override public void close() throws IOException { } @Override public Iterator<Integer> iterator() { <START> return new Iterator<Integer>() <END> { int currentIndex = 0; @Override public boolean hasNext() { return currentIndex < size; } @Override public Integer next() { return get(currentIndex++); } @Override public void remove() { throw new UnsupportedOperationException("remove not supported"); } }; } }; }</code><technical_language>Suggest IndexedIntsIterator</technical_language>

Target:
public IndexedInts get(int index) { final int offset = offsets.get(index); final int size = offsets.get(index + 1) - offset; return new IndexedInts() { @Override public int size() { return size; } @Override public int get(int index) { if (index >= size) { throw new IllegalArgumentException(String.format("Index[%s] >= size[%s]", index, size)); } return values.get(index + offset); } @Override public void fill(int index, int[] toFill) { throw new UnsupportedOperationException("fill not supported"); } @Override public void close() throws IOException { } @Override public Iterator<Integer> iterator() { return new IndexedIntsIterator(this); } }; }
Source:
<code>public void equal_shouldReturnTrueIfObjectReferenceAreTheSame() { CohortMembership cohortMembership = new CohortMembership(12); <START> boolean result = cohortMembership.equals(cohortMembership); <END> assertTrue(result); }</code><technical_language>I guess assert temporary variable</technical_language>

Target:
public void equal_shouldReturnTrueIfObjectReferenceAreTheSame() { CohortMembership cohortMembership = new CohortMembership(12); assertTrue(cohortMembership.equals(cohortMembership)); }
Source:
<code>private static Object deserializePayload(byte[] bytes, MimeType contentType, Map<String, Class<?>> payloadTypeCache, Codec codec) { if ("text".equalsIgnoreCase(contentType.getType()) || MimeTypeUtils.APPLICATION_JSON.equals(contentType)) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { String errorMessage = "unable to deserialize [java.lang.String]. Encoding not supported. " + e.getMessage(); MessageSerializationUtils.LOGGER.error(errorMessage); throw new SerializationFailedException(errorMessage, e); } } else { String className = JavaClassMimeTypeUtils.classNameFromMimeType(contentType); try { Class<?> targetType = payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); payloadTypeCache.put(className, targetType); } return codec.decode(bytes, targetType); } catch (Exception e) { String errorMessage = "Unable to deserialize [" + className + "] using the contentType [" + contentType + "] " + e.getMessage(); <START> MessageSerializationUtils.LOGGER.error(errorMessage); <END> throw new SerializationFailedException(errorMessage, e); } } }</code><technical_language>I log error if I throw it. is this method user decide do exception, utility</technical_language>

Target:
private static Object deserializePayload(byte[] bytes, MimeType contentType, Map<String, Class<?>> payloadTypeCache, Codec codec) { if ("text".equalsIgnoreCase(contentType.getType()) || MimeTypeUtils.APPLICATION_JSON.equals(contentType)) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { String errorMessage = "unable to deserialize [java.lang.String]. Encoding not supported. " + e.getMessage(); throw new SerializationFailedException(errorMessage, e); } } else { String className = JavaClassMimeTypeUtils.classNameFromMimeType(contentType); try { Class<?> targetType = payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); payloadTypeCache.put(className, targetType); } return codec.decode(bytes, targetType); } catch (Exception e) { String errorMessage = "Unable to deserialize [" + className + "] using the contentType [" + contentType + "] " + e.getMessage(); throw new SerializationFailedException(errorMessage, e); } } }
Source:
<code>public RowSignature resultArraySignature(TimeseriesQuery query) { RowSignature.Builder rowSignatureBuilder = RowSignature.builder(); if (query.getDimensionSpec() != null) { <START> rowSignatureBuilder.addDimensions(Collections.singletonList(query.getDimensionSpec())); <END> } else { rowSignatureBuilder.addTimeColumn(); } rowSignatureBuilder.addAggregators(query.getAggregatorSpecs()); rowSignatureBuilder.addPostAggregators(query.getPostAggregatorSpecs()); return rowSignatureBuilder.build(); }</code><technical_language>do name do field floor(timestamp) actual timestamp? "the name" I meant timestampResultField. (I thinking do "timestampResultField": "d0".) floored timestamp, point query results returned, is timestamp in response (it floored)</technical_language>

Target:
public RowSignature resultArraySignature(TimeseriesQuery query) { RowSignature.Builder rowSignatureBuilder = RowSignature.builder(); rowSignatureBuilder.addTimeColumn(); if (StringUtils.isNotEmpty(query.getTimestampResultField())) { rowSignatureBuilder.add(query.getTimestampResultField(), ValueType.LONG); } rowSignatureBuilder.addAggregators(query.getAggregatorSpecs()); rowSignatureBuilder.addPostAggregators(query.getPostAggregatorSpecs()); return rowSignatureBuilder.build(); }
Source:
<code>Optional<FileSystem> create(Configuration conf) { Supplier<FileSystem> fileSystemSupplier = () -> { try { return FileSystem.get(conf); } catch (Exception e) { logger.error("FileSystem creation failed."); <START> e.printStackTrace(); <END> return null; } }; return create(fileSystemSupplier); }</code><technical_language>Logging</technical_language>

Target:
Optional<FileSystem> create(Configuration conf) { Supplier<FileSystem> fileSystemSupplier = () -> { try { return FileSystem.get(conf); } catch (Exception e) { logger.error("FileSystem creation failed.", e); return null; } }; return create(fileSystemSupplier); }
Source:
<code>public static Object getStaticField(OgnlContext context, String className, String fieldName) throws OgnlException { Exception reason = null; try { Class c = classForName(context, className); if (c == null) throw new OgnlException("Unable to find class " + className + " when resolving field name of " + fieldName); if (fieldName.equals("class")) { return c; } else if (OgnlRuntime.isJdk15() && c.isEnum()) { try { return Enum.valueOf(c, fieldName); } catch (IllegalArgumentException e) { } } Field f = getField(c, fieldName); if (f == null) { throw new NoSuchFieldException(fieldName); } if (!Modifier.isStatic(f.getModifiers())) throw new OgnlException("Field " + fieldName + " of class " + className + " is not static"); Object result = null; <START> if (!f.isAccessible() && context.getMemberAccess().isAccessible(context, null, f, null)) { <END> context.getMemberAccess().setup(context, null, f, null); try { result = f.get(null); } finally { context.getMemberAccess().restore(context, null, f, null, null); } } else { result = f.get(null); } return result; } catch (ClassNotFoundException e) { reason = e; } catch (NoSuchFieldException e) { reason = e; } catch (SecurityException e) { reason = e; } catch (IllegalAccessException e) { reason = e; } throw new OgnlException("Could not get static field " + fieldName + " from class " + className, reason); }</code><technical_language>suggestion if (context.getMemberAccess().isAccessible(context, null, f, null)) { !f.isAccessible() is needed IMO</technical_language>

Target:
public static Object getStaticField(OgnlContext context, String className, String fieldName) throws OgnlException { Exception reason = null; try { Class c = classForName(context, className); if (c == null) throw new OgnlException("Unable to find class " + className + " when resolving field name of " + fieldName); if (fieldName.equals("class")) { return c; } else if (OgnlRuntime.isJdk15() && c.isEnum()) { try { return Enum.valueOf(c, fieldName); } catch (IllegalArgumentException e) { } } Field f = getField(c, fieldName); if (f == null) { throw new NoSuchFieldException(fieldName); } if (!Modifier.isStatic(f.getModifiers())) throw new OgnlException("Field " + fieldName + " of class " + className + " is not static"); Object result = null; if (context.getMemberAccess().isAccessible(context, null, f, null)) { Object state = context.getMemberAccess().setup(context, null, f, null); try { result = f.get(null); } finally { context.getMemberAccess().restore(context, null, f, null, state); } } else { throw new IllegalAccessException("Access to " + fieldName + " of class " + className + " is forbidden"); } return result; } catch (ClassNotFoundException e) { reason = e; } catch (NoSuchFieldException e) { reason = e; } catch (SecurityException e) { reason = e; } catch (IllegalAccessException e) { reason = e; } throw new OgnlException("Could not get static field " + fieldName + " from class " + className, reason); }
Source:
<code>private void directoryRadioSelected() { if (fImportFromDirectoryRadio.getSelection()) { directoryNameField.setEnabled(true); directoryBrowseButton.setEnabled(true); fArchiveNameField.setEnabled(false); fArchiveBrowseButton.setEnabled(false); updateFromSourceField(); directoryNameField.setFocus(); <START> fCreateLinksInWorkspaceButton.setSelection(true); <END> fCreateLinksInWorkspaceButton.setEnabled(true); } }</code><technical_language>want preserve previous selection (before archive radio selected)</technical_language>

Target:
private void directoryRadioSelected() { if (fImportFromDirectoryRadio.getSelection()) { directoryNameField.setEnabled(true); directoryBrowseButton.setEnabled(true); fArchiveNameField.setEnabled(false); fArchiveBrowseButton.setEnabled(false); updateFromSourceField(); directoryNameField.setFocus(); fCreateLinksInWorkspaceButton.setSelection(fPreviousCreateLinksValue); fCreateLinksInWorkspaceButton.setEnabled(true); } }
Source:
<code>private Object convertValue(Object value, Type type) { if (value == null) { return null; } <START> if (BOOLEAN.equals(type) || DATE.equals(type) || Varchars.isVarcharType(type)) { <END> return value; } if (BIGINT.equals(type)) { return ((Number) value).longValue(); } if (INTEGER.equals(type)) { return ((Number) value).intValue(); } if (DOUBLE.equals(type)) { return ((Number) value).doubleValue(); } throw new IllegalArgumentException("Unhandled type: " + type); }</code><technical_language>== instead of equals: if (type == BOOLEAN || type == DATE || isVarcharType(type)) { return value; } if (type == BIGINT) { return ((Number) value).longValue(); } if (type == INTEGER) { return ((Number) value).intValue(); } if (type == DOUBLE) { return ((Number) value).doubleValue(); }</technical_language>

Target:
private Object convertValue(Object value, Type type) { if (value == null) { return null; } if (type == BOOLEAN || type == DATE || isVarcharType(type)) { return value; } if (type == BIGINT) { return ((Number) value).longValue(); } if (type == INTEGER) { return ((Number) value).intValue(); } if (type == DOUBLE) { return ((Number) value).doubleValue(); } throw new IllegalArgumentException("Unhandled type: " + type); }
Source:
<code>public HttpRequest filter(HttpRequest request) throws HttpException { <START> this.sasAuthentication = authSAS(this.credential); <END> if (this.sasAuthentication){ request = filterSAS(request, this.credential); } else { request = filterKey(request); } utils.logRequest(signatureLog, request, "<<"); return request; }</code><technical_language>This set in constructor instead of checking this request</technical_language>

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); utils.logRequest(signatureLog, request, "<<"); return request; }
Source:
<code>public void validateTextSearchIsAvailable() { assertThat(im.isTextSearchEnabled(), is(true)); <START> } <END></code><technical_language>Do want check compile options asserting this</technical_language>

Target:
public void validateTextSearchIsAvailable() throws Exception { Set<String> compileOptions = SQLDatabaseTestUtils.getCompileOptions(db); assertThat(compileOptions, hasItems("ENABLE_FTS3", "ENABLE_FTS3_PARENTHESIS")); assertThat(im.isTextSearchEnabled(), is(true)); }
Source:
<code>private static TimeBudget createTimeBudget(Properties properties) { String timeoutString = properties.getProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, Long.toString(DEFAULT_LEASED_CONNECTION_TIMEOUT.toMillis())); <START> long timeout = Long.parseLong(timeoutString); <END> return new TimeBudget(timeout, TimeUnit.MILLISECONDS); }</code><technical_language>Inelegant convert default timeout a string parsed a long</technical_language>

Target:
private static TimeBudget createTimeBudget(Properties properties) { String timeoutString = properties.getProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, DEFAULT_LEASED_CONNECTION_TIMEOUT); long timeout = Long.parseLong(timeoutString); return new TimeBudget(timeout, TimeUnit.MILLISECONDS); }
Source:
<code>public ObjectStat statObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InvalidResponseException { checkReadRequestSse(sse); Map<String, String> headers = null; if (sse != null) { headers = sse.headers(); } checkBucketName(bucketName); String errorMessage = ""; if ( objectName == null ) { errorMessage += " Object name cannot be null."; } else if ( objectName.equals("") ) { errorMessage += " Object name cannot be empty."; } if ( !errorMessage.equals("") ) { throw new InvalidArgumentException("Invalid Stat Object Argument(s)." + errorMessage); } HttpResponse response = executeHead(bucketName, objectName, headers); ResponseHeader header = response.header(); if ( header.contentLength() == 0 && header.contentType() == null <START> && header.statusCode() == null ) { <END> throw new InvalidArgumentException("Invalid Stat Object Arguments."); } Map<String,List<String>> httpHeaders = response.httpHeaders(); ObjectStat objectStat = new ObjectStat(bucketName, objectName, header, httpHeaders); return objectStat; }</code><technical_language>I this check is useful. S3 specification, Content-Length returned else server bug. statusCode is (else get exception) contentTypecan treated optional</technical_language>

Target:
public ObjectStat statObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InvalidResponseException { checkReadRequestSse(sse); checkBucketName(bucketName); if ( objectName == null || objectName.equals("") ) { throw new InvalidArgumentException("Invalid Stat Object Argument(s). Object name cannot be empty."); } Map<String, String> headers = null; if (sse != null) { headers = sse.headers(); } HttpResponse response = executeHead(bucketName, objectName, headers); ResponseHeader header = response.header(); Map<String,List<String>> httpHeaders = response.httpHeaders(); ObjectStat objectStat = new ObjectStat(bucketName, objectName, header, httpHeaders); return objectStat; }
Source:
<code>public String submitXMLFile(String sessionId, File file) throws RestServerException, ServiceException { HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/submit"); method.addHeader("sessionId", sessionId); boolean isJar = isJarFile(file); try { String name = isJar ? "jar" : "file"; String mime = isJar ? "application/java-archive" : "application/xml"; String charset = "ISO-8859-1"; MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file, name, mime, charset)); method.setEntity(entity); HttpResponse execute = httpClient.execute(method); InputStream is = execute.getEntity().getContent(); String ret = convertToString(is); <START> if (execute.getStatusLine().getStatusCode() == 200) { <END> return ret; } else { throw new RestServerException(execute.getStatusLine().getStatusCode(), ret); } } catch (IOException e) { throw new ServiceException("Failed to read response: " + e.getMessage()); } finally { method.releaseConnection(); if (file != null) { file.delete(); } } }</code><technical_language>200-> enum</technical_language>

Target:
public String submitXMLFile(String sessionId, File file) throws RestServerException, ServiceException { HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/submit"); method.addHeader("sessionId", sessionId); boolean isJar = isJarFile(file); try { String name = isJar ? "jar" : "file"; String mime = isJar ? "application/java-archive" : "application/xml"; String charset = "ISO-8859-1"; MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file, name, mime, charset)); method.setEntity(entity); HttpResponse execute = httpClient.execute(method); InputStream is = execute.getEntity().getContent(); String ret = convertToString(is); if (execute.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) { return ret; } else { throw new RestServerException(execute.getStatusLine().getStatusCode(), ret); } } catch (IOException e) { throw new ServiceException("Failed to read response: " + e.getMessage()); } finally { method.releaseConnection(); if (file != null) { file.delete(); } } }
Source:
<code>protected void prepareTestData() { removeAndRestoreTypicalDataBundle(); FeedbackSessionAttributes gracePeriodSession; FeedbackSessionAttributes session1InCourse1; <START> FeedbackSessionAttributes closedSession; <END> session1InCourse1 = typicalBundle.feedbackSessions.get("session1InCourse1"); gracePeriodSession = typicalBundle.feedbackSessions.get("gracePeriodSession"); closedSession = typicalBundle.feedbackSessions.get("closedSession"); instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); student1InCourse1 = typicalBundle.students.get("student1InCourse1"); qn1InSession1InCourse1 = logic.getFeedbackQuestion( session1InCourse1.getFeedbackSessionName(), session1InCourse1.getCourseId(), 1); qn2InGracePeriodInCourse1 = logic.getFeedbackQuestion( gracePeriodSession.getFeedbackSessionName(), gracePeriodSession.getCourseId(), 2); qn1InClosedSessionInCourse1 = logic.getFeedbackQuestion( closedSession.getFeedbackSessionName(), closedSession.getCourseId(), 1); instructor1OfCourse2 = typicalBundle.instructors.get("instructor1OfCourse2"); student2InCourse1 = typicalBundle.students.get("student2InCourse1"); student5InCourse1 = typicalBundle.students.get("student5InCourse1"); instructor2OfCourse1 = typicalBundle.instructors.get("instructor2OfCourse1"); qn2InSession1InCourse1 = logic.getFeedbackQuestion( session1InCourse1.getFeedbackSessionName(), session1InCourse1.getCourseId(), 2); }</code><technical_language>definition is unnecessary? java FeedbackSessionAttributes session1InCourse1 = typicalBundle.feedbackSessions.get("session1InCourse1");</technical_language>

Target:
protected void prepareTestData() { removeAndRestoreTypicalDataBundle(); FeedbackSessionAttributes gracePeriodSession = typicalBundle.feedbackSessions.get("gracePeriodSession"); FeedbackSessionAttributes session1InCourse1 = typicalBundle.feedbackSessions.get("session1InCourse1"); FeedbackSessionAttributes closedSession = typicalBundle.feedbackSessions.get("closedSession"); instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); student1InCourse1 = typicalBundle.students.get("student1InCourse1"); qn1InSession1InCourse1 = logic.getFeedbackQuestion( session1InCourse1.getFeedbackSessionName(), session1InCourse1.getCourseId(), 1); qn2InGracePeriodInCourse1 = logic.getFeedbackQuestion( gracePeriodSession.getFeedbackSessionName(), gracePeriodSession.getCourseId(), 2); qn1InClosedSessionInCourse1 = logic.getFeedbackQuestion( closedSession.getFeedbackSessionName(), closedSession.getCourseId(), 1); instructor1OfCourse2 = typicalBundle.instructors.get("instructor1OfCourse2"); student2InCourse1 = typicalBundle.students.get("student2InCourse1"); student5InCourse1 = typicalBundle.students.get("student5InCourse1"); instructor2OfCourse1 = typicalBundle.instructors.get("instructor2OfCourse1"); qn2InSession1InCourse1 = logic.getFeedbackQuestion( session1InCourse1.getFeedbackSessionName(), session1InCourse1.getCourseId(), 2); }
Source:
<code>@Test public void dragNDropByElementTest() throws Exception { Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo"); driver.startActivity(activity); WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); assertEquals("Drag text not empty", "", dragText.getText()); TouchAction dragNDrop = new TouchAction(driver) <START> .longPress(elementOption(dragDot1)) <END> .moveTo(elementOption(dragDot3)) .release(); dragNDrop.perform(); assertNotEquals("Drag text empty", "", dragText.getText()); }</code><technical_language>withOffset(elementOption(...))</technical_language>

Target:
@Test public void dragNDropByElementTest() throws Exception { Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo"); driver.startActivity(activity); WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); assertEquals("Drag text not empty", "", dragText.getText()); TouchAction dragNDrop = new TouchAction(driver) .longPress(element(dragDot1)) .moveTo(element(dragDot3)) .release(); dragNDrop.perform(); assertNotEquals("Drag text empty", "", dragText.getText()); }
Source:
<code>public void loadKeyRSAPassword() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("rsa-password").getFile()); String password = "password"; <START> assertkeyPair(file, password); <END> }</code><technical_language>suggestion assertKeyPair(file, password);</technical_language>

Target:
public void loadKeyRSAPassword() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("rsa-password").getFile()); String password = "password"; assertKeyPairNotNull(file, password); }
Source:
<code>public @ResponseBody Team getTeamById( HttpSession session, @PathVariable int id) { <START> if(session.getAttribute("session") == null) { <END> return null; } TeamDao teamDao = new TeamDao(); return teamDao.getTeamById(id, false, true, false); }</code><technical_language>this member? I a bunch of places session, too</technical_language>

Target:
public @ResponseBody Team getTeamById( HttpSession session, @PathVariable int id) { if(session.getAttribute("member") == null) { return null; } TeamDao teamDao = new TeamDao(); return teamDao.getTeamById(id, false, true, false); }
Source:
<code>private void printUsage(ArgumentsParser parser) { StringBuilder sb = new StringBuilder(); for(String action : actions.keySet()) { sb.append(String.format(" %-32s - %s\n", action, parser.getActionHeader(action))); } System.out.format( <START> "usage: %s", <END> parser.getUsage() .replace("@PROGRAM_NAME@", (String) context.get(PROGRAM_NAME)) .replace("@ACTION_LIST@", sb.toString()) ); }</code><technical_language>s/usage/Usage/</technical_language>

Target:
private void printUsage(ArgumentsParser parser) { StringBuilder sb = new StringBuilder(); for(String action : actions.keySet()) { sb.append(String.format(" %-32s - %s\n", action, parser.getActionHeader(action))); } System.out.format( "Usage: %s", parser.getUsage() .replace("@PROGRAM_NAME@", (String) context.get(PROGRAM_NAME)) .replace("@ACTION_LIST@", sb.toString()) ); }
Source:
<code><START> public void save(){ <END> checkIfCustomDataNeedsUpdate(); super.save(); }</code><technical_language>discussion, need delete removed custom data properties saving account custom data changes</technical_language>

Target:
public void save(){ applyCustomDataUpdatesIfNecessary(); super.save(); }
Source:
<code>protected Address getReplyToAddress(Message request) throws Exception { Address replyTo; <START> replyTo = AddressUtils.decodeReplyToAddress(request); <END> if (replyTo == null) { if (this.responseExchange == null) { throw new AmqpException( "Cannot determine ReplyTo message property value: " + "Request message does not contain reply-to property, " + "and no default response Exchange was set."); } replyTo = new Address(this.responseExchange, this.responseRoutingKey); } return replyTo; }</code><technical_language>declaration initialization splitted</technical_language>

Target:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo = AddressUtils.decodeReplyToAddress(request); if (replyTo == null) { if (this.responseExchange == null) { throw new AmqpException( "Cannot determine ReplyTo message property value: " + "Request message does not contain reply-to property, " + "and no default response Exchange was set."); } replyTo = new Address(this.responseExchange, this.responseRoutingKey); } return replyTo; }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; <START> result = prime * result + ((key == null) ? 0 : key.hashCode()); <END> result = prime * result + ((state == null) ? 0 : state.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; }</code><technical_language>null checks key state redundand</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + key.hashCode(); result = prime * result + state.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; }
Source:
<code>public String toString() { Class<Map<String, String>> clazz = (Class) Map.class; Map<String, String> params = MAPPER.convertValue(this.getParams(), clazz); if (params.containsKey("password")) { params.put("password", <START> "XXX"); <END> } return "<JsonRpcRequest id: " + this.getId() + ", method: " + this.getMethod() + ", params: " + params + ">"; }</code><technical_language>a nit: ***** XXX</technical_language>

Target:
public String toString() { Class<Map<String, String>> clazz = (Class) Map.class; Map<String, String> params = MAPPER.convertValue(this.getParams(), clazz); if (params.containsKey("password")) { params.put("password", "*****"); } return "<JsonRpcRequest id: " + this.getId() + ", method: " + this.getMethod() + ", params: " + params + ">"; }
Source:
<code>public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } <START> return credential.getToken(tokenRequestContext) <END> .flatMap(token -> { context.getHttpRequest().getHeaders().put(AUTHORIZATION_HEADER, BEARER + " " + token.getToken()); return next.process(); }); }</code><technical_language>need plumb this change in custom Token Credential Auth policies a cache is maintained. open issue, for now, track this work get change added Track 2 SDKs Identity is GA</technical_language>

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } return cache.getToken() .flatMap(token -> { context.getHttpRequest().getHeaders().put(AUTHORIZATION_HEADER, BEARER + " " + token.getToken()); return next.process(); }); }
Source:
<code>public void add(final int number, final int megaBytes, final int cores, final EventHandler<AllocatedEvaluator> evaluatorAllocatedHandler, final List<EventHandler <ActiveContext>> contextActiveHandlerList) { addQueue.add(new Tuple2<>(evaluatorAllocatedHandler, contextActiveHandlerList)); <START> } <END></code><technical_language>do need queues? invoke handlers in add(), delete(), move() methods? benefits of queues failed catch</technical_language>

Target:
public void add(final int number, final int megaBytes, final int cores, final EventHandler<AllocatedEvaluator> evaluatorAllocatedHandler, final List<EventHandler <ActiveContext>> contextActiveHandlerList) { try { addHandlerQueue.put(new Tuple2<>(evaluatorAllocatedHandler, contextActiveHandlerList)); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while putting Add to queue", e); } }
Source:
<code>public boolean initQueue() { <START> if (isInitialized.compareAndSet(false, true)) { <END> log.info("InMemoryPersistentBus initialized"); return true; } else { return false; } }</code><technical_language>orthogonal this change, add check for isProcessingOff -- similarly DefaultPersistentBus#initQueue</technical_language>

Target:
public boolean initQueue() { if (config.isProcessingOff()) { log.warn("InMemoryPersistentBus processing is off, cannot be initialized"); return false; } if (isInitialized.compareAndSet(false, true)) { log.info("InMemoryPersistentBus initialized"); return true; } else { return false; } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder().append(this.getClass().getSimpleName()) .append("{keyBytes=").append(keyBytes) <START> .append(", valueBytes=").append(valueBytes) <END> .append(", metadataBytes=").append(metadataBytes) .append(", key=").append(key); if (key == null && keyBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(keyBytes)); } sb.append(", value=").append(value); if (value == null && valueBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(valueBytes)); } sb.append(", metadata=").append(metadata); if (metadata == null && metadataBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(metadataBytes)); } sb.append(", marshaller=").append(marshaller).append('}'); return sb.toString(); }</code><technical_language>Util.hexDump() for keyBytes log key null if unmarshalled before, I noticed I guess bother :)</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder().append(this.getClass().getSimpleName()) .append("{keyBytes=").append(keyBytes) .append(", valueBytes=").append(valueBytes) .append(", metadataBytes=").append(metadataBytes) .append(", key=").append(key); if (key == null && keyBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(keyBytes)); } sb.append(", value=").append(value); if (value == null && valueBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(valueBytes)); } sb.append(", metadata=").append(metadata); if (metadata == null && metadataBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(metadataBytes)); } sb.append(", created=").append(created); sb.append(", lastUsed=").append(lastUsed); sb.append(", marshaller=").append(marshaller).append('}'); return sb.toString(); }
Source:
<code>void verifyConstructLength(String constructType, int maxLength, ParserRuleContext ctx) { if (SourceFileUtil.constructTooLong(ctx, maxLength)) { int constructLength = ctx.getStop().getLine() - ctx.getStart().getLine(); String lengthVersusLimit = " (" + constructLength + "/" + maxLength + ")"; Location location = ListenerUtil.getContextStartLocation(ctx); <START> this.printer.error(constructType + Messages.EXCEEDS_LINE_LIMIT + lengthVersusLimit, location); <END> } }</code><technical_language>Liens [24,26] similar [32,24]. refactor</technical_language>

Target:
void verifyConstructLength(String constructType, int maxLength, ParserRuleContext ctx) { if (SourceFileUtil.constructTooLong(ctx, maxLength)) { int constructLength = ctx.getStop().getLine() - ctx.getStart().getLine(); createErrorMessage(constructLength, ctx, constructType, maxLength, Messages.EXCEEDS_LINE_LIMIT); } }
Source:
<code>public void startWithBadInputTest() throws InstantiationException, IOException { <START> for (int i = 0; i < 2; i++) { <END> Properties properties = new Properties(); properties.setProperty(i == 0 ? "netty.server.port" : "netty.server.ssl.port", "-1"); NioServer nioServer = getNettyServer(properties); try { nioServer.start(); fail("NettyServer start() should have failed because of bad port number value"); } catch (IllegalArgumentException e) { } finally { if (nioServer != null) { nioServer.shutdown(); } } } }</code><technical_language>minor: prefer writing a function verifyStartFailure(Properties properties) instead of manipulating loop variables</technical_language>

Target:
public void startWithBadInputTest() throws InstantiationException, IOException { Properties properties = new Properties(); properties.setProperty("netty.server.port", "-1"); doStartFailureTest(properties); properties = new Properties(); properties.setProperty("netty.server.ssl.port", "-1"); doStartFailureTest(properties); }
Source:
<code>private void interruptAndWaitCleanupTime() { threadToKill.interrupt(); Sleeper cleanupTimeSleeper = getCleanupTimeSleeper(); <START> cleanupTimeSleeper.sleep(); <END> }</code><technical_language>problem this implementation, is sleeper wait for 10 more seconds matter if threads finish quickly</technical_language>

Target:
private void interruptAndWaitCleanupTime() { threadToKill.interrupt(); long iterationsToHitWaitingTimeLimit = getCleanupTimeSeconds() * MULTIPLIER_FROM_SECONDS_TO_ITERATION_WITH_CLEANUP_TIME_SLEEPER; for (long i = 0; threadToKill.isAlive() && i < iterationsToHitWaitingTimeLimit; i++) { cleanupTimeSleeper.sleep(); } }
Source:
<code>public void remove(PrioritizedSplitRunner split) { lock.lock(); for (int level = 0; level < LEVELS.length; level++) { <START> levelWaitingSplits.get(level).remove(split); <END> } lock.unlock(); }</code><technical_language>check split is null - levelWaitingSplits.get(split.getLevel()).remove</technical_language>

Target:
public void remove(PrioritizedSplitRunner split) { checkArgument(split != null, "split is null"); lock.lock(); try { for (PriorityQueue<PrioritizedSplitRunner> level : levelWaitingSplits) { level.remove(split); } } finally { lock.unlock(); } }
Source:
<code>public ValidationResult runPoolValidationForActivationKey(ActivationKey key, Pool pool, Long quantity) { ValidationResult result = new ValidationResult(); if (quantity != null && quantity < 1) { result.addError("rulefailed.invalid.quantity"); } <START> if (!"yes".equalsIgnoreCase(pool.getMergedProductAttribute(Pool.Attributes.MULTI_ENTITLEMENT))) { <END> if (quantity != null && quantity > 1) { result.addError("rulefailed.invalid.nonmultient.quantity"); } for (ActivationKeyPool akPool : key.getPools()) { if (pool.getId().equals(akPool.getPool().getId())) { result.addError("rulefailed.already.exists"); break; } } } if (ConsumerType.ConsumerTypeEnum.PERSON.getLabel().equalsIgnoreCase( pool.getMergedAttribute(Pool.Attributes.REQUIRES_CONSUMER_TYPE))) { result.addError("rulefailed.actkey.cannot.use.person.pools"); } return result; }</code><technical_language>I if transition magic strings stringified-boolean check covers affirmative string values (i.e. "yes", "y", "true", "t", "1", etc.). a give flexibility standardize values some undetermined point in future remove a magic string code</technical_language>

Target:
public ValidationResult runPoolValidationForActivationKey(ActivationKey key, Pool pool, Long quantity) { ValidationResult result = new ValidationResult(); if (quantity != null && quantity < 1) { result.addError(ErrorKeys.INVALID_QUANTITY); } if (!PropertyConverter.toBoolean(pool.getMergedProductAttribute(Pool.Attributes.MULTI_ENTITLEMENT))) { if (quantity != null && quantity > 1) { result.addError(ErrorKeys.INVALID_NON_MULTIENT_QUANTITY); } for (ActivationKeyPool akPool : key.getPools()) { if (pool.getId().equals(akPool.getPool().getId())) { result.addError(ErrorKeys.ALREADY_EXISTS); break; } } } if (ConsumerType.ConsumerTypeEnum.PERSON.getLabel().equalsIgnoreCase( pool.getMergedAttribute(Pool.Attributes.REQUIRES_CONSUMER_TYPE))) { result.addError(ErrorKeys.CANNOT_USE_PERSON_POOLS); } return result; }
Source:
<code>public void close() throws IOException { <START> flush(); <END> started.set(false); exec.shutdown(); }</code><technical_language>need call flush is in queue synchronize start</technical_language>

Target:
public void close() throws IOException { synchronized (started) { flush(); exec.shutdown(); started.set(false); } }
Source:
<code>public AbstractResponse getErrorResponse(int throttleTimeMs, Errors error) { OffsetDeleteResponseTopicCollection topics = new OffsetDeleteResponseTopicCollection(); <START> for (OffsetDeleteRequestTopic topic : data.topics()) { <END> OffsetDeleteResponsePartitionCollection partitions = new OffsetDeleteResponsePartitionCollection(); for (OffsetDeleteRequestPartition partition : topic.partitions()) { partitions.add(new OffsetDeleteResponsePartition() .setPartitionIndex(partition.partitionIndex()) .setErrorCode(error.code()) ); } topics.add(new OffsetDeleteResponseTopic() .setName(topic.name()) .setPartitions(partitions) ); } return new OffsetDeleteResponse( new OffsetDeleteResponseData() .setTopics(topics) .setThrottleTimeMs(throttleTimeMs) .setErrorCode(error.code()) ); }</code><technical_language>In this case, reasonable set top level error? If client sees a top-level error code is NONE, is need process partition-level errors</technical_language>

Target:
public AbstractResponse getErrorResponse(int throttleTimeMs, Errors error) { return new OffsetDeleteResponse( new OffsetDeleteResponseData() .setThrottleTimeMs(throttleTimeMs) .setErrorCode(error.code()) ); }
Source:
<code>public void testSelectByWeightLeastActive() { int loop = 10000; Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, LeastActiveLoadBalance.NAME); int test3Weight = 0; for (Entry<Invoker, InvokeResult> entry : resultMap.entrySet()) { String protocol = entry.getKey().getUrl().getProtocol(); if (protocol.equals("test3")) { Assert.assertEquals(0, entry.getValue().getCount().get()); test3Weight = entry.getValue().getWeight(); } } for (Entry<Invoker, InvokeResult> entry : resultMap.entrySet()) { String protocol = entry.getKey().getUrl().getProtocol(); if (!protocol.equals("test3")) { InvokeResult invokeResult = entry.getValue(); invokeResult.setTotalWeight(invokeResult.getTotalWeight() - test3Weight); <START> Assert.assertTrue(invokeResult.getDeltaPercentage(loop) < 12); <END> } } }</code><technical_language>I this is a good calc percentage of select. is stable</technical_language>

Target:
public void testSelectByWeightLeastActive() { int sumInvoker1 = 0; int sumInvoker2 = 0; int loop = 10000; LeastActiveLoadBalance lb = new LeastActiveLoadBalance(); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokers, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } Assert.assertTrue("select is not the least active one", !selected.getUrl().getProtocol().equals("test3")); } System.out.println(sumInvoker1); System.out.println(sumInvoker2); Assert.assertEquals("select failed!", sumInvoker1 + sumInvoker2, loop); }
Source:
<code>public PlanNode visitTableScan(TableScanNode node, RewriteContext<Void> context) { if (subfieldPaths.isEmpty()) { return node; } ImmutableMap.Builder<Symbol, ColumnHandle> newAssignmentsBuilder = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, List<SubfieldPath>> leafSubfieldsBuilder = ImmutableMap.builder(); for (Map.Entry<Symbol, ColumnHandle> entry : node.getAssignments().entrySet()) { if (fullColumnUses.contains(entry.getKey())) { newAssignmentsBuilder.put(entry); continue; } List<SubfieldPath> subfields = new ArrayList(); for (SubfieldPath path : subfieldPaths) { if (path.getColumnName().equals(entry.getKey().getName())) { subfields.add(path); } } if (subfields.isEmpty()) { newAssignmentsBuilder.put(entry); continue; } List<SubfieldPath> leafPaths = new ArrayList(); for (SubfieldPath path : subfields) { if (!prefixExists(path, subfields)) { leafPaths.add(path); } } newAssignmentsBuilder.put(entry); leafSubfieldsBuilder.put(entry.getKey(), leafPaths); } Map<Symbol, List<SubfieldPath>> leafSubfields = leafSubfieldsBuilder.build(); if (leafSubfields.isEmpty()) { return node; } return new TableScanNode( node.getId(), node.getTable(), node.getOutputSymbols(), <START> newAssignmentsBuilder.build(), <END> node.getLayout(), node.getCurrentConstraint(), node.getEnforcedConstraint(), leafSubfields); }</code><technical_language>this node.getAssignments() newAssignmentsBuilder variable removed</technical_language>

Target:
public PlanNode visitTableScan(TableScanNode node, RewriteContext<Void> context) { if (subfieldPaths.isEmpty()) { return node; } ImmutableMap.Builder<Symbol, List<Subfield>> leafSubfieldsBuilder = ImmutableMap.builder(); for (Map.Entry<Symbol, ColumnHandle> entry : node.getAssignments().entrySet()) { if (fullColumnUses.contains(entry.getKey())) { continue; } List<Subfield> subfields = new ArrayList(); for (Subfield path : subfieldPaths) { if (path.getRootName().equals(entry.getKey().getName())) { subfields.add(path); } } if (subfields.isEmpty()) { continue; } List<Subfield> leafPaths = new ArrayList(); for (Subfield path : subfields) { if (!prefixExists(path, subfields)) { leafPaths.add(path); } } leafSubfieldsBuilder.put(entry.getKey(), leafPaths); } Map<Symbol, List<Subfield>> leafSubfields = leafSubfieldsBuilder.build(); if (leafSubfields.isEmpty()) { return node; } return new TableScanNode( node.getId(), node.getTable(), node.getOutputSymbols(), node.getAssignments(), node.getCurrentConstraint(), node.getEnforcedConstraint(), node.isTemporaryTable(), leafSubfields); }
Source:
<code>public void createAnomalyAlertConfiguration(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion) { final AtomicReference<String> alertConfigurationId = new AtomicReference<>(); try { client = getMetricsAdvisorAdministrationBuilder(httpClient, serviceVersion).buildAsyncClient(); creatAnomalyAlertRunner(inputAnomalyAlert -> StepVerifier.create(client.createAnomalyAlertConfiguration(inputAnomalyAlert)) .assertNext(createdAnomalyAlert -> { alertConfigurationId.set(createdAnomalyAlert.getId()); validateAnomalyAlertResult(inputAnomalyAlert, createdAnomalyAlert); }) .verifyComplete()); } finally { Mono<Void> deleteAnomalyAlertConfiguration = client.deleteAnomalyAlertConfiguration(alertConfigurationId.get()); <START> StepVerifier.create(deleteAnomalyAlertConfiguration).verifyComplete(); <END> } }</code><technical_language>In finally attempt clean resource if alertConfigurationId a (which means creation succeeded)</technical_language>

Target:
public void createAnomalyAlertConfiguration(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion) { final AtomicReference<String> alertConfigurationId = new AtomicReference<>(); try { client = getMetricsAdvisorAdministrationBuilder(httpClient, serviceVersion).buildAsyncClient(); creatAnomalyAlertRunner(inputAnomalyAlert -> StepVerifier.create(client.createAnomalyAlertConfiguration(inputAnomalyAlert)) .assertNext(createdAnomalyAlert -> { alertConfigurationId.set(createdAnomalyAlert.getId()); validateAnomalyAlertResult(inputAnomalyAlert, createdAnomalyAlert); }) .verifyComplete()); } finally { if (!CoreUtils.isNullOrEmpty(alertConfigurationId.get())) { Mono<Void> deleteAnomalyAlertConfiguration = client.deleteAnomalyAlertConfiguration(alertConfigurationId.get()); StepVerifier.create(deleteAnomalyAlertConfiguration).verifyComplete(); } } }
Source:
<code>protected UserSimpleFilterChain createFilterChain(FilterExpression<UserEntity> filter) { <START> return new UserSimpleFilterChain(entityManager.getCriteriaBuilder(), extensionDao, (UserFilterExpression) filter); <END> }</code><technical_language>a method then. abstract method needs FilterExpression<UserEntity> instances of UserFilterExpression. a this</technical_language>

Target:
protected UserSimpleFilterChain createFilterChain(FilterExpression<UserEntity> filter) { return new UserSimpleFilterChain(entityManager.getCriteriaBuilder(), extensionDao, filter); }
Source:
<code>public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ProductDTO && super.equals(obj)) { ProductDTO that = (ProductDTO) obj; EqualsBuilder builder = new EqualsBuilder() .append(this.getUuid(), that.getUuid()) .append(this.getId(), that.getId()) .append(this.getName(), that.getName()) .append(this.getMultiplier(), that.getMultiplier()) .append(this.getAttributes(), that.getAttributes()) .append(this.getDependentProductIds(), that.getDependentProductIds()) .append(this.getHref(), that.getHref()) .append(this.isLocked(), that.isLocked()) .append(this.getBranding(), that.getBranding()); boolean equals = builder.isEquals(); equals = equals && Util.collectionsAreEqual(this.getProductContent(), that.getProductContent()); equals = equals && <START> Util.collectionsAreEqual(this.getProvidedProducts(), that.getProvidedProducts()); <END> return equals; } return false; }</code><technical_language>of Util.collectionsAreEqual unnecessary other DTOs (manifest ProductDTO, ProductData)? @Ceiu I right in thinking need this method in hibernate entity classes, hibernate collections implement .equals properly</technical_language>

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ProductDTO && super.equals(obj)) { ProductDTO that = (ProductDTO) obj; EqualsBuilder builder = new EqualsBuilder() .append(this.getUuid(), that.getUuid()) .append(this.getId(), that.getId()) .append(this.getName(), that.getName()) .append(this.getMultiplier(), that.getMultiplier()) .append(this.getAttributes(), that.getAttributes()) .append(this.getDependentProductIds(), that.getDependentProductIds()) .append(this.getHref(), that.getHref()) .append(this.isLocked(), that.isLocked()) .append(this.getBranding(), that.getBranding()) .append(this.getProvidedProducts(), that.getProvidedProducts()); boolean equals = builder.isEquals(); equals = equals && Util.collectionsAreEqual(this.getProductContent(), that.getProductContent()); return equals; } return false; }