auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Set<Event> getEvents(@Parameter(hidden = true) @ApiParam(hidden = true) @Auth User user, @QueryParam("event_search_type") EventSearchType eventSearchType, @Min(1) @Max(MAX_LIMIT) @DefaultValue(PAGINATION_DEFAULT_STRING) @ApiParam(defaultValue = PAGINATION_DEFAULT_STRING, allowableValues = PAGINATION_RANGE) @Parameter(schema = @Schema(maximum = "100", minimum = "1")) @QueryParam("limit") int limit, @QueryParam("offset") @DefaultValue("0") Integer offset) { <END> User userWithSession = this.userDAO.findById(user.getId()); Set<Event> events = new HashSet<>(); switch (eventSearchType) { case STARRED_ENTRIES: Set<Long> entryIDs = userWithSession.getStarredEntries().stream().map(Entry::getId).collect(Collectors.toSet()); events.addAll(this.eventDAO.findEventsByEntryIDs(entryIDs, offset, limit)); return events; case STARRED_ORGANIZATION: Set<Long> organizationIDs = userWithSession.getStarredOrganizations().stream().map(Organization::getId).collect(Collectors.toSet()); events.addAll(this.eventDAO.findAllByOrganizationIds(organizationIDs, offset, limit)); return events; case ALL_STARRED: Set<Long> organizationIDs2 = userWithSession.getStarredOrganizations().stream().map(Organization::getId).collect(Collectors.toSet()); Set<Long> entryIDs2 = userWithSession.getStarredEntries().stream().map(Entry::getId).collect(Collectors.toSet()); events.addAll(this.eventDAO.findAllByOrganizationIdsOrEntryIds(organizationIDs2, entryIDs2, offset, limit)); return events; default: return Collections.emptySet(); } }</code><technical_language>change this a List a Set? lose queries' sort orders</technical_language>

Target:
public List<Event> getEvents(@Parameter(hidden = true) @ApiParam(hidden = true) @Auth User user, @QueryParam("event_search_type") EventSearchType eventSearchType, @Min(1) @Max(MAX_LIMIT) @DefaultValue(PAGINATION_DEFAULT_STRING) @ApiParam(defaultValue = PAGINATION_DEFAULT_STRING, allowableValues = PAGINATION_RANGE) @Parameter(schema = @Schema(maximum = "100", minimum = "1")) @QueryParam("limit") int limit, @QueryParam("offset") @DefaultValue("0") Integer offset) { User userWithSession = this.userDAO.findById(user.getId()); switch (eventSearchType) { case STARRED_ENTRIES: Set<Long> entryIDs = userWithSession.getStarredEntries().stream().map(Entry::getId).collect(Collectors.toSet()); return this.eventDAO.findEventsByEntryIDs(entryIDs, offset, limit); case STARRED_ORGANIZATION: Set<Long> organizationIDs = userWithSession.getStarredOrganizations().stream().map(Organization::getId).collect(Collectors.toSet()); return this.eventDAO.findAllByOrganizationIds(organizationIDs, offset, limit); case ALL_STARRED: Set<Long> organizationIDs2 = userWithSession.getStarredOrganizations().stream().map(Organization::getId).collect(Collectors.toSet()); Set<Long> entryIDs2 = userWithSession.getStarredEntries().stream().map(Entry::getId).collect(Collectors.toSet()); return this.eventDAO.findAllByOrganizationIdsOrEntryIds(organizationIDs2, entryIDs2, offset, limit); default: return Collections.emptyList(); } }
Source:
<code><START> private XGyro getBrokenGyro() <END> { MockGyro brokenGyro = new MockGyro(new MockRobotIO()); brokenGyro.setIsBroken(true); return brokenGyro; }</code><technical_language>add optional argument isBroken in MockGyro constructor? This more elegant easy understand a glance a one-liner</technical_language>

Target:
private XGyro getBrokenGyro() { MockGyro brokenGyro = new MockGyro(new MockRobotIO(), true); return brokenGyro; }
Source:
<code>public void showProgress(int message) { <START> FragmentBase fragment = (CheckPhoneNumberFragment) <END> getSupportFragmentManager().findFragmentByTag(CheckPhoneNumberFragment.TAG); if (fragment == null || fragment.getView() == null) { fragment = (SubmitConfirmationCodeFragment) getSupportFragmentManager().findFragmentByTag(SubmitConfirmationCodeFragment.TAG); } if (fragment == null || fragment.getView() == null) { throw new IllegalStateException("No fragments added"); } else { fragment.showProgress(message); } }</code><technical_language>DRY lines showProgress hideProgress some getActiveFragment method something</technical_language>

Target:
public void showProgress(int message) { getActiveFragment().showProgress(message); }
Source:
<code>public void testNewInstanceForNonDefaultConstructor() { Object x = ReflectionUtils.newInstance( NoDefaultCtor.class, null, new Class[] {int.class}, 1); <START> Assert.assertTrue(x instanceof NoDefaultCtor); <END> }</code><technical_language>I Assert is imported compilation fail. test cases number of parameter argument match</technical_language>

Target:
public void testNewInstanceForNonDefaultConstructor() { Object x = ReflectionUtils.newInstance( NoDefaultCtor.class, null, new Class[] {int.class}, 1); assertTrue(x instanceof NoDefaultCtor); }
Source:
<code>public long getAsLong() { <START> TimestampService timestampServiceForThisCall = timestampService; <END> if (timestampServiceForThisCall == null) { throwNotInitializedException(); } return timestampServiceForThisCall.getFreshTimestamp(); }</code><technical_language>is this variable necessary? Is avoid edge case do check get fresh timestamp, calls setTimestampService(null)? If (maybe if so), is setTimestampService(null) a valid do</technical_language>

Target:
public long getAsLong() { if (timestampService == null) { throwNotInitializedException(); } return timestampService.getFreshTimestamp(); }
Source:
<code>public void setUp() throws IOException, YarnException { conf = new YarnConfiguration(); conf.set(YarnConfiguration.CLIENT_FAILOVER_PROXY_PROVIDER, ConfiguredRMFailoverProxyProvider.class.getName()); <START> conf.set(YarnConfiguration.RM_HA_ENABLED, "true"); <END> }</code><technical_language>setBoolean()</technical_language>

