auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; int finishedChildren = 0; for (Guid childCmdId : childCmdIds) { CommandStatus commandStatus = CommandCoordinatorUtil.getCommandStatus(childCmdId); switch (commandStatus) { case NOT_STARTED: case ACTIVE: log.info("Waiting on CloneCinderDisksCommandCallback child commands to complete"); <START> return; <END> case SUCCEEDED: finishedChildren++; break; case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; default: finishedChildren++; log.error("Invalid command status: '{}", commandStatus); break; } } T command = getCommand(cmdId); if (finishedChildren == childCmdIds.size()) { command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); } else { log.info("Waiting for all child commands to finish. Number of child commands: {}. Finished child commands: {}. ", childCmdIds.size(), finishedChildren); } }</code><technical_language>return statement of finishedChildren redundant. purpose of 'finishedChildren' in this patch is check if execution of child command is done, however, if active commands, return examine of child commands</technical_language>

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; int finishedChildren = 0; for (Guid childCmdId : childCmdIds) { CommandStatus commandStatus = CommandCoordinatorUtil.getCommandStatus(childCmdId); switch (commandStatus) { case SUCCEEDED: finishedChildren++; break; case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; default: finishedChildren++; log.error("Invalid command status: '{}", commandStatus); break; } } if (finishedChildren == childCmdIds.size()) { T command = getCommand(cmdId); command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); } else { log.info("Waiting for all child commands to finish. Number of child commands: {}. Finished child commands: {}. ", childCmdIds.size(), finishedChildren); } }
Source:
<code>public void testAttemptLoadWithSpring() throws Exception { Properties testProperties = PropertiesLoader.attemptLoadWithSpring( PROPERTIES_FILENAME, this.getClass().getClassLoader()); <START> this.getClass().getClassLoader().getResource("pom.xml"); <END> Assert.assertEquals( "Returns the correct properties", exampleMap.entrySet(), testProperties.entrySet()); }</code><technical_language>do this line</technical_language>

Target:
public void testAttemptLoadWithSpring() throws Exception { Properties testProperties = PropertiesLoader.attemptLoadWithSpring( PROPERTIES_FILENAME, this.getClass().getClassLoader()); assertThat(testProperties.entrySet(), equalTo(EXAMPLE_MAP.entrySet())); }
Source:
<code>private void invalidateAmbientCache() { OfflineManager fileSource = OfflineManager.getInstance(CacheManagementActivity.this); fileSource.invalidateAmbientCache(new OfflineManager.FileSourceCallback() { @Override public void onSuccess() { showToast(R.string.cache_invalidated_toast_confirmation); } @Override public void onError(@NonNull String message) { <START> showToast(R.string.cache_invalidated_toast_error); <END> } }); }</code><technical_language>nice pass error message tom toast well. for occurrences</technical_language>

Target:
private void invalidateAmbientCache() { OfflineManager fileSource = OfflineManager.getInstance(CacheManagementActivity.this); fileSource.invalidateAmbientCache(new OfflineManager.FileSourceCallback() { @Override public void onSuccess() { showToast(getString(R.string.cache_invalidated_toast_confirmation)); } @Override public void onError(@NonNull String message) { showToast(String.format(getString( R.string.cache_invalidated_toast_error), message)); } }); }
Source:
<code>private ChildSessionStateMachine buildChildSession(ChildSessionOptions childOptions) { boolean isNatDetected = mIsLocalBehindNat || mIsRemoteBehindNat; ChildSessionStateMachine childSession = ChildSessionStateMachineFactory.makeChildSessionStateMachine( <START> "ChildSessionStateMachine", <END> getHandler().getLooper(), mContext, childOptions, new ChildSessionSmCallback(), mLocalAddress, mRemoteAddress, (isNatDetected ? mIkeSessionOptions.getUdpEncapsulationSocket() : null), mIkePrf, mCurrentIkeSaRecord.getSkD()); return childSession; }</code><technical_language>Do need pass this in if same</technical_language>

Target:
private ChildSessionStateMachine buildChildSession(ChildSessionOptions childOptions) { boolean isNatDetected = mIsLocalBehindNat || mIsRemoteBehindNat; ChildSessionStateMachine childSession = ChildSessionStateMachineFactory.makeChildSessionStateMachine( getHandler().getLooper(), mContext, childOptions, new ChildSessionSmCallback(), mLocalAddress, mRemoteAddress, (isNatDetected ? mIkeSessionOptions.getUdpEncapsulationSocket() : null), mIkePrf, mCurrentIkeSaRecord.getSkD()); return childSession; }
Source:
<code>protected void refreshChildren() { ITmfTrace trace = getParent().getTrace(); if (trace == null) { return; } if (!fInitialized) { Set<IOnDemandAnalysis> analyses = OnDemandAnalysisManager.getInstance().getOndemandAnalyses(trace); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); <START> IPath nodePath = this.getResource().getFullPath(); <END> analyses.forEach(analysis -> { IFolder analysisRes = checkNotNull(root.getFolder(nodePath.append(analysis.getName()))); TmfOnDemandAnalysisElement elem = new TmfOnDemandAnalysisElement( analysis.getName(), analysisRes, this, analysis); addChild(elem); }); } getChildren().forEach(child -> ((TmfProjectModelElement) child).refreshChildren()); }</code><technical_language>remove this</technical_language>

