auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String getUrl() { <START> String sql = ((customSQL != null) && (!customSQL.isEmpty())) ? getCustomSQL() : getSql(); <END> return "/orientdb/query/db/sql/"+ UrlEncoder.PATH_INSTANCE.encode(sql, "UTF-8")+ "/99999?rnd="+ noCacheRnd; }</code><technical_language>do previously method "getSql()" required logic method? More over: is cool method Strings.isEmpty() for checks this</technical_language>

Target:
public String getUrl() { String sql = getSql(); return "/orientdb/query/db/sql/"+ UrlEncoder.PATH_INSTANCE.encode(sql, "UTF-8")+ "/99999?rnd="+ noCacheRnd; }
Source:
<code>public static void actionDelete(PageContext pc, Resource dir, boolean forceDelete, String serverPassword) throws PageException { SecurityManager securityManager = pc.getConfig().getSecurityManager(); securityManager.checkFileLocation(pc.getConfig(), dir, serverPassword); if (!dir.exists()) { if (dir.isDirectory()) throw new ApplicationException("directory [" + dir.toString() + "] doesn't exist"); else if (dir.isFile()) throw new ApplicationException("file [" + dir.toString() + "] doesn't exist and isn't a directory"); } if (dir.isFile()) throw new ApplicationException("can't delete [" + dir.toString() + "], it isn't a directory, it's a file"); <START> if (dir.listResources() != null && dir.listResources().length > 0 && forceDelete == false) throw new ApplicationException("directory [" + dir.toString() + "] is not empty","Enable recurse to delete sub-directories and files too"); <END> try { dir.remove(forceDelete); } catch (IOException e) { throw Caster.toPageException(e); } }</code><technical_language>listResources() called</technical_language>

Target:
public static void actionDelete(PageContext pc, Resource dir, boolean forceDelete, String serverPassword) throws PageException { SecurityManager securityManager = pc.getConfig().getSecurityManager(); securityManager.checkFileLocation(pc.getConfig(), dir, serverPassword); if (!dir.exists()) { if (dir.isDirectory()) throw new ApplicationException("directory [" + dir.toString() + "] doesn't exist"); else if (dir.isFile()) throw new ApplicationException("file [" + dir.toString() + "] doesn't exist and isn't a directory"); } if (dir.isFile()) throw new ApplicationException("can't delete [" + dir.toString() + "], it isn't a directory, it's a file"); Resource[] dirList = dir.listResources(); if (dirList != null && dirList.length > 0 && forceDelete == false) throw new ApplicationException("directory [" + dir.toString() + "] is not empty","set recurse=true to delete sub-directories and files too"); try { dir.remove(forceDelete); } catch (IOException e) { throw Caster.toPageException(e); } }
Source:
<code>public ListenableFuture<?> execute(CreateFunction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Analyzer analyzer = new Analyzer(stateMachine.getSession(), metadata, sqlParser, accessControl, Optional.empty(), parameters, stateMachine.getWarningCollector()); Analysis analysis = analyzer.analyze(statement); if (analysis.getFunctionHandles().values().stream() .anyMatch(SqlFunctionHandle.class::isInstance)) { <START> throw new PrestoException(NOT_SUPPORTED, "Invoking a SQL function in SQL function body is not yet supported"); <END> } metadata.getFunctionManager().createFunction(createSqlInvokedFunction(statement), statement.isReplace()); return immediateFuture(null); }</code><technical_language>"not supported". "yet" sound coming in future</technical_language>

Target:
public ListenableFuture<?> execute(CreateFunction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Analyzer analyzer = new Analyzer(stateMachine.getSession(), metadata, sqlParser, accessControl, Optional.empty(), parameters, stateMachine.getWarningCollector()); Analysis analysis = analyzer.analyze(statement); if (analysis.getFunctionHandles().values().stream() .anyMatch(SqlFunctionHandle.class::isInstance)) { throw new PrestoException(NOT_SUPPORTED, "Invoking a dynamically registered function in SQL function body is not supported"); } metadata.getFunctionManager().createFunction(createSqlInvokedFunction(statement), statement.isReplace()); return immediateFuture(null); }
Source:
<code>private void setItemEnabled(final Class<? extends ClientSessionCommand> type, <START> final boolean enabled) { <END> menuItems.get(type).setEnabled(enabled); }</code><technical_language>This parameter of private method is False</technical_language>

Target:
public void setItemEnabled(final Class<? extends ClientSessionCommand> type, final boolean enabled) { menuItems.get(type).setEnabled(enabled); }
Source:
<code>public String toString() { <START> return "EvalExprNode (" + StringUtils.join(exprs.toArray(new Target[exprs.size()])) + ")"; <END> }</code><technical_language>add a new join() method takes a list of objects parameter</technical_language>

Target:
public String toString() { return "EvalExprNode (" + StringUtils.join(exprs) + ")"; }
Source:
<code>public static void toJSON(OutputWriter outputWriter, JobInstance jobInstance) { outputWriter.add("name", jobInstance.getName()); if (jobInstance.getState() != null) { outputWriter.add("state", jobInstance.getState().toString()); } if (jobInstance.getResult() != null) { outputWriter.add("result", jobInstance.getResult().toString()); } <START> if (jobInstance.isNull()) { renderNullJobInstance(outputWriter); return; } <END> if (jobInstance.getOriginalJobId() == null) { outputWriter.renderNull("original_job_id"); } else { outputWriter.add("original_job_id", jobInstance.getOriginalJobId()); } outputWriter.addIfNotNull("scheduled_date", jobInstance.getScheduledDate()) .add("rerun", jobInstance.isRerun()) .add("agent_uuid", jobInstance.getAgentUuid()) .add("pipeline_name", jobInstance.getPipelineName()) .add("pipeline_counter", jobInstance.getPipelineCounter()) .add("stage_name", jobInstance.getStageName()) .add("stage_counter", jobInstance.getStageCounter()) .addChildList("job_state_transitions", outputListWriter -> jobInstance.getTransitions().forEach(jobStateTransition -> outputListWriter.addChild(itemWriter -> JobStateTransitionRepresenter.toJSON(itemWriter, jobStateTransition)))); }</code><technical_language>returning a 404 instead of 200 for a NullJobInstance. bumping API version, consider this bug-fix</technical_language>