Target:
public void setUp() throws IOException, YarnException { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, ConfiguredRMFailoverProxyProvider.class, RMFailoverProxyProvider.class); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); }
Source:
<code>static List<String> restoreFromPreferences(Repository repo, String branch) { String key = getPreferenceKey(repo, branch); String value = Activator.getDefault().getPreferenceStore() .getString(key); if (value.length() == 0) return Collections.emptyList(); XMLMemento memento; try { memento = XMLMemento.createReadRoot(new StringReader(value)); } catch (WorkbenchException e) { Activator.logError("Error reading branch-project associations", e); return <START> Collections.<String> emptyList(); <END> } IMemento[] children = memento.getChildren(KEY_PROJECT); if (children.length == 0) return Collections.<String> emptyList(); List<String> projectPaths = Stream.of(children) .map(child -> child.getTextData()) .filter(x -> !StringUtils.isEmptyOrNull(x)) .collect(Collectors.toList()); return projectPaths; }</code><technical_language>needed</technical_language>

Target:
static List<String> restoreFromPreferences(Repository repo, String branch) { String key = getPreferenceKey(repo, branch); String value = Activator.getDefault().getPreferenceStore() .getString(key); if (value.length() == 0) return Collections.emptyList(); XMLMemento memento; try { memento = XMLMemento.createReadRoot(new StringReader(value)); } catch (WorkbenchException e) { Activator.logError("Error reading branch-project associations", e); return Collections.emptyList(); } IMemento[] children = memento.getChildren(KEY_PROJECT); if (children.length == 0) return Collections.emptyList(); List<String> projectPaths = Stream.of(children) .map(child -> child.getTextData()) .filter(x -> !StringUtils.isEmptyOrNull(x)) .collect(Collectors.toList()); return projectPaths; }
Source:
<code>public JailPanel(int totalPieces, int teamIndex) { mJailDimension = (totalPieces / 4) + (totalPieces % 4); setOpaque(false); setLayout(new GridLayout(mJailDimension, mJailDimension)); setPreferredSize(new Dimension(mJailDimension * 48, mJailDimension * 48)); mSquareLabels = new SquareJLabel[mJailDimension][mJailDimension]; mTeamIndex = teamIndex; setBorder(GuiUtility.createBorder(Messages.getString("PlayGamePanel.capturedPieces"))); setLayout(new GridLayout(mJailDimension, mJailDimension)); setPreferredSize(new Dimension((mJailDimension + 1) * 25, (mJailDimension + 1) * 25)); <START> createGrid(mJailDimension); <END> }</code><technical_language>if mJailDimension is a field now, do need pass in createGrid() createGrid() directly</technical_language>

Target:
public JailPanel(int totalPieces, int teamIndex) { mJailDimension = (totalPieces / 4) + (totalPieces % 4); setOpaque(false); setLayout(new GridLayout(mJailDimension, mJailDimension)); setPreferredSize(new Dimension(mJailDimension * 48, mJailDimension * 48)); mSquareLabels = new SquareJLabel[mJailDimension][mJailDimension]; mTeamIndex = teamIndex; setBorder(GuiUtility.createBorder(Messages.getString("PlayGamePanel.capturedPieces"))); setLayout(new GridLayout(mJailDimension, mJailDimension)); setPreferredSize(new Dimension((mJailDimension + 1) * 25, (mJailDimension + 1) * 25)); createGrid(); }
Source:
<code>public void testMetricsExportedThroughPrometheusEndpoint() { <START> final Counter promCounter = Counter.build("foo_bar","test counter" ) <END> .labelNames("label1", "label2") .register(); final Counter filteredCounter = Counter.build("filtered_foo_bar","test counter" ) .labelNames("label1", "label2") .register(); promCounter.labels("val1", "val2").inc(3); filteredCounter.labels("val1", "val2").inc(6); ResponseEntity<String> metricsResponse = template.getForEntity(getBaseUrl() + "/prometheus?names[]=foo_bar", String.class); assertEquals(HttpStatus.OK, metricsResponse.getStatusCode()); assertTrue(MediaType.TEXT_PLAIN.isCompatibleWith(metricsResponse.getHeaders().getContentType())); List<String> responseLines = Arrays.asList(metricsResponse.getBody().split("\n")); assertThat(responseLines, CustomMatchers.<String>exactlyNItems(1, matchesPattern("foo_bar\\{label1=\"val1\",label2=\"val2\",?\\} 3.0"))); }</code><technical_language>spaces</technical_language>

Target:
public void testMetricsExportedThroughPrometheusEndpoint() { final Counter promCounter = Counter.build("foo_bar", "test counter") .labelNames("label1", "label2") .register(); final Counter filteredCounter = Counter.build("filtered_foo_bar", "test counter") .labelNames("label1", "label2") .register(); promCounter.labels("val1", "val2").inc(3); filteredCounter.labels("val1", "val2").inc(6); ResponseEntity<String> metricsResponse = template.getForEntity(getBaseUrl() + "/prometheus?names[]=foo_bar", String.class); assertEquals(HttpStatus.OK, metricsResponse.getStatusCode()); assertTrue(StringUtils.deleteWhitespace(TextFormat.CONTENT_TYPE_004).equals(metricsResponse.getHeaders().getContentType().toString())); List<String> responseLines = Arrays.asList(metricsResponse.getBody().split("\n")); assertThat(responseLines, CustomMatchers.<String>exactlyNItems(1, matchesPattern("foo_bar\\{label1=\"val1\",label2=\"val2\",?\\} 3.0"))); }
Source:
<code><START> public boolean hasLazyResultSet() { <END> return involvesIO; }</code><technical_language>rename instance var well</technical_language>

