auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void refreshHasSelfRestrictions(final Map<Resource, URI> restrictions) throws QueryEvaluationException { hasSelfByType = new HashMap<>(); hasSelfByProperty = new HashMap<>(); restrictions.forEach((type, property) -> { try { final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, type, HASSELF, null, conf); try { if (iter.hasNext()) { Set<URI> typeSet = hasSelfByType.get(type); Set<Resource> propSet = hasSelfByProperty.get(property); if (typeSet == null) { typeSet = new HashSet<>(); } if (propSet == null) { propSet = new HashSet<>(); } typeSet.add(property); propSet.add(type); hasSelfByType.put(type, typeSet); hasSelfByProperty.put(property, propSet); } } catch (final QueryEvaluationException e) { if (iter != null) { iter.close(); } } <START> } catch (final QueryEvaluationException e) { <END> } }); }</code><technical_language>silently swallow this Exception. a Java 8 lambda poor handling throwing checked Exceptions. some workarounds for throwing Exception of ideal</technical_language>

Target:
private void refreshHasSelfRestrictions(final Map<Resource, URI> restrictions) throws QueryEvaluationException { hasSelfByType = new HashMap<>(); hasSelfByProperty = new HashMap<>(); for(final Resource type : restrictions.keySet()) { final URI property = restrictions.get(type); final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, type, HAS_SELF, null, conf); try { if (iter.hasNext()) { Set<URI> typeSet = hasSelfByType.get(type); Set<Resource> propSet = hasSelfByProperty.get(property); if (typeSet == null) { typeSet = new HashSet<>(); } if (propSet == null) { propSet = new HashSet<>(); } typeSet.add(property); propSet.add(type); hasSelfByType.put(type, typeSet); hasSelfByProperty.put(property, propSet); } } finally { if (iter != null) { iter.close(); } } } }
Source:
<code>public FeedbackResponseAttributes(FeedbackResponseAttributes copy) { this.feedbackResponseId = copy.getId(); this.feedbackSessionName = copy.feedbackSessionName; this.courseId = copy.courseId; this.feedbackQuestionId = copy.feedbackQuestionId; this.feedbackQuestionType = copy.feedbackQuestionType; this.giverEmail = copy.giverEmail; this.giverSection = copy.giverSection; this.recipientEmail = copy.recipientEmail; this.recipientSection = copy.recipientSection; this.responseMetaData = copy.responseMetaData; this.createdAt = copy.getCreatedAt(); <START> this.updatedAt = copy.getUpdatedAt(); <END> }</code><technical_language>this.*At = copy.*At instead. want copy a perfect copy, i.e if source null field, need copy initialized default value</technical_language>

Target:
public FeedbackResponseAttributes(FeedbackResponseAttributes copy) { this.feedbackResponseId = copy.getId(); this.feedbackSessionName = copy.feedbackSessionName; this.courseId = copy.courseId; this.feedbackQuestionId = copy.feedbackQuestionId; this.feedbackQuestionType = copy.feedbackQuestionType; this.giverEmail = copy.giverEmail; this.giverSection = copy.giverSection; this.recipientEmail = copy.recipientEmail; this.recipientSection = copy.recipientSection; this.responseMetaData = copy.responseMetaData; this.createdAt = copy.createdAt; this.updatedAt = copy.updatedAt; }
Source:
<code>protected void processMultiValuedEReference(EReference eReference, SIRIUS processedDescription, SIRIUS currentDescription, TransformationCache cache) { Object processedValue = processedDescription.eGet(eReference); Object currentValue = currentDescription.eGet(eReference); if (currentValue instanceof Iterable<?> && processedValue instanceof Iterable<?>) { List<Object> newValue = new ArrayList<>(); Iterable<?> currentIterable = (Iterable<?>) currentValue; Iterable<?> processedIterable = (Iterable<?>) processedValue; <START> for (Object object : currentIterable) { if (object instanceof EObject) { <END> IDescriptionPreprocessor preprocessor = SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessor((EObject) object); if (preprocessor != null) { EObject processedObject = preprocessor.convert((EObject) object, cache); newValue.add(processedObject); } } } for (Object object : processedIterable) { newValue.add(object); } processedDescription.eSet(eReference, newValue); } }</code><technical_language>java8-isation [forEach][filter]</technical_language>

Target:
protected void processMultiValuedEReference(EReference eReference, SIRIUS processedDescription, SIRIUS currentDescription, TransformationCache cache) { Object processedValue = processedDescription.eGet(eReference); Object currentValue = currentDescription.eGet(eReference); if (currentValue instanceof Iterable<?> && processedValue instanceof Iterable<?>) { List<Object> newValue = new ArrayList<>(); Iterable<?> currentIterable = (Iterable<?>) currentValue; Iterable<?> processedIterable = (Iterable<?>) processedValue; StreamSupport.stream(currentIterable.spliterator(), false).filter(EObject.class::isInstance).map(EObject.class::cast).forEach(object -> { SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessor(object).map(preprocessor -> preprocessor.convert(object, cache)).map(newValue::add); }); processedIterable.forEach(newValue::add); processedDescription.eSet(eReference, newValue); } }
Source:
<code>private static String toHexString(byte b) { char[] hexes <START> = new char[] <END> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuilder hexStringBuilder = new StringBuilder(2); hexStringBuilder.append(hexes[(b & 0xF0) >> 4]); hexStringBuilder.append(hexes[b & 0x0F]); return hexStringBuilder.toString(); }</code><technical_language>static? Also, missing docs</technical_language>

