auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public @NonNull List<@NonNull String> getMarkerCategories() { ITmfTrace activeTrace = TmfTraceManager.getInstance().getActiveTrace(); if (activeTrace == null) { return Collections.emptyList(); } UUID uuid = activeTrace.getUUID(); Collection<String> collection = fCategories.computeIfAbsent(uuid, new <START> Function<Object, Collection<String>>() <END> { @Override public Collection<String> apply(Object t) { ContextDataSource dataProvider = DataProviderManager.getInstance().getDataProvider(activeTrace, ContextDataSource.ID, ContextDataSource.class); if (dataProvider == null) { return Collections.emptyList(); } TmfModelResponse<@NonNull List<@NonNull TmfTreeDataModel>> tree = dataProvider.fetchTree(new TimeQueryFilter(Collections.emptyList()), new NullProgressMonitor()); List<@NonNull TmfTreeDataModel> model = tree.getModel(); if (model == null) { return Collections.emptyList(); } Set<String> data = new HashSet<>(); for (TmfTreeDataModel elem : model) { data.add(elem.getName()); } return data; } }); List<String> retVal = new ArrayList<>(collection); retVal.sort(null); return retVal; }</code><technical_language>UUID</technical_language>

Target:
public @NonNull List<@NonNull String> getMarkerCategories() { ITmfTrace activeTrace = TmfTraceManager.getInstance().getActiveTrace(); if (activeTrace == null) { return Collections.emptyList(); } UUID uuid = activeTrace.getUUID(); Collection<String> collection = fCategories.computeIfAbsent(uuid, t -> { ContextDataSource dataProvider = DataProviderManager.getInstance().getDataProvider(activeTrace, ContextDataSource.ID, ContextDataSource.class); if (dataProvider == null) { return Collections.emptyList(); } TmfModelResponse<@NonNull List<@NonNull TimeGraphEntryModel>> tree = dataProvider.fetchTree(new TimeQueryFilter(Collections.emptyList()), new NullProgressMonitor()); List<@NonNull TimeGraphEntryModel> model = tree.getModel(); if (model == null) { return Collections.emptyList(); } Set<String> data = new HashSet<>(); for (TmfTreeDataModel elem : model) { data.add(elem.getName()); } List<String> dataList = Lists.newArrayList(data); dataList.sort(null); return dataList; }); List<String> retVal = new ArrayList<>(collection); retVal.sort(null); return retVal; }
Source:
<code>public Receive createReceive() { return receiveBuilder() .match(Execute.class, e -> { getSelf().tell(PoisonPill.getInstance(), getSelf()); final Job j = e.getRepo().get(e.getJobId()); if (j == null) { LOGGER.error() .setMessage("repository has no job with given id") .addData("repo", e.getRepo()) .addData("jobId", e.getJobId()) .log(); e.getNotifiee().tell(new Failure(new NoSuchElementException(e.getJobId())), getSelf()); return; } <START> j.start().handle((result, err) -> { <END> e.getNotifiee().tell( err == null ? Success.INSTANCE : new Failure(err), getSelf() ); return null; }); }) .build(); }</code><technical_language>PatternsCS.pipe( ... )</technical_language>

Target:
public Receive createReceive() { return receiveBuilder() .match(Execute.class, e -> { getSelf().tell(PoisonPill.getInstance(), getSelf()); final Optional<Job> job = e.getRepo().getJob(e.getJobId()); if (!job.isPresent()) { e.getNotifiee().tell(new Failure(new NoSuchElementException(e.getJobId().toString())), getSelf()); return; } PatternsCS.pipe( job.get().start().handle((r, err) -> err == null ? Success.INSTANCE : new Failure(err)), getContext().dispatcher() ).to(e.getNotifiee()); }) .build(); }
Source:
<code>public void setUp() { <START> this.model = new SortedListModel<TestItem>() { <END> @Override protected Configurator lookupConfigurator() { return null; } @Override protected ILogger lookupLogger() { return null; } }; model.comparator = makeValueAscComparator(); }</code><technical_language>If this test class, consider Mockito.spy() mocking methods instead of extending SortedListModel. invasive respect class testing - instead of modifying behavior, a proxy intercept some method invocations</technical_language>

Target:
public void setUp() { testedModel = new SortedListModel<TestItem>() { @Override protected Configurator lookupConfigurator() { return null; } @Override protected ILogger lookupLogger() { return null; } }; }
Source:
<code>public void onReady(IPCClient client) { if (reconnecting) { getLogger().info("Discord RPC >> Reconnected!"); reconnectTries = 1; } else { getLogger().info("Discord RPC >> Connected!"); connectedBefore = true; } this.ipcClient = client; if (!ready) { ready = true; } if (lastRichPresence == null) { RichPresence.Builder builder = new RichPresence.Builder(); <START> builder.setLargeImage("ss_6"); <END> lastRichPresence = builder.build(); } client.sendRichPresence(lastRichPresence); }</code><technical_language>client id: try extract kinds of magic values a constant describes is (in this case asset identifier show in Discord)</technical_language>

Target:
public void onReady(IPCClient client) { if (reconnecting) { logger.info("Discord RPC >> Reconnected!"); reconnectTries = 1; } else { logger.info("Discord RPC >> Connected!"); connectedBefore = true; } this.ipcClient = client; if (!ready) { ready = true; } if (lastRichPresence == null) { RichPresence.Builder builder = new RichPresence.Builder(); builder.setLargeImage(DISCORD_APP_LARGE_IMAGE); lastRichPresence = builder.build(); } client.sendRichPresence(lastRichPresence); }
Source:
<code>public ClusteredQueryCommandWorker getCommand(Cache<?, ?> cache, QueryDefinition queryDefinition, UUID lazyQueryId, int docIndex) { <START> ClusteredQueryCommandWorker command = null; <END> command = getNewInstance(); command.init(cache, queryDefinition, lazyQueryId, docIndex); return command; }</code><technical_language>Declaration initialization of command done in line</technical_language>

