auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testUpsertSelectDoesntSeeUpsertedData() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.MUTATE_BATCH_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_CACHE_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_RESULT_CHUNK_SIZE, Integer.toString(3)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(true); conn.createStatement().execute("CREATE SEQUENCE "+seqName); <START> BaseTest.createSchema(getUrl(), fullTableName, null); <END> conn.createStatement().execute("CREATE TABLE " + fullTableName + "(pk INTEGER PRIMARY KEY, val INTEGER)"+(!mutable? " IMMUTABLE_ROWS=true" : "")); conn.createStatement().execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + "(val)"); conn.createStatement().execute("UPSERT INTO " + fullTableName + " VALUES (NEXT VALUE FOR " + seqName + ",1)"); for (int i=0; i<6; i++) { Statement stmt = conn.createStatement(); int upsertCount = stmt.executeUpdate("UPSERT INTO " + fullTableName + " SELECT NEXT VALUE FOR " + seqName + ", val FROM " + fullTableName); assertEquals((int)Math.pow(2, i), upsertCount); } conn.close(); }</code><technical_language>Is this change needed</technical_language>

Target:
public void testUpsertSelectDoesntSeeUpsertedData() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.MUTATE_BATCH_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_CACHE_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_RESULT_CHUNK_SIZE, Integer.toString(3)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(true); conn.createStatement().execute("CREATE SEQUENCE "+seqName); conn.createStatement().execute("CREATE TABLE " + fullTableName + "(pk INTEGER PRIMARY KEY, val INTEGER)"+(!mutable? " IMMUTABLE_ROWS=true" : "")); conn.createStatement().execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + "(val)"); conn.createStatement().execute("UPSERT INTO " + fullTableName + " VALUES (NEXT VALUE FOR " + seqName + ",1)"); for (int i=0; i<6; i++) { Statement stmt = conn.createStatement(); int upsertCount = stmt.executeUpdate("UPSERT INTO " + fullTableName + " SELECT NEXT VALUE FOR " + seqName + ", val FROM " + fullTableName); assertEquals((int)Math.pow(2, i), upsertCount); } conn.close(); }
Source:
<code>private ActionEventRequest buildCreateObservationJSON(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createObservationJSON"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); <START> actionParameters.add(prepareParameter(Keys.OBSERVATION_JSON, DisplayNames.OBSERVATION_JSON, TEXTAREA, "{}", true, order++)); <END> actionParameters.add(prepareParameter(Keys.ENCOUNTER_UUID, DisplayNames.ENCOUNTER_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.CONCEPT_UUID, DisplayNames.CONCEPT_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_DATETIME, DisplayNames.OBSERVATION_DATETIME, DATE, false, order++)); actionParameters.add(prepareParameter(Keys.COMMENT, DisplayNames.COMMENT, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_OBSERVATION_JSON, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(actionParameters) .createActionEventRequest(); }</code><technical_language>please create a variable named 'defaultValueForJsonField = "{}". more readable</technical_language>

Target:
private ActionEventRequest buildCreateObservationJSON(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createObservationJSON"; String defaultValueForJsonField = "{}"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_JSON, DisplayNames.OBSERVATION_JSON, TEXTAREA, defaultValueForJsonField, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_UUID, DisplayNames.ENCOUNTER_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.CONCEPT_UUID, DisplayNames.CONCEPT_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_DATETIME, DisplayNames.OBSERVATION_DATETIME, DATE, false, order++)); actionParameters.add(prepareParameter(Keys.COMMENT, DisplayNames.COMMENT, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_OBSERVATION_JSON, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(actionParameters) .createActionEventRequest(); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } <START> BenchmarkQuery other = (BenchmarkQuery) obj; return Objects.equals(this.querySet, other.querySet) && Objects.equals(this.name, other.name) && Objects.equals(this.query, other.query) && Objects.equals(this.catalog, other.catalog) && Objects.equals(this.schema, other.schema); <END> }</code><technical_language>nit: a QueryConfiguration for this part, for consistency</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } BenchmarkQuery o = (BenchmarkQuery) obj; return Objects.equals(querySet, o.querySet) && Objects.equals(name, o.name) && Objects.equals(query, o.query) && Objects.equals(catalog, o.catalog) && Objects.equals(schema, o.schema); }
Source:
<code>public Opt<Identity> enter(final Request request) throws IOException { final Iterator<String> headers = new RqHeaders.Smart( new RqHeaders.Base(request) ).header("authorization").iterator(); if (!headers.hasNext()) { throw new RsForward( new RsWithHeader( String.format( "WWW-Authenticate: Basic ream=\"%s\" ", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } final String decoded = new Utf8String( DatatypeConverter.parseBase64Binary( PsBasic.AUTH.split(headers.next())[1] ) <START> ).asString().trim(); <END> final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }</code><technical_language>@Iprogrammerr TrimmedText instead trim() here</technical_language>

Target:
public Opt<Identity> enter(final Request request) throws IOException { final Iterator<String> headers = new RqHeaders.Smart( new RqHeaders.Base(request) ).header("authorization").iterator(); if (!headers.hasNext()) { throw new RsForward( new RsWithHeader( String.format( "WWW-Authenticate: Basic ream=\"%s\" ", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } final String decoded = new UncheckedText( new TrimmedText( new Utf8String( DatatypeConverter.parseBase64Binary( PsBasic.AUTH.split(headers.next())[1] ) ) ) ).asString(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }
Source:
<code><START> private void checkObjectCollision(AnyObjectId obj, int type, byte[] data) throws IOException { try { <END> final ObjectLoader ldr = readCurs.open(obj, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } } catch (MissingObjectException notLocal) { } }</code><technical_language>missing duplicated bytes instrumenting this method (for deltas) too</technical_language>

Target:
private void checkObjectCollision(AnyObjectId obj, int type, byte[] data) throws IOException { try { final ObjectLoader ldr = readCurs.open(obj, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } stats.increaseNumBytesDuplicated(data.length()); stats.incrementObjectsDuplicated(); } catch (MissingObjectException notLocal) { } }
Source:
<code>public static String formatTimeAbs(long time, Resolution res) { StringBuilder str = new StringBuilder(); String stime = TIME_FORMAT.format(new Date(time / MILLISEC_IN_NS)); <START> str.append(stime); <END> String ns = formatNs(time, res); if (!ns.isEmpty()) { str.append('.'); str.append(ns); } return str.toString(); }</code><technical_language>init string builder stime arg</technical_language>

Target:
public static String formatTimeAbs(long time, Resolution res) { String stime = TIME_FORMAT.format(new Date(time / MILLISEC_IN_NS)); StringBuilder str = new StringBuilder(stime); String ns = formatNs(time, res); if (!ns.isEmpty()) { str.append('.'); str.append(ns); } return str.toString(); }
Source:
<code>public String toString() { return file + ": " + contig.toString() + ", locus size = " + sizeInLoci(); <START> } <END></code><technical_language>change cached instead if cached set output ? if computation in some decision making cachedvalue is zero outputted if cares it</technical_language>

Target:
public String toString() { String str = file + ": " + contig.toString() + ", locus size = " + sizeInLoci(); if (cachedSizeInBytes >= 0) { str += ", span size = " + cachedSizeInBytes; } return str; }
Source:
<code>private <T> Message<O> toMessage(T value, Message<I> originalMessage) { <START> logger.debug("Converting result back to message using the original message: " + originalMessage); <END> if (value instanceof Message) { value = (T) ((Message<?>)value).getPayload(); } Message<O> result = (Message<O>) this.messageConverter.toMessage(value, originalMessage.getHeaders()); return result; }</code><technical_language>If build string runtime, need wrap logger.isDebugEnabled() condition</technical_language>

Target:
private <T> Message<O> toMessage(T value, Message<I> originalMessage) { if (logger.isDebugEnabled()) { logger.debug("Converting result back to message using the original message: " + originalMessage); } Message<O> result = value instanceof Message ? result = (Message<O>) value : (Message<O>) this.messageConverter.toMessage(value, originalMessage.getHeaders()); return result; }
Source:
<code>static ClassPathElement getClassPathElement(File file) throws ZipException, IOException { if (file.isDirectory()) { return new FolderPathElement(file); } else if (file.isFile()) { return new ArchivePathElement(new ZipFile(file)); } else if (file.exists()) { throw new <START> IOException(file.getAbsolutePath() <END> + " is not a directory neither a zip file"); } else { throw new FileNotFoundException(file.getAbsolutePath()); } }</code><technical_language>Absolute path</technical_language>

Target:
static ClassPathElement getClassPathElement(File file) throws ZipException, IOException { if (file.isDirectory()) { return new FolderPathElement(file); } else if (file.isFile()) { return new ArchivePathElement(new ZipFile(file)); } else if (file.exists()) { throw new IOException("\"" + file.getPath() + "\" is not a directory neither a zip file"); } else { throw new FileNotFoundException("File \"" + file.getPath() + "\" not found"); } }
Source:
<code><START> public void finished(boolean successful, Operation operation) { <END> statistics.record(this, operation); this.successful = successful; }</code><technical_language>redundant</technical_language>

Target:
public void finished(boolean successful, Operation operation) { this.successful = successful; statistics.record(this, operation); }
Source:
<code>private EntityDamageHandler getEntityDamageHandler() { return (e, entity, item1) -> { if (entity instanceof Skeleton || entity instanceof SkeletonHorse) { ((Creature) entity).damage(e.getFinalDamage() + 4D); <START> e.setCancelled(true); <END> } }; }</code><technical_language>damage cancel. set damage continue. break sorts of protection plugins sorts this</technical_language>

Target:
private EntityDamageHandler getEntityDamageHandler() { return (e, entity, item1) -> { if (entity instanceof Skeleton || entity instanceof SkeletonHorse) { e.setDamage(e.getFinalDamage() + 4); } }; }
Source:
<code>public void testAggregationPushdownThroughOuterJoinNotFiringInCorrelatedAggregatesRightSide() { <START> assertQuery("SELECT max(y) from (SELECT * from (VALUES 1) t(x) LEFT JOIN (VALUES 1) t2(y) ON t.x = t2.y) GROUP BY y", <END> "VALUES 1"); }</code><technical_language>please put parameter in separate line :)</technical_language>

Target:
public void testAggregationPushdownThroughOuterJoinNotFiringInCorrelatedAggregatesRightSide() { assertQuery("SELECT max(y) FROM" + "(SELECT * from (VALUES 1) t(x) LEFT JOIN (VALUES 1) t2(y) ON t.x = t2.y)" + "GROUP BY y", "VALUES 1"); }
Source:
<code>private void setTitleSpan(Editable editable) { for (RelativeSizeSpan span : editable.getSpans(0, editable.length(), RelativeSizeSpan.class)) { editable.removeSpan(span); } for (StyleSpan span : editable.getSpans(0, editable.length(), StyleSpan.class)) { editable.removeSpan(span); <START> } <END> int newLinePosition = getNoteContentString().indexOf("\n"); if (newLinePosition == 0) { return; } int titleEndPosition = (newLinePosition > 0) ? newLinePosition : editable.length(); editable.setSpan(new RelativeSizeSpan(1.3f), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); editable.setSpan(new StyleSpan(Typeface.BOLD), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); }</code><technical_language>call clearSpans() instead of iterating of removing them? <LINK_0> java private void setTitleSpan(Editable editor) { // if clear out spans leak // performance suffer title longer // add editable.clearSpans(); int newLinePosition = getNoteContentString().indexOf("\n"); }</technical_language>

Target:
private void setTitleSpan(Editable editable) { for (MetricAffectingSpan span : editable.getSpans(0, editable.length(), MetricAffectingSpan.class)) { editable.removeSpan(span); } int newLinePosition = getNoteContentString().indexOf("\n"); if (newLinePosition == 0) { return; } int titleEndPosition = (newLinePosition > 0) ? newLinePosition : editable.length(); editable.setSpan(new RelativeSizeSpan(1.3f), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); editable.setSpan(new StyleSpan(Typeface.BOLD), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); }
Source:
<code>private void setTaskOffsetSumDataFromTaskOffsetSumMap(final Map<TaskId, Long> taskOffsetSums) { final Map<Integer, List<SubscriptionInfoData.PartitionToOffsetSum>> topicGroupIdToPartitionOffsetSum = new HashMap<>(); for (final Map.Entry<TaskId, Long> taskEntry : taskOffsetSums.entrySet()) { final TaskId task = taskEntry.getKey(); <START> topicGroupIdToPartitionOffsetSum.putIfAbsent(task.topicGroupId, new ArrayList<>()); topicGroupIdToPartitionOffsetSum.get(task.topicGroupId).add( <END> new SubscriptionInfoData.PartitionToOffsetSum() .setPartition(task.partition) .setOffsetSum(taskEntry.getValue())); } data.setTaskOffsetSums(topicGroupIdToPartitionOffsetSum.entrySet().stream().map(t -> { final SubscriptionInfoData.TaskOffsetSum taskOffsetSum = new SubscriptionInfoData.TaskOffsetSum(); taskOffsetSum.setTopicGroupId(t.getKey()); taskOffsetSum.setPartitionToOffsetSum(t.getValue()); return taskOffsetSum; }).collect(Collectors.toList())); }</code><technical_language>prop: suggestion topicGroupIdToPartitionOffsetSum.computeIfAbsent(task.topicGroupId, new ArrayList<>()).add(</technical_language>

Target:
private void setTaskOffsetSumDataFromTaskOffsetSumMap(final Map<TaskId, Long> taskOffsetSums) { final Map<Integer, List<SubscriptionInfoData.PartitionToOffsetSum>> topicGroupIdToPartitionOffsetSum = new HashMap<>(); for (final Map.Entry<TaskId, Long> taskEntry : taskOffsetSums.entrySet()) { final TaskId task = taskEntry.getKey(); topicGroupIdToPartitionOffsetSum.computeIfAbsent(task.topicGroupId, t -> new ArrayList<>()).add( new SubscriptionInfoData.PartitionToOffsetSum() .setPartition(task.partition) .setOffsetSum(taskEntry.getValue())); } data.setTaskOffsetSums(topicGroupIdToPartitionOffsetSum.entrySet().stream().map(t -> { final SubscriptionInfoData.TaskOffsetSum taskOffsetSum = new SubscriptionInfoData.TaskOffsetSum(); taskOffsetSum.setTopicGroupId(t.getKey()); taskOffsetSum.setPartitionToOffsetSum(t.getValue()); return taskOffsetSum; }).collect(Collectors.toList())); }
Source:
<code>public IssueColumn(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.ui = ui; getChildren().add(createFilterBox()); setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); getParent().requestFocus(); }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> unused, Boolean wasFocused, Boolean isFocused) { if (!isFocused) { if (getStyleClass().contains("issue-panel-focused")) getStyleClass().remove("issue-panel-focused"); return; } getStyleClass().add("issue-panel-focused"); } }); <START> } <END></code><technical_language>Is a need check for presence of style class, i.e. work? java if (isFocused) { getStyleClass().add("issue-panel-focused"); } else { getStyleClass().remove("issue-panel-focused"); }</technical_language>

Target:
public IssueColumn(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.ui = ui; getChildren().add(createFilterBox()); setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); getParent().requestFocus(); }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> unused, Boolean wasFocused, Boolean isFocused) { if (isFocused) { getStyleClass().add("issue-panel-focused"); } else { getStyleClass().remove("issue-panel-focused"); } } }); }
Source:
<code>public static List<InetSocketAddress> getRMAddresses(Configuration conf) { List<InetSocketAddress> rmAddresses = new ArrayList<>(); <START> String rmWebAppAddress = conf.get(YarnConfiguration.RM_WEBAPP_ADDRESS); <END> if (rmWebAppAddress != null) { if (ConfigUtils.isRMHAEnabled(conf)) { for (String rmId : ConfigUtils.getRMHAIds(conf)) { InetSocketAddress socketAddress = getRMWebAddress(conf, rmId); rmAddresses.add(socketAddress); } } else { InetSocketAddress socketAddress = getRMWebAddress(conf, null); rmAddresses.add(socketAddress); } } return rmAddresses; }</code><technical_language>need get webapp address if, else provides defaults if webapp address is</technical_language>