Target:
private static String toHexString(byte b) { StringBuilder hexStringBuilder = new StringBuilder(2); hexStringBuilder.append(hexes[(b & 0xF0) >> 4]); hexStringBuilder.append(hexes[b & 0x0F]); return hexStringBuilder.toString(); }
Source:
<code>public void process(MetadataRepository repository, ComplexTypeMetadata type, XSDAnnotation annotation, XmlSchemaAnnotationProcessorState state) { if (annotation != null) { EList<Element> appInfoElements = annotation.getApplicationInformation(); for (Element appInfo : appInfoElements) { String source = appInfo.getAttribute("source"); String textContent = appInfo.getTextContent(); if ("X_Hide".equals(source)) { state.getHide().add(textContent); } else if ("X_Write".equals(source)) { state.getAllowWrite().add(textContent); } else if ("X_Deny_Create".equals(source)) { state.getDenyCreate().add(textContent); } else if ("X_Deny_LogicalDelete".equals(source)) { state.getDenyLogicalDelete().add(textContent); } else if ("X_Deny_PhysicalDelete".equals(source)) { state.getDenyPhysicalDelete().add(textContent); } else if ("X_Workflow".equals(source)) { state.getWorkflowAccessRights().add(textContent); } else if ("X_Visible_Rule".equals(source)) { state.setVisibilityRule(textContent); } else if ("X_No_Add".equals(source) || "X_No_Remove".equals(source)) { <START> handleAddOrRemoveRightInfo(repository, state, appInfo); <END> } } } }</code><technical_language>I work process here, a question, is separate handling for "X_No_Add" "X_No_Remove", "X_Deny_Create"? a consistent handling here, function name 'getNoAdd' 'getNoRemove'</technical_language>