Target:
public static void toJSON(OutputWriter outputWriter, JobInstance jobInstance) { outputWriter.add("name", jobInstance.getName()); if (jobInstance.getState() != null) { outputWriter.add("state", jobInstance.getState().toString()); } if (jobInstance.getResult() != null) { outputWriter.add("result", jobInstance.getResult().toString()); } if (jobInstance.getOriginalJobId() == null) { outputWriter.renderNull("original_job_id"); } else { outputWriter.add("original_job_id", jobInstance.getOriginalJobId()); } outputWriter.addIfNotNull("scheduled_date", jobInstance.getScheduledDate()) .add("rerun", jobInstance.isRerun()) .add("agent_uuid", jobInstance.getAgentUuid()) .add("pipeline_name", jobInstance.getPipelineName()) .add("pipeline_counter", jobInstance.getPipelineCounter()) .add("stage_name", jobInstance.getStageName()) .add("stage_counter", jobInstance.getStageCounter()) .addChildList("job_state_transitions", outputListWriter -> jobInstance.getTransitions().forEach(jobStateTransition -> outputListWriter.addChild(itemWriter -> JobStateTransitionRepresenter.toJSON(itemWriter, jobStateTransition)))); }
Source:
<code>public void loadAttachmentFailureTest() throws ExecutionException, IOException { String[] expectedValues = {"1", "testResume/Test Resume.doc", "0"}; <START> Result expectedResult = new Result(Result.Status.FAILURE, Result.Action.NOT_SET, -1, "Test"); <END> task = new LoadAttachmentTask(Method.LOADATTACHMENTS, "Candidate", dataMap, csvFileWriter, propertyFileUtil, bullhornData, printUtil, actionTotals); List<Candidate> candidates = new ArrayList<>(); candidates.add(new Candidate(1)); ListWrapper<Candidate> listWrapper = new CandidateListWrapper(); listWrapper.setData(candidates); FileContent mockedFileContent = Mockito.mock(FileContent.class); FileMeta mockedFileMeta = Mockito.mock(FileMeta.class); StandardFileWrapper fileWrapper = new StandardFileWrapper(mockedFileContent, mockedFileMeta); when(bullhornData.search(anyObject(), anyString(), anySet(), anyObject())).thenReturn(listWrapper); when(bullhornData.addFile(anyObject(), anyInt(), any(File.class), anyString(), anyObject(), anyBoolean())).thenThrow(new RestApiException("Test")); task.run(); verify(csvFileWriter).writeAttachmentRow(eq(expectedValues), resultArgumentCaptor.capture()); Result actualResult = resultArgumentCaptor.getValue(); Assert.assertThat(expectedResult, new ReflectionEquals(actualResult)); }</code><technical_language>benefit replacing new Result(Result.Status.FAILURE, null, null, "Test") with: Result.Failure("Test")</technical_language>

Target:
public void loadAttachmentFailureTest() throws ExecutionException, IOException { String[] expectedValues = {"1", "testResume/Test Resume.doc", "0"}; Result expectedResult = Result.Failure(new RestApiException("Test").toString()); task = new LoadAttachmentTask(Method.LOADATTACHMENTS, "Candidate", dataMap, csvFileWriter, propertyFileUtil, bullhornData, printUtil, actionTotals); List<Candidate> candidates = new ArrayList<>(); candidates.add(new Candidate(1)); ListWrapper<Candidate> listWrapper = new CandidateListWrapper(); listWrapper.setData(candidates); FileContent mockedFileContent = Mockito.mock(FileContent.class); FileMeta mockedFileMeta = Mockito.mock(FileMeta.class); StandardFileWrapper fileWrapper = new StandardFileWrapper(mockedFileContent, mockedFileMeta); when(bullhornData.search(anyObject(), anyString(), anySet(), anyObject())).thenReturn(listWrapper); when(bullhornData.addFile(anyObject(), anyInt(), any(File.class), anyString(), anyObject(), anyBoolean())).thenThrow(new RestApiException("Test")); task.run(); verify(csvFileWriter).writeRow(eq(expectedValues), resultArgumentCaptor.capture()); Result actualResult = resultArgumentCaptor.getValue(); Assert.assertThat(expectedResult, new ReflectionEquals(actualResult)); }
Source:
<code>public DocumentModel publishRendition(DocumentModel doc, DocumentModel target, String renditionName, boolean override) { <START> RenditionService rs = Framework.getService(RenditionService.class); <END> Rendition rendition = StringUtils.isEmpty(renditionName) ? rs.getDefaultRendition(doc, "publish", true, null) : rs.getRendition(doc, renditionName, true); if (rendition == null) { throw new NuxeoException("Unable to render the document"); } DocumentModel renditionDocument = rendition.getHostDocument(); DocumentModel publishedDocument = doc.getCoreSession().publishDocument(renditionDocument, target, override); if (override) { RenditionsRemover remover = new RenditionsRemover(publishedDocument); remover.runUnrestricted(); } return publishedDocument; }</code><technical_language>This is RenditionService</technical_language>