Target:
public static List<InetSocketAddress> getRMAddresses(Configuration conf) { List<InetSocketAddress> rmAddresses = new ArrayList<>(); if (ConfigUtils.isRMHAEnabled(conf)) { for (String rmId : ConfigUtils.getRMHAIds(conf)) { InetSocketAddress socketAddress = getRMWebAddress(conf, rmId); rmAddresses.add(socketAddress); } } else { InetSocketAddress socketAddress = getRMWebAddress(conf, null); rmAddresses.add(socketAddress); } return rmAddresses; }
Source:
<code><START> public static final List<ConsumableInArrearDetail> fromJson(String itemDetails){ <END> List<ConsumableInArrearDetail> toBeBilledConsumableInArrearDetails = null; if (itemDetails != null){ ObjectMapper objectMapper = new ObjectMapper(); try { toBeBilledConsumableInArrearDetails = objectMapper.reader() .forType(new TypeReference<List<ConsumableInArrearDetail>>() {}) .readValue(itemDetails); } catch (IOException e) { Preconditions.checkState(false, e.getMessage()); } } return toBeBilledConsumableInArrearDetails; }</code><technical_language>a private method</technical_language>

Target:
private static final List<UsageInArrearDetail> fromJson(String itemDetails){ List<UsageInArrearDetail> toBeBilledUsageInArrearDetails = null; if (itemDetails != null){ try { toBeBilledUsageInArrearDetails = objectMapper.readValue(itemDetails, new TypeReference<List<UsageInArrearDetail>>() {}); } catch (IOException e) { Preconditions.checkState(false, e.getMessage()); } } return toBeBilledUsageInArrearDetails; }
Source:
<code>Mono<Response<SearchDocument>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(res -> { ObjectMapper mapper = new ObjectMapper(); SerializationUtil.configureMapper(mapper); <START> SearchDocument document = mapper.convertValue(res.getValue(), SearchDocument.class); <END> return new SimpleResponse<>(res, document); }) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>is res.getValue() here? convertValue efficient operation convert passed object JSON deserialize targeting new Class type. validate type is returned here</technical_language>