Target:
public void process(MetadataRepository repository, ComplexTypeMetadata type, XSDAnnotation annotation, XmlSchemaAnnotationProcessorState state) { if (annotation != null) { EList<Element> appInfoElements = annotation.getApplicationInformation(); for (Element appInfo : appInfoElements) { String source = appInfo.getAttribute("source"); String textContent = appInfo.getTextContent(); if ("X_Hide".equals(source)) { state.getHide().add(textContent); } else if ("X_Write".equals(source)) { state.getAllowWrite().add(textContent); } else if ("X_Deny_Create".equals(source)) { state.getDenyCreate().add(textContent); } else if ("X_Deny_LogicalDelete".equals(source)) { state.getDenyLogicalDelete().add(textContent); } else if ("X_Deny_PhysicalDelete".equals(source)) { state.getDenyPhysicalDelete().add(textContent); } else if ("X_Workflow".equals(source)) { state.getWorkflowAccessRights().add(textContent); } else if ("X_Visible_Rule".equals(source)) { state.setVisibilityRule(textContent); } else if (NO_ADD.equals(source)) { handleAddRightInfo(repository, state, appInfo); } else if (NO_REMOVE.equals(source)) { handleRemoveRightInfo(repository, state, appInfo); } } } }
Source:
<code>private void doInsert(Exchange exchange, String tableName) throws KuduException { KuduClient connection = endpoint.getKuduClient(); KuduTable table = connection.openTable(tableName); Insert insert = table.newInsert(); PartialRow row = insert.getRow(); Map<?, ?> rows = exchange.getIn().getBody(Map.class); for (Map.Entry<?, ?> entry : rows.entrySet()) { String key = (String) entry.getKey(); Object value = entry.getValue(); switch (value.getClass().toString()) { <START> case "class java.lang.String": <END> row.addString(key, (String) value); break; case "class java.lang.Long": row.addLong(key, (long) value); break; case "class java.lang.Integer": row.addInt(key, (int) value); break; case "class java.lang.Double": row.addDouble(key, (double) value); break; case "class java.lang.Float": row.addFloat(key, (float) value); break; default: throw new IllegalArgumentException("The type " + value.getClass().toString() + " is not supported"); } } connection.newSession().apply(insert); }</code><technical_language>a express this, ugly :-(</technical_language>

Target:
private void doInsert(Exchange exchange, String tableName) throws KuduException { KuduClient connection = endpoint.getKuduClient(); KuduTable table = connection.openTable(tableName); Insert insert = table.newInsert(); PartialRow row = insert.getRow(); Map<?, ?> rows = exchange.getIn().getBody(Map.class); for (Map.Entry<?, ?> entry : rows.entrySet()) { row.addObject(entry.getKey().toString(), entry.getValue()); } connection.newSession().apply(insert); }
Source:
<code>String getInstallId() { String hostName = "Unknown"; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception ignore) { } try { String installIdString = hostName + System.getProperty("user.name"); StringBuilder sb = new StringBuilder(); <START> byte[] bytes = installIdString.getBytes(); <END> for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02X%s", bytes[i], (i < bytes.length - 1) ? "-" : "")); } return sb.toString(); } catch (Exception e) { return "Unknown"; } }</code><technical_language>encoding here</technical_language>

Target:
String getInstallId() { String hostName = "Unknown"; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception ignore) { } try { String installIdString = hostName + System.getProperty("user.name"); StringBuilder sb = new StringBuilder(); byte[] bytes = installIdString.getBytes(StandardCharsets.UTF_8); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02X%s", bytes[i], (i < bytes.length - 1) ? "-" : "")); } return sb.toString(); } catch (Exception e) { return "Unknown"; } }
Source:
<code>public static void verifyPartitionTypeSupported(String partitionName, Type type) { if (!(type instanceof DecimalType || BOOLEAN.equals(type) || TINYINT.equals(type) || SMALLINT.equals(type) || INTEGER.equals(type) || BIGINT.equals(type) || DATE.equals(type) || TIMESTAMP.equals(type) || REAL.equals(type) || DOUBLE.equals(type) || <START> type instanceof VarcharType || <END> type instanceof CharType)) { throw new PrestoException(NOT_SUPPORTED, format("Unsupported type [%s] for partition: %s", type, partitionName)); } }</code><technical_language>isVarcharType Varchars. change check in parsePartitionValue</technical_language>

Target:
public static void verifyPartitionTypeSupported(String partitionName, Type type) { if (!isValidPartitionType(type)) { throw new PrestoException(NOT_SUPPORTED, format("Unsupported type [%s] for partition: %s", type, partitionName)); } }
Source:
<code>private Object getDefaultValue(Type type, String value) { switch (type) { case BOOLEAN: return Boolean.valueOf(value); case INTEGER: return Integer.valueOf(value); case DECIMAL: <START> return Double.valueOf(value); <END> } return null; }</code><technical_language>else in ESH BigDecimal for INTEGER DECIMAL configuration values. Is option well</technical_language>

Target:
private Object getDefaultValue(Type type, String value) { switch (type) { case BOOLEAN: return Boolean.valueOf(value); case INTEGER: return Integer.valueOf(value); case DECIMAL: return new BigDecimal(value); } return null; }
Source:
<code>static void doPrompt(boolean newStatement, LocalizedOutput out, String tag) { <START> final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); <END> String clock = showPromptClock ? " " + sdf.format(new Timestamp(System.currentTimeMillis())) : ""; if (newStatement) { out.print("splice" + clock + "> "); } else { out.print(clock + "> "); } out.flush(); }</code><technical_language>Please ISO 8601 delimiters for date: yyyy-MM-dd</technical_language>

Target:
static void doPrompt(boolean newStatement, LocalizedOutput out, String tag) { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZZZZ"); String clock = showPromptClock ? " " + sdf.format(new Timestamp(System.currentTimeMillis())) : ""; if (newStatement) { out.print("splice" + clock + "> "); } else { out.print(clock + "> "); } out.flush(); }
Source:
<code>public void testInterleaveNoDuplicateCells() throws IOException { String rowKeyPrefix = dataHelper.randomString("interleave-no-dups-"); byte[] qualA = dataHelper.randomData("interleave-no-dups-qual"); Table table = addDataForTesting(rowKeyPrefix, qualA); ColumnPrefixFilter prefixFilter = new ColumnPrefixFilter(Bytes.toBytes("interleave-no-dups-qual")); FilterList filterList = new FilterList( Operator.MUST_PASS_ONE, new QualifierFilter(CompareOp.EQUAL, new BinaryComparator(qualA)), prefixFilter); Scan scan = new Scan(Bytes.toBytes(rowKeyPrefix)); scan.setFilter(filterList); try (ResultScanner scanner = table.getScanner(scan)) { Iterator<Result> iterator = scanner.iterator(); <START> while (iterator.hasNext()) { <END> Assert.assertEquals(1, iterator.next().getColumnCells(COLUMN_FAMILY, qualA).size()); } } }</code><technical_language>not? for(Result result : scanner)</technical_language>

Target:
public void testInterleaveNoDuplicateCells() throws IOException { String rowKeyPrefix = dataHelper.randomString("interleave-no-dups-"); byte[] qualA = dataHelper.randomData("interleave-no-dups-qual"); Table table = addDataForTesting(rowKeyPrefix, qualA); ColumnPrefixFilter prefixFilter = new ColumnPrefixFilter(Bytes.toBytes("interleave-no-dups-qual")); FilterList filterList = new FilterList( Operator.MUST_PASS_ONE, new QualifierFilter(CompareOp.EQUAL, new BinaryComparator(qualA)), prefixFilter); Scan scan = new Scan(Bytes.toBytes(rowKeyPrefix)); scan.setFilter(filterList); try (ResultScanner scanner = table.getScanner(scan)) { for (Result result: scanner) { Assert.assertEquals(1, result.getColumnCells(COLUMN_FAMILY, qualA).size()); } } }
Source:
<code>private Event parseEvent(String eventName) throws TypeImportException, XMLStreamException { Event e = LibraryElementFactory.eINSTANCE.createEvent(); e.setType(EventTypeLibrary.getInstance().getType(null)); readNameCommentAttributes(e); List<String> withVars = new ArrayList<>(); processChildren(eventName, name -> { if <START> (name.equals(LibraryElementTags.WITH_ELEMENT)) <END> { String val = getAttributeValue(LibraryElementTags.VAR_ATTRIBUTE); if (null != val) { withVars.add(val); } proceedToEndElementNamed(LibraryElementTags.WITH_ELEMENT); return true; } return false; }); if (!withVars.isEmpty()) { withList.put(e, withVars); } return e; }</code><technical_language>call equals constant</technical_language>

Target:
private Event parseEvent(String eventName) throws TypeImportException, XMLStreamException { Event e = LibraryElementFactory.eINSTANCE.createEvent(); e.setType(EventTypeLibrary.getInstance().getType(null)); readNameCommentAttributes(e); List<String> withVars = new ArrayList<>(); processChildren(eventName, name -> { if (LibraryElementTags.WITH_ELEMENT.equals(name)) { String val = getAttributeValue(LibraryElementTags.VAR_ATTRIBUTE); if (null != val) { withVars.add(val); } proceedToEndElementNamed(LibraryElementTags.WITH_ELEMENT); return true; } return false; }); if (!withVars.isEmpty()) { withList.put(e, withVars); } return e; }
Source:
<code>public String serialize(Object object, SerializerEncoding encoding) throws IOException { final String contents = jacksonAdapter.serialize(object, encoding); final Class<?> clazz = object.getClass(); if (!CreateQueueBody.class.equals(clazz) && !CreateRuleBody.class.equals(clazz) && !CreateSubscriptionBody.class.equals(clazz)) { return contents; } final Matcher namespaceMatcher = NAMESPACE_PATTERN.matcher(contents); if (!namespaceMatcher.find()) { logger.info("Could not find in {}", NAMESPACE_PATTERN.pattern(), contents); return contents; } final String namespace = namespaceMatcher.group("namespace"); final String replaced = contents .replaceAll(namespace + ":", "") .replace("xmlns:" + namespace + "=", "xmlns="); if (!CreateRuleBody.class.equals(clazz)) { return replaced; } final Matcher filterType = FILTER_ACTION_PATTERN.matcher(replaced); if (filterType.find()) { <START> return filterType.replaceAll("<$1 xmlns:ns0=\"<LINK_0>\" ns0:type="); <END> } else { logger.info("Could not find filter name pattern '{}' in {}.", FILTER_ACTION_PATTERN.pattern(), contents); return replaced; } }</code><technical_language>Rules ns1 in some cases</technical_language>

Target:
public String serialize(Object object, SerializerEncoding encoding) throws IOException { final String contents = jacksonAdapter.serialize(object, encoding); final Class<?> clazz = object.getClass(); if (!CreateQueueBody.class.equals(clazz) && !CreateRuleBody.class.equals(clazz) && !CreateSubscriptionBody.class.equals(clazz)) { return contents; } final Matcher namespaceMatcher = NAMESPACE_PATTERN.matcher(contents); if (!namespaceMatcher.find()) { logger.warning("Could not find in {}", NAMESPACE_PATTERN.pattern(), contents); return contents; } final String namespace = namespaceMatcher.group("namespace"); final String replaced = contents .replaceAll(namespace + ":", "") .replace("xmlns:" + namespace + "=", "xmlns="); if (!CreateRuleBody.class.equals(clazz)) { return replaced; } final Matcher filterType = FILTER_ACTION_PATTERN.matcher(replaced); if (filterType.find()) { return filterType.replaceAll("<$1 xmlns:ns0=\"<LINK_0>\" ns0:type="); } else { logger.warning("Could not find filter name pattern '{}' in {}.", FILTER_ACTION_PATTERN.pattern(), contents); return replaced; } }
Source:
<code>public void updateVisibility(IEclipseContext context) { ExpressionContext exprContext = new ExpressionContext(context); updateIsVisible(exprContext); HashSet<ToolBarContributionRecord> recentlyUpdated = new HashSet<>(); recentlyUpdated.add(this); boolean changed = false; for (MToolBarElement item : generatedElements) { boolean currentVisibility = computeVisibility(recentlyUpdated, item, exprContext); if (item.isVisible() != currentVisibility) { item.setVisible(currentVisibility); changed = true; } } for (MToolBarElement item : sharedElements) { boolean currentVisibility = computeVisibility(recentlyUpdated, item, exprContext); if (item.isVisible() != currentVisibility) { item.setVisible(currentVisibility); changed = true; } } if (changed) { ToolBarManager managerForModel = getManagerForModel(); managerForModel.markDirty(); if (isVisible) { <START> Stream.of(managerForModel.getItems()).filter(org.eclipse.jface.action.IContributionItem::isVisible).findFirst().ifPresent(i -> { <END> MWindow window = getWindow(); if (window != null) { Object widget = window.getWidget(); if (widget instanceof Shell) { ((Shell) widget).requestLayout(); } } }); } } }</code><technical_language>i this is more readable</technical_language>

Target:
public void updateVisibility(IEclipseContext context) { ExpressionContext exprContext = new ExpressionContext(context); updateIsVisible(exprContext); HashSet<ToolBarContributionRecord> recentlyUpdated = new HashSet<>(); recentlyUpdated.add(this); boolean changed = false; for (MToolBarElement item : generatedElements) { boolean currentVisibility = computeVisibility(recentlyUpdated, item, exprContext); if (item.isVisible() != currentVisibility) { item.setVisible(currentVisibility); changed = true; } } for (MToolBarElement item : sharedElements) { boolean currentVisibility = computeVisibility(recentlyUpdated, item, exprContext); if (item.isVisible() != currentVisibility) { item.setVisible(currentVisibility); changed = true; } } if (!changed) { return; } ToolBarManager managerForModel = getManagerForModel(); managerForModel.markDirty(); if (!isVisible) { return; } boolean anyMatch = Stream.of(managerForModel.getItems()).anyMatch(IContributionItem::isVisible); if (anyMatch) { MWindow window = getWindow(); if (window != null) { Object widget = window.getWidget(); if (widget instanceof Shell) { ((Shell) widget).requestLayout(); } } } }
Source:
<code>private static String getUnsupportedType(String component, String[] supportedTypes, Map<String, String> typeMapping) { String componentType = typeMapping.get(component); <START> if (component == null || componentType == null) { <END> return null; } for (String okayType: supportedTypes) { if (okayType.equalsIgnoreCase(componentType)) { return null; } } return componentType; }</code><technical_language>If component is null, this NPE'd this point if typeMapping happen a type allows null keys (most don't)</technical_language>

Target:
private static String getUnsupportedType(String component, String[] supportedTypes, Map<String, String> typeMapping) { if (component == null) { return null; } String componentType = typeMapping.get(component); if (componentType == null) { return null; } for (String okayType: supportedTypes) { if (okayType.equalsIgnoreCase(componentType)) { return null; } } return componentType; }
Source:
<code><START> public void stopGracefully() <END> { log.info("Stopping gracefully."); publishOnStop = true; stopping = true; if (paused) { try { resume(); } catch (InterruptedException e) { log.error(e, "Thread interrupted while trying to stop gracefully"); } } }</code><technical_language>This a stopGracefully do. rename method suspend (not in this PR though). But, supposed do is suspend a task quickly jvm shut restarted. Specifically publish - persist disk stop</technical_language>

Target:
public void stopGracefully() { log.info("Stopping gracefully."); stopRequested = true; if (runThread.isAlive()) { log.info("Interrupting run thread (status: [%s])", status); runThread.interrupt(); } }
Source:
<code>public void receive(String combinedEndpointId, String message) { checkNotNull(combinedEndpointId, "Endpoint ID must not be null"); checkArgument(!combinedEndpointId.isEmpty(), "Endpoint ID name must not be empty"); checkNotNull(message, "Message must not be null"); checkArgument(!message.isEmpty(), "Message must not be empty"); LOGGER.debug("Receiving message: " + message + ", from endpoint: " + combinedEndpointId); if (!jsonRpcQualifier.isValidJson(message)) { String error = "An error occurred on the server while parsing the JSON text"; errorTransmitter.transmit(combinedEndpointId, new JsonRpcException(-32700, error)); } List<String> messages = jsonRpcUnmarshaller.unmarshalArray(message); for (String innerMessage : messages) { if (jsonRpcQualifier.isJsonRpcRequest(innerMessage)) { <START> String endpointId = combinedEndpointId.split("<-:->")[1]; <END> ProcessRequestTask task = new ProcessRequestTask(combinedEndpointId, innerMessage); requestProcessor.process(endpointId, task); } else if (jsonRpcQualifier.isJsonRpcResponse(innerMessage)) { processResponse(combinedEndpointId, innerMessage); } else { processError(); } } }</code><technical_language>elaborate this specific separator is used? I complex separator before</technical_language>

Target:
public void receive(String combinedEndpointId, String message) { checkNotNull(combinedEndpointId, "Endpoint ID must not be null"); checkArgument(!combinedEndpointId.isEmpty(), "Endpoint ID name must not be empty"); checkNotNull(message, "Message must not be null"); checkArgument(!message.isEmpty(), "Message must not be empty"); LOGGER.debug("Receiving message: " + message + ", from endpoint: " + combinedEndpointId); if (!jsonRpcQualifier.isValidJson(message)) { String error = "An error occurred on the server while parsing the JSON text"; errorTransmitter.transmit(combinedEndpointId, new JsonRpcException(-32700, error)); } List<String> messages = jsonRpcUnmarshaller.unmarshalArray(message); for (String innerMessage : messages) { if (jsonRpcQualifier.isJsonRpcRequest(innerMessage)) { String endpointId = combinedEndpointId.split(SEPARATOR)[1]; ProcessRequestTask task = new ProcessRequestTask(combinedEndpointId, innerMessage); requestProcessor.process(endpointId, task); } else if (jsonRpcQualifier.isJsonRpcResponse(innerMessage)) { processResponse(combinedEndpointId, innerMessage); } else { processError(); } } }
Source:
<code>private static Map<Integer, KeyCodeCombination> populateJumpToNthIssueMap() { <START> Map<Integer, KeyCodeCombination> result = Collections.unmodifiableMap(new HashMap<>()); <END> result.put(1, new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.CONTROL_DOWN)); result.put(2, new KeyCodeCombination(KeyCode.DIGIT2, KeyCombination.CONTROL_DOWN)); result.put(3, new KeyCodeCombination(KeyCode.DIGIT3, KeyCombination.CONTROL_DOWN)); result.put(4, new KeyCodeCombination(KeyCode.DIGIT4, KeyCombination.CONTROL_DOWN)); result.put(5, new KeyCodeCombination(KeyCode.DIGIT5, KeyCombination.CONTROL_DOWN)); result.put(6, new KeyCodeCombination(KeyCode.DIGIT6, KeyCombination.CONTROL_DOWN)); result.put(7, new KeyCodeCombination(KeyCode.DIGIT7, KeyCombination.CONTROL_DOWN)); result.put(8, new KeyCodeCombination(KeyCode.DIGIT8, KeyCombination.CONTROL_DOWN)); result.put(9, new KeyCodeCombination(KeyCode.DIGIT9, KeyCombination.CONTROL_DOWN)); return result; }</code><technical_language>This work -- point of unmodifiable map is immutable. map unmodifiable putting key combinations in, returning</technical_language>

Target:
private static Map<Integer, KeyCodeCombination> populateJumpToNthIssueMap() { Map<Integer, KeyCodeCombination> result = new HashMap<>(); result.put(1, new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.CONTROL_DOWN)); result.put(2, new KeyCodeCombination(KeyCode.DIGIT2, KeyCombination.CONTROL_DOWN)); result.put(3, new KeyCodeCombination(KeyCode.DIGIT3, KeyCombination.CONTROL_DOWN)); result.put(4, new KeyCodeCombination(KeyCode.DIGIT4, KeyCombination.CONTROL_DOWN)); result.put(5, new KeyCodeCombination(KeyCode.DIGIT5, KeyCombination.CONTROL_DOWN)); result.put(6, new KeyCodeCombination(KeyCode.DIGIT6, KeyCombination.CONTROL_DOWN)); result.put(7, new KeyCodeCombination(KeyCode.DIGIT7, KeyCombination.CONTROL_DOWN)); result.put(8, new KeyCodeCombination(KeyCode.DIGIT8, KeyCombination.CONTROL_DOWN)); result.put(9, new KeyCodeCombination(KeyCode.DIGIT9, KeyCombination.CONTROL_DOWN)); return Collections.unmodifiableMap(result); }
Source:
<code><START> private long copyHeadAndBody(String filePath) { <END> long linesInBody = 0; try { headFile = File.createTempFile("headFile", ".gz"); bodyFile = File.createTempFile("headFile", ".gz"); } catch (IOException e) { throw new RuntimeException("Error creating file", e); } try (Writer head = getOutputStreamWriter(headFile); Writer body = getOutputStreamWriter(bodyFile); Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(filePath)))) { while (scanner.hasNextLine() && linesInBody < MAX_NUMBER_OF_LINES) { String line = scanner.nextLine(); if (line.startsWith(HEADER_PREFIX)) { head.write(line); head.write("\n"); } else { linesInBody++; body.write(line); body.write("\n"); } } } catch (IOException e) { throw new RuntimeException("Error writing to file", e); } return linesInBody; }</code><technical_language>Agreed offline create 2 functions, copy head another copy body, call a private common behavior</technical_language>