Target:
public DocumentModel publishRendition(DocumentModel doc, DocumentModel target, String renditionName, boolean override) { Rendition rendition = StringUtils.isEmpty(renditionName) ? getDefaultRendition(doc, Constants.DEFAULT_RENDTION_PUBLISH_REASON, true, null) : getRendition(doc, renditionName, true); if (rendition == null) { throw new NuxeoException("Unable to render the document"); } DocumentModel renditionDocument = rendition.getHostDocument(); DocumentModel publishedDocument = doc.getCoreSession().publishDocument(renditionDocument, target, override); if (override) { RenditionsRemover remover = new RenditionsRemover(publishedDocument); remover.runUnrestricted(); } return publishedDocument; }
Source:
<code>private LwM2mNode decodeCoapResponse(LwM2mPath path, Response coapResponse, LwM2mRequest<?> request, String endpoint) { ContentFormat contentFormat = null; if (coapResponse.getOptions().hasContentFormat()) { contentFormat = ContentFormat.fromCode(coapResponse.getOptions().getContentFormat()); } else { throw new InvalidResponseException( String.format("ContentFormat is mandatory for request [%s] from client [%s]", request, endpoint)); } try { return decoder.decode(coapResponse.getPayload(), contentFormat, path, model); } catch (final CodecException e) { byte[] payload = coapResponse.getPayload() == null ? new byte[0] : coapResponse.getPayload(); throw new InvalidResponseException( String.format("Unable do decode response payload [%s] of request [%s] from client [%s]", <START> Hex.encodeHexString(payload), request, endpoint), <END> e); } }</code><technical_language>include payload in exception message. debug log</technical_language>

Target:
private LwM2mNode decodeCoapResponse(LwM2mPath path, Response coapResponse, LwM2mRequest<?> request, String endpoint) { ContentFormat contentFormat = null; if (coapResponse.getOptions().hasContentFormat()) { contentFormat = ContentFormat.fromCode(coapResponse.getOptions().getContentFormat()); } try { return decoder.decode(coapResponse.getPayload(), contentFormat, path, model); } catch (final CodecException e) { if (LOG.isDebugEnabled()) { byte[] payload = coapResponse.getPayload() == null ? new byte[0] : coapResponse.getPayload(); LOG.debug( String.format("Unable do decode response payload of request [%s] from client [%s] [payload:%s]", request, endpoint, Hex.encodeHexString(payload))); } throw new InvalidResponseException(String.format( "Unable do decode response payload of request [%s] from client [%s]", request, endpoint), e); } }
Source:
<code>private static Properties readProperties(URL url) { log.debug("Testcontainers configuration overrides will be loaded from {}", url); Properties properties = new Properties(); try (InputStream inputStream = url.openStream()) { properties.load(inputStream); } catch (FileNotFoundException e) { <START> log.warn("Testcontainers config override was found on but the file was not found", url, e); <END> } catch (IOException e) { log.warn("Testcontainers config override was found on but could not be loaded", url, e); } return properties; }</code><technical_language>this fix issue in #2253. If I understood correctly, @vmassol talking **not** displaying stacktrace error message, logs verbose</technical_language>

Target:
private static Properties readProperties(URL url) { log.debug("Testcontainers configuration overrides will be loaded from {}", url); Properties properties = new Properties(); try (InputStream inputStream = url.openStream()) { properties.load(inputStream); } catch (FileNotFoundException e) { log.warn("Testcontainers config override was found on but the file was not found. Exception message: {}", url, ExceptionUtils.getRootCauseMessage(e)); } catch (IOException e) { log.warn("Testcontainers config override was found on but could not be loaded. Exception message: {}", url, ExceptionUtils.getRootCauseMessage(e)); } return properties; }
Source:
<code>private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Runnable onLowerWatermarkCrossed, Runnable onUpperWatermarkCrossed) { <START> assert lowerWatermark >= 0 && lowerWatermark < upperWatermark; <END> this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = x -> null; this.onLowerWatermarkCrossed = x -> onLowerWatermarkCrossed.run(); this.onUpperWatermarkCrossed = x -> onUpperWatermarkCrossed.run(); final StreamTracker streamTracker = new StreamTracker(null); this.trackerSupplier = key -> streamTracker; }</code><technical_language>I a fan of assertions in non-test code. Assertions disabled default anyway. please remove them? Thanks</technical_language>

Target:
private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Runnable onLowerWatermarkCrossed, Runnable onUpperWatermarkCrossed) { this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = x -> null; this.onLowerWatermarkCrossed = x -> onLowerWatermarkCrossed.run(); this.onUpperWatermarkCrossed = x -> onUpperWatermarkCrossed.run(); final StreamTracker streamTracker = new StreamTracker(null); this.trackerSupplier = key -> streamTracker; }
Source:
<code>private void extractHiddenItems(Map<String, String> infraParams, Map<String, String> infraFileParams, String formFieldValue) { for (String row : formFieldValue.split(ROW_SEPARATOR)) { <START> String[] fields = row.split(FIELD_SEPARATOR); <END> boolean isFile = fields[0].equals(FILE); String name = fields[1]; String value = fields.length > 2 ? fields[2] : ""; if (isFile) { infraFileParams.put(name, value); } else { infraParams.put(name, value); } } }</code><technical_language>need check fields length</technical_language>