Target:
Mono<Response<SearchDocument>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(res -> { SearchDocument document = MAPPER.convertValue(res.getValue(), SearchDocument.class); return new SimpleResponse<>(res, document); }) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code>public void testFirstBlockedThenSucceed() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 200; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); CountDownLatch[] allocated = new CountDownLatch[2]; CountDownLatch[] used = new CountDownLatch[2]; BufferConsumer[] consumers = new BufferConsumer[2]; Thread[] consumerThreads = new Thread[2]; for (int i = 0; i < 2; i++) { allocated[i] = new CountDownLatch(1); used[i] = new CountDownLatch(1); consumers[i] = new BufferConsumer(size, maxBlockTimeInMs, pool, allocated[i], used[i]); consumerThreads[i] = new Thread(consumers[i]); } consumerThreads[0].start(); if (!allocated[0].await(100, TimeUnit.MILLISECONDS)) { fail("SimpleByteBufferPool takes too long time to allocate a buffer to BufferConsumer[0]."); } assertEquals(0, pool.availableMemory()); <START> consumerThreads[1].start(); <END> used[0].countDown(); consumerThreads[0].join(); used[1].countDown(); consumerThreads[1].join(); for (int i = 0; i < 2; i++) { if (consumers[i].exception != null) { throw consumers[i].exception; } } assertEquals(capacity, pool.availableMemory()); }</code><technical_language>is tested here? is verified thread blocks</technical_language>