Target:
private long copyHeadAndBody(String filePath) { long linesInBody = 0; try { headFile = File.createTempFile("headFile", ".gz"); bodyFile = File.createTempFile("bodyFile", ".gz"); } catch (IOException e) { throw new RuntimeException("Error creating file", e); } try (Writer head = getOutputStreamWriter(headFile); Writer body = getOutputStreamWriter(bodyFile); Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(filePath)))) { while (scanner.hasNextLine() && linesInBody < MAX_NUMBER_OF_LINES) { String line = scanner.nextLine(); if (line.startsWith(HEADER_PREFIX)) { head.write(line); head.write("\n"); } else { linesInBody++; body.write(line); body.write("\n"); } } } catch (IOException e) { throw new RuntimeException("Error writing to file", e); } return linesInBody; }
Source:
<code>Map<String, List<PartitionInfo>> getTopicMetadata(Set<String> topics) { <START> final Map<String, List<PartitionInfo>> listPartitionsInfo = new HashMap(); <END> List<PartitionInfo> l; for (String topic : topics) { l = metadataConsumer.partitionsFor(topic); listPartitionsInfo.put(topic, l); } return listPartitionsInfo; }</code><technical_language>s/listPartitionsInfo/streamToPartitionInfoMapping</technical_language>

Target:
Map<String, List<PartitionInfo>> getTopicMetadata(Set<String> topics) { Map<String, List<PartitionInfo>> streamToPartitionsInfo = new HashMap(); List<PartitionInfo> partitionInfoList; for (String topic : topics) { partitionInfoList = metadataConsumer.partitionsFor(topic); streamToPartitionsInfo.put(topic, partitionInfoList); } return streamToPartitionsInfo; }
Source:
<code>private FileStatus[] consolidateFileStatuses(FileStatus[] fallbackStatuses, FileStatus[] mountPointStatuses) { ArrayList<FileStatus> result = new ArrayList<>(); Set<String> pathSet = new HashSet<>(); <START> int i = 0; <END> for (FileStatus status : mountPointStatuses) { result.add(status); pathSet.add(status.getPath().getName()); } for (FileStatus status : fallbackStatuses) { if (!pathSet.contains(status.getPath().getName())) { result.add(status); } } return result.toArray(new FileStatus[0]); }</code><technical_language>Please remove unused variable</technical_language>