Target:
protected void refreshChildren() { ITmfTrace trace = getParent().getTrace(); if (trace == null) { return; } if (!fInitialized) { Set<IOnDemandAnalysis> analyses = OnDemandAnalysisManager.getInstance().getOndemandAnalyses(trace); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath nodePath = getResource().getFullPath(); analyses.forEach(analysis -> { IFolder analysisRes = checkNotNull(root.getFolder(nodePath.append(analysis.getName()))); TmfOnDemandAnalysisElement elem = new TmfOnDemandAnalysisElement( analysis.getName(), analysisRes, this, analysis); addChild(elem); }); } getChildren().forEach(child -> ((TmfProjectModelElement) child).refreshChildren()); }
Source:
<code>public JdbcSecurityRealm build() { List<QueryConfiguration> configuration = new ArrayList<>(); for (QueryBuilder query : this.queries) { configuration.add(query.buildQuery()); } <START> if (hashCharset == null) { <END> return new JdbcSecurityRealm(configuration, providers, StandardCharsets.UTF_8); } else { return new JdbcSecurityRealm(configuration, providers, hashCharset); } }</code><technical_language>This block simplified slightly follows: if (hashCharset == null) { hashCharset = StandardCharsets.UTF_8; } return new JdbcSecurityRealm(configuration, providers, hashCharset);</technical_language>

Target:
public JdbcSecurityRealm build() { List<QueryConfiguration> configuration = new ArrayList<>(); for (QueryBuilder query : this.queries) { configuration.add(query.buildQuery()); } if (hashCharset == null) { hashCharset = StandardCharsets.UTF_8; } return new JdbcSecurityRealm(configuration, providers, hashCharset); }
Source:
<code>public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); ModelType type = value.getType(); <START> if (type == ModelType.STRING && !value.isProtected()) { <END> String tuString = ExpressionResolver.SIMPLE.resolveExpressions(value).asString(); E enumValue = toStringMap.get(tuString); if (enumValue == null) { try { enumValue = Enum.valueOf(enumType, tuString.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw ControllerLogger.ROOT_LOGGER.invalidEnumValue(tuString, parameterName, toStringMap.keySet()); } } if (!allowedValues.contains(enumValue)) { throw ControllerLogger.ROOT_LOGGER.invalidEnumValue(tuString, parameterName, toStringMap.keySet()); } value.set(enumValue.toString()); } }</code><technical_language>This if (!value.isProtected()) guard 'value.set(enumValue.toString());' call. disables validation. protected need validation</technical_language>

Target:
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); ModelType type = value.getType(); if (type == ModelType.STRING ) { String tuString = ExpressionResolver.SIMPLE.resolveExpressions(value).asString(); E enumValue = toStringMap.get(tuString); if (enumValue == null) { try { enumValue = Enum.valueOf(enumType, tuString.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw ControllerLogger.ROOT_LOGGER.invalidEnumValue(tuString, parameterName, toStringMap.keySet()); } } if (!allowedValues.contains(enumValue)) { throw ControllerLogger.ROOT_LOGGER.invalidEnumValue(tuString, parameterName, toStringMap.keySet()); } if (!value.isProtected()) { value.set(enumValue.toString()); } } }
Source:
<code>public int getAverageResultSize() { if (currentReader == null) { <START> return 16; <END> } return currentReader.getAverageResultSize(); }</code><technical_language>16</technical_language>

Target:
public int getAverageResultSize() { if (currentReader == null) { return 2 * Long.BYTES + Integer.BYTES; } return currentReader.getAverageResultSize(); }
Source:
<code><START> EventBus createEventBus(PostCommentedEventHandler postCommentedEventHandler) { <END> EventBus eventBus = new EventBus(); return eventBus; }</code><technical_language>passing EventHandler if of ? :sweat:</technical_language>

Target:
EventBus createEventBus(PostCommentedEventHandler postCommentedEventHandler) { EventBus eventBus = new EventBus(); eventBus.register(postCommentedEventHandler); return eventBus; }
Source:
<code>static boolean isTopStrand(final SAMRecord rec) { final int read1FivePrimeCoordinate; final int read2FivePrimeCoordinate; if (rec.getFirstOfPairFlag()) { read1FivePrimeCoordinate = (rec.getReadNegativeStrandFlag()) ? rec.getAlignmentEnd() : rec.getAlignmentStart(); read2FivePrimeCoordinate = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec); } else { read1FivePrimeCoordinate = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec); <START> read2FivePrimeCoordinate = (rec.getReadNegativeStrandFlag()) ? rec.getAlignmentEnd() : rec.getAlignmentStart(); <END> } return read1FivePrimeCoordinate < read2FivePrimeCoordinate; }</code><technical_language>code compute values is identical variable stored in is swapped. nice if compute done once, obvious reader formula is same. variable names be, done if determine weather test a < b a >= b, e.g. if (rec.getFirstOrPairFlag()) { return a < b; } else { return a >= b; } (Which is identical return rec.getFirstOrPairFlag() == (a < b); this a clear write this.)</technical_language>

Target:
static boolean isTopStrand(final SAMRecord rec) { if (!rec.getReferenceIndex().equals(rec.getMateReferenceIndex())) { return rec.getFirstOfPairFlag() == (rec.getReferenceIndex() < rec.getMateReferenceIndex()); } final int read5PrimeStart = (rec.getReadNegativeStrandFlag()) ? rec.getUnclippedEnd() : rec.getUnclippedStart(); final int mate5PrimeStart = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec); return rec.getFirstOfPairFlag() == (read5PrimeStart < mate5PrimeStart); }
Source:
<code>@Test public void deserializeWrongClass() throws Exception { ResponseBody body = ResponseBody.create(MEDIA_TYPE, JSON); try { converter.fromBody(body, String.class); <START> } catch (NoSuchMapperException ignored) { <END> } }</code><technical_language>Missing fail() in try block</technical_language>

Target:
public void deserializeWrongClass() throws Exception { ResponseBody body = ResponseBody.create(MEDIA_TYPE, JSON); try { converter.fromBody(body, String.class); fail(); } catch (Exception ignored) { } }
Source:
<code><START> public long getTablePtr() { <END> return table.getNativePtr(); }</code><technical_language>public? call JNI if private</technical_language>