Target:
public void testFirstBlockedThenSucceed() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 200; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); CountDownLatch[] allocated = new CountDownLatch[2]; CountDownLatch[] used = new CountDownLatch[2]; BufferConsumer[] consumers = new BufferConsumer[2]; Thread[] consumerThreads = new Thread[2]; for (int i = 0; i < 2; i++) { allocated[i] = new CountDownLatch(1); used[i] = new CountDownLatch(1); consumers[i] = new BufferConsumer(size, maxBlockTimeInMs, pool, allocated[i], used[i]); consumerThreads[i] = new Thread(consumers[i]); } consumerThreads[0].start(); if (!allocated[0].await(100, TimeUnit.MILLISECONDS)) { fail("SimpleByteBufferPool takes too long time to allocate a buffer to BufferConsumer[0]."); } assertEquals(0, pool.availableMemory()); consumerThreads[1].start(); assertEquals("BufferConsumer-1 should not have got buffer from the buffer pool.", 1, allocated[1].getCount()); used[0].countDown(); consumerThreads[0].join(); used[1].countDown(); consumerThreads[1].join(); for (int i = 0; i < 2; i++) { if (consumers[i].exception != null) { throw consumers[i].exception; } } assertEquals(capacity, pool.availableMemory()); }
Source:
<code>public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { <START> logger.warn(e.getMessage()); <END> Thread.currentThread().interrupt(); } }</code><technical_language>[ ] select log level debug trace. developer intensionaly sleep thread InterruptedException meaning here</technical_language>