Target:
public ClusteredQueryCommandWorker getCommand(Cache<?, ?> cache, QueryDefinition queryDefinition, UUID lazyQueryId, int docIndex) { ClusteredQueryCommandWorker command = getNewInstance(); command.init(cache, queryDefinition, lazyQueryId, docIndex); return command; }
Source:
<code>public void initFromPage(int valueCount, ByteBuffer in, int offset) throws IOException { int effectiveBitLength = valueCount * bitsPerValue; int length = BytesUtils.paddedByteCountFromBits(effectiveBitLength); if (Log.DEBUG) LOG.debug("reading " + length + " bytes for " + valueCount + " values of size " + bitsPerValue + " bits." ); <START> this.in = new ByteBufferInputStream(in.duplicate(), offset, length); <END> this.bitPackingReader = createBitPackingReader(bitsPerValue, this.in, valueCount); this.nextOffset = offset + length; }</code><technical_language>is duplicate() necessary</technical_language>

Target:
public void initFromPage(int valueCount, ByteBuffer in, int offset) throws IOException { int effectiveBitLength = valueCount * bitsPerValue; int length = BytesUtils.paddedByteCountFromBits(effectiveBitLength); if (Log.DEBUG) LOG.debug("reading " + length + " bytes for " + valueCount + " values of size " + bitsPerValue + " bits." ); this.in = new ByteBufferInputStream(in, offset, length); this.bitPackingReader = createBitPackingReader(bitsPerValue, this.in, valueCount); this.nextOffset = offset + length; }
Source:
<code>protected void _sendAdditionalNotification(NotificationContext context, NotificationStatus status) { requireArgument(context != null, "Notification context cannot be null."); super.sendAdditionalNotification(context); Notification notification = null; Trigger trigger = null; for (Notification tempNotification : context.getAlert().getNotifications()) { if (tempNotification.getName().equalsIgnoreCase(context.getNotification().getName())) { notification = tempNotification; break; } } requireArgument(notification != null, "Notification in notification context cannot be null."); for (Trigger tempTrigger : context.getAlert().getTriggers()) { if (tempTrigger.getName().equalsIgnoreCase(context.getTrigger().getName())) { trigger = tempTrigger; break; } } requireArgument(trigger != null, "Trigger in notification context cannot be null."); String body = getGOCMessageBody(notification, trigger, context); Severity sev = status == NotificationStatus.CLEARED ? Severity.OK : Severity.ERROR; <START> sendMessage(sev, context.getNotification().getName(), getDisplayedName(context, context.getAlert().getName()), getDisplayedName(context, context.getTrigger().getName()), body, <END> context.getNotification().getSeverityLevel(),context.getNotification().getSRActionable(), context.getTriggerFiredTime(), context.getTriggeredMetric()); }</code><technical_language>need add template notification name</technical_language>

Target:
protected void _sendAdditionalNotification(NotificationContext context, NotificationStatus status) { requireArgument(context != null, "Notification context cannot be null."); super.sendAdditionalNotification(context); Notification notification = null; Trigger trigger = null; for (Notification tempNotification : context.getAlert().getNotifications()) { if (tempNotification.getName().equalsIgnoreCase(context.getNotification().getName())) { notification = tempNotification; break; } } requireArgument(notification != null, "Notification in notification context cannot be null."); for (Trigger tempTrigger : context.getAlert().getTriggers()) { if (tempTrigger.getName().equalsIgnoreCase(context.getTrigger().getName())) { trigger = tempTrigger; break; } } requireArgument(trigger != null, "Trigger in notification context cannot be null."); String body = getGOCMessageBody(notification, trigger, context); Severity sev = status == NotificationStatus.CLEARED ? Severity.OK : Severity.ERROR; sendMessage(sev, getDisplayedName(context, context.getNotification().getName()), getDisplayedName(context, context.getAlert().getName()), getDisplayedName(context, context.getTrigger().getName()), body, context.getNotification().getSeverityLevel(),context.getNotification().getSRActionable(), context.getTriggerFiredTime(), context.getTriggeredMetric()); }
Source:
<code>public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); <START> response.setBody("Only support GET method to retrieve GC details." <END> + " If you want to trigger gc, send a POST to gc endpoint."); return response; } StateManager sm = bookie.getStateManager(); BookieState bs = new BookieState(); bs.running = sm.isRunning(); bs.readOnly = sm.isReadOnly(); bs.shuttingDown = sm.isShuttingDown(); bs.availableForHighPriorityWrites = sm.isAvailableForHighPriorityWrites(); String jsonResponse = JsonUtil.toJson(bs); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; }</code><technical_language>content in body match endpoint</technical_language>

Target:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve bookie state."); return response; } StateManager sm = bookie.getStateManager(); BookieState bs = new BookieState(); bs.running = sm.isRunning(); bs.readOnly = sm.isReadOnly(); bs.shuttingDown = sm.isShuttingDown(); bs.availableForHighPriorityWrites = sm.isAvailableForHighPriorityWrites(); String jsonResponse = JsonUtil.toJson(bs); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; }
Source:
<code>public List<NetworkAttachment> getAllForNic(Guid nicId) { return getCallsHandler().executeReadList("GetNetworkAttachmentsByNicId", <START> new NetworkAttachmentRowMapper(qosDaoRetriever, <END> dnsResolverConfigurationDao), getCustomMapSqlParameterSource().addValue("nic_id", nicId)); }</code><technical_language>NetworkAttachmentRowMapper created new, instead of one</technical_language>