Target:
public boolean hasLazyResultSet() { return hasLazyResultSet; }
Source:
<code>void downloadBlob(CloudBlobMetadata cloudBlobMetadata, BlobId blobId, OutputStream outputStream) throws StoreException { try { if (cloudBlobMetadata.getEncryptionOrigin() == EncryptionOrigin.VCR) { ByteBuffer encryptedBlob = ByteBuffer.allocate((int) cloudBlobMetadata.getEncryptedSize()); requestAgent.doWithRetries(() -> { cloudDestination.downloadBlob(blobId, new ByteBufferOutputStream(encryptedBlob)); return null; <START> }, "Download", cloudBlobMetadata.getPartitionId()); <END> ByteBuffer decryptedBlob = cryptoAgent.decrypt(encryptedBlob); outputStream.write(decryptedBlob.array()); } else { requestAgent.doWithRetries(() -> { cloudDestination.downloadBlob(blobId, outputStream); return null; }, "Download", cloudBlobMetadata.getPartitionId()); } } catch (CloudStorageException | GeneralSecurityException | IOException e) { throw new StoreException("Error occured in downloading blob for blobid :" + blobId, StoreErrorCodes.IOError); } }</code><technical_language>Minor: consistent java doc of doWithRetries method, I parameter cloudBlobMetadata.getPartitionId().toPathString()</technical_language>

Target:
void downloadBlob(CloudBlobMetadata cloudBlobMetadata, BlobId blobId, OutputStream outputStream) throws StoreException { try { if (cloudBlobMetadata.getEncryptionOrigin() == EncryptionOrigin.VCR) { ByteBuffer encryptedBlob = ByteBuffer.allocate((int) cloudBlobMetadata.getEncryptedSize()); requestAgent.doWithRetries(() -> { cloudDestination.downloadBlob(blobId, new ByteBufferOutputStream(encryptedBlob)); return null; }, "Download", cloudBlobMetadata.getPartitionId()); ByteBuffer decryptedBlob = cryptoAgent.decrypt(encryptedBlob); outputStream.write(decryptedBlob.array()); } else { requestAgent.doWithRetries(() -> { cloudDestination.downloadBlob(blobId, outputStream); return null; }, "Download", cloudBlobMetadata.getPartitionId()); } } catch (CloudStorageException | GeneralSecurityException | IOException e) { throw new StoreException("Error occurred in downloading blob for blobid :" + blobId, StoreErrorCodes.IOError); } }
Source:
<code>public Person updateFavouritesection(Person person, Long sectionId) { Section section = sectionRepository.findById(sectionId) .orElseThrow(() -> new RestException("Section not found", 404)); <START> person.setFavouritesection(section); <END> return personRepository.saveAndFlush(person); }</code><technical_language>HttpServletResponse.SC_NOT_FOUND</technical_language>

Target:
public Person updateFavouritesection(Person person, Long sectionId) { Section section = sectionRepository.findById(sectionId) .orElseThrow(() -> new RestException("Section not found", HttpServletResponse.SC_NOT_FOUND)); person.setFavouritesection(section); return personRepository.saveAndFlush(person); }
Source:
<code>public void setUp() throws Exception { URL resource = getClass().getResource("/projects/check-maven-plugin-test"); testProjectServiceClient.importProject( workspace.getId(), <START> Paths.get(resource.toURI()), <END> PROJECT_NAME, ProjectTemplates.MAVEN_SPRING); ide.open(workspace); projectExplorer.waitProjectExplorer(); }</code><technical_language>static import improve readability of code</technical_language>

Target:
public void setUp() throws Exception { URL resource = getClass().getResource("/projects/check-maven-plugin-test"); testProjectServiceClient.importProject( workspace.getId(), get(resource.toURI()), PROJECT_NAME, MAVEN_SPRING); ide.open(workspace); projectExplorer.waitProjectExplorer(); }
Source:
<code>public void beforeAll() { seed = Microservices.builder() .metrics(registry()) .discovery( <START> (serviceRegistry, serviceEndpoint) -> <END> new ScalecubeServiceDiscovery(serviceRegistry, serviceEndpoint).start()) .startAwait(); io.scalecube.transport.Address seedAddress = toAddress(seed.discovery().address()); node = Microservices.builder() .metrics(registry()) .discovery( (serviceRegistry, serviceEndpoint) -> new ScalecubeServiceDiscovery(serviceRegistry, serviceEndpoint) .options(opts -> opts.seedMembers(seedAddress)) .start()) .services(services) .startAwait(); LOGGER.info( "Seed address: " + seed.discovery().address() + ", services address: " + node.serviceAddress()); }</code><technical_language>convoluted, do another necessary options</technical_language>

Target:
public void beforeAll() { seed = Microservices.builder() .metrics(registry()) .discovery(ScalecubeServiceDiscovery::new) .startAwait(); io.scalecube.transport.Address seedAddress = toAddress(seed.discovery().address()); node = Microservices.builder() .metrics(registry()) .discovery( (serviceRegistry, serviceEndpoint) -> new ScalecubeServiceDiscovery(serviceRegistry, serviceEndpoint) .options(opts -> opts.seedMembers(seedAddress))) .services(services) .startAwait(); LOGGER.info( "Seed address: " + seed.discovery().address() + ", services address: " + node.serviceAddress()); }
Source:
<code>private void refresh() { Collection<OutputChannelBinding> channels = this.configuration.getOutputChannels(); for (OutputChannelBinding channel : channels) { channel.setTapped(true); } this.adapter.setOutputChannels(channels); <START> this.adapter.stop(); <END> this.adapter.start(); }</code><technical_language>this line above, setOutputChannels()</technical_language>

Target:
private void refresh() { Collection<OutputChannelBinding> channels = this.configuration.getOutputChannels(); for (OutputChannelBinding channel : channels) { channel.setTapped(true); } this.adapter.stop(); this.adapter.setOutputChannels(channels); this.adapter.start(); }
Source:
<code>public String toString() { <START> return hasRevision() ? String.format("%d-%d-%d-%d", getMajorVersion(), getMinorVersion(), getSnapshot(), getRevision()) : String.format("%d-%d-%d", getMajorVersion(), getMinorVersion(), getSnapshot()); <END> }</code><technical_language>dashes instead of dots</technical_language>