Target:
public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { logger.trace(e.getMessage()); Thread.currentThread().interrupt(); } }
Source:
<code>public void logNodeCompAssignments() { if (nodeCompAssignmentCnts == null || nodeCompAssignmentCnts.isEmpty()) { LOG.info("NodeCompAssignment is empty"); return; } StringBuffer sb = new StringBuffer(); int cntAllNodes = 0; int cntFilledNodes = 0; <START> for (RasNode node: new TreeSet<RasNode>(nodeCompAssignmentCnts.keySet())) { <END> cntAllNodes++; Map<String, Integer> oneMap = nodeCompAssignmentCnts.get(node); if (oneMap.isEmpty()) { continue; } cntFilledNodes++; String oneMapJoined = String.join( ",", oneMap.entrySet() .stream().map(e -> String.format("%s: %s", e.getKey(), e.getValue())) .collect(Collectors.toList()) ); sb.append(String.format("\n\t(%d) Node %s: %s", cntFilledNodes, node.getId(), oneMapJoined)); } LOG.info("NodeCompAssignments available for of nodes {}", cntFilledNodes, cntAllNodes, sb); LOG.info("Executors assignments attempted (cnt={}) are: \n\t{}", execs.size(), execs.stream().map(x -> x.toString()).collect(Collectors.joining(",")) ); }</code><technical_language>new TreeSet<RasNode> new TreeSet<></technical_language>

Target:
public void logNodeCompAssignments() { if (nodeCompAssignmentCnts == null || nodeCompAssignmentCnts.isEmpty()) { LOG.info("NodeCompAssignment is empty"); return; } StringBuffer sb = new StringBuffer(); int cntAllNodes = 0; int cntFilledNodes = 0; for (RasNode node: new TreeSet<>(nodeCompAssignmentCnts.keySet())) { cntAllNodes++; Map<String, Integer> oneMap = nodeCompAssignmentCnts.get(node); if (oneMap.isEmpty()) { continue; } cntFilledNodes++; String oneMapJoined = String.join( ",", oneMap.entrySet() .stream().map(e -> String.format("%s: %s", e.getKey(), e.getValue())) .collect(Collectors.toList()) ); sb.append(String.format("\n\t(%d) Node %s: %s", cntFilledNodes, node.getId(), oneMapJoined)); } LOG.info("NodeCompAssignments available for of nodes {}", cntFilledNodes, cntAllNodes, sb); LOG.info("Executors assignments attempted (cnt={}) are: \n\t{}", execs.size(), execs.stream().map(x -> x.toString()).collect(Collectors.joining(",")) ); }
Source:
<code>public static void openConfigurationEditor(ILaunchDescriptor desc) { if (desc == null) return; Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IStatus s = canOpenConfigurationEditor(desc); if( !s.isOK()) { <START> MessageDialog.openError(shell, s.getMessage(), s.getException() == null ? s.getMessage() : s.getException().getMessage()); <END> } try { LaunchBarManager manager = Activator.getDefault().getLaunchBarUIManager().getManager(); ILaunchMode mode = manager.getActiveLaunchMode(); IRemoteConnection target = manager.getActiveLaunchTarget(); ILaunchConfigurationType configType = manager.getLaunchConfigurationType(desc, target); ILaunchGroup group = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(configType, mode.getIdentifier()); LaunchGroupExtension groupExt = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(group.getIdentifier()); ILaunchConfiguration config = manager.getLaunchConfiguration(desc, target); if (config.isWorkingCopy() && ((ILaunchConfigurationWorkingCopy) config).isDirty()) { config = ((ILaunchConfigurationWorkingCopy) config).doSave(); } final LaunchConfigurationEditDialog dialog = new LaunchConfigurationEditDialog(shell, config, groupExt); dialog.setInitialStatus(Status.OK_STATUS); dialog.open(); } catch (CoreException e2) { Activator.log(e2); } }</code><technical_language>return this</technical_language>

Target:
public static void openConfigurationEditor(ILaunchDescriptor desc) { if (desc == null) return; Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IStatus s = canOpenConfigurationEditor(desc); if( !s.isOK()) { MessageDialog.openError(shell, s.getMessage(), s.getException() == null ? s.getMessage() : s.getException().getMessage()); return; } try { LaunchBarManager manager = Activator.getDefault().getLaunchBarUIManager().getManager(); ILaunchMode mode = manager.getActiveLaunchMode(); IRemoteConnection target = manager.getActiveLaunchTarget(); ILaunchConfigurationType configType = manager.getLaunchConfigurationType(desc, target); ILaunchGroup group = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(configType, mode.getIdentifier()); LaunchGroupExtension groupExt = DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchGroup(group.getIdentifier()); ILaunchConfiguration config = manager.getLaunchConfiguration(desc, target); if (config.isWorkingCopy() && ((ILaunchConfigurationWorkingCopy) config).isDirty()) { config = ((ILaunchConfigurationWorkingCopy) config).doSave(); } final LaunchConfigurationEditDialog dialog = new LaunchConfigurationEditDialog(shell, config, groupExt); dialog.setInitialStatus(Status.OK_STATUS); dialog.open(); } catch (CoreException e2) { Activator.log(e2); } }
Source:
<code>private SourceResponse executePostFederationQueryPlugins( SourceResponse sourceResponse, QueryRequest queryRequest) { QueryResponse queryResponse = new QueryResponseImpl( queryRequest, sourceResponse.getResults(), true, sourceResponse.getHits(), sourceResponse.getProperties()); try { for (PostFederatedQueryPlugin service : postQuery) { try { queryResponse = service.process(queryResponse); } catch (PluginExecutionException e) { LOGGER.info("Error executing PostFederatedQueryPlugin", e); } } } catch (StopProcessingException e) { LOGGER.info("Plugin stopped processing", e); } SourceResponseImpl responseAfterPlugins = <START> new SourceResponseImpl( <END> queryRequest, sourceResponse.getProperties(), queryResponse.getResults(), queryResponse.getHits()); Set<SourceProcessingDetails> detailsOfResponseAfterPlugins = responseAfterPlugins.getProcessingDetails(); detailsOfResponseAfterPlugins.addAll(queryResponse.getProcessingDetails()); detailsOfResponseAfterPlugins.addAll(sourceResponse.getProcessingDetails()); return responseAfterPlugins; }</code><technical_language>add a constructor SourceResponseImpl takes a Set<SourceProcessingDetails> this is awkward</technical_language>