Target:
private long getTablePtr() { return table.getNativePtr(); }
Source:
<code>private void handleMetadata(Versioned<LedgerMetadata> result, Throwable exception) { if (exception == null) { final Set<LedgerMetadataListener> listenerSet = listeners.get(ledgerId); if (null != listenerSet) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger metadata is changed for : {}.", ledgerId, result); } scheduler.submit(() -> { synchronized (listenerSet) { for (LedgerMetadataListener listener : listenerSet) { listener.onChanged(ledgerId, result); } } }); } <START> } else if (exception instanceof BKException.BKNoSuchLedgerExistsException) { <END> Set<LedgerMetadataListener> listenerSet = listeners.remove(ledgerId); if (null != listenerSet) { if (LOG.isDebugEnabled()) { LOG.debug("Removed ledger metadata listener set on ledger as its ledger is deleted : {}", ledgerId, listenerSet.size()); } synchronized (listenerSet) { for (LedgerMetadataListener listener : listenerSet) { listener.onChanged(ledgerId, null); } } } } else { LOG.warn("Failed on read ledger metadata of ledger {}", ledgerId, exception); scheduler.schedule(this, ZK_CONNECT_BACKOFF_MS, TimeUnit.MILLISECONDS); } }</code><technical_language>I suggest instanceof here. getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsException</technical_language>

Target:
private void handleMetadata(Versioned<LedgerMetadata> result, Throwable exception) { if (exception == null) { final Set<LedgerMetadataListener> listenerSet = listeners.get(ledgerId); if (null != listenerSet) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger metadata is changed for : {}.", ledgerId, result); } scheduler.submit(() -> { synchronized (listenerSet) { for (LedgerMetadataListener listener : listenerSet) { listener.onChanged(ledgerId, result); } } }); } } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsException) { Set<LedgerMetadataListener> listenerSet = listeners.remove(ledgerId); if (null != listenerSet) { if (LOG.isDebugEnabled()) { LOG.debug("Removed ledger metadata listener set on ledger as its ledger is deleted : {}", ledgerId, listenerSet.size()); } synchronized (listenerSet) { for (LedgerMetadataListener listener : listenerSet) { listener.onChanged(ledgerId, null); } } } } else { LOG.warn("Failed on read ledger metadata of ledger {}: {}", ledgerId, BKException.getExceptionCode(exception)); scheduler.schedule(this, ZK_CONNECT_BACKOFF_MS, TimeUnit.MILLISECONDS); } }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode source = lookup.resolve(parent.getSource()); if (!(source instanceof TableScanNode)) { return Optional.empty(); } TableScanNode child = (TableScanNode) source; Optional<Set<Symbol>> dependencies = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!dependencies.isPresent()) { return Optional.empty(); } List<Symbol> newOutputs = filter(child.getOutputSymbols(), dependencies.get()::contains); return Optional.of( new ProjectNode( parent.getId(), new TableScanNode( child.getId(), child.getTable(), newOutputs, <START> filterKeys(child.getAssignments(), newOutputs::contains), <END> child.getLayout(), child.getCurrentConstraint(), child.getOriginalConstraint()), parent.getAssignments())); }</code><technical_language>purpose of newOutputs is preserve previous order of outputs change node unnecessarily. dependencies.get()::contains in filterKeys in opinion more direct scale properly number of columns</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode source = lookup.resolve(parent.getSource()); if (!(source instanceof TableScanNode)) { return Optional.empty(); } TableScanNode child = (TableScanNode) source; Optional<Set<Symbol>> dependencies = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!dependencies.isPresent()) { return Optional.empty(); } return Optional.of( new ProjectNode( parent.getId(), new TableScanNode( child.getId(), child.getTable(), filteredCopy(child.getOutputSymbols(), dependencies.get()::contains), filterKeys(child.getAssignments(), dependencies.get()::contains), child.getLayout(), child.getCurrentConstraint(), child.getOriginalConstraint()), parent.getAssignments())); }
Source:
<code><START> public HashMap<String, String> getAttributes() { <END> if (attributes == null) { attributes = new HashMap<>(); } return attributes; }</code><technical_language>this method returns HashMap Map</technical_language>

Target:
public Map<String, String> getAttributes() { if (attributes == null) { attributes = new HashMap<>(); } return attributes; }
Source:
<code><START> private File getFeatureTypeDir( <END> File featureTypesBaseDir, String namespacePrefix, String typeName) { return new File(featureTypesBaseDir, getDataStoreName(namespacePrefix, typeName)); }</code><technical_language>specific reason this method static anymore</technical_language>

Target:
protected File getFeatureTypeDir( File featureTypesBaseDir, String namespacePrefix, String typeName) { return new File(featureTypesBaseDir, getDataStoreName(namespacePrefix, typeName)); }
Source:
<code>public static SystemTapView createView(final String viewID) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { IViewPart view = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(). showView(viewID); if (!(view instanceof SystemTapView)) <START> throw new RuntimeException("Miscast type: " + view.getClass().toString()); END> newView = ((SystemTapView) view); newView.setViewID(); } catch (PartInitException e) { e.printStackTrace(); } } }); addView(newView); return newView; }</code><technical_language>Is safe throw RuntimeException instead of Exception. This changes semantic aka checked unchecked exception. is this exception thrown? usual of handling stuff is do instanceof check satisfy code</technical_language>