Target:
public String toString() { return String.format("%d.%d.%d", getMajorVersion(), getMinorVersion(), getSnapshot()) + (hasRevision() ? ("." + getRevision()) : ""); }
Source:
<code>public void onPistonExtend(BlockPistonExtendEvent e) { <START> if(BlockStorage.check(e.getBlock()) != null) { <END> e.setCancelled(true); } else { for (Block b : e.getBlocks()) { if (BlockStorage.hasBlockInfo(b) || (b.getRelative(e.getDirection()).getType() == Material.AIR && BlockStorage.hasBlockInfo(b.getRelative(e.getDirection())))) { e.setCancelled(true); return; } } } }</code><technical_language>Please BlockStorage#hasBlockInfo() instead. Also, formatting (put a space if)</technical_language>

Target:
public void onPistonExtend(BlockPistonExtendEvent e) { if (BlockStorage.hasBlockInfo(e.getBlock())) { e.setCancelled(true); } else { for (Block b : e.getBlocks()) { if (BlockStorage.hasBlockInfo(b) || (b.getRelative(e.getDirection()).getType() == Material.AIR && BlockStorage.hasBlockInfo(b.getRelative(e.getDirection())))) { e.setCancelled(true); break; } } } }
Source:
<code>public int getNumOpenConnections() { <START> if (!isServerStarted() || this.server.connectionList == null) { <END> return 0; } return server.numConnections; }</code><technical_language>remove this.server.connectionList == null is relevant anymore (also, null)</technical_language>

Target:
public int getNumOpenConnections() { if (!isServerStarted()) { return 0; } return server.numConnections; }
Source:
<code><START> @Test public void testGetBranchFromTag() throws Exception { <END> initRepoWithTag(); FreeStyleProject p = j.createFreeStyleProject(); p.setScm(new MercurialSCM(hgInstallation(), repo.getPath(), MercurialSCM.RevisionType.TAG, "release", null, null, null, false, null)); FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()); MercurialTagAction action = b.getAction(MercurialTagAction.class); assertNotNull(action); assertEquals("stable", action.getBranch()); assertEquals("stable", b.getEnvironment().get("MERCURIAL_REVISION_BRANCH")); }</code><technical_language>BTW for tracking purposes, annotate tests @Issue("JENKINS-10706") (or @Bug(10706) if Issue is in classpath, I remember offhand)</technical_language>

Target:
@Test public void testGetBranchFromTag() throws Exception { initRepoWithTag(); FreeStyleProject p = j.createFreeStyleProject(); p.setScm(new MercurialSCM(hgInstallation(), repo.getPath(), MercurialSCM.RevisionType.TAG, "release", null, null, null, false, null)); FreeStyleBuild b = j.buildAndAssertSuccess(p); MercurialTagAction action = b.getAction(MercurialTagAction.class); assertNotNull(action); assertEquals("stable", action.getBranch()); assertEquals("stable", b.getEnvironment().get("MERCURIAL_REVISION_BRANCH")); }
Source:
<code>private List<Map<String, Object>> getSubjectNotifications(Subject subject) { String userid = subjectIdentity.getUniqueIdentifier(subject); try { <START> String filter = String.format("user = '%s'", userid); <END> List<Map<String, Object>> notificationsList = persistentStore.get( PersistenceType.NOTIFICATION_TYPE.toString(), filter, 0, MAX_PAGE_SIZE); return notificationsList.stream().map(this::mapAttributes).collect(Collectors.toList()); } catch (PersistenceException e) { LOGGER.debug( "PersistenceException while trying to retrieve persisted notifications for user {}", userid, e); } return Collections.emptyList(); }</code><technical_language>This moved try</technical_language>

Target:
private List<Map<String, Object>> getSubjectNotifications(Subject subject) { String userid = subjectIdentity.getUniqueIdentifier(subject); String filter = String.format("user = '%s'", userid); try { List<Map<String, Object>> notificationsList = persistentStore.get( PersistenceType.NOTIFICATION_TYPE.toString(), filter, 0, determineAndRetrieveMaxPageSize()); return notificationsList.stream().map(this::mapAttributes).collect(Collectors.toList()); } catch (PersistenceException e) { LOGGER.debug( "PersistenceException while trying to retrieve persisted notifications for user {}", userid, e); } return Collections.emptyList(); }
Source:
<code>public void display_tags_without_edit() { executeBuild("shared/xoo-sample", "sample", "Sample"); wsClient.wsConnector().call( new PostRequest("api/project_tags/set") .setParam("project", "sample") .setParam("tags", "foo,bar,baz") ); ProjectDashboardPage page = nav.openProjectDashboard("sample"); SelenideElement tags = page.getTags(); <START> tags.$(".tags-list > span").should(hasText("foo, bar, baz")); <END> tags.$("button").shouldNot(exist); tags.$("div.multi-select").shouldNot(exist); }</code><technical_language>hide implementation detail in ProjectDashboardPage class, instead write page .shouldHaveTags("foo", "bar", "baz") .shouldNotBeEditable()</technical_language>

Target:
public void display_tags_without_edit() { executeBuild("shared/xoo-sample", "sample", "Sample"); wsClient.wsConnector().call( new PostRequest("api/project_tags/set") .setParam("project", "sample") .setParam("tags", "foo,bar,baz") ); ProjectDashboardPage page = nav.openProjectDashboard("sample"); page .shouldHaveTags("foo", "bar", "baz") .shouldNotBeEditable(); }
Source:
<code>public void startWsAgent(String workspaceId) throws NotFoundException, MachineException, InterruptedException { final Instance devMachine = machineManager.getDevMachine(workspaceId); try { machineManager.exec(devMachine.getId(), new CommandImpl(WS_AGENT_PROCESS_NAME, wsAgentStartCommandLine, "Arbitrary"), <START> String.format(WS_AGENT_PROCESS_OUTPUT_CHANNEL, workspaceId)); <END> final HttpJsonRequest wsAgentPingRequest = createPingRequest(devMachine); long pingStartTimestamp = System.currentTimeMillis(); boolean pingPassed; do { pingPassed = pingWsAgent(wsAgentPingRequest); Thread.sleep(wsAgentPingDelayMs); } while (!pingPassed && System.currentTimeMillis() - pingStartTimestamp < wsAgentMaxStartTimeMs); } catch (BadRequestException wsAgentLaunchingExc) { throw new MachineException(wsAgentLaunchingExc.getLocalizedMessage(), wsAgentLaunchingExc); } }</code><technical_language>I in this case is public static method for channel. Why: modifier of WS_AGENT_PROCESS_OUTPUT_CHANNEL is public, means want reuse in other place, do operation String.format(WS_AGENT_PROCESS_OUTPUT_CHANNEL, workspaceId). If create method for usage obvious developer miss</technical_language>