Target:
private SourceResponse executePostFederationQueryPlugins( SourceResponse sourceResponse, QueryRequest queryRequest) { QueryResponse queryResponse = new QueryResponseImpl( queryRequest, sourceResponse.getResults(), true, sourceResponse.getHits(), sourceResponse.getProperties()); try { for (PostFederatedQueryPlugin service : postQuery) { try { queryResponse = service.process(queryResponse); } catch (PluginExecutionException e) { LOGGER.info("Error executing PostFederatedQueryPlugin", e); } } } catch (StopProcessingException e) { LOGGER.info("Plugin stopped processing", e); } Set<SourceProcessingDetails> detailsOfResponseAfterPlugins = new HashSet<>(queryResponse.getProcessingDetails()); detailsOfResponseAfterPlugins.addAll(sourceResponse.getProcessingDetails()); return new SourceResponseImpl( queryRequest, sourceResponse.getProperties(), queryResponse.getResults(), queryResponse.getHits(), detailsOfResponseAfterPlugins); }
Source:
<code>public void doRemoveRoles(@QueryParameter(required = true) String type, <START> @QueryParameter(required = true) String roleNames) throws IOException { <END> checkAdminPerm(); RoleMap roleMap = this.roleMaps.get(RoleType.fromString(type)); if (roleMap != null) { String[] split = roleNames.split(","); for (String aSplit : split) { Role role = roleMap.getRole(aSplit); if (role != null) { roleMap.removeRole(role); } } } persistChanges(); }</code><technical_language>I stapler do conversion</technical_language>

Target:
public void doRemoveRoles(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleNames) throws IOException { checkAdminPerm(); RoleMap roleMap = getRoleMap(RoleType.fromString(type)); String[] split = roleNames.split(","); for (String aSplit : split) { Role role = roleMap.getRole(aSplit); if (role != null) { roleMap.removeRole(role); } } persistChanges(); }
Source:
<code>public GeneXref fetchAndCache(String accession, String geneSymbol) throws ResourceMappingException, HttpClientErrorException, ResourceAccessException { boolean saveValue = true; Optional<GeneXref> entrezGeneXrefOptional = null; try { entrezGeneXrefOptional = this.repository.findById(accession); } catch (DataAccessResourceFailureException e) { LOG.warn("Failed to read from Mongo database - falling back on the external web service. " + "Will not attempt to store variant in Mongo database."); saveValue = false; } final boolean saveValueFinal = saveValue; <START> <END> return entrezGeneXrefOptional.map(x -> x).orElseGet(() -> { try { GeneXref entrezGeneXref = this.fetchEntrezGeneXref(accession, geneSymbol); if (saveValueFinal && entrezGeneXref != null) { entrezGeneXref.setEnsemblGeneId(accession); this.repository.save(entrezGeneXref); } return entrezGeneXref; } catch (DataIntegrityViolationException e) { LOG.info(e.getLocalizedMessage()); } catch (ResourceMappingException e) { LOG.info(e.getLocalizedMessage()); } return null; }); }</code><technical_language>if (entrezGeneXrefOptional.isPresent()) instead of .map(x -> x)? This eliminate need of introducing a redundant saveValueFinal variable. Is advantages of orElseGet</technical_language>