Target:
public static SystemTapView createView(final String viewID) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { IViewPart view = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(). showView(viewID); if (!(view instanceof SystemTapView)) return; newView = ((SystemTapView) view); newView.setViewID(); } catch (PartInitException e) { e.printStackTrace(); } } }); addView(newView); return newView; }
Source:
<code>@Test public void testRoundingNPE() { CalciteAssert.that() .query("SELECT ROUND(CAST((X/Y) AS NUMERIC), 2) " + "FROM (VALUES (1, 2), (NULLIF(5, 5), NULLIF(5, 5))) A(X, Y)") <START> .planContains(" final Object[] current = (Object[]) inputEnumerator.current();\n" <END> + " final Integer input_value = (Integer) current[0];\n" + " final Integer input_value0 = (Integer) current[1];\n" + " final Integer binary_call_value = input_value == null || input_value0 == null ? (Integer) null : Integer.valueOf(input_value / input_value0);\n" + " final java.math.BigDecimal cast_value = binary_call_value == null ? (java.math.BigDecimal) null : binary_call_value == null ? (java.math.BigDecimal) null : new java.math.BigDecimal(\n" + " binary_call_value.intValue());\n" + " return cast_value == null ? (java.math.BigDecimal) null : org.apache.calcite.runtime.SqlFunctions.sround(cast_value, 2);") .returns("EXPR$0=0.00\n" + "EXPR$0=null\n"); }</code><technical_language>Is a reason verify generated code is included in test? I for this test suffices verify query runs correctly NPE checking code line line</technical_language>

Target:
@Test public void testRoundingNPE() { CalciteAssert.that() .query("SELECT ROUND(CAST((X/Y) AS NUMERIC), 2) " + "FROM (VALUES (1, 2), (NULLIF(5, 5), NULLIF(5, 5))) A(X, Y)") .returns("EXPR$0=0.00\n" + "EXPR$0=null\n"); }
Source:
<code>public int hashCode() { <START> int result = processId.hashCode(); <END> result = 31 * result + taskId.hashCode(); result = 31 * result + taskName.hashCode(); result = 31 * result + formName.hashCode(); return result; }</code><technical_language>for luck ;-)</technical_language>

Target:
public int hashCode() { int result = processId.hashCode(); result = ~~result; result = 31 * result + taskId.hashCode(); result = ~~result; result = 31 * result + taskName.hashCode(); result = ~~result; result = 31 * result + formName.hashCode(); result = ~~result; return result; }
Source:
<code>public BroadcasterMessageHandler(Processor processor) { Assert.notNull(processor, "processor cannot be null."); this.reactorProcessor = processor; Environment.initializeIfEmpty(); this.inputType = ReactorReflectionUtils.extractInputType(processor); <START> this.stream = RingBufferProcessor.share("xd-reactor", 8192); END> Publisher<?> outputStream = processor.process(Streams.wrap(stream)); outputStream.subscribe(new DefaultSubscriber<Object>() { @Override public void onSubscribe(Subscription s) { processorSubscription = s; s.request(Long.MAX_VALUE); } @Override public void onNext(Object outputObject) { if (ClassUtils.isAssignable(Message.class, outputObject.getClass())) { getOutputChannel().send((Message) outputObject); } else { getOutputChannel().send(MessageBuilder.withPayload(outputObject).build()); } } @Override public void onError(Throwable throwable) { logger.error(throwable); } @Override public void onComplete() { } }); }</code><technical_language>add setter for bufferSize merge</technical_language>

Target:
public BroadcasterMessageHandler(Processor processor) { super(processor); }
Source:
<code>public synchronized void updated(final Map<String, Object> properties) { s_logger.debug(s_message.updatingCloudPublisher()); this.options = new CloudPublisherOptions(properties); if (this.cloudServiceTracker != null) { this.cloudServiceTracker.close(); } initCloudServiceTracking(); s_logger.debug(s_message.updatingCloudPublisherDone()); <START> } <END></code><technical_language>tracker needs closed while deactivating in component</technical_language>

Target:
public synchronized void updated(final Map<String, Object> properties) { logger.debug(message.updatingCloudPublisher()); this.cloudPublisherOptions = new CloudPublisherOptions(properties); if (this.cloudServiceTracker != null) { this.cloudServiceTracker.close(); } initCloudServiceTracking(); logger.debug(message.updatingCloudPublisherDone()); }
Source:
<code>protected Response JSONRepresentation(Object entity) { <START> if (entity == null) { return OK(""); } <END> try { String jsonStr = toJson(entity); return OK(jsonStr); } catch (IOException e) { _logger.error("Failed to convert " + entity + " to JSON response", e); return serverError(); } }</code><technical_language>1) is this necessary of a sudden? 2) do checks this in toJson function</technical_language>

Target:
protected Response JSONRepresentation(Object entity) { try { String jsonStr = toJson(entity); return OK(jsonStr); } catch (IOException e) { _logger.error("Failed to convert " + entity + " to JSON response", e); return serverError(); } }
Source:
<code>@Test public void responseBodyStreams() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.getUrl("/").toString()) .converterFactory(new ToStringConverterFactory()) .build(); Service example = retrofit.create(Service.class); server.enqueue(new MockResponse() .setBody("1234") .setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY)); Response<ResponseBody> response = example.getStreamingBody().execute(); try { <START> response.body().string(); <END> } catch (IOException e) { assertThat(e).hasMessage("unexpected end of stream"); } }</code><technical_language>fail fail</technical_language>