Target:
private void extractHiddenItems(Map<String, String> infraParams, Map<String, String> infraFileParams, String formFieldValue) { for (String row : formFieldValue.split(ROW_SEPARATOR)) { String[] fields = row.split(FIELD_SEPARATOR); if (fields.length != 2 && fields.length != 3) { LOGGER.warn("Failed extract hidden value from: " + row); continue; } boolean isFile = fields[0].equals(FILE); String name = fields[1]; String value = fields.length > 2 ? fields[2] : ""; if (isFile) { infraFileParams.put(name, value); } else { infraParams.put(name, value); } } }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; SymbolMetadata classMetadata = classTree.symbol().metadata(); Optional<AnnotationTree> sessionAttributesAnnotation = classTree.modifiers().annotations() .stream() .filter(a -> a.annotationType().symbolType().fullyQualifiedName().equals("org.springframework.web.bind.annotation.SessionAttributes")) .findFirst(); if (classMetadata.isAnnotatedWith("org.springframework.stereotype.Controller") && sessionAttributesAnnotation.isPresent() <START> && classTree.members().stream().noneMatch(ControllerWithSessionAttributesCheck::methodCompletesSessionStatus)) { <END> reportIssue(sessionAttributesAnnotation.get().annotationType(), "Add a call to \"setComplete()\" on the SessionStatus object in a \"@RequestMapping\" method that handles \"POST\"."); } }</code><technical_language>Applying MethodInvocationVisitor "classTree" itself, visit methods, field initializers (and field a lambda calling "setComplete()")</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; SymbolMetadata classMetadata = classTree.symbol().metadata(); Optional<AnnotationTree> sessionAttributesAnnotation = classTree.modifiers().annotations() .stream() .filter(a -> a.annotationType().symbolType().is("org.springframework.web.bind.annotation.SessionAttributes")) .findFirst(); if (sessionAttributesAnnotation.isPresent() && classMetadata.isAnnotatedWith("org.springframework.stereotype.Controller")) { MethodInvocationVisitor methodInvocationVisitor = new MethodInvocationVisitor(); classTree.accept(methodInvocationVisitor); if (!methodInvocationVisitor.setCompleteIsCalled) { reportIssue(sessionAttributesAnnotation.get().annotationType(), "Add a call to \"setComplete()\" on the SessionStatus object in a \"@RequestMapping\" method."); } } }
Source:
<code>private void readFromParcel(Parcel source) { source.readTypedList(users, User.CREATOR); startTime = source.readLong(); endTime = source.readLong(); <START> source.readTypedList(orders, null); <END> sessToken = source.readInt(); tableID = source.readInt(); }</code><technical_language>this Order.CREATOR</technical_language>

Target:
private void readFromParcel(Parcel source) { source.readTypedList(users, UserInfo.CREATOR); startTime = source.readLong(); endTime = source.readLong(); source.readTypedList(orders, Order.CREATOR); sessToken = source.readInt(); tableID = source.readInt(); }
Source:
<code><START> public static void e(String tag, String message) { <END> SalesforceLogger.getLogger(COMPONENT_NAME, SalesforceSDKManager.getInstance().getAppContext()).e( tag, message); }</code><technical_language>code java SalesforceLogger.getLogger(COMPONENT_NAME, SalesforceSDKManager.getInstance().getAppContext()) is repeated a lot introduce a helper method: java private static SalesforceSDKLogger getLogger() { return SalesforceLogger.getLogger(COMPONENT_NAME, SalesforceSDKManager.getInstance().getAppContext()); }</technical_language>

Target:
public static void e(String tag, String message) { getLogger().e(tag, message); }
Source:
<code><START> public long countTriggers() { <END> try (Connection conn = DBConnectionManager.getInstance().getConnection(sqlProperties.getProperty(DATA_SOURCE)); Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery(buildCountTriggersQuery()); if (rs.next()) { return rs.getInt(1); } return 0; } catch (Exception e) { throw new TriggerRetrievalException("Couldn't count triggers for Scheduler channel", e); } }</code><technical_language>belong in scheduler database service</technical_language>

Target:
public long countTriggers() { try { return motechSchedulerDatabaseService.countTriggers(); } catch (SQLException e) { throw new TriggerRetrievalException("Couldn't count triggers for Scheduler channel", e); } }
Source:
<code>private boolean isUsingSPDMFlow() { return isDataOperationsByHSM() && (getParameters().getParentCommand() == ActionType.MoveOrCopyDisk || <START> (getParameters().getParentCommand() <END> == ActionType.CloneVm || getParameters().getParentCommand() == ActionType.CloneVmNoCollapse)); }</code><technical_language>redundant</technical_language>

Target:
private boolean isUsingSPDMFlow() { return isDataOperationsByHSM() && (getParameters().getParentCommand() == ActionType.MoveOrCopyDisk || getParameters().getParentCommand() == ActionType.CloneVm || getParameters().getParentCommand() == ActionType.CloneVmNoCollapse); }
Source:
<code>synchronized void doSynchronizationWithPrimary(InternalDistributedMember primary, InternalCache cache) { <START> if (hasSynchronizedWithPrimary.get()) { <END> return; } synchronizeWithPrimaryInProgress.set(true); int maxChunkSize = 1000; try { List<EventID> giiEvents = getGIIEvents(); if (giiEvents.size() == 0) { hasSynchronizedWithPrimary.set(true); return; } Collection<List<EventID>> chunks = null; if (giiEvents.size() > maxChunkSize) { chunks = getChunks(giiEvents, maxChunkSize); } if (chunks == null) { if (!removeDispatchedEvents(primary, cache, giiEvents)) { return; } } else { for (List<EventID> chunk : chunks) { if (!removeDispatchedEvents(primary, cache, chunk)) { return; } } } if (logger.isDebugEnabled()) { logger.debug("hasSynchronizedWithPrimary has synced with primary on queue: ", primary, regionName); } hasSynchronizedWithPrimary.set(true); } finally { synchronizeWithPrimaryInProgress.set(false); } }</code><technical_language>Is get this point, synchronizeWithPrimaryInProgress is true? Do want check continuing, in case another thread initiated synchronization already</technical_language>

Target:
synchronized void doSynchronizationWithPrimary(InternalDistributedMember primary, InternalCache cache) { int maxChunkSize = 1000; try { List<EventID> giiEvents = getGIIEvents(); if (giiEvents.size() == 0) { hasSynchronizedWithPrimary.set(true); return; } Collection<List<EventID>> chunks = null; if (giiEvents.size() > maxChunkSize) { chunks = getChunks(giiEvents, maxChunkSize); } if (chunks == null) { if (!removeDispatchedEvents(primary, cache, giiEvents)) { return; } } else { for (List<EventID> chunk : chunks) { if (!removeDispatchedEvents(primary, cache, chunk)) { return; } } } if (logger.isDebugEnabled()) { logger.debug("HARegionQueue has synced with primary on {}", regionName, primary); } hasSynchronizedWithPrimary.set(true); } finally { scheduleSynchronizationWithPrimaryInProgress.set(false); } }
Source:
<code>private void updateDiskImage(DiskImage diskImage) { <START> VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction( <END> VdcActionType.UpdateVolume, buildUpdateVolumeCommandParameters(diskImage), ExecutionHandler.createDefaultContextForTasks(getContext())); if (!returnValue.getSucceeded()) { throw new EngineException(returnValue.getFault().getError(), returnValue.getFault().getMessage()); } }</code><technical_language>runInternalActionWithTasksContext</technical_language>