Target:
public void startWsAgent(String workspaceId) throws NotFoundException, MachineException, InterruptedException { final Instance devMachine = machineManager.getDevMachine(workspaceId); try { machineManager.exec(devMachine.getId(), new CommandImpl(WS_AGENT_PROCESS_NAME, wsAgentStartCommandLine, "Arbitrary"), getWsAgentProcessOutputChannel(workspaceId)); final HttpJsonRequest wsAgentPingRequest = createPingRequest(devMachine); long pingStartTimestamp = System.currentTimeMillis(); boolean pingPassed; do { pingPassed = pingWsAgent(wsAgentPingRequest); Thread.sleep(wsAgentPingDelayMs); } while (!pingPassed && System.currentTimeMillis() - pingStartTimestamp < wsAgentMaxStartTimeMs); } catch (BadRequestException wsAgentLaunchingExc) { throw new MachineException(wsAgentLaunchingExc.getLocalizedMessage(), wsAgentLaunchingExc); } }
Source:
<code><START> public String getModifiedIndex() { <END> if (!eventIndexName.isEmpty()) { return String.format("%s-%s", eventIndexName, TYPE); } return TYPE; }</code><technical_language>suggestion private String getModifiedIndex() {</technical_language>

Target:
private String getModifiedIndex() { if (!eventIndexName.isEmpty()) { return String.format("%s-%s", eventIndexName, TYPE); } return TYPE; }
Source:
<code>public void testLoadNullType() { Dataset<Object> expected = mock(Dataset.class); when(repo.load("test", Object.class)).thenReturn(expected); URI datasetUri = new URIBuilder(repoUri, "test").build(); <START> Dataset<Object> ds = Datasets.load(datasetUri, null); <END> verify(repo).load("test", Object.class); verifyNoMoreInteractions(repo); verifyNoMoreInteractions(expected); Assert.assertEquals(expected, ds); }</code><technical_language>I thought correct behavior for Datasets reject a null type, default Object.class. This required, right</technical_language>

Target:
public void testLoadNullType() { URI datasetUri = new URIBuilder(repoUri, "test").build(); Datasets.<Object, Dataset<Object>> load(datasetUri, null); }
Source:
<code>protected CreateElementRequest getCreatePartitionChildRequest(CreateElementRequest req) { <START> CreateElementRequest result = new CreateElementRequest(req.getEditingDomain(), findActivity(req.getContainer()), req.getElementType()); <END> result.setParameter(IN_PARTITION, (ActivityPartition)req.getContainer()); result.setContainmentFeature(findActivityFeature(req)); return result; }</code><technical_language>is null's here</technical_language>

Target:
protected CreateElementRequest getCreatePartitionChildRequest(CreateElementRequest req) { if (req == null) { return null; } CreateElementRequest result = new CreateElementRequest(req.getEditingDomain(), findActivity(req.getContainer()), req.getElementType()); result.setParameter(IN_PARTITION, (ActivityPartition)req.getContainer()); result.setContainmentFeature(findActivityFeature(req.getElementType().getEClass())); return result; }
Source:
<code>private ResultQueueEntry<ReadRowsResponse> getNext() throws IOException { ResultQueueEntry<ReadRowsResponse> queueEntry; try { queueEntry = resultQueue.poll(readPartialRowTimeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for next result", e); } if (queueEntry == null) { throw new ScanTimeoutException("Timeout while merging responses."); } if (!queueEntry.isCompletionMarker()) { <START> call.request(1); <END> } return queueEntry; }</code><technical_language>this means, capacity is N response consumption is quick ~N active requests. a problem? end, N -1 requests return result</technical_language>

Target:
private ResultQueueEntry<ReadRowsResponse> getNext() throws IOException { while (!completionMarkerFound.get() && moreCanBeRequested()) { call.request(batchRequestSize); outstandingRequestCount.addAndGet(batchRequestSize); } ResultQueueEntry<ReadRowsResponse> queueEntry; try { queueEntry = resultQueue.poll(readPartialRowTimeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for next result", e); } if (queueEntry == null) { throw new ScanTimeoutException("Timeout while merging responses."); } return queueEntry; }
Source:
<code>public int compareTo(@NotNull FileSystemWALPointer o) { <START> if (this.partNum < o.partNum) { <END> return -1; } if (this.partNum > o.partNum) { return 1; } if (this.offset < o.offset) { return -1; } if (this.offset > o.offset) { return 1; } return 0; }</code><technical_language>Integer.compare this short :-)</technical_language>

Target:
public int compareTo(@NotNull FileSystemWALPointer o) { int partNumComparison = Integer.compare(this.partNum, o.partNum); return partNumComparison == 0 ? Long.compare(this.offset, o.offset) : partNumComparison; }
Source:
<code>public void stop() { try { <START> final Class<?> logManagerClazz = Class.forName("org.apache.logging.log4j.LogManager"); <END> final Field shutdownCallbackRegistryField = Log4jContextFactory.class.getDeclaredField( "shutdownCallbackRegistry" ); shutdownCallbackRegistryField.setAccessible(true); final Log4jShutdown log4jShutdown = (Log4jShutdown) shutdownCallbackRegistryField.get(LogManager.getFactory()); log.info("Shutting down log4j callbacks"); log4jShutdown.runCallbacks(); } catch (ClassNotFoundException | ClassCastException | NoSuchFieldException | IllegalAccessException e) { log.warn(e, "Not attempting log shutdown"); } }</code><technical_language>run check in configure() register Lifecycle module if a log4j LogManager instead</technical_language>

Target:
public void stop() { if (log4jShutdown != null) { log.debug("Shutting down log4j"); log4jShutdown.stop(); } else { log.warn("Log4j shutdown was registered in lifecycle but no shutdown object exists!"); } }
Source:
<code>public Builder exposedPorts(Map<String, ?> exposedPorts) { <START> this.exposedPorts = exposedPorts; <END> return this; }</code><technical_language>create a copy ImmutableMap.copyOf</technical_language>

Target:
public Builder exposedPorts(Map<String, ?> exposedPorts) { this.exposedPorts = ImmutableMap.copyOf(checkNotNull(exposedPorts, "exposedPorts")); return this; }
Source:
<code>public boolean isModified(File path) { long currLastModified; long currSize; Object currFileKey; try { BasicFileAttributes fileAttributes = FS.DETECTED.fileAttributes(path); currLastModified = fileAttributes.lastModifiedTime().toMillis(); currSize = fileAttributes.size(); currFileKey = getFileKey(fileAttributes); } catch (IOException e) { currLastModified = path.lastModified(); currSize = path.length(); currFileKey = MISSING_FILEKEY; } r = new ModificationReason(isSizeChanged(currSize), <START> isFileKeyChanged(currFileKey), isModified(currLastModified)); <END> return r.sizeChanged || r.fileKeyChanged || r.lastModifiedChanged; }</code><technical_language>This means do checks: size, FileKey isModified. skip isModified call size told file changed. performance wise optimal</technical_language>

Target:
public boolean isModified(File path) { long currLastModified; long currSize; Object currFileKey; try { BasicFileAttributes fileAttributes = FS.DETECTED.fileAttributes(path); currLastModified = fileAttributes.lastModifiedTime().toMillis(); currSize = fileAttributes.size(); currFileKey = getFileKey(fileAttributes); } catch (IOException e) { currLastModified = path.lastModified(); currSize = path.length(); currFileKey = MISSING_FILEKEY; } sizeChanged = isSizeChanged(currSize); if (sizeChanged) { return true; } fileKeyChanged = isFileKeyChanged(currFileKey); if (fileKeyChanged) { return true; } lastModifiedChanged = isModified(currLastModified); if (lastModifiedChanged) { return true; } return false; }
Source:
<code>public int compareTo(Broadcast other) { <START> int startTimeComparison = transmissionTime.compareTo(other.transmissionTime); <END> if (startTimeComparison != 0) { return startTimeComparison; } int durationComparison = broadcastDuration.compareTo(other.broadcastDuration); if (durationComparison != 0) { return durationComparison; } if (Strings.isNullOrEmpty(broadcastOn) && !Strings.isNullOrEmpty(other.broadcastOn)) { return -1; } if (!Strings.isNullOrEmpty(broadcastOn) && Strings.isNullOrEmpty(other.broadcastOn)) { return 1; } if (Strings.isNullOrEmpty(broadcastOn) && Strings.isNullOrEmpty(other.broadcastOn)) { return 0; } return broadcastOn.compareTo(other.broadcastOn); }</code><technical_language>a comparison chain (<LINK_0> clearer</technical_language>

Target:
public int compareTo(Broadcast other) { return ComparisonChain.start() .compare(transmissionTime, other.transmissionTime) .compare(broadcastDuration, other.broadcastDuration) .compare(broadcastOn, other.broadcastOn, Ordering.natural().nullsFirst()) .result(); }
Source:
<code>public Reply<?> update(@Named("id") Object id, Request request) { AccessPointRequestDTO dto = request.read(AccessPointRequestDTO.class).as(Json.class); <START> AccessPointRequest accessPointRequest = adapt(dto); <END> repository.update(accessPointRequest); return Reply.with("Successfully updated AP").ok(); }</code><technical_language>please short names apRequest</technical_language>

Target:
public Reply<?> update(@Named("id") Object id, Request request) { AccessPointRequestDTO dto = request.read(AccessPointRequestDTO.class).as(Json.class); AccessPointRequest apRequest = adapt(dto); repository.update(apRequest); return Reply.with("Successfully updated AP").ok(); }
Source:
<code>public void before() { fBot = new SWTWorkbenchBot(); SWTBotUtils.openView(CALLGRAPHDENSITY_ID); SWTBotView view = fBot.viewById(CALLGRAPHDENSITY_ID); assertNotNull(view); fView = view; CallGraphDensityView funcDensityView = UIThreadRunnable.syncExec((Result<CallGraphDensityView>) () -> { IViewPart viewRef = fView.getViewReference().getView(true); return (viewRef instanceof CallGraphDensityView) ? (CallGraphDensityView) viewRef : null; }); assertNotNull(funcDensityView); fTableBot = fView.bot().table(); assertNotNull(fTableBot); fDensityBot = fView.bot().canvas(); assertNotNull(fDensityBot); fDensityViewer = funcDensityView.getDensityViewer(); fLatch = new CountDownLatch(1); fDensityViewer.removeDataListener(fSyncListener); fDensityViewer.addDataListener(fSyncListener); <START> assertNotNull(fDensityViewer); <END> fTableViewer = funcDensityView.getTableViewer(); assertNotNull(fTableViewer); SWTBotUtils.maximize(funcDensityView); fFuncDensityView = funcDensityView; }</code><technical_language>do calling methods fDensityViewer</technical_language>

Target:
public void before() { fBot = new SWTWorkbenchBot(); SWTBotUtils.openView(CALLGRAPHDENSITY_ID); SWTBotView view = fBot.viewById(CALLGRAPHDENSITY_ID); assertNotNull(view); fView = view; CallGraphDensityView funcDensityView = UIThreadRunnable.syncExec((Result<CallGraphDensityView>) () -> { IViewPart viewRef = fView.getViewReference().getView(true); return (viewRef instanceof CallGraphDensityView) ? (CallGraphDensityView) viewRef : null; }); assertNotNull(funcDensityView); fTableBot = fView.bot().table(); assertNotNull(fTableBot); fDensityBot = fView.bot().canvas(); assertNotNull(fDensityBot); fDensityViewer = funcDensityView.getDensityViewer(); assertNotNull(fDensityViewer); fLatch = new CountDownLatch(1); fDensityViewer.removeDataListener(fSyncListener); fDensityViewer.addDataListener(fSyncListener); fTableViewer = funcDensityView.getTableViewer(); assertNotNull(fTableViewer); SWTBotUtils.maximize(funcDensityView); fFuncDensityView = funcDensityView; }
Source:
<code>public void draw(Canvas canvas) { super.draw(canvas); <START> createAndSetBitmap(); <END> }</code><technical_language>this creating a new bitmap draw call? bad for performance. create objects a drawing call, bitmaps expensive</technical_language>

Target:
public void draw(Canvas canvas) { super.draw(canvas); if(boxHeight < previousBoxHeight || boxHeight > previousBoxHeight || boxWidth < previousBoxWidth || boxWidth > previousBoxWidth) { createAndSetBitmap(); } }
Source:
<code>public void addInventoryListener(InventoryListener listener) { try { <START> this.inventoryListenerSupport.inventoryListenerRWLock.writeLock().lock(); <END> status.assertInitialOrStopped(getClass(), "addInventoryListener()"); this.inventoryListenerSupport.inventoryListeners.add(listener); LOG.debugf("Added inventory listener [%s] for endpoint [%s]", listener, getMonitoredEndpoint()); } finally { this.inventoryListenerSupport.inventoryListenerRWLock.writeLock().unlock(); } }</code><technical_language>acquisition of locks (just before) entering try-catch. if wrong, finally block is try unlock a lock acquired. swap lines 247-248. Do for others</technical_language>

Target:
public void addInventoryListener(InventoryListener listener) { this.inventoryListenerSupport.inventoryListenerRWLock.writeLock().lock(); try { status.assertInitialOrStopped(getClass(), "addInventoryListener()"); this.inventoryListenerSupport.inventoryListeners.add(listener); LOG.debugf("Added inventory listener [%s] for endpoint [%s]", listener, getMonitoredEndpoint()); } finally { this.inventoryListenerSupport.inventoryListenerRWLock.writeLock().unlock(); } }
Source:
<code>public Token getAccessToken(final Token requestToken, final Verifier verifier) { final boolean oob = ((ImgurApi) getApi()).isOob(getConfig()); final OAuthRequest request = new OAuthRequest(getApi().getAccessTokenVerb(), getApi().getAccessTokenEndpoint(), this); request.addBodyParameter(OAuthConstants.CLIENT_ID, getConfig().getApiKey()); request.addBodyParameter(OAuthConstants.CLIENT_SECRET, getConfig().getApiSecret()); request.addBodyParameter(OAuthConstants.GRANT_TYPE, oob ? "pin" : OAuthConstants.AUTHORIZATION_CODE); <START> request.addBodyParameter(oob ? "pin" : OAuthConstants.CODE, verifier.getValue()); <END> return getApi().getAccessTokenExtractor().extract(request.send().getBody()); }</code><technical_language>IMO ternary operators. if(oob) { request.addBodyParameter(OAuthConstants.GRANT_TYPE, "pin"); request.addBodyParameter("pin", verifier.getValue()); } else { request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); }</technical_language>

Target:
public Token getAccessToken(final Token requestToken, final Verifier verifier) { final OAuthRequest request = new OAuthRequest(getApi().getAccessTokenVerb(), getApi().getAccessTokenEndpoint(), this); request.addBodyParameter(OAuthConstants.CLIENT_ID, getConfig().getApiKey()); request.addBodyParameter(OAuthConstants.CLIENT_SECRET, getConfig().getApiSecret()); if(ImgurApi.isOob(getConfig())) { request.addBodyParameter(OAuthConstants.GRANT_TYPE, "pin"); request.addBodyParameter("pin", verifier.getValue()); } else { request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); } return getApi().getAccessTokenExtractor().extract(request.send().getBody()); }
Source:
<code><START> private String createResults() <END> { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", "bigint", new ClientTypeSignature("bigint", ImmutableList.of()))), ImmutableList.of(ImmutableList.of(123)), new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }</code><technical_language>put private methods end</technical_language>

Target:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", "bigint", new ClientTypeSignature("bigint", ImmutableList.of()))), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), null, null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }
Source:
<code>public AccountResource.Email parse(AccountResource parent, IdString id) throws AuthException, ResourceNotFoundException { if (!(self.get() instanceof IdentifiedUser)) { throw new AuthException("Authentication required"); } IdentifiedUser s = (IdentifiedUser) self.get(); if (s.getAccountId().get() == parent.getUser().getAccountId().get() || s.getCapabilities().canAdministrateServer()) { for (Account.Id a : byEmailCache.get(id.get())) { <START> if (s.getAccountId().equals(a)) { <END> return new AccountResource.Email(parent.getUser(), id.get()); } } } throw new ResourceNotFoundException(); }</code><technical_language>This is preventing admin user email address of another user</technical_language>

Target:
public AccountResource.Email parse(AccountResource parent, IdString id) throws AuthException, ResourceNotFoundException { if (!(self.get() instanceof IdentifiedUser)) { throw new AuthException("Authentication required"); } IdentifiedUser s = (IdentifiedUser) self.get(); if (s.getAccountId().get() == parent.getUser().getAccountId().get() || s.getCapabilities().canAdministrateServer()) { for (Account.Id a : byEmailCache.get(id.get())) { if (parent.getUser().getAccountId().equals(a)) { return new AccountResource.Email(parent.getUser(), id.get()); } } } throw new ResourceNotFoundException(); }
Source:
<code>private static Headers toOkHttpHeaders(HttpHeaders headers) { <START> Headers.Builder bld = new Headers.Builder(); <END> for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) { String name = e.getKey(); List<String> values = e.getValue(); for (String value : values) { bld.add(name, value); } } return bld.build(); }</code><technical_language>headersBuilder</technical_language>

Target:
private static Headers toOkHttpHeaders(HttpHeaders headers) { Headers.Builder headersBuilder = new Headers.Builder(); if (headers != null) { for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) { String name = e.getKey(); List<String> values = e.getValue(); for (String value : values) { headersBuilder.add(name, value); } } } return headersBuilder.build(); }
Source:
<code>private void copyTemplatePermissions() { PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> templatePermissions = dao.getAllForEntity(getVmTemplateId(), getCurrentUser().getUserId(), false); List<permissions> vmPermissions = new ArrayList<permissions>(); for (permissions templatePermission : templatePermissions) { boolean templateOwnerRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_OWNER.getId()); boolean templateUserRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_USER.getId()); if (templateOwnerRole || templateUserRole) { continue; } vmPermissions.add(new permissions(getCurrentUser().getUserId(), templatePermission.getrole_id(), getVmId(), VdcObjectType.VM)); } if (vmPermissions.size() > 0) { <START> MultiLevelAdministrationHandler.addPermission(vmPermissions.toArray(new permissions[vmPermissions.size()])); <END> } }</code><technical_language>command is transactive, is a need snapshot entity, for compensation in case of failure</technical_language>

Target:
private void copyTemplatePermissions() { PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> templatePermissions = dao.getAllForEntity(getVmTemplateId(), getCurrentUser().getUserId(), false); List<permissions> vmPermissions = new ArrayList<permissions>(); for (permissions templatePermission : templatePermissions) { boolean templateOwnerRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_OWNER.getId()); boolean templateUserRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_USER.getId()); if (templateOwnerRole || templateUserRole) { continue; } vmPermissions.add(new permissions(getCurrentUser().getUserId(), templatePermission.getrole_id(), getVmId(), VdcObjectType.VM)); } if (vmPermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(vmPermissions.toArray(new permissions[vmPermissions.size()])); getCompensationContext().snapshotNewEntities(vmPermissions); } }
Source:
<code>public static Sensor fromString(String sensorName) { for(Sensor sensor: Sensor.values()) { if(sensor.toString().equalsIgnoreCase(sensorName)) { return sensor; } } <START> throw new IllegalArgumentException("Invalid Sensor Name"); <END> }</code><technical_language>throw exception name of invalid sensor for easier debugging</technical_language>