Target:
@Test public void responseBodyStreams() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.getUrl("/").toString()) .converterFactory(new ToStringConverterFactory()) .build(); Service example = retrofit.create(Service.class); server.enqueue(new MockResponse() .setBody("1234") .setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY)); Response<ResponseBody> response = example.getStreamingBody().execute(); ResponseBody streamedBody = response.body(); try { streamedBody.string(); fail(); } catch (IOException e) { assertThat(e).hasMessage("unexpected end of stream"); } }
Source:
<code>public static void sendToTMaster(String command, String topologyName, SchedulerStateManagerAdaptor stateManager, NetworkUtils.TunnelConfig tunnelConfig) throws TMasterException { LOG.fine("Fetching TMaster location for topology: " + topologyName); TopologyMaster.TMasterLocation location = stateManager.getTMasterLocation(topologyName); Preconditions.checkNotNull(location, "Failed to fetch TMaster Location for topology: " + topologyName); LOG.fine("Fetched TMaster location for topology: " + topologyName); String url = String.format("http://%s:%d/%s?topologyid=%s", location.getHost(), location.getControllerPort(), command, location.getTopologyId()); try { URL endpoint = new URL(url); LOG.fine("HTTP URL for TMaster: " + endpoint); sendGetRequest(endpoint, command, tunnelConfig); } catch (MalformedURLException e) { <START> throw new RuntimeException("Invalid URL for Tmaster endpoint: " + url, e); <END> } }</code><technical_language>TMasterException instead of RuntimeException? TM in TMaster in caps</technical_language>

Target:
public static void sendToTMaster(String command, String topologyName, SchedulerStateManagerAdaptor stateManager, NetworkUtils.TunnelConfig tunnelConfig) throws TMasterException { LOG.fine("Fetching TMaster location for topology: " + topologyName); TopologyMaster.TMasterLocation location = stateManager.getTMasterLocation(topologyName); if (location == null) { throw new TMasterException("Failed to fetch TMaster location for topology: " + topologyName); } LOG.fine("Fetched TMaster location for topology: " + topologyName); String url = String.format("http://%s:%d/%s?topologyid=%s", location.getHost(), location.getControllerPort(), command, location.getTopologyId()); try { URL endpoint = new URL(url); LOG.fine("HTTP URL for TMaster: " + endpoint); sendGetRequest(endpoint, command, tunnelConfig); } catch (MalformedURLException e) { throw new TMasterException("Invalid URL for TMaster endpoint: " + url, e); } }
Source:
<code>public T getUniqueByProperty(String property, Object value, boolean enforceType) throws NonUniqueResultException { Iterable<T> results = findAllByProperty(property, value, enforceType); T result = null; Iterator<? extends WindupVertexFrame> iterator = results.iterator(); do { if (!iterator.hasNext()) return result; WindupVertexFrame item = iterator.next(); if (!type.isInstance(item)) continue; <START> if ("jsf".equals(value)) END> Logger.getLogger("FOO").info("Model with name 'jsf', type: " + type + " item: " + StringUtils.join(item.getClass().getInterfaces(), ", ")); if (result != null) { throw new NonUniqueResultException("Expected unique value, but returned non-unique: " + property + " Conflicting models:" + NL + "\t" + StringUtils.join(item.getClass().getInterfaces(), ", ") + NL + "\t\t" + item.toPrettyString() + NL + "\t" + StringUtils.join(result.getClass().getInterfaces(), ", ") + NL + "\t\t" + result.toPrettyString()); } result = (T) item; } while (iterator != null); return result; }</code><technical_language>I this entry in log file: [FOO] (main) Model name 'jsf', type: interface org.jboss.windup.reporting.model.TagModel item: interface org.jboss.windup.graph.model.WindupVertexFrame, interface com.tinkerpop.frames.VertexFrame, interface org.jboss.windup.reporting.model.TagModel Is useful debug? removed</technical_language>

Target:
public T getUniqueByProperty(String property, Object value, boolean enforceType) throws NonUniqueResultException { Iterable<T> results = findAllByProperty(property, value, enforceType); T result = null; for (WindupVertexFrame item : results) { if (!type.isInstance(item)) continue; if (result != null) { throw new NonUniqueResultException("Expected unique value, but returned non-unique: " + property + " Conflicting models:" + NL + "\t" + StringUtils.join(item.getClass().getInterfaces(), ", ") + NL + "\t\t" + item.toPrettyString() + NL + "\t" + StringUtils.join(result.getClass().getInterfaces(), ", ") + NL + "\t\t" + result.toPrettyString()); } result = (T) item; } return result; }
Source:
<code><START> public void onKeyUp(KeyUpEvent event){ <END> if (event.isLeftArrow() && event.isRightArrow()) { } else if (event.isDownArrow()) { if (dropDownPopup != null) { String itemText = dropDownPopup.selectNextItem(); if (itemText != null) { textBox.setText(itemText); } } } else if (event.isUpArrow()) { if (dropDownPopup != null) { String itemText = dropDownPopup.selectPreviousItem(); if (itemText != null) { textBox.setText(itemText); } else { textBox.setText(previousSearchString); } } } else if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) { if (dropDownPopup != null) { setSelectedDisplayItem(dropDownPopup.getSelectedItem()); } } else if (textBox.getText().length() >= this.minCharCount && !textBox.getText().equals(previousSearchString)) { selectedObject = null; previousSearchString = textBox.getText(); this.setValue(textBox.getText()); createDropDownPopup(); applyFilter(); } else if (textBox.getText().length() < this.minCharCount) { selectedObject = null; previousSearchString = textBox.getText(); this.setValue(textBox.getText()); destroyDropDownPopup(); } }</code><technical_language>space )</technical_language>