Target:
public List<NetworkAttachment> getAllForNic(Guid nicId) { return getCallsHandler().executeReadList("GetNetworkAttachmentsByNicId", qosDaoAttachmentMapper, getCustomMapSqlParameterSource().addValue("nic_id", nicId)); }
Source:
<code>public void onRetryCompletion(long id) { if (!outstandingRetries.containsValue(id)) { return; <START> } <END> lock.lock(); try { outstandingRetries.remove(id); if (isFlushed()) { flushedCondition.signal(); isFlushed = true; } } finally { lock.unlock(); } resetNoSuccessWarningDeadline(); }</code><technical_language>I this is threadsafe</technical_language>

Target:
public void onRetryCompletion(long id) { lock.lock(); try { if (outstandingRetries.remove(id) != null && isFlushed()) { flushedCondition.signal(); isFlushed = true; } } finally { lock.unlock(); } resetNoSuccessWarningDeadline(); }
Source:
<code><START> public Mono<Response<TextAnalyticsResultCollection<AnalyzeSentimentResult>>> analyzeSentimentBatch( <END> Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getAnalyzedSentimentResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>Name for TextAnalyticsResultCollection is discussed in API view tool</technical_language>

Target:
public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatch( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getAnalyzedSentimentResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code>protected Control createDialogArea(Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); createSubtitleLabel(composite, Messages.AddAnalysisDialog_Name); fNameText = new Text(composite, getInputTextStyle()); fNameText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); fNameText.addModifyListener(e -> validateInputs()); fNameErrorLabel = createErrorLabel(composite); new Label(composite, SWT.WRAP); createSubtitleLabel(composite, Messages.AddAnalysisDialog_Command); fCommandText = new Text(composite, getInputTextStyle()); fCommandText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); final Font <START> mono = <END> new Font(parent.getDisplay(), "Monospace", 9, SWT.NONE); fCommandText.setFont(mono); fCommandText.addModifyListener(e -> validateInputs()); fCommandErrorLabel = createErrorLabel(composite); applyDialogFont(composite); return composite; }</code><technical_language>This font resource leaks. disposed dialog is disposed. add a dispose listener text</technical_language>

Target:
protected Control createDialogArea(Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); createSubtitleLabel(composite, Messages.AddAnalysisDialog_Name); fNameText = new Text(composite, getInputTextStyle()); fNameText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); fNameText.addModifyListener(e -> validateInputs()); fNameErrorLabel = createErrorLabel(composite); new Label(composite, SWT.WRAP); createSubtitleLabel(composite, Messages.AddAnalysisDialog_Command); fCommandText = new Text(composite, getInputTextStyle()); fCommandText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); final Font mono = new Font(parent.getDisplay(), "Monospace", 9, SWT.NONE); fCommandText.setFont(mono); fCommandText.addModifyListener(e -> validateInputs()); fCommandText.addDisposeListener(e -> mono.dispose()); fCommandErrorLabel = createErrorLabel(composite); applyDialogFont(composite); return composite; }
Source:
<code>public Future<Task> blockingSubmit(EngineWorker<Task> taskWorker) throws InterruptedException { <START> semaphore.acquire(); <END> GenWorker genWorker = (GenWorker) taskWorker; genWorker.getTask().setGenStartTime(new Date(System.currentTimeMillis())); Future<Task> future = completionService.submit(genWorker); executingGenTasks.put(future, genWorker.getTask()); return future; }</code><technical_language>expect code in this method throw exception, in case release semaphore</technical_language>

Target:
public Future<Task> blockingSubmit(EngineWorker<Task> taskWorker) throws InterruptedException { semaphore.acquire(); Future<Task> future = null; try { GenWorker genWorker = (GenWorker) taskWorker; genWorker.getTask().setGenStartTime(new Date(System.currentTimeMillis())); future = completionService.submit(genWorker); executingGenTasks.put(future, genWorker.getTask()); } catch (Exception ex) { semaphore.release(); throw ex; } return future; }
Source:
<code>public Optional<DyeableData> fill(DataContainer container, DyeableData dyeableData) { Optional<String> id = container.getString(Keys.DYE_COLOR.getQuery()); if (id.isPresent()) { <START> dyeableData.set(Keys.DYE_COLOR, Sponge.getGame().getRegistry().getType(DyeColor.class, id.get()).get()); <END> return Optional.of(dyeableData); } return Optional.empty(); }</code><technical_language>Multiple points of failure in line. Split this multiple lines able throw exceptions necessary</technical_language>

Target:
public Optional<DyeableData> fill(DataContainer container, DyeableData dyeableData) { Optional<String> id = container.getString(Keys.DYE_COLOR.getQuery()); if (id.isPresent()) { Optional<DyeColor> color = Sponge.getGame().getRegistry().getType(DyeColor.class, id.get()); dyeableData.set(Keys.DYE_COLOR, color.orElseThrow(() -> new RegistryException("Corresponding color " + id.get() + " missing in registry"))); return Optional.of(dyeableData); } return Optional.empty(); }
Source:
<code>public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet != null) { final RevId revision = patchSet.getRevision(); if (revision != null) { final AnyObjectId objectId = ObjectId.fromString(revision.get()); <START> final Change change = object.getChange(); <END> if (change != null) { final Project.NameKey projectName = change.getProject(); if (projectName != null && (objectId != null)) { try { final RevWalk walk = new RevWalk(repoManager.openRepository(projectName.get())); final RevCommit revCommit = walk.parseCommit(objectId); return rFilter.include(walk, revCommit); } catch (RepositoryNotFoundException e) { log.error("Repository \"" + projectName.get() + "\" unknown.", e); } catch (MissingObjectException e) { log.error("Commit Id \"" + revision.get() + "\" does not exist.", e); } catch (IncorrectObjectTypeException e) { log.error("Id \"" + revision.get() + "\" is not a commit.", e); } catch (IOException e) { log.error("Could not search for commit message in \"" + projectName.get() + "\" repository.", e); } catch (NullPointerException e) { } } } } } return false; }</code><technical_language>object.change(db). Change lazily loaded, PatchSet Change yet. need pass db in case, ChangeData load Change demand if necessary</technical_language>