Target:
private FileStatus[] consolidateFileStatuses(FileStatus[] fallbackStatuses, FileStatus[] mountPointStatuses) { ArrayList<FileStatus> result = new ArrayList<>(); Set<String> pathSet = new HashSet<>(); for (FileStatus status : mountPointStatuses) { result.add(status); pathSet.add(status.getPath().getName()); } for (FileStatus status : fallbackStatuses) { if (!pathSet.contains(status.getPath().getName())) { result.add(status); } } return result.toArray(new FileStatus[0]); }
Source:
<code>private static DataType<byte[]> byteaDataType() { return DataType.dataType( "bytea", VARBINARY, <START> bytes -> format("bytea E'\\\\x%s'", base16().encode(requireNonNull(bytes, "bytes is null"))), <END> Function.identity()); }</code><technical_language>need for requireNonNull encode method throw NPE. rationale for null checks in constructors other places is ensure object invariants exception occur right time, provided null. In this case, caller get NPE proper stack trace. Occasionally, want explicit check provide a message, needed object. Now, if bytes argument this method put lambda capture, want a null check ensure capture is valid</technical_language>

Target:
private static DataType<byte[]> byteaDataType() { return DataType.dataType( "bytea", VARBINARY, bytes -> format("bytea E'\\\\x%s'", base16().encode(bytes)), Function.identity()); }
Source:
<code>public List<Order> getOrderHistoryByOrderNumber(String orderNumber) { Order initial = getOrderByOrderNumber(orderNumber); String workNumber = initial.getPreviousOrderNumber(); List<Order> previousOrders = new ArrayList<Order>(); while (workNumber != null) { Order previous = getOrderByOrderNumber(workNumber); <START> previousOrders.add(0, previous); <END> workNumber = previous.getPreviousOrderNumber(); } Order nextOrder = null; workNumber = orderNumber; List<Order> nextOrders = new ArrayList<Order>(); do { Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Order.class, "order"); searchCriteria.add(Restrictions.eq("order.previousOrderNumber", workNumber)); nextOrder = (Order) searchCriteria.uniqueResult(); if (nextOrder != null) { nextOrders.add(nextOrder); workNumber = nextOrder.getOrderNumber(); } } while (nextOrder != null); List<Order> result = new ArrayList<Order>(previousOrders); result.add(initial); result.addAll(nextOrders); return result; }</code><technical_language>more efficient LinkedList call addFirst</technical_language>