Target:
public void onKeyUp(KeyUpEvent event) { if (event.isLeftArrow() || event.isRightArrow()) { } else if (event.isDownArrow()) { if (dropDownPopup != null) { String itemText = dropDownPopup.selectNextItem(); if (itemText != null) { textBox.setText(itemText); } } } else if (event.isUpArrow()) { if (dropDownPopup != null) { String itemText = dropDownPopup.selectPreviousItem(); if (itemText != null) { textBox.setText(itemText); } else { textBox.setText(previousSearchString); } } } else if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) { if (dropDownPopup != null) { setSelectedDisplayItem(dropDownPopup.getSelectedItem()); } } else if (textBox.getText().length() >= this.minCharCount && !textBox.getText().equals(previousSearchString)) { selectedObject = null; previousSearchString = textBox.getText(); createDropDownPopup(); applyFilter(); } else if (textBox.getText().length() < this.minCharCount) { selectedObject = null; previousSearchString = textBox.getText(); destroyDropDownPopup(); } }
Source:
<code>private WritableSupplier<IndexedInts> readSingleValuedColumn(VERSION version, ByteBuffer buffer) { switch (version) { case UNCOMPRESSED_SINGLE_VALUE: return VSizeIndexedInts.readFromByteBuffer(buffer).asWritableSupplier(); case COMPRESSED: return CompressedVSizeIntsIndexedSupplier.fromByteBuffer(buffer, byteOrder); } <START> throw new IAE("Unsupported version[%s]", version); <END> }</code><technical_language>Suggest Unsupported single-value version</technical_language>

Target:
private WritableSupplier<IndexedInts> readSingleValuedColumn(VERSION version, ByteBuffer buffer) { switch (version) { case UNCOMPRESSED_SINGLE_VALUE: return VSizeIndexedInts.readFromByteBuffer(buffer).asWritableSupplier(); case COMPRESSED: return CompressedVSizeIntsIndexedSupplier.fromByteBuffer(buffer, byteOrder); } throw new IAE("Unsupported single-value version[%s]", version); }
Source:
<code>public boolean deleteChunk(Chunk chunk) { IChunkProvider provider = this.getChunkProvider(); Vector3i chunkPos = chunk.getPosition(); <START> if (provider instanceof ChunkProviderServer) { <END> ((ChunkProviderServer) provider).dropChunk(chunkPos.getX(), chunkPos.getZ()); return true; } return false; }</code><technical_language>worldserver creates a ChunkProviderServer instance, is need check else. needs a check for forced chunks forge mods blocks chunks loaded. If a forced chunk is found, this method needs return false</technical_language>

Target:
public boolean deleteChunk(Chunk chunk) { ChunkProviderServer provider = (ChunkProviderServer) this.getChunkProvider(); Vector3i chunkPos = chunk.getPosition(); if (ForgeChunkManager.getPersistentChunksFor((net.minecraft.world.World) (Object) this).containsKey( new ChunkCoordIntPair(chunkPos.getX(), chunkPos.getZ()))) { return false; } provider.dropChunk(chunkPos.getX(), chunkPos.getZ()); return true; }
Source:
<code>public int getBufferedBytes() { <START> return toIntExact((rowCount * otherColumnsBytesPerRow) + <END> dictionaryColumns.stream() .mapToLong(TestDictionaryColumn::getBufferedBytes) .sum()); }</code><technical_language>Consider making method return long instead</technical_language>

Target:
public long getBufferedBytes() { return (long) rowCount * otherColumnsBytesPerRow + dictionaryColumns.stream() .mapToLong(TestDictionaryColumn::getBufferedBytes) .sum(); }
Source:
<code>public void createDirectoriesAndFiles() throws Exception { <START> root = new File("target", "configuration").toPath(); <END> Files.createDirectories(root); File baseDir = root.toAbsolutePath().toFile(); File gitDir = new File(baseDir, Constants.DOT_GIT); if (!gitDir.exists()) { try (Git git = Git.init().setDirectory(baseDir).call()) { git.commit().setMessage("Repository initialized").call(); } } repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build(); }</code><technical_language>root configuration (aka server.config.dir) another directory corresponds server.base.dir</technical_language>

Target:
public void createDirectoriesAndFiles() throws Exception { root = new File("target", "standalone").toPath(); Files.createDirectories(root); File baseDir = root.toAbsolutePath().toFile(); File gitDir = new File(baseDir, Constants.DOT_GIT); if (!gitDir.exists()) { try (Git git = Git.init().setDirectory(baseDir).setGitDir(gitDir).call()) { git.commit().setMessage("Repository initialized").call(); } } repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build(); }
Source:
<code>private void flushDeadQueue() { executorService.submit(new Runnable() { @Override public void run() { while (!deadQueue.isEmpty()) { try { Entry entry = deadQueue.poll(); graphite.send(entry.getName(), entry.getValue(), entry.getTimestamp()); } catch (IOException ex) { <START> LOGGER.warn("Error closing Graphite", graphite, ex); <END> } } } }); }</code><technical_language>wrong error message</technical_language>

Target:
private void flushDeadQueue() { executorService.submit(new Runnable() { @Override public void run() { while (!deadQueue.isEmpty()) { try { Entry entry = deadQueue.poll(); graphite.send(entry.getName(), entry.getValue(), entry.getTimestamp()); } catch (IOException ex) { LOGGER.warn("Unable to report to Graphite", graphite, ex); } } } }); }
Source:
<code><START> public static <END> Resource getResource(final ResourceSet resourceSet, final URI resourceURI) { Resource resource = null; try { resource = resourceSet.getResource(resourceURI, true); } catch (WrappedException e) { SiriusPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, SiriusPlugin.ID, e.getMessage(), e)); } return resource; }</code><technical_language>private, reason expose this helper more strictly necessary</technical_language>

Target:
private static Resource getResource(final ResourceSet resourceSet, final URI resourceURI) { Resource resource = null; try { resource = resourceSet.getResource(resourceURI, true); } catch (WrappedException e) { SiriusPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, SiriusPlugin.ID, e.getMessage(), e)); } return resource; }
Source:
<code>public void testRoundTripPoint() throws Exception { PointSymbolizer sym = (PointSymbolizer) parse("example-pointsymbolizer-local-uom.xml"); <START> assertEquals("pixel", Units.toName( sym.getUnitOfMeasure() )); <END> assertEquals("8m", sym.getGraphic().getSize().evaluate(null, String.class)); Document doc = encode(sym, SE.PointSymbolizer); }</code><technical_language>is constant for pixels? deal here</technical_language>