Target:
public static Sensor fromString(String sensorName) { for(Sensor sensor: Sensor.values()) { if(sensor.toString().equalsIgnoreCase(sensorName)) { return sensor; } } throw new IllegalArgumentException(String.format("Invalid sensor name: %s", sensorName)); }
Source:
<code>private SidebarPanel createLeftSidebar() { <START> leftSidebar = new SidebarPanel("leftSidebar", getModel(), detailEditor, () -> <END> getEditorCas(), AnnotationPage.this); leftSidebar.add(new AttributeModifier("style", LambdaModel.of(() -> String .format("flex-basis: %d%%;", getModelObject().getPreferences().getSidebarSize())))); return leftSidebar; }</code><technical_language>do assign leftSidebar in line 209</technical_language>

Target:
private SidebarPanel createLeftSidebar() { SidebarPanel leftSidebar = new SidebarPanel("leftSidebar", getModel(), detailEditor, () -> getEditorCas(), AnnotationPage.this); leftSidebar.add(new AttributeModifier("style", LambdaModel.of(() -> String .format("flex-basis: %d%%;", getModelObject().getPreferences().getSidebarSize())))); return leftSidebar; }
Source:
<code>private static PsiElement getAfterElement(PsiElement element) { PsiElement elementParent = element.getParent(); if (element instanceof GoConstDefinition) { if (((GoConstSpec)elementParent).getExpressionList().size() > 0) { return ((GoConstSpec)elementParent).getExpressionList() .get(((GoConstSpec)elementParent).getExpressionList().size() - 1); } return ((GoConstSpec)elementParent).getType() == null <START> ? ((GoConstSpec)elementParent).getConstDefinitionList() <END> .get(((GoConstSpec)elementParent).getConstDefinitionList().size() - 1) : ((GoConstSpec)elementParent).getType(); } if (((GoVarSpec)elementParent).getExpressionList().size() > 0) { return ((GoVarSpec)elementParent).getExpressionList() .get(((GoVarSpec)elementParent).getExpressionList().size() - 1); } return ((GoVarSpec)elementParent).getType() == null ? ((GoVarSpec)elementParent).getVarDefinitionList() .get(((GoVarSpec)elementParent).getVarDefinitionList().size() - 1) : ((GoVarSpec)elementParent).getType(); }</code><technical_language>ContainerUtil#getLastItem</technical_language>