Target:
public List<Order> getOrderHistoryByOrderNumber(String orderNumber) { Order initial = getOrderByOrderNumber(orderNumber); String workNumber = initial.getPreviousOrderNumber(); LinkedList<Order> previousOrders = new LinkedList<Order>(); while (workNumber != null) { Order previous = getOrderByOrderNumber(workNumber); previousOrders.addFirst(previous); workNumber = previous.getPreviousOrderNumber(); } Order nextOrder = null; workNumber = orderNumber; List<Order> nextOrders = new ArrayList<Order>(); do { Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Order.class, "order"); searchCriteria.add(Restrictions.eq("order.previousOrderNumber", workNumber)); nextOrder = (Order) searchCriteria.uniqueResult(); if (nextOrder != null) { nextOrders.add(nextOrder); workNumber = nextOrder.getOrderNumber(); } } while (nextOrder != null); List<Order> result = previousOrders; result.add(initial); result.addAll(nextOrders); return result; }
Source:
<code>public Map<String, DbParameterAccessor> getAllColumns(String tableOrViewName) throws SQLException { String objectDatabaseName = ""; String[] objnameParts = tableOrViewName.split("\\."); if (objnameParts.length == 3) { <START> objectDatabaseName = objnameParts[0] + "."; <END> } String qry = " select c.[name], TYPE_NAME(c.system_type_id) as [Type], c.max_length, " + " 0 As is_output, 0 As is_cursor_ref " + " from " + objectDatabaseName + "sys.columns c " + " where c.object_id = OBJECT_ID(?) " + " order by column_id"; return readIntoParams(tableOrViewName, qry); }</code><technical_language>sounds a bit odd glimpse named objectDatabaseName end . (I if figure out a name)</technical_language>