Target:
public void testRoundTripPoint() throws Exception { PointSymbolizer sym = (PointSymbolizer) parse("example-pointsymbolizer-local-uom.xml"); assertEquals("pixel", Units.toName( sym.getUnitOfMeasure() )); assertEquals(Units.PIXEL, sym.getUnitOfMeasure() ); assertEquals("8m", sym.getGraphic().getSize().evaluate(null, String.class)); Document doc = encode(sym, SE.PointSymbolizer); }
Source:
<code>protected CollectionRest createAndReturn(Context context, UUID id) throws AuthorizeException { if (id == null) { throw new DSpaceBadRequestException("The given parent parameter was invalid: " <START> + id); <END> } HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); CollectionRest collectionRest; try { ServletInputStream input = req.getInputStream(); collectionRest = mapper.readValue(input, CollectionRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("Error parsing request body: " + e1.toString()); } Collection collection; try { Community parent = communityService.find(context, id); if (parent == null) { throw new UnprocessableEntityException("Parent community for id: " + id + " not found"); } collection = cs.create(context, parent); cs.update(context, collection); metadataConverter.setMetadata(context, collection, collectionRest.getMetadata()); } catch (SQLException e) { throw new RuntimeException("Unable to create new Collection under parent Community " + id, e); } return converter.convert(collection); }</code><technical_language>If id is null here, return a message null (i.e. point in printing out (as null). So, reword this error similar ("Parent Community UUID is null. create a Collection providing a parent Community")</technical_language>

Target:
protected CollectionRest createAndReturn(Context context, UUID id) throws AuthorizeException { if (id == null) { throw new DSpaceBadRequestException("Parent Community UUID is null. " + "Cannot create a Collection without providing a parent Community"); } HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); CollectionRest collectionRest; try { ServletInputStream input = req.getInputStream(); collectionRest = mapper.readValue(input, CollectionRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("Error parsing request body.", e1); } Collection collection; try { Community parent = communityService.find(context, id); if (parent == null) { throw new UnprocessableEntityException("Parent community for id: " + id + " not found"); } collection = cs.create(context, parent); cs.update(context, collection); metadataConverter.setMetadata(context, collection, collectionRest.getMetadata()); } catch (SQLException e) { throw new RuntimeException("Unable to create new Collection under parent Community " + id, e); } return converter.convert(collection); }
Source:
<code>private ConfigurationInstance getConfiguration(Pair<ResolverSetResult, ResolverSetResult> resolverSetResult, CoreEvent event) throws Exception { ConfigurationInstance configuration = cache.getIfPresent(resolverSetResult); if (configuration != null) { <START> updateUsageStatistic(configuration); <END> return configuration; } configuration = cache.getIfPresent(resolverSetResult); if (configuration == null) { configuration = createConfiguration(resolverSetResult, event); cache.put(resolverSetResult, configuration); } updateUsageStatistic(configuration); return configuration; }</code><technical_language>statistics shouldn'e needed here, handled cache, in theory</technical_language>

Target:
private ConfigurationInstance getConfiguration(Pair<ResolverSetResult, ResolverSetResult> resolverSetResult, CoreEvent event) { return cache.get(new ResolverResultAndEvent(resolverSetResult, event)); }
Source:
<code>protected void executeVdsBrokerCommand() { status = getBroker().glusterVolumeGeoRepSessionStop(getParameters().getVolumeName(), <START> getParameters().getSlaveHost(), <END> getParameters().getVolumeName(), getParameters().getForce()); proceedProxyReturnValue(); }</code><technical_language>U pass slaveVolumeName here</technical_language>

Target:
protected void executeVdsBrokerCommand() { status = getBroker().glusterVolumeGeoRepSessionStop(getParameters().getVolumeName(), getParameters().getSlaveHost(), getParameters().getSlaveVolume(), getParameters().getForce()); proceedProxyReturnValue(); }
Source:
<code>private void writeResponse(Request httpRequest, Response httpResponse, List<OrganizationDto> organizations, Set<String> adminOrganizationUuids, Paging paging) { Organizations.SearchWsResponse.Builder response = Organizations.SearchWsResponse.newBuilder(); response.setPaging(paging); Organization.Builder wsOrganization = Organization.newBuilder(); organizations .forEach(o -> { <START> boolean isAdmin = userSession.isRoot() || adminOrganizationUuids.contains(o.getUuid()); <END> wsOrganization.clear(); wsOrganization.setIsAdmin(isAdmin); response.addOrganizations(wsSupport.toOrganization(wsOrganization, o)); }); writeProtobuf(response.build(), httpRequest, httpResponse); }</code><technical_language>Please remove **userSession.isRoot()**, root is a special status, permission deal</technical_language>

Target:
private void writeResponse(Request httpRequest, Response httpResponse, List<OrganizationDto> organizations, Set<String> adminOrganizationUuids, Paging paging) { Organizations.SearchWsResponse.Builder response = Organizations.SearchWsResponse.newBuilder(); response.setPaging(paging); Organization.Builder wsOrganization = Organization.newBuilder(); organizations .forEach(o -> { boolean isAdmin = adminOrganizationUuids.contains(o.getUuid()); wsOrganization.clear(); wsOrganization.setIsAdmin(isAdmin); response.addOrganizations(wsSupport.toOrganization(wsOrganization, o)); }); writeProtobuf(response.build(), httpRequest, httpResponse); }
Source:
<code>public Callback getCallback(ObjectNode node, String location, ParseResult result) { if (node == null) { return null; } Callback callback = new Callback(); Set<String> keys = getKeys(node); for(String name : keys) { JsonNode value = node.get(name); if (!value.getNodeType().equals(JsonNodeType.OBJECT)) { result.invalidType(location, name, "object", value); } else { if (node!= null){ callback.addPathItem(name,getPathItem((ObjectNode) value,location,result)); callback.setExtensions(new LinkedHashMap<>()); keys = getKeys(node); for (String key : keys) { if (key.startsWith("x-")) { callback.getExtensions().put(key, Json.mapper().convertValue(node.get(key), Object.class)); } } } } } <START> return callback; <END> }</code><technical_language>Provide messages in ParseResult if missing required fields</technical_language>

Target:
public Callback getCallback(ObjectNode node, String location, ParseResult result) { if (node == null) { return null; } Callback callback = new Callback(); Set<String> keys = getKeys(node); for(String name : keys) { JsonNode value = node.get(name); if (!value.getNodeType().equals(JsonNodeType.OBJECT)) { result.invalidType(location, name, "object", value); } else { if (node!= null){ callback.addPathItem(name,getPathItem((ObjectNode) value,location,result)); Map <String,Object> extensions = getExtensions(node,location,result); if(extensions != null && extensions.size() > 0) { callback.setExtensions(extensions); } } } } return callback; }
Source:
<code>public void onRunningTask(final RunningTask task) { final ActiveContext context = pendingTaskSubmissions.get(task.getActiveContext().getId()); <START> if (context != null) { <END> runningTasks.put(task.getId(), task); runningTaskLatch.countDown(); } }</code><technical_language>This done containsKey()</technical_language>

Target:
public void onRunningTask(final RunningTask task) { if (pendingTaskSubmissions.containsKey(task.getActiveContext().getId())) { runningTasks.put(task.getId(), task); runningTaskLatch.countDown(); } }
Source:
<code><START> protected void runInProtocolStage(final Runnable task) { <END> try { executor.execute(new Runnable() { @Override public void run() { try { task.run(); } catch (final Throwable t) { LOGGER.error("exception in protocol stage thread: {}", t.getMessage(), t); } } }); } catch (RejectedExecutionException e) { LOGGER.debug("{} execute:", this, e); } }</code><technical_language>scope changes in OSCoreEndpoint. Maybe, if offer a create a special CoapStack, subclassing obsolete all</technical_language>

Target:
private void runInProtocolStage(final Runnable task) { try { executor.execute(new Runnable() { @Override public void run() { try { task.run(); } catch (final Throwable t) { LOGGER.error("exception in protocol stage thread: {}", t.getMessage(), t); } } }); } catch (RejectedExecutionException e) { LOGGER.debug("{} execute:", this, e); } }
Source:
<code>public void buildCidMap__onPartWithNoBody__shouldReturnEmptyMap() throws Exception { <START> AttachmentInfoExtractor attachmentInfoExtractor = mock(AttachmentInfoExtractor.class); <END> Part part = mock(Part.class); when(part.getContentId()).thenReturn(null); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, part); assertTrue(result.isEmpty()); }</code><technical_language>This line is part of test. extract a setUp() method</technical_language>