Target:
private void updateDiskImage(DiskImage diskImage) { VdcReturnValueBase returnValue = runInternalActionWithTasksContext( VdcActionType.UpdateVolume, buildUpdateVolumeCommandParameters(diskImage)); if (!returnValue.getSucceeded()) { throw new EngineException(returnValue.getFault().getError(), returnValue.getFault().getMessage()); } }
Source:
<code>private void discardRequests() { logger.trace("Discarding requests on account of shutdown"); RestServiceException e = new RestServiceException("Service shutdown", RestServiceErrorCode.ServiceUnavailable); if (requests.size() > 0) { logger.info("There were requests in flight during shutdown", requests.size()); <START> restServerMetrics.residualRequestQueueSize.inc(requests.size()); <END> AsyncRequestInfo residualRequestInfo = requests.poll(); while (residualRequestInfo != null && residualRequestInfo.restRequest != null) { onRequestDequeue(residualRequestInfo); onProcessingFailure(residualRequestInfo.restRequest, residualRequestInfo.restResponseChannel, e); residualRequestInfo = requests.poll(); } } }</code><technical_language>Also, this exact number, including poison. I would've count in while loop print it, I clear guard new requests added poison</technical_language>

Target:
private void discardRequests() { logger.trace("Discarding requests on account of shutdown"); RestServiceException e = new RestServiceException("Service shutdown", RestServiceErrorCode.ServiceUnavailable); AsyncRequestInfo residualRequestInfo = requests.poll(); int discardCount = 0; while (residualRequestInfo != null) { if (residualRequestInfo.restRequest != null) { discardCount++; onRequestDequeue(residualRequestInfo); onProcessingFailure(residualRequestInfo.restRequest, residualRequestInfo.restResponseChannel, e); } residualRequestInfo = requests.poll(); } if(discardCount > 0) { restServerMetrics.residualRequestQueueSize.inc(discardCount); logger.info("There were requests in flight during shutdown", discardCount); } }
Source:
<code>List<IRemoteTest> createIndividualTests(Set<TestInfo> testInfos, String configPath) { List<IRemoteTest> tests = new ArrayList<>(); testInfos = dedupTestInfos(testInfos); for (TestInfo testInfo : testInfos) { super.cleanUpSuiteSetup(); super.cleanModuleArgs(); super.cleanConfigPaths(); super.setConfigPaths(new <START> File(configPath)); <END> parseOptions(testInfo); LinkedHashMap<String, IConfiguration> config = super.loadTests(); for (Map.Entry<String, IConfiguration> entry : config.entrySet()) { tests.addAll(entry.getValue().getTests()); } } return tests; }</code><technical_language>check path exists</technical_language>

Target:
List<IRemoteTest> createIndividualTests(Set<TestInfo> testInfos, String configPath) { List<IRemoteTest> tests = new ArrayList<>(); if (configPath == null) { return tests; } File configFie = new File(configPath); if (!configFie.exists()) { return tests; } testInfos = dedupTestInfos(testInfos); for (TestInfo testInfo : testInfos) { super.cleanUpSuiteSetup(); super.clearModuleArgs(); super.clearConfigPaths(); super.addConfigPaths(configFie); parseOptions(testInfo); LinkedHashMap<String, IConfiguration> config = super.loadTests(); for (Map.Entry<String, IConfiguration> entry : config.entrySet()) { tests.addAll(entry.getValue().getTests()); } } return tests; }
Source:
<code>public static void tearDown() throws InterruptedException, CommandFailedException, TimeoutException, IOException, OperationException { operations.removeIfExists(AJP_LISTENER_ADDRESS); operations.removeIfExists(AJP_LISTENER_ADDRESS_TBA); operations.removeIfExists(AJP_LISTENER_ADDRESS_TBR); operations.removeIfExists(HTTP_SERVER_ADDRESS); undertowOps.removeSocketBinding(REDIRECT_SOCKET_VALUE); undertowOps.removeSocketBinding(SOCKET_BINDING_AJP); undertowOps.removeSocketBinding(SOCKET_BINDING_AJP_TBA); undertowOps.removeSocketBinding(SOCKET_BINDING_AJP_TBR); administration.reloadIfRequired(); <START> administration.restartIfRequired(); <END> }</code><technical_language>If switch order of reloadIfRequired() restartIfRequired() save some seconds reload needed</technical_language>

Target:
public static void tearDown() throws InterruptedException, CommandFailedException, TimeoutException, IOException, OperationException { operations.removeIfExists(AJP_LISTENER_ADDRESS); operations.removeIfExists(AJP_LISTENER_ADDRESS_TBA); operations.removeIfExists(AJP_LISTENER_ADDRESS_TBR); operations.removeIfExists(HTTP_SERVER_ADDRESS); administration.restartIfRequired(); administration.reloadIfRequired(); }
Source:
<code>public void showSurvey(View view) { Wootric.with(this) .user(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN) <START> .endUser("junkuits@gmail.com", "ORIGIN URL") <END> .forceSurvey() .survey(); }</code><technical_language>Please previous version (without email)</technical_language>