Target:
public Map<String, DbParameterAccessor> getAllColumns(String tableOrViewName) throws SQLException { String qry = " select c.[name], TYPE_NAME(c.system_type_id) as [Type], c.max_length, " + " 0 As is_output, 0 As is_cursor_ref " + " from " + objectDatabasePrefix(tableOrViewName) + "sys.columns c " + " where c.object_id = OBJECT_ID(?) " + " order by column_id"; return readIntoParams(tableOrViewName, qry); }
Source:
<code>public Observable<List<Comment>> getComments(final News news) { return Observable.from(news.getCommentIds()) .flatMap(new Func1<Integer, Observable<Comment>>() { @Override public Observable<Comment> call(Integer commentId) { return RestClient.service().getComment(commentId) .onErrorReturn(new Func1<Throwable, Comment>() { @Override public Comment call(Throwable throwable) { return null; } }); } }) .flatMap(new Func1<Comment, Observable<Comment>>() { @Override public Observable<Comment> call(Comment comment) { return getInnerComments(comment); } }) <START> .timeout(10, TimeUnit.SECONDS) <END> .filter(new Func1<Comment, Boolean>() { @Override public Boolean call(Comment comment) { return (comment != null) && !comment.isDeleted() && !comment.isDead(); } }) .toList() .map(new Func1<List<Comment>, List<Comment>>() { @Override public List<Comment> call(List<Comment> comments) { Dictionary<Integer, Comment> commentDict = new Hashtable<>(); List<Comment> retval = new ArrayList<>(); for (Comment comment : comments) { commentDict.put(comment.getId(), comment); } for (Integer commentId : news.getCommentIds()) { Comment comment = commentDict.get(commentId); if (comment != null) { retval.add(getCommentWithChild(0, comment, commentDict)); } } return flattenComments(retval); } }) .map(new Func1<List<Comment>, List<Comment>>() { @Override public List<Comment> call(List<Comment> comments) { for (Comment comment : comments) { comment.setAllChildCount(getAllChildCount(comment)); } return comments; } }); }</code><technical_language>logic HTTP request timeout, I need timeout user-configureable</technical_language>

Target:
public Observable<List<Comment>> getComments(final News news) { return Observable.from(news.getCommentIds()) .flatMap(new Func1<Integer, Observable<Comment>>() { @Override public Observable<Comment> call(Integer commentId) { return RestClient.service().getComment(commentId) .onErrorReturn(new Func1<Throwable, Comment>() { @Override public Comment call(Throwable throwable) { return null; } }); } }) .flatMap(new Func1<Comment, Observable<Comment>>() { @Override public Observable<Comment> call(Comment comment) { return getInnerComments(comment); } }) .timeout(Constants.CONN_TIMEOUT_SEC, TimeUnit.SECONDS) .filter(new Func1<Comment, Boolean>() { @Override public Boolean call(Comment comment) { return (comment != null) && !comment.isDeleted() && !comment.isDead(); } }) .toList() .map(new Func1<List<Comment>, List<Comment>>() { @Override public List<Comment> call(List<Comment> comments) { Dictionary<Integer, Comment> commentDict = new Hashtable<>(); List<Comment> retval = new ArrayList<>(); for (Comment comment : comments) { commentDict.put(comment.getId(), comment); } for (Integer commentId : news.getCommentIds()) { Comment comment = commentDict.get(commentId); if (comment != null) { retval.add(getCommentWithChild(0, comment, commentDict)); } } return flattenComments(retval); } }) .map(new Func1<List<Comment>, List<Comment>>() { @Override public List<Comment> call(List<Comment> comments) { for (Comment comment : comments) { comment.setAllChildCount(getAllChildCount(comment)); } return comments; } }); }
Source:
<code>private void setUpClusterArtifacts(Topology topology, TopologyActions topologyActions) throws IOException { Namespace namespace = getNamespace(topology.getNamespaceId()); if (namespace == null) { throw new RuntimeException("Corresponding namespace not found: " + topology.getNamespaceId()); } ObjectMapper objectMapper = new ObjectMapper(); Path artifactsDir = topologyActions.getArtifactsLocation(getTopologyLayout(topology)); makeEmptyDir(artifactsDir); <START> <END> Collection<NamespaceServiceClusterMapping> serviceClusterMappings = listServiceClusterMapping(namespace.getId()); serviceClusterMappings.stream() .map(x -> getServiceByName(x.getClusterId(), x.getServiceName())) .filter(Objects::nonNull) .flatMap((Service x) -> Optional.ofNullable(listServiceConfigurations(x.getId())) .orElse(Collections.emptyList()).stream()) .forEach(x -> { try { writeConfigurationFile(objectMapper, artifactsDir, x); } catch (IOException e) { throw new RuntimeException(e); } }); }</code><technical_language>I a big fan of java 8 streams code, I read more inefficient for loops. consideration code readability. get a bit cryptic java8 streams. If code is easier follow for loops, I favor approach</technical_language>

Target:
private void setUpClusterArtifacts(Topology topology, TopologyActions topologyActions) throws IOException { Namespace namespace = getNamespace(topology.getNamespaceId()); if (namespace == null) { throw new RuntimeException("Corresponding namespace not found: " + topology.getNamespaceId()); } ObjectMapper objectMapper = new ObjectMapper(); Path artifactsDir = topologyActions.getArtifactsLocation(getTopologyLayout(topology)); makeEmptyDir(artifactsDir); Collection<NamespaceServiceClusterMapping> serviceClusterMappings = listServiceClusterMapping(namespace.getId()); for (NamespaceServiceClusterMapping serviceClusterMapping : serviceClusterMappings) { Service service = getServiceByName(serviceClusterMapping.getClusterId(), serviceClusterMapping.getServiceName()); if (service != null) { Collection<ServiceConfiguration> serviceConfigurations = listServiceConfigurations(service.getId()); if (serviceConfigurations != null) { for (ServiceConfiguration serviceConfiguration : serviceConfigurations) { writeConfigurationFile(objectMapper, artifactsDir, serviceConfiguration); } } } } }
Source:
<code>public Optional<ZombieType> getById(String id) { <START> return Optional.ofNullable(types.get(id)); <END> }</code><technical_language>this</technical_language>

Target:
public Optional<ZombieType> getById(String id) { if (!id.contains(":")) { id = "minecraft:" + id; } return Optional.ofNullable(types.get(id)); }
Source:
<code>private ActionListener createJdbcActionListener(final String databaseName) { return new ActionListener() { @Override public void actionPerformed(ActionEvent event) { <START> Injector injectorWithDatastore = _dcModule.createInjectorBuilder().with(JdbcDatastore.class, null) <END> .createInjector(); JdbcDatastoreDialog dialog = injectorWithDatastore.getInstance(JdbcDatastoreDialog.class); dialog.setSelectedDatabase(databaseName); dialog.setVisible(true); } }; }</code><technical_language>final</technical_language>