Target:
public GeneXref fetchAndCache(String accession, String geneSymbol) throws ResourceMappingException, HttpClientErrorException, ResourceAccessException { boolean saveValue = true; Optional<GeneXref> entrezGeneXrefOptional = null; try { entrezGeneXrefOptional = this.repository.findById(accession); } catch (DataAccessResourceFailureException e) { LOG.warn("Failed to read from Mongo database - falling back on the external web service. " + "Will not attempt to store variant in Mongo database."); saveValue = false; } if (!entrezGeneXrefOptional.isPresent()) { try { GeneXref entrezGeneXref = this.fetchEntrezGeneXref(accession, geneSymbol); if (saveValue && entrezGeneXref != null) { entrezGeneXref.setEnsemblGeneId(accession); this.repository.save(entrezGeneXref); } return entrezGeneXref; } catch (DataIntegrityViolationException e) { LOG.info(e.getLocalizedMessage()); } catch (ResourceMappingException e) { LOG.info(e.getLocalizedMessage()); } } try { return entrezGeneXrefOptional.get(); } catch (NoSuchElementException e) { return null; } }
Source:
<code>public void testCleanDirsWithSubmodule() throws Exception { SubmoduleAddCommand command = new SubmoduleAddCommand(db); String path = "sub"; command.setPath(path); String uri = db.getDirectory().toURI().toString(); command.setURI(uri); Repository repo = command.call(); repo.close(); Status beforeCleanStatus = git.status().call(); <START> assertTrue(beforeCleanStatus.getAdded().contains(Constants.DOT_GIT_MODULES)); <END> assertTrue(beforeCleanStatus.getAdded().contains(path)); Set<String> cleanedFiles = git.clean().setCleanDirectories(true) .call(); assertTrue(!cleanedFiles.contains(path + "/")); assertTrue(cleanedFiles.contains("File2.txt")); assertTrue(cleanedFiles.contains("File3.txt")); assertTrue(!cleanedFiles.contains("sub-noclean/File1.txt")); assertTrue(cleanedFiles.contains("sub-noclean/File2.txt")); assertTrue(cleanedFiles.contains("sub-clean/")); assertTrue(cleanedFiles.size() == 4); }</code><technical_language>Import this static</technical_language>

Target:
public void testCleanDirsWithSubmodule() throws Exception { SubmoduleAddCommand command = new SubmoduleAddCommand(db); String path = "sub"; command.setPath(path); String uri = db.getDirectory().toURI().toString(); command.setURI(uri); Repository repo = command.call(); repo.close(); Status beforeCleanStatus = git.status().call(); assertTrue(beforeCleanStatus.getAdded().contains(DOT_GIT_MODULES)); assertTrue(beforeCleanStatus.getAdded().contains(path)); Set<String> cleanedFiles = git.clean().setCleanDirectories(true) .call(); assertTrue(!cleanedFiles.contains(path + "/")); assertTrue(cleanedFiles.contains("File2.txt")); assertTrue(cleanedFiles.contains("File3.txt")); assertTrue(!cleanedFiles.contains("sub-noclean/File1.txt")); assertTrue(cleanedFiles.contains("sub-noclean/File2.txt")); assertTrue(cleanedFiles.contains("sub-clean/")); assertTrue(cleanedFiles.size() == 4); }
Source:
<code>public static Object[][] data() { return new Object[][] { params( KeyContext::asInteger, "foo", 42, "For input string: \"foo\"", <START> InvalidType.class.getName() + " cannot be cast to java.lang.String" <END> ), params( KeyContext::asLong, "bar", 42L, "For input string: \"bar\"", InvalidType.class.getName() + " cannot be cast to java.lang.String" ), params( KeyContext::asBoolean, "foobar", true, "Invalid boolean value: expected either a Boolean, the String 'true' or the String 'false'.", "Invalid boolean value: expected either a Boolean, the String 'true' or the String 'false'." ) }; }</code><technical_language>Hum, is convert a string integer error message cast a String? BTW, if a JVM error message, I strongly advise test change quickly a nightmare (been there, done that)</technical_language>