Target:
public void showSurvey(View view) { Wootric.with(this) .user(CLIENT_ID, CLIENT_SECRET, ACCOUNT_TOKEN) .endUser("END USER EMAIL", "ORIGIN URL") .forceSurvey() .survey(); }
Source:
<code>private void validateThereIsMatchingRuntime(List<ImageInfoV4Response> upgradeCandidates, List<ImageInfoV4Response> imagesWithMatchingRuntime, String runtime) { <START> boolean hasNoCompatbileImageWithRuntime = imagesWithMatchingRuntime.isEmpty(); <END> if (hasNoCompatbileImageWithRuntime) { String availableRuntimes = collectAvailableRuntimes(upgradeCandidates); if (StringUtils.isEmpty(availableRuntimes)) { throw new BadRequestException(String.format("There is no image eligible for the cluster upgrade with runtime: %s.", runtime)); } else { throw new BadRequestException(String.format("There is no image eligible for the cluster upgrade with runtime: %s. " + "Please choose a runtime from the following: %s", runtime, availableRuntimes)); } } }</code><technical_language>typo + 2 lines unified in 1 line</technical_language>

Target:
private void validateThereIsMatchingRuntime(List<ImageInfoV4Response> upgradeCandidates, List<ImageInfoV4Response> imagesWithMatchingRuntime, String runtime) { if (imagesWithMatchingRuntime.isEmpty()) { String availableRuntimes = collectAvailableRuntimes(upgradeCandidates); if (StringUtils.isEmpty(availableRuntimes)) { throw new BadRequestException(String.format("There is no image eligible for the cluster upgrade with runtime: %s.", runtime)); } else { throw new BadRequestException(String.format("There is no image eligible for the cluster upgrade with runtime: %s. " + "Please choose a runtime from the following: %s", runtime, availableRuntimes)); } } }
Source:
<code>public static boolean isKPrefixed(String name) { if (isUpperCamelCase(name)) { <START> return name.charAt(0) == 'K' && Character.isUpperCase(name.charAt(1)); <END> } if (isLowerCamelCase(name)) { return name.charAt(0) == 'k' && Character.isUpperCase(name.charAt(1)); } return false; }</code><technical_language>name is checked for length, single letter constant names result in java.lang.StringIndexOutOfBoundsException :disappointed:</technical_language>

Target:
public static boolean isKPrefixed(String name) { if (name.length() < 2) return false; if (isUpperCamelCase(name)) { return name.charAt(0) == 'K' && Character.isUpperCase(name.charAt(1)); } if (isLowerCamelCase(name)) { return name.charAt(0) == 'k' && Character.isUpperCase(name.charAt(1)); } return false; }
Source:
<code>public void copyWithIterationBoth( final Img< IntType > srcImg, final Img< IntType > dstImg ) { final Cursor< IntType > src = srcImg.cursor(); final Cursor< IntType > dst = dstImg.cursor(); while ( src.hasNext() ) { if ( !dst.hasNext() ) { <START> throw new NoSuchElementException("Cursor does not have next element"); <END> } dst.next().set( src.next().get() ); } }</code><technical_language>call JUnit's fail method here, for consistency? methods, while public, intended for unit tests, right</technical_language>

Target:
public void copyWithIterationBoth( final Img< IntType > srcImg, final Img< IntType > dstImg ) { final Cursor< IntType > src = srcImg.cursor(); final Cursor< IntType > dst = dstImg.cursor(); while ( src.hasNext() ) { if ( !dst.hasNext() ) { throw new NoSuchElementException(" Cursor dst does not have next element" ); } dst.next().set( src.next().get() ); } }
Source:
<code>public String getDisplayString() { <START> final String <END> refsHeads = "refs/heads/"; if (branch.ref().startsWith(refsHeads)) { return branch.ref().substring(refsHeads.length()); } return branch.ref(); }</code><technical_language>Unnecessary final. Do access JGit's Constants class in gwtui</technical_language>

Target:
public String getDisplayString() { if (branch.ref().startsWith(Branch.R_HEADS)) { return branch.ref().substring(Branch.R_HEADS.length()); } return branch.ref(); }
Source:
<code>public CustomLabelSlider(final DoubleFunction<Double> function) { super(); valueProperty().addListener( (observable, oldVal, newVal) -> setValue(newVal.intValue())); setLabelFormatter(new StringConverter<Double>() { @Override public String toString(final Double number) { return String.format("%1$.0f", function.apply(number)); } @Override public Double fromString(final String string) { <START> return null; <END> } }); }</code><technical_language>Is this desired</technical_language>