Target:
private ActionListener createJdbcActionListener(final String databaseName) { return new ActionListener() { @Override public void actionPerformed(ActionEvent event) { final Injector injectorWithDatastore = _dcModule.createInjectorBuilder().with(JdbcDatastore.class, null) .createInjector(); final JdbcDatastoreDialog dialog = injectorWithDatastore.getInstance(JdbcDatastoreDialog.class); dialog.setSelectedDatabase(databaseName); dialog.setVisible(true); } }; }
Source:
<code>public PayloadIterator(InputStream input, ContentMetadata meta) { this.input = checkNotNull(input, "input"); this.metaData = checkNotNull(meta, "meta"); <START> this.readLen = this.metaData.getContentLength().intValue(); <END> this.nextPayload = getNextPayload(); }</code><technical_language>getContentLength() [is nullable](<LINK_0>, need a checkNotNull some null handling here</technical_language>

Target:
public PayloadIterator(InputStream input, ContentMetadata meta) { this.input = checkNotNull(input, "input"); this.metaData = checkNotNull(meta, "meta"); this.readLen = checkNotNull(this.metaData.getContentLength(), "content-length").intValue(); this.nextPayload = getNextPayload(); }
Source:
<code>public <START> <T> List<T> <END> getNextPages() { return (List<T>) nextPages; }</code><technical_language>this correlated 'expectedClass'? unchecked conversion needed</technical_language>

Target:
public List<IPage> getNextPages() { return nextPages; }
Source:
<code>public Visitable visit(AnnotationMemberDeclaration _n, Object _arg) { NodeList<AnnotationExpr> annotations = cloneList(_n.getAnnotations(), _arg); Type<?> type_ = cloneNode(_n.getType(), _arg); <START> Expression defaultValue = cloneNode(_n.getDefaultValue().orElse(null), _arg); <END> Comment comment = cloneNode(_n.getComment(), _arg); AnnotationMemberDeclaration r = new AnnotationMemberDeclaration( _n.getRange(), _n.getModifiers(), annotations, type_, _n.getName(), defaultValue ); r.setComment(comment); return r; }</code><technical_language>Consider making optional-specific "cloneNode" for this</technical_language>

Target:
public Visitable visit(AnnotationMemberDeclaration _n, Object _arg) { NodeList<AnnotationExpr> annotations = cloneList(_n.getAnnotations(), _arg); Type<?> type_ = cloneNode(_n.getType(), _arg); Expression defaultValue = cloneNode(_n.getDefaultValue(), _arg); Comment comment = cloneNode(_n.getComment(), _arg); AnnotationMemberDeclaration r = new AnnotationMemberDeclaration( _n.getRange(), _n.getModifiers(), annotations, type_, _n.getName(), defaultValue ); r.setComment(comment); return r; }
Source:
<code>public void testMany() { final UnweightedDoubleReservoirSample reservoir = new UnweightedDoubleReservoirSample(200); <START> long streamLength = 1000000; <END> for (int i = 0; i < streamLength; ++i) { double value = i * 10 + i % 2; reservoir.add(value); } double[] quantized = new double[4]; reservoir.stream().forEach(s -> { int index = (int) (4.0 * s / (10.0 * streamLength + 1)); ++quantized[index]; }); for (int i = 0; i < 4; ++i) { assertTrue(quantized[i] > 35); } }</code><technical_language>long -> int - streamLength -> totalSamples - 1000000 -> 1_000_000 - inline int totalSamples = 1_000_000; for (int i = 0; i < totalSamples; ++i) { reservoir.add(i * 10.0 + i % 2); }</technical_language>

Target:
public void testMany() { UnweightedDoubleReservoirSample reservoir = new UnweightedDoubleReservoirSample(200); long streamLength = 1_000_000; for (int i = 0; i < streamLength; ++i) { double value = i * 10 + i % 2; reservoir.add(value); } double[] quantized = new double[4]; for (double sample : reservoir.getSamples()) { int index = (int) (4.0 * sample / (10.0 * streamLength + 1)); ++quantized[index]; } for (int i = 0; i < 4; ++i) { assertTrue(quantized[i] > 35, format("Expected quantized[i] > got: i=%s, quantized=%s, got=%s", i, quantized[i], 35)); } }
Source:
<code>public void testDelete() throws IOException, OmiseException { <START> String scheduleId = "schd_test_57s33hm9fg1pzcqihxs"; <END> Request<Schedule> request = new Schedule.DeleteRequestBuilder(scheduleId).build(); Schedule schedule = requester.sendRequest(request); assertRequested("DELETE", "/schedules/" + scheduleId, 200); assertEquals(scheduleId, schedule.getId()); assertEquals(ScheduleStatus.Deleted, schedule.getStatus()); }</code><technical_language>I scheduleId extracted out of methods in test line 65</technical_language>

Target:
public void testDelete() throws IOException, OmiseException { Request<Schedule> request = new Schedule.DeleteRequestBuilder(SCHEDULE_ID).build(); Schedule schedule = requester.sendRequest(request); assertRequested("DELETE", "/schedules/" + SCHEDULE_ID, 200); assertEquals(SCHEDULE_ID, schedule.getId()); assertEquals(ScheduleStatus.Deleted, schedule.getStatus()); }
Source:
<code><START> private Long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) { <END> List<Criteria> criteriaList = getFiltersCriteria(filters); criteriaList.add(existingCriteria); Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()])); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(criteria), Aggregation.group().count().as("count") ); AggregationResults<VariantAggregationCount> aggregationResults = mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class); return aggregationResults.getMappedResults().size() > 0 ? aggregationResults.getMappedResults().get(0).getCount() : 0; }</code><technical_language>Long instead of long open door for returning a null object</technical_language>

Target:
private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) { List<Criteria> criteriaList = getFiltersCriteria(filters); criteriaList.add(existingCriteria); Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()])); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(criteria), Aggregation.group().count().as("count") ); AggregationResults<VariantAggregationCount> aggregationResults = mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class); return aggregationResults.getMappedResults().size() > 0 ? aggregationResults.getMappedResults().get(0).getCount() : 0; }