Target:
public void buildCidMap__onPartWithNoBody__shouldReturnEmptyMap() throws Exception { Part part = new MimeBodyPart(); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, part); assertTrue(result.isEmpty()); }
Source:
<code><START> public void setAuditorLedgerVerificationPercentage(long auditorLedgerVerificationPercentage) { <END> setProperty(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, auditorLedgerVerificationPercentage); }</code><technical_language>return ServerConfiguration here, consistent other setters here</technical_language>

Target:
public ServerConfiguration setAuditorLedgerVerificationPercentage(long auditorLedgerVerificationPercentage) { setProperty(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, auditorLedgerVerificationPercentage); return this; }
Source:
<code>public String ensureIndexed(List<FieldSort> fieldNames, String indexName, IndexType indexType, String tokenize) throws QueryException { if (indexName == null) { List<Index> indexes = this.listIndexes(); List<FieldSort> mFieldNames = new ArrayList<FieldSort>(fieldNames); <START> Collections.sort(mFieldNames); <END> for (Index index : indexes) { Collections.sort(index.fieldNames); if (!mFieldNames.equals(filterMeta(index.fieldNames))) { continue; } boolean equalTokenize = tokenize == null ? index.tokenize == null : tokenize.equals(index.tokenize); if(!equalTokenize){ continue; } if (index.indexType != indexType){ continue; } return index.indexName; } } return IndexCreator.ensureIndexed(new Index(fieldNames, indexName, indexType, tokenize), database, dbQueue); }</code><technical_language>keen this copy sort. do index.fieldNames (inside for loop) need copied sorting well? I prefer a strategy as: - put a Set Set.equals() - sort a.containsAll(b) && a.size() == b.size()</technical_language>

Target:
public String ensureIndexed(List<FieldSort> fieldNames, String indexName, IndexType indexType, String tokenize) throws QueryException { if (indexName == null) { List<Index> indexes = this.listIndexes(); Set<FieldSort> fieldNamesSet = new HashSet<FieldSort>(filterMeta(fieldNames)); for (Index index : indexes) { Set<FieldSort> indexFieldNamesSet = new HashSet<FieldSort>(filterMeta(index.fieldNames)); if (!indexFieldNamesSet.equals(fieldNamesSet)) { continue; } boolean equalTokenize = tokenize == null ? index.tokenize == null : tokenize.equals(index.tokenize); if(!equalTokenize){ continue; } if (index.indexType != indexType){ continue; } return index.indexName; } } return IndexCreator.ensureIndexed(new Index(fieldNames, indexName, indexType, tokenize), database, dbQueue); }