Target:
public CustomLabelSlider(final DoubleFunction<Double> function) { super(); valueProperty().addListener( (observable, oldVal, newVal) -> setValue(newVal.intValue())); setLabelFormatter(new StringConverter<Double>() { @Override public String toString(final Double number) { return String.format("%1$.0f", function.apply(number)); } @Override public Double fromString(final String string) { return function.apply(Double.parseDouble(string)); } }); }
Source:
<code>public void setConf(Configuration conf) { super.setConf(conf); try { <START> lock.writeLock().lock(); <END> this.fs = FileSystem.get(this.getConf()); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't instantiate the file system, not deleting file, just in case. " + FileSystem.FS_DEFAULT_NAME_KEY + "=" + getConf().get(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS)); } } finally { lock.writeLock().unlock(); } }</code><technical_language>move this line try block</technical_language>

Target:
public void setConf(Configuration conf) { super.setConf(conf); lock.writeLock().lock(); try { this.fs = FileSystem.get(this.getConf()); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't instantiate the file system, not deleting file, just in case. " + FileSystem.FS_DEFAULT_NAME_KEY + "=" + getConf().get(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS)); } } finally { lock.writeLock().unlock(); } }
Source:
<code><START> public void testCheckOutOfBoundsDataTrue() throws IOException { <END> Mockito.when(this.dataImportService.checkForOutOfBoundsData(Mockito.any(org.generationcp.middleware.domain.etl.Workbook.class), Mockito.eq(PROGRAM_UUID))).thenReturn(true); final int datasetType = DataSetType.PLOT_DATA.getId(); this.fillStudyDetailsOfUserSelection(this.userSelection, STUDY_ID); this.userSelection.setDatasetType(datasetType); this.userSelection.getPhenotypicMap().putAll(this.createPhenotyicMapTestData()); final ArgumentCaptor<org.generationcp.middleware.domain.etl.Workbook> workbookCaptor = ArgumentCaptor.forClass(org.generationcp.middleware.domain.etl.Workbook.class); Assert.assertTrue(this.etlService.checkOutOfBoundsData(this.userSelection)); Mockito.verify(this.dataImportService, Mockito.times(1)).checkForOutOfBoundsData( workbookCaptor.capture(), Mockito.eq(PROGRAM_UUID)); Assert.assertNotNull(workbookCaptor.getValue()); }</code><technical_language>Remove unused import in ETLServiceTest class</technical_language>

Target:
public void testCheckOutOfBoundsDataTrue() throws IOException { Mockito.when(this.dataImportService.checkForOutOfBoundsData( Matchers.any(org.generationcp.middleware.domain.etl.Workbook.class), Matchers.eq(ETLServiceTest.PROGRAM_UUID))).thenReturn(true); final int datasetType = DataSetType.PLOT_DATA.getId(); this.fillStudyDetailsOfUserSelection(this.userSelection, ETLServiceTest.STUDY_ID); this.userSelection.setDatasetType(datasetType); this.userSelection.getPhenotypicMap().putAll(this.createPhenotyicMapTestData()); final ArgumentCaptor<org.generationcp.middleware.domain.etl.Workbook> workbookCaptor = ArgumentCaptor .forClass(org.generationcp.middleware.domain.etl.Workbook.class); Assert.assertTrue(this.etlService.checkOutOfBoundsData(this.userSelection)); Mockito.verify(this.dataImportService, Mockito.times(1)).checkForOutOfBoundsData(workbookCaptor.capture(), Matchers.eq(ETLServiceTest.PROGRAM_UUID)); Assert.assertNotNull(workbookCaptor.getValue()); }
Source:
<code>private void updatePointer(final ILogData data) { <START> if (!data.hasCheckpointMetadata()) { <END> getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }</code><technical_language>reason data.getType() == DataType.DATA is removed</technical_language>

Target:
private void updatePointer(final ILogData data) { if (data.getType() == DataType.DATA && !data.hasCheckpointMetadata()) { getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }
Source:
<code>public static String getQuranAudioDirectory(Context context){ String path = getQuranBaseDirectory(context); if (path == null) { return null; } path += AUDIO_DIRECTORY; File dir = new File(path); <START> if (dir.exists() && !dir.isDirectory() && !dir.delete()) { <END> return null; } if (!dir.exists() && !dir.mkdirs()) { return null; } writeNoMediaFile(path); return path + File.separator; }</code><technical_language>yes, worry is if manually manually, if did, fault. note though, i 100% - this writes .nomedia in audio/ - media players if .nomedia in audio, need in audio/{qari}</technical_language>

Target:
public static String getQuranAudioDirectory(Context context){ String path = getQuranBaseDirectory(context); if (path == null) { return null; } path += AUDIO_DIRECTORY; File dir = new File(path); if (!dir.exists() && !dir.mkdirs()) { return null; } writeNoMediaFile(path); return path + File.separator; }
Source:
<code>private String getItemInfo(final Item item) { <START> StringBuilder sb = new StringBuilder(configurationService.getProperty("dspace.url")); <END> sb.append("/handle/").append(item.getHandle()); return sb.toString(); }</code><technical_language>Again, dspace.url exist anymore. This dspace.ui.url</technical_language>

Target:
private String getItemInfo(final Item item) { StringBuilder sb = new StringBuilder(configurationService.getProperty("dspace.ui.url")); sb.append("/handle/").append(item.getHandle()); return sb.toString(); }
Source:
<code>public void addingListChangeListenerThrows() { realm.executeTransaction(r -> { r.createObject(AllTypes.class); }); Realm frozenRealm = realm.freeze(); AllTypes obj = frozenRealm.where(AllTypes.class).findFirst(); try { obj.getColumnStringList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<String>>() { @Override public void onChange(RealmList<String> strings, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { <START> RealmLog.error(ignore.toString()); <END> } try { obj.getColumnRealmList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> dogs, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { RealmLog.error(ignore.toString()); } frozenRealm.close(); looperThread.testComplete(); }</code><technical_language>This is expected assert error type & content instead (same for other tests below)</technical_language>

Target:
public void addingListChangeListenerThrows() { realm.executeTransaction(r -> { r.createObject(AllTypes.class); }); Realm frozenRealm = realm.freeze(); AllTypes obj = frozenRealm.where(AllTypes.class).findFirst(); try { obj.getColumnStringList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<String>>() { @Override public void onChange(RealmList<String> strings, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { } try { obj.getColumnRealmList().addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> dogs, OrderedCollectionChangeSet changeSet) { } }); fail(); } catch (IllegalStateException ignore) { } frozenRealm.close(); looperThread.testComplete(); }
Source:
<code>public Set<String> getAnnotationProcessors() { ExperimentalExtension experimentalExtension = getOkbuck().getExperimentalExtension(); if (experimentalExtension.useAnnotationProcessorPlugin) { return getApts() .stream() <START> .filter(i -> !i.getAnnotationProcessors().isEmpty()) <END> .map(Scope::getAnnotationProcessorRulePath) .collect(Collectors.toSet()); } else { return getApt().getAnnotationProcessors(); } }</code><technical_language>a name i</technical_language>

Target:
public Set<String> getAnnotationProcessors() { ExperimentalExtension experimentalExtension = getOkbuck().getExperimentalExtension(); if (experimentalExtension.useAnnotationProcessorPlugin) { return getAptScopes() .stream() .filter(scope -> !scope.getAnnotationProcessors().isEmpty()) .map(Scope::getAnnotationProcessorsUID) .collect(Collectors.toSet()); } else { return getApt().getAnnotationProcessors(); } }
Source:
<code>public void deleteFieldsByContentType(final ContentType type) throws DotDataException { <START> List<Field> fields = byContentTypeId(type.id()); <END> for (Field field : fields) { delete(field); } }</code><technical_language>set final</technical_language>

Target:
public void deleteFieldsByContentType(final ContentType type) throws DotDataException { final List<Field> fields = byContentTypeId(type.id()); for (Field field : fields) { delete(field); } }
Source:
<code>int read(ReadableByteChannel channel, int maxBytes, NetworkDBBPool pool) throws IOException { int bytesRead = 0; int lastRead = 1; DBBPool.BBContainer poolCont = null; try { while (bytesRead < maxBytes && lastRead > 0) { if (poolCont == null) { poolCont = pool.acquire(); poolCont.b().clear(); } lastRead = channel.read(poolCont.b()); if (lastRead < 0 && bytesRead == 0) { return -1; } if (lastRead > 0) { bytesRead += lastRead; if (!poolCont.b().hasRemaining()) { poolCont.b().flip(); getReadContainers().addLast(poolCont); poolCont = null; } } } } finally { if (poolCont != null) { if (poolCont.b().position() > 0) { poolCont.b().flip(); getReadContainers().addLast(poolCont); } else { poolCont.discard(); } } if (bytesRead > 0) { m_totalAvailable += bytesRead; } <START> } <END> return bytesRead; }</code><technical_language>This method identical in NIOReadStream. reimplement here</technical_language>

Target:
public int read(ReadableByteChannel channel, int maxBytes, NetworkDBBPool pool) throws IOException { int bytesRead = 0; int lastRead = 1; DBBPool.BBContainer poolCont = null; try { while (bytesRead < maxBytes && lastRead > 0) { if (poolCont == null) { poolCont = pool.acquire(); poolCont.b().clear(); } lastRead = channel.read(poolCont.b()); if (lastRead < 0 && bytesRead == 0) { return -1; } if (lastRead > 0) { bytesRead += lastRead; if (!poolCont.b().hasRemaining()) { poolCont.b().flip(); m_readBBContainers.addLast(poolCont); poolCont = null; } } } } finally { if (poolCont != null) { if (poolCont.b().position() > 0) { poolCont.b().flip(); m_readBBContainers.addLast(poolCont); } else { poolCont.discard(); } } if (bytesRead > 0) { m_bytesRead.addAndGet(bytesRead); m_totalAvailable.addAndGet(bytesRead); } } return bytesRead; }
Source:
<code>private void attemptXOAuth2() throws MessagingException, IOException { <START> String command = Commands.AUTHENTICATE_XOAUTH2; <END> String tag = sendSaslIrCommand(command, Authentication.computeXoauth(settings.getUsername(), oauthTokenProvider.getToken(settings.getUsername(), OAuth2TokenProvider.OAUTH2_TIMEOUT)), true); extractCapabilities( responseParser.readStatusResponse(tag, command, getLogId(), new UntaggedHandler() { @Override public void handleAsyncUntaggedResponse(ImapResponse response) throws IOException { if(response.isContinuationRequested()) { outputStream.write("\r\n".getBytes()); outputStream.flush(); } } }) ); }</code><technical_language>putting this in a variable unnecessary, put getToken output in a variable instead sendSaslIrCommand call more clear</technical_language>

Target:
private void attemptXOAuth2() throws MessagingException, IOException { String token = oauthTokenProvider.getToken(settings.getUsername(), OAuth2TokenProvider.OAUTH2_TIMEOUT); String tag = sendSaslIrCommand(Commands.AUTHENTICATE_XOAUTH2, Authentication.computeXoauth(settings.getUsername(), token), true); extractCapabilities( responseParser.readStatusResponse(tag, Commands.AUTHENTICATE_XOAUTH2, getLogId(), new UntaggedHandler() { @Override public void handleAsyncUntaggedResponse(ImapResponse response) throws IOException { handleXOAuthUntaggedResponse(response); } }) ); }
Source:
<code>public AmbryBlobStorageServiceFactory(VerifiableProperties verifiableProperties, ClusterMap clusterMap, RestResponseHandler responseHandler, Router router) throws Exception { if (verifiableProperties == null || clusterMap == null || responseHandler == null || router == null) { throw new IllegalArgumentException("Null arguments were provided during instantiation!"); } else { MetricRegistry metricRegistry = clusterMap.getMetricRegistry(); frontendConfig = new FrontendConfig(verifiableProperties); frontendMetrics = new FrontendMetrics(metricRegistry); this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.router = router; AclServiceFactory aclServiceFactory = Utils.getObj(frontendConfig.frontendAclServiceFactory, verifiableProperties, metricRegistry); AclService aclService = aclServiceFactory.getAclService(); idConverterFactory = Utils.getObj(frontendConfig.frontendIdConverterFactory, verifiableProperties, metricRegistry); securityServiceFactory = Utils.getObj(frontendConfig.frontendSecurityServiceFactory, verifiableProperties, <START> clusterMap.getMetricRegistry(), aclService); <END> } logger.trace("Instantiated AmbryBlobStorageServiceFactory"); }</code><technical_language>for passing acl service SecurityService. is internal decision of SecurityService wants acls not</technical_language>

Target:
public AmbryBlobStorageServiceFactory(VerifiableProperties verifiableProperties, ClusterMap clusterMap, RestResponseHandler responseHandler, Router router) throws Exception { if (verifiableProperties == null || clusterMap == null || responseHandler == null || router == null) { throw new IllegalArgumentException("Null arguments were provided during instantiation!"); } else { MetricRegistry metricRegistry = clusterMap.getMetricRegistry(); frontendConfig = new FrontendConfig(verifiableProperties); frontendMetrics = new FrontendMetrics(metricRegistry); this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.router = router; idConverterFactory = Utils.getObj(frontendConfig.frontendIdConverterFactory, verifiableProperties, metricRegistry); securityServiceFactory = Utils.getObj(frontendConfig.frontendSecurityServiceFactory, verifiableProperties, clusterMap.getMetricRegistry()); } logger.trace("Instantiated AmbryBlobStorageServiceFactory"); }