Target:
public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet == null) { return false; } final RevId revision = patchSet.getRevision(); if (revision == null) { return false; } final AnyObjectId objectId = ObjectId.fromString(revision.get()); if (objectId == null) { return false; } final Change change = object.change(db); if (change == null) { return false; } final Project.NameKey projectName = change.getProject(); if (projectName == null) { return false; } try { final Repository repo = repoManager.openRepository(projectName.get()); try { final RevWalk rw = new RevWalk(repo); try { return rFilter.include(rw, rw.parseCommit(objectId)); } finally { rw.release(); } } finally { repo.close(); } } catch (RepositoryNotFoundException e) { log.error("Repository \"" + projectName.get() + "\" unknown.", e); } catch (MissingObjectException e) { log.error(projectName.get() + "\" commit does not exist.", e); } catch (IncorrectObjectTypeException e) { log.error(projectName.get() + "\" revision is not a commit.", e); } catch (IOException e) { log.error("Could not search for commit message in \"" + projectName.get() + "\" repository.", e); } return false; }
Source:
<code><START> public TestApplicationContext() { <END> super(); }</code><technical_language>I said: TestUtils.createTestApplicationContext() so, changes here, please</technical_language>

Target:
TestApplicationContext() { super(); }
Source:
<code>public void setBlockProxy( final String repoId, final boolean block ) throws Exception { RepositoryStatusResource status = new RepositoryStatusResource(); status.setId( repoId ); status.setRepoType( "proxy" ); status.setLocalStatus( LocalStatus.IN_SERVICE.name() ); if ( block ) { status.setRemoteStatus( RemoteStatus.AVAILABLE.name() ); status.setProxyMode( ProxyMode.BLOCKED_MANUAL.name() ); } else { status.setRemoteStatus( RemoteStatus.UNAVAILABLE.name() ); status.setProxyMode( ProxyMode.ALLOW.name() ); } <START> Response response = RepositoryStatusMessageUtil.changeStatus( status ); <END> assertThat( "Could not unblock proxy: " + repoId + ", status: " + response.getStatus().getName() + " (" + response.getStatus().getCode() + ") - " + response.getStatus().getDescription(), response, isSuccessful() ); TaskScheduleUtil.waitForAllTasksToStop(); getTest().getEventInspectorsUtil().waitForCalmPeriod(); }</code><technical_language>Release response</technical_language>

Target:
public void setBlockProxy( final String repoId, final boolean block ) throws Exception { RepositoryStatusResource status = new RepositoryStatusResource(); status.setId( repoId ); status.setRepoType( "proxy" ); status.setLocalStatus( LocalStatus.IN_SERVICE.name() ); if ( block ) { status.setRemoteStatus( RemoteStatus.AVAILABLE.name() ); status.setProxyMode( ProxyMode.BLOCKED_MANUAL.name() ); } else { status.setRemoteStatus( RemoteStatus.UNAVAILABLE.name() ); status.setProxyMode( ProxyMode.ALLOW.name() ); } Response response = RepositoryStatusMessageUtil.changeStatus( status ); try { assertThat( "Could not unblock proxy: " + repoId + ", status: " + response.getStatus().getName() + " (" + response.getStatus().getCode() + ") - " + response.getStatus().getDescription(), response, isSuccessful() ); } finally { RequestFacade.releaseResponse( response ); } TaskScheduleUtil.waitForAllTasksToStop(); getTest().getEventInspectorsUtil().waitForCalmPeriod(); }
Source:
<code>public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_argument.getResultMetadata().getDataType() != FieldSpec.DataType.INT) { return super.transformToIntValuesSV(projectionBlock); } if (_intValuesSV == null) { _intValuesSV = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } int length = projectionBlock.getNumDocs(); int[][] intValuesMV = _argument.transformToIntValuesMV(projectionBlock); for (int i = 0; i < length; i++) { int maxRes = Integer.MIN_VALUE; <START> for (int j = 0; j < intValuesMV[i].length; j++) { maxRes = Math.max(maxRes, intValuesMV[i][j]); } <END> _intValuesSV[i] = maxRes; } return _intValuesSV; }</code><technical_language>(nit) for other places suggestion for (int : intValuesMV[i]) { maxRes = Math.max(maxRes, value); }</technical_language>