Target:
private static PsiElement getAfterElement(PsiElement element) { PsiElement elementParent = element.getParent(); if (element instanceof GoConstDefinition) { if (!((GoConstSpec)elementParent).getExpressionList().isEmpty()) { return ContainerUtil.getLastItem(((GoConstSpec)elementParent).getExpressionList()); } return ((GoConstSpec)elementParent).getType() == null ? ContainerUtil.getLastItem(((GoConstSpec)elementParent).getConstDefinitionList()) : ((GoConstSpec)elementParent).getType(); } if (!((GoVarSpec)elementParent).getExpressionList().isEmpty()) { return ContainerUtil.getLastItem(((GoVarSpec)elementParent).getExpressionList()); } return ((GoVarSpec)elementParent).getType() == null ? ContainerUtil.getLastItem(((GoVarSpec)elementParent).getVarDefinitionList()) : ((GoVarSpec)elementParent).getType(); }
Source:
<code>public void switchToConversationTab() { <START> if (isCurrentUrlIssue() && GitHubURL.isPullRequestLoaded(getCurrentUrl())) { <END> driver.findElement(By.xpath(" } }</code><technical_language>do need check here? called in cases this method is called</technical_language>

Target:
public void switchToConversationTab() { if (GitHubURL.isPullRequestLoaded(getCurrentUrl())) { driver.findElement(By.xpath(" } }