Target:
public static Object[][] data() { return new Object[][] { params( KeyContext::asInteger, "foo", 42, "Invalid Integer value: expected either a Number or a String that can be parsed into an Integer.", "For input string: \"foo\"" ), params( KeyContext::asLong, "bar", 42L, "Invalid Long value: expected either a Number or a String that can be parsed into a Long.", "For input string: \"bar\"" ), params( KeyContext::asBoolean, "foobar", true, "Invalid Boolean value: expected either a Boolean, the String 'true' or the String 'false'.", "" ), params( c -> c.as( MyPropertyType.class, MyPropertyType::new ), MyPropertyType.INVALID_VALUE, new MyPropertyType( "foobar" ), "Invalid value: expected either an instance of '" + MyPropertyType.class.getName() + "' or a String that can be parsed.", MyPropertyType.INVALID_VALUE_ERROR_MESSAGE ) }; }
Source:
<code>public boolean isModifiable(final Object element) { boolean isModifiable = true; if (element instanceof SessionEditorInput) { SessionEditorInput sessionEditorInput = (SessionEditorInput) element; Session session = sessionEditorInput.getSession(); if (session != null) { ResourceSet resourceSet = session.getTransactionalEditingDomain().getResourceSet(); URI inputURI = sessionEditorInput.getURI(); URI resourceURI = inputURI.trimFragment(); Resource resource = resourceSet.getResource(resourceURI, false); <START> assert resource != null : "No resource in resourceSet corresponding to " + resourceURI.toString(); <END> String fragment = inputURI.fragment(); if (fragment != null) { EObject intputEObject = resource.getEObject(fragment); IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(resourceSet); isModifiable = intputEObject != null && permissionAuthority.canEditInstance(intputEObject); if (isModifiable && intputEObject instanceof Diagram) { Diagram diagram = (Diagram) intputEObject; EObject diagramElt = diagram.getElement(); isModifiable = permissionAuthority.canEditInstance(diagramElt); } } } } return isModifiable; }</code><technical_language>This kind of assert is related JUnit asserts. enabled in production if user starts JVM -ea option, in a JUnit test context enabled test runner -ea. This want. I idea users enable -ea in production, for do, if bug occurs crashing is correct solution? a normal test this: if (resource == null) { log(ERROR, "message"; makeSureWeExitTheMethodInAConsistentState(); }</technical_language>

Target:
public boolean isModifiable(final Object element) { boolean isModifiable = true; if (element instanceof SessionEditorInput) { SessionEditorInput sessionEditorInput = (SessionEditorInput) element; Session session = sessionEditorInput.getSession(); if (session != null) { ResourceSet resourceSet = session.getTransactionalEditingDomain().getResourceSet(); URI inputURI = sessionEditorInput.getURI(); URI resourceURI = inputURI.trimFragment(); Resource resource = resourceSet.getResource(resourceURI, false); if (resource == null) { SiriusDiagramEditorPlugin.getInstance().logError("No resource in resourceSet corresponding to " + resourceURI.toString()); } else { String fragment = inputURI.fragment(); if (fragment != null) { EObject intputEObject = resource.getEObject(fragment); IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(resourceSet); isModifiable = intputEObject != null && permissionAuthority.canEditInstance(intputEObject); if (isModifiable && intputEObject instanceof Diagram) { Diagram diagram = (Diagram) intputEObject; EObject diagramElt = diagram.getElement(); isModifiable = permissionAuthority.canEditInstance(diagramElt); } } } } } return isModifiable; }
Source:
<code>void session_does_not_check_for_strict_stubs_on_test_failure() { TestExecutionResult result = invokeTestClassAndRetrieveMethodResult(StrictStubsNotReportedOnTestFailure.class); assertThat(result.getStatus()).isEqualTo(TestExecutionResult.Status.FAILED); Throwable throwable = result.getThrowable().get(); <START> assertThat(throwable).isInstanceOf(AssertionError.class); <END> assertThat(throwable.getSuppressed()).isEmpty(); }</code><technical_language>assertion stronger a more specific exception? create a custom exception type in test</technical_language>

Target:
void session_does_not_check_for_strict_stubs_on_test_failure() { TestExecutionResult result = invokeTestClassAndRetrieveMethodResult(StrictStubsNotReportedOnTestFailure.class); assertThat(result.getStatus()).isEqualTo(TestExecutionResult.Status.FAILED); Throwable throwable = result.getThrowable().get(); assertThat(throwable).isInstanceOf(MyAssertionError.class); assertThat(throwable.getSuppressed()).isEmpty(); }
Source:
<code>public List<ComponentTag> getFreeComponentTags( @PathParam("id") @RequiredParam String componentId) { Component componentExample = new Component(); componentExample.setComponentId(componentId); List<Component> components = componentExample.findByExample(); if (!components.isEmpty()) { <START> List<ComponentTag> componentTags = service.getComponentService().getComponentDetails(componentId).getTags(); <END> List<ComponentTag> allTags = service.getComponentService().getTagCloud(); List<ComponentTag> filteredTags = new ArrayList<>(); for (ComponentTag tag : allTags) { boolean pass = true; for (ComponentTag myTag : componentTags) { if (myTag.getText().toLowerCase().equals(tag.getText().toLowerCase())) { pass = false; break; } } if (pass) { filteredTags.add(tag); } } return filteredTags; } else { return service.getComponentService().getTagCloud(); } }</code><technical_language>//This needed //List<Component> components = componentExample.findByExample(); //change componentExample.find(); //change this service.getComponentService().getComponentDetails(componentId). //to ComponentTag componentTagExample = new ComponentTag(); componentTagExample.setComponentId(componentId); List<ComponentTag> componentTags = componentTagExample.findByExample();</technical_language>

Target:
public List<ComponentTag> getFreeComponentTags( @PathParam("id") @RequiredParam String componentId) { Component componentExample = new Component(); componentExample.setComponentId(componentId); Component component = componentExample.find(); if (component != null) { ComponentTag componentTagExample = new ComponentTag(); componentTagExample.setComponentId(componentId); List<ComponentTag> componentTags = componentTagExample.findByExample(); List<ComponentTag> allTags = service.getComponentService().getTagCloud(); List<ComponentTag> filteredTags = new ArrayList<>(); for (ComponentTag tag : allTags) { boolean pass = true; for (ComponentTag myTag : componentTags) { if (myTag.getText().toLowerCase().equals(tag.getText().toLowerCase())) { pass = false; break; } } if (pass) { filteredTags.add(tag); } } return filteredTags; } else { return service.getComponentService().getTagCloud(); } }
Source:
<code>public BlockStem(Material plantType) { if (plantType.equals(Material.MELON_STEM)) { fruitType = Material.MELON_BLOCK; seedsType = Material.MELON_SEEDS; } else if (plantType.equals(Material.PUMPKIN_STEM)) { fruitType = Material.PUMPKIN; seedsType = Material.PUMPKIN_SEEDS; <START> } <END> }</code><technical_language>For sanity, else throw new IllegalArgumentException("insert message"); proper formatting :3</technical_language>

Target:
public BlockStem(Material plantType) { if (plantType == Material.MELON_STEM) { fruitType = Material.MELON_BLOCK; seedsType = Material.MELON_SEEDS; } else if (plantType == Material.PUMPKIN_STEM) { fruitType = Material.PUMPKIN; seedsType = Material.PUMPKIN_SEEDS; } else throw new IllegalArgumentException("Invalid plant material " + plantType.name() + " for BlockStem"); }