Target:
public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_argument.getResultMetadata().getDataType() != FieldSpec.DataType.INT) { return super.transformToIntValuesSV(projectionBlock); } if (_intValuesSV == null) { _intValuesSV = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } int length = projectionBlock.getNumDocs(); int[][] intValuesMV = _argument.transformToIntValuesMV(projectionBlock); for (int i = 0; i < length; i++) { int maxRes = Integer.MIN_VALUE; for (int value : intValuesMV[i]) { maxRes = Math.max(maxRes, value); } _intValuesSV[i] = maxRes; } return _intValuesSV; }
Source:
<code>public void testEffectivelyReadOnlyDisablesControl() throws DatabindingFailedException, NoRendererFoundException, NoPropertyDescriptorFoundExeption { showMoveButtons = true; when(renderer.getVElement().isReadonly()).thenReturn(false); when(renderer.getVElement().isEffectivelyReadonly()).thenReturn(true); final VView parent = mock(VView.class); when(parent.isReadonly()).thenReturn(true); when(renderer.getVElement().eContainer()).thenReturn(parent); final TestObservableValue observableValue = mock(TestObservableValue.class); when(databindingService.getObservableValue(any(VDomainModelReference.class), any(EObject.class))).thenReturn( observableValue); when(observableValue.getObserved()).thenReturn(mock(EObject.class)); final Composite composite = (Composite) renderer.render(new SWTGridCell(0, 0, renderer), shell); renderer.finalizeRendering(shell); assertFalse(composite.isEnabled()); <START> final Button upButton = SWTTestUtil.findControlById(composite, UUID_UP, Button.class); <END> assertThat(upButton, notNullValue()); assertFalse(upButton.getVisible()); final Button downButton = SWTTestUtil.findControlById(composite, UUID_DOWN, Button.class); assertThat(downButton, notNullValue()); assertFalse(downButton.getVisible()); final Button linkButton = SWTTestUtil.findControlById(composite, UUID_LINK, Button.class); assertThat(linkButton, nullValue()); final Button addButton = SWTTestUtil.findControlById(composite, UUID_ADD, Button.class); assertThat(addButton, nullValue()); final Button deleteButton = SWTTestUtil.findControlById(composite, UUID_DELETE, Button.class); assertThat(deleteButton, notNullValue()); assertFalse(deleteButton.getVisible()); }</code><technical_language>assertion block moved out a helper method reduce duplication</technical_language>

Target:
public void testEffectivelyReadOnlyDisablesControl() throws DatabindingFailedException, NoRendererFoundException, NoPropertyDescriptorFoundExeption { showMoveButtons = true; when(renderer.getVElement().isReadonly()).thenReturn(false); when(renderer.getVElement().isEffectivelyReadonly()).thenReturn(true); when(renderer.getVElement().isEffectivelyEnabled()).thenReturn(true); final VView parent = mock(VView.class); when(parent.isReadonly()).thenReturn(true); when(renderer.getVElement().eContainer()).thenReturn(parent); final TestObservableValue observableValue = mock(TestObservableValue.class); when(databindingService.getObservableValue(any(VDomainModelReference.class), any(EObject.class))).thenReturn( observableValue); when(observableValue.getObserved()).thenReturn(mock(EObject.class)); final Composite composite = (Composite) renderer.render(new SWTGridCell(0, 0, renderer), shell); renderer.finalizeRendering(shell); assertTrue(composite.isEnabled()); checkButton(composite, UUID_UP, false, false); checkButton(composite, UUID_DOWN, false, false); checkButton(composite, UUID_DELETE, false, false); checkNoButton(composite, UUID_LINK); checkNoButton(composite, UUID_ADD); }
Source:
<code>public synchronized CoordinatorEvent take() throws InterruptedException { while (_eventQueue.isEmpty()) { wait(); } CoordinatorEvent queuedEvent = _eventQueue.poll(); if (CoordinatorEvent.NO_OP_EVENT == queuedEvent) { return null; } if (queuedEvent != null) { LOG.info("De-queuing event " + queuedEvent.getType()); LOG.debug("Event queue size: {}", _eventQueue.size()); <START> _eventSet.remove(queuedEvent); <END> return queuedEvent; } return null; }</code><technical_language>put() permits null inserted _eventSet, move this of if block? A quick show places explicitly put(null) I this method returning null line 70 I 100% some piece of code put back</technical_language>

Target:
public synchronized CoordinatorEvent take() throws InterruptedException { while (_eventQueue.isEmpty()) { wait(); } CoordinatorEvent queuedEvent = _eventQueue.poll(); if (CoordinatorEvent.NO_OP_EVENT == queuedEvent) { return null; } if (queuedEvent != null) { LOG.info("De-queuing event " + queuedEvent.getType()); LOG.debug("Event queue size: {}", _eventQueue.size()); _eventSet.remove(queuedEvent); } return queuedEvent; }
Source:
<code>public static Bundle saveUiStateToBundle(CommCareActivity activity) { Bundle bundle = new Bundle(); Class classHoldingFields = getClassHoldingFields(activity); for (Field f : classHoldingFields.getDeclaredFields()) { if (f.isAnnotationPresent(UiElement.class)) { UiElement element = f.getAnnotation(UiElement.class); try { f.setAccessible(true); try { View v; if (activity.usesUIController()) { v = (View)f.get(activity.getUIController()); } else { v = (View)f.get(activity); <START> } <END> String elementKey = getElementKey(element); int vis = v.getVisibility(); bundle.putInt(elementKey + "_visibility", vis); boolean enabled = v.isEnabled(); bundle.putBoolean(elementKey + "_enabled", enabled); if (v instanceof TextView) { bundle.putString(elementKey + "_text", ((TextView)v).getText().toString()); } } catch (IllegalArgumentException e) { e.printStackTrace(); throw new RuntimeException("Bad Object type for field " + f.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't access the activity field for some reason"); } } finally { f.setAccessible(false); } } } return bundle; }</code><technical_language>I lift this out of for loop, get proper class instance once. sort of coincides result of getClassHoldingFields, some of setup work shared</technical_language>

Target:
public static Bundle saveUiStateToBundle(CommCareActivity activity) { Bundle bundle = new Bundle(); Object objectHoldingFields = activity.getUIManager(); for (Field f : objectHoldingFields.getClass().getDeclaredFields()) { if (f.isAnnotationPresent(UiElement.class)) { UiElement element = f.getAnnotation(UiElement.class); try { f.setAccessible(true); try { View v = (View)f.get(objectHoldingFields); String elementKey = getElementKey(element); int vis = v.getVisibility(); bundle.putInt(elementKey + "_visibility", vis); boolean enabled = v.isEnabled(); bundle.putBoolean(elementKey + "_enabled", enabled); if (v instanceof TextView) { bundle.putString(elementKey + "_text", ((TextView)v).getText().toString()); } } catch (IllegalArgumentException e) { e.printStackTrace(); throw new RuntimeException("Bad Object type for field " + f.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't access the activity field for some reason"); } } finally { f.setAccessible(false); } } } return bundle; }
Source:
<code>private static ImmutableSortedMap<String, ImmutableSet<String>> buildRegistry( ImmutableSet<String> modulePaths) { SortedMap<String, Set<String>> registry = new TreeMap<>(new Comparator<String>() { @Override public int compare(String a, String b) { int comparison = Integer.compare(b.length(), a.length()); if (comparison != 0) { return comparison; } return a.compareTo(b); } }); for (String modulePath : modulePaths) { <START> String[] nodeModulesDirs = modulePath.split("/node_modules/"); <END> String parentPath = ""; for (int i = 0; i < nodeModulesDirs.length - 1; i++) { if (i + 1 < nodeModulesDirs.length) { parentPath += nodeModulesDirs[i] + "/"; } String subPath = modulePath.substring(parentPath.length() + "node_modules/".length()); if (!registry.containsKey(parentPath)) { registry.put(parentPath, new HashSet<String>()); } registry.get(parentPath).add(subPath); parentPath += "node_modules/"; } } SortedMap<String, ImmutableSet<String>> immutableRegistry = new TreeMap<>(new Comparator<String>() { @Override public int compare(String a, String b) { int comparison = Integer.compare(b.length(), a.length()); if (comparison != 0) { return comparison; } return a.compareTo(b); } }); for (Map.Entry<String, Set<String>> entry : registry.entrySet()) { immutableRegistry.put(entry.getKey(), ImmutableSet.copyOf(entry.getValue())); } return ImmutableSortedMap.copyOfSorted(immutableRegistry); }</code><technical_language>MODULE_SLASH & other places below</technical_language>

Target:
private static ImmutableSortedMap<String, ImmutableSet<String>> buildRegistry( ImmutableSet<String> modulePaths) { SortedMap<String, Set<String>> registry = new TreeMap<>(new Comparator<String>() { @Override public int compare(String a, String b) { int comparison = Integer.compare(b.length(), a.length()); if (comparison != 0) { return comparison; } return a.compareTo(b); } }); for (String modulePath : modulePaths) { String[] nodeModulesDirs = modulePath.split(MODULE_SLASH + "node_modules" + MODULE_SLASH); String parentPath = ""; for (int i = 0; i < nodeModulesDirs.length - 1; i++) { if (i + 1 < nodeModulesDirs.length) { parentPath += nodeModulesDirs[i] + MODULE_SLASH; } String subPath = modulePath.substring(parentPath.length() + "node_modules/".length()); if (!registry.containsKey(parentPath)) { registry.put(parentPath, new HashSet<String>()); } registry.get(parentPath).add(subPath); parentPath += "node_modules" + MODULE_SLASH; } } SortedMap<String, ImmutableSet<String>> immutableRegistry = new TreeMap<>(new Comparator<String>() { @Override public int compare(String a, String b) { int comparison = Integer.compare(b.length(), a.length()); if (comparison != 0) { return comparison; } return a.compareTo(b); } }); for (Map.Entry<String, Set<String>> entry : registry.entrySet()) { immutableRegistry.put(entry.getKey(), ImmutableSet.copyOf(entry.getValue())); } return ImmutableSortedMap.copyOfSorted(immutableRegistry); }
Source:
<code>private void bpBelongsToContext( IExecutionDMContext execContext, final MIBreakpointDMData data, final DataRequestMonitor<Boolean> rm ) { if ( execContext == null ) { rm.done( true ); return; } IMIExecutionDMContext threadContext = DMContexts.getAncestorOfType( execContext, IMIExecutionDMContext.class ); if ( threadContext != null ) { if ( data.getThreadId() != null && data.getThreadId().length() > 0 ) { try { int bpThreadId = Integer.parseInt( data.getThreadId() ); if ( bpThreadId != 0 ) { <START> int ctxThreadId = Integer.parseInt(threadContext.getThreadId()); <END> rm.done( ctxThreadId == bpThreadId ); return; } } catch( NumberFormatException e ) { assert false; GdbUIPlugin.getDefault().getLog().log( new Status( IStatus.ERROR, GdbUIPlugin.getUniqueIdentifier(), "Invalid breakpoint thread id" ) ); rm.done( true ); return; } } } final IMIContainerDMContext containerContext = DMContexts.getAncestorOfType( execContext, IMIContainerDMContext.class ); if ( containerContext != null ) { if ( data.getGroupIds() != null ) { List<String> groupIds = Arrays.asList( data.getGroupIds() ); rm.done( groupIds.contains( containerContext.getGroupId() ) ); } else { rm.done( true ); } } else { rm.done( true ); } }</code><technical_language>In this case too, I suggest consider avoiding conversions, new String values compare (with .equals())</technical_language>

Target:
private void bpBelongsToContext( IExecutionDMContext execContext, final MIBreakpointDMData data, final DataRequestMonitor<Boolean> rm ) { if ( execContext == null ) { rm.done( true ); return; } IMIExecutionDMContext threadContext = DMContexts.getAncestorOfType( execContext, IMIExecutionDMContext.class ); if ( threadContext != null ) { if (data.getThreadId() != null && data.getThreadId().length() > 0) { String bpThreadId = data.getThreadId().trim(); if (!bpThreadId.equals("0")) { String ctxThreadId = threadContext.getThreadId(); rm.done(ctxThreadId.equals(bpThreadId)); return; } } } final IMIContainerDMContext containerContext = DMContexts.getAncestorOfType( execContext, IMIContainerDMContext.class ); if ( containerContext != null ) { if ( data.getGroupIds() != null ) { List<String> groupIds = Arrays.asList( data.getGroupIds() ); rm.done( groupIds.contains( containerContext.getGroupId() ) ); } else { rm.done( true ); } } else { rm.done( true ); } }
Source:
<code>public ReadAheadDispatcher(NestableBlock... blocks) { <START> this.blocks = blocks; <END> this.lookAheadReader = new LookAheadReader(); }</code><technical_language>array of blocks copied</technical_language>

Target:
public ReadAheadDispatcher(NestableBlock... blocks) { this.blocks = cloneBlocks(Arrays.asList(blocks)); this.lookAheadReader = new LookAheadReader(); }
Source:
<code>public static String stripHtml(String text) { String cleanText = text.replaceAll("\\<.*?\\>", " "); <START> cleanText = cleanText.replaceAll("\\n", " "); <END> cleanText = cleanText.replaceAll("\\r", " "); cleanText = cleanText.replaceAll("\\s{2,}", " "); return cleanText.trim(); }</code><technical_language>This is stripping out html anymore. confusing if name of **HTML**Filter.strip**HTML**(String) next lines</technical_language>

Target:
public static String stripHtml(String text) { if (StringUtils.isEmpty(text)) return text; String cleanText = Jsoup.parse(text).text().trim(); return cleanText.trim(); }
Source:
<code>public void overSizedCacheOps() throws Exception { <START> final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder <END> = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm")) .autoCreate() .defaultServerResource("primary-server-resource")); final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); try { CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))).build(); Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config); cache.put(1L, "The one"); assertThat(cache.containsKey(2L), is(false)); cache.put(2L, "The two"); assertThat(cache.containsKey(2L), is(true)); cache.put(1L, "Another one"); cache.put(3L, "The three"); assertThat(cache.get(1L), equalTo("Another one")); assertThat(cache.get(2L), equalTo("The two")); assertThat(cache.get(3L), equalTo("The three")); String veryLargeString = buildLargeString(2); cache.put(1L, veryLargeString); assertThat(cache.get(1L), is(nullValue())); assertThat(cache.get(3L), equalTo("The three")); cache.clear(); assertThat(cache.get(1L), is(nullValue())); assertThat(cache.get(2L), is(nullValue())); assertThat(cache.get(3L), is(nullValue())); System.out.println(" TEST COMPLETED SUCCESSFULLY "); } finally { cacheManager.close(); } }</code><technical_language>Please remove useless final keywords</technical_language>

Target:
public void overSizedCacheOps() throws Exception { CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm")) .autoCreate() .defaultServerResource("primary-server-resource")); try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) { CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))).build(); Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config); cache.put(1L, "The one"); cache.put(2L, "The two"); cache.put(1L, "Another one"); cache.put(3L, "The three"); assertThat(cache.get(1L), equalTo("Another one")); assertThat(cache.get(2L), equalTo("The two")); assertThat(cache.get(3L), equalTo("The three")); cache.put(1L, buildLargeString(2)); assertThat(cache.get(1L), is(nullValue())); assertThat(cache.get(2L), equalTo("The two")); assertThat(cache.get(3L), equalTo("The three")); } }
Source:
<code>private MetricName partitionPreferredReadReplicaMetricName(TopicPartition tp) { <START> Map<String, String> metricTags = new HashMap<>(2); <END> metricTags.put("topic", tp.topic().replace('.', '_')); metricTags.put("partition", String.valueOf(tp.partition())); return this.metrics.metricInstance(metricsRegistry.partitionPreferredReadReplica, metricTags); }</code><technical_language>nit: this logic in a couple other places. sufficient turn a method</technical_language>

Target:
private MetricName partitionPreferredReadReplicaMetricName(TopicPartition tp) { Map<String, String> metricTags = topicPartitionTags(tp); return this.metrics.metricInstance(metricsRegistry.partitionPreferredReadReplica, metricTags); }
Source:
<code><START> public void testParse() { <END> assertEquals(Optional.of(ASSIGNEE), parse("assignee")); assertFalse(parse("malformed").isPresent()); assertFalse(parse("").isPresent()); assertFalse(parse(null).isPresent()); }</code><technical_language>some alias parse test well? ensure resolveAlias() is called</technical_language>

Target:
public void testParse() { assertEquals(Optional.of(ASSIGNEE), parse("assignee")); assertFalse(parse("malformed").isPresent()); assertFalse(parse("").isPresent()); assertFalse(parse(null).isPresent()); assertFalse(parse("empty").isPresent()); assertFalse(parse("false").isPresent()); assertFalse(parse("keyword").isPresent()); }
Source:
<code>public Datum eval(Tuple params) { Datum valueDatum = params.get(0); Datum roundDatum = params.get(1); if(valueDatum instanceof NullDatum || roundDatum instanceof NullDatum) { return NullDatum.get(); } double value = valueDatum.asFloat8(); int rountPoint = roundDatum.asInt4(); if (Double.isNaN(value)) { throw new InvalidOperationException("value is not a number"); } if (Double.isInfinite(value)) { <START> throw new InvalidOperationException("/ by zero"); <END> } try { return DatumFactory.createFloat8(BigDecimal.valueOf(value).setScale(rountPoint, RoundingMode.HALF_UP).doubleValue()); } catch (Exception e) { throw new InvalidOperationException("RoundFloat8 eval error cause " + e.getMessage() + ", value=" + value + ", round point=" + rountPoint); } }</code><technical_language>exception message fixed this is divide operation</technical_language>

Target:
public Datum eval(Tuple params) { Datum valueDatum = params.get(0); Datum roundDatum = params.get(1); if(valueDatum instanceof NullDatum || roundDatum instanceof NullDatum) { return NullDatum.get(); } double value = valueDatum.asFloat8(); int rountPoint = roundDatum.asInt4(); if (Double.isNaN(value)) { throw new InvalidOperationException("value is not a number."); } if (Double.isInfinite(value)) { throw new InvalidOperationException("value is infinite."); } try { return DatumFactory.createFloat8(BigDecimal.valueOf(value).setScale(rountPoint, RoundingMode.HALF_UP).doubleValue()); } catch (Exception e) { throw new InvalidOperationException("RoundFloat8 eval error cause " + e.getMessage() + ", value=" + value + ", round point=" + rountPoint); } }
Source:
<code>void considerDetachedPlugin(String shortName) { if (new File(rootDir, shortName + ".jpi").isFile() || new File(rootDir, shortName + ".hpi").isFile() || new File(rootDir, shortName + ".jpl").isFile() || new File(rootDir, shortName + ".hpl").isFile()) { LOGGER.fine(() -> "not considering loading a detached dependency " + shortName + " as it is already on disk"); return; } LOGGER.finer(() -> "considering loading a detached dependency " + shortName); for (String loadedFile : loadPluginsFromWar("/WEB-INF/detached-plugins", (dir, name) -> normalisePluginName(name).equals(shortName))) { String loaded = normalisePluginName(loadedFile); File arc = new File(rootDir, loaded + ".jpi"); <START> LOGGER.finer(() -> "Loading a detached plugin as a dependency: " + arc); <END> try { plugins.add(strategy.createPluginWrapper(arc)); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(), e)); } } }</code><technical_language>This important debugging default visible INFO</technical_language>

Target:
void considerDetachedPlugin(String shortName) { if (new File(rootDir, shortName + ".jpi").isFile() || new File(rootDir, shortName + ".hpi").isFile() || new File(rootDir, shortName + ".jpl").isFile() || new File(rootDir, shortName + ".hpl").isFile()) { LOGGER.fine(() -> "not considering loading a detached dependency " + shortName + " as it is already on disk"); return; } LOGGER.fine(() -> "considering loading a detached dependency " + shortName); for (String loadedFile : loadPluginsFromWar("/WEB-INF/detached-plugins", (dir, name) -> normalisePluginName(name).equals(shortName))) { String loaded = normalisePluginName(loadedFile); File arc = new File(rootDir, loaded + ".jpi"); LOGGER.info(() -> "Loading a detached plugin as a dependency: " + arc); try { plugins.add(strategy.createPluginWrapper(arc)); } catch (IOException e) { failedPlugins.add(new FailedPlugin(arc.getName(), e)); } } }
Source:
<code>restartRadio() { Log.d(LOG_TAG, "************TURN OFF RADIO**************"); cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); phone.mCM.setRadioPower(false, null); <START> int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0")); <END> SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1)); }</code><technical_language>Doesn sense for CDMA</technical_language>

Target:
protected void restartRadio() { Log.d(LOG_TAG, "************TURN OFF RADIO**************"); cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); phone.mCM.setRadioPower(false, null); }
Source:
<code>@Override public int getRuntime(PreferenceManager pm) { if (getMax_runtime() != null && <START> !getMax_runtime().equals(PreferenceManager.MAX_RUNTIME_DISABLED)) <END> return 30 + getMax_runtime(); else if (getInputs() != null) return 30 + getInputs().size() * super.getRuntime(pm); else if(pm.isMaxRuntimeEnabled()) return 30 + pm.getMaxRuntime(); else return PreferenceManager.MAX_RUNTIME_DISABLED; }</code><technical_language>check for max runtime >= 0 here</technical_language>

Target:
@Override public int getRuntime(PreferenceManager pm) { if (getMax_runtime() != null && getMax_runtime() > PreferenceManager.MAX_RUNTIME_DISABLED) return 30 + getMax_runtime(); else if (getInputs() != null) return 30 + getInputs().size() * super.getRuntime(pm); else if(pm.isMaxRuntimeEnabled()) return 30 + pm.getMaxRuntime(); else return PreferenceManager.MAX_RUNTIME_DISABLED; }
Source:
<code>private void emitThisParameter(FunctionType ftype, Iterator<Node> parameters) { final JSType typeOfThis = ftype.getTypeOfThis(); <START> if (typeOfThis != null && !ftype.isConstructor()) { <END> final JSDocInfo jsDocInfo = ftype.getJSDocInfo(); if (typeOfThis.isTemplateType() || (jsDocInfo != null && jsDocInfo.getThisType() != null)) { emitNoSpace("this :"); visitType(typeOfThis); if (parameters.hasNext()) { emit(", "); } } } }</code><technical_language>prefer early exits: invert condition return</technical_language>

Target:
private void emitThisParameter(FunctionType ftype, Iterator<Node> parameters) { final JSType typeOfThis = ftype.getTypeOfThis(); if (typeOfThis == null || ftype.isConstructor()) { return; } final JSDocInfo jsDocInfo = ftype.getJSDocInfo(); if (!typeOfThis.isTemplateType() && (jsDocInfo == null || jsDocInfo.getThisType() == null)) { return; } emitNoSpace("this :"); visitType(typeOfThis); if (parameters.hasNext()) { emit(", "); } }