auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void configure(Binder binder) { String typeName = MomentSketchAggregatorFactory.TYPE_NAME; <START> if (ComplexMetrics.getSerdeForType(typeName) == null) { <END> ComplexMetrics.registerSerde(typeName, new MomentSketchComplexMetricSerde()); } }</code><technical_language>please replace this boilerplate pattern a single method registerSerde(String, Supplier<ComplexMetricSerde>) thoughout code</technical_language>

Target:
public void configure(Binder binder) { ComplexMetrics.registerSerde( MomentSketchAggregatorFactory.TYPE_NAME, MomentSketchComplexMetricSerde::new ); }
Source:
<code>protected void configure() { <START> Names.bindProperties(binder(), Collections.singletonMap(Constants.PROPERTY_PRETTY_PRINT_PAYLOADS, "true")); <END> bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); }</code><technical_language>is need bind this. is bound context users able configure this property creating it. remove this line</technical_language>

Target:
protected void configure() { }
Source:
<code>public HighAvailabilityServices createHAServices(Configuration configuration, Executor executor) throws Exception { return new KubernetesHaServices( <START> KubeClientFactory.fromConfiguration(configuration), <END> executor, configuration, BlobUtils.createBlobStoreFromConfig(configuration)); }</code><technical_language>IIUC, this means create 2 KubeClients in JobManager process? a problem</technical_language>

Target:
public HighAvailabilityServices createHAServices(Configuration configuration, Executor executor) throws Exception { final KubeClientFactory kubeClientFactory = new DefaultKubeClientFactory(); return new KubernetesHaServices( kubeClientFactory.fromConfiguration(configuration, executor), executor, configuration, BlobUtils.createBlobStoreFromConfig(configuration)); }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); <START> sb.append("\t\tDiffie-Hellman public key: "); <END> sb.append(getPublicKey().toString()); sb.append(StringUtil.lineSeparator()); return sb.toString(); }</code><technical_language>EC Diffie-Hellman public</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); if (hint.equals("")) { sb.append("\t\tPSK Identity Hint: ").append("psk hint not present"); } else { sb.append("\t\tPSK Identity Hint: ").append(hint); } sb.append("\t\tEC Diffie-Hellman public key: "); sb.append(getPublicKey().toString()); sb.append(StringUtil.lineSeparator()); return sb.toString(); }
Source:
<code>private boolean fullyDelete(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File <START> children1 : <END> children) { fullyDelete(new File(file, children1.getName())); } } } if (file.delete()) { return true; } return !file.exists(); }</code><technical_language>child</technical_language>

Target:
private boolean fullyDelete(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { fullyDelete(new File(file, child.getName())); } } } if (file.delete()) { return true; } return !file.exists(); }
Source:
<code>public ResponseEntity<AppUserDTO> activateUser(@PathVariable("code") String code) { UserRegistration userRegistration = userRegistrationDao.findByCode(code); if (userRegistration == null) { throw new BadRequestException("Invalid registration code"); } else { AppUser user = userRegistration.getUser(); user.setActivated(true); user.setUserRegistration(null); appUserDao.saveAndFlush(user); <START> userRegistrationDao.delete(userRegistration.getId()); <END> return new ResponseEntity<>(appUserConverter.convertTo(user), HttpStatus.OK); } }</code><technical_language>fixed orphanRemoval = true</technical_language>

Target:
public ResponseEntity<AppUserDTO> activateUser(@PathVariable("code") String code) { UserRegistration userRegistration = userRegistrationDao.findByCode(code); if (userRegistration == null) { throw new BadRequestException("Invalid registration code"); } else { AppUser user = userRegistration.getUser(); user.setActivated(true); user.setUserRegistration(null); appUserDao.saveAndFlush(user); return new ResponseEntity<>(appUserConverter.convertTo(user), HttpStatus.OK); } }
Source:
<code>public Response<?> apply(ReviewerResource rsrc, Input input) throws AuthException, ResourceNotFoundException, OrmException, IOException { ChangeControl control = rsrc.getControl(); Change.Id changeId = rsrc.getChange().getId(); ReviewDb db = dbProvider.get(); StringBuilder msg = new StringBuilder(); <START> msg.append("Remove the following approvals:\n\n"); <END> db.changes().beginTransaction(changeId); try { List<PatchSetApproval> del = Lists.newArrayList(); for (PatchSetApproval a : approvals(db, rsrc)) { if (control.canRemoveReviewer(a)) { del.add(a); msg.append("* ") .append(a.getLabel()).append(" ").append(a.getValue()) .append(" by ").append(userFactory.create(a.getAccountId()).getNameEmail()) .append("\n"); } else { throw new AuthException("delete not permitted"); } } if (del.isEmpty()) { throw new ResourceNotFoundException(); } ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db); db.patchSetApprovals().delete(del); db.commit(); ChangeMessage changeMessage = new ChangeMessage(new ChangeMessage.Key(rsrc.getChange().getId(), ChangeUtil.messageUUID(db)), ((IdentifiedUser) control.getCurrentUser()).getAccountId(), TimeUtil.nowTs(), rsrc.getChange().currentPatchSetId()); changeMessage.setMessage(msg.toString()); db.changeMessages().insert(Collections.singleton(changeMessage)); } finally { db.rollback(); } indexer.index(rsrc.getChange()); return Response.none(); }</code><technical_language>this tense, "Removed approvals:"</technical_language>

Target:
public Response<?> apply(ReviewerResource rsrc, Input input) throws AuthException, ResourceNotFoundException, OrmException, IOException { ChangeControl control = rsrc.getControl(); Change.Id changeId = rsrc.getChange().getId(); ReviewDb db = dbProvider.get(); StringBuilder msg = new StringBuilder(); msg.append("Removed the following approvals:\n\n"); db.changes().beginTransaction(changeId); try { List<PatchSetApproval> del = Lists.newArrayList(); for (PatchSetApproval a : approvals(db, rsrc)) { if (control.canRemoveReviewer(a)) { del.add(a); if (a.getValue() != 0) { msg.append("* ") .append(a.getLabel()).append(formatLabelValue(a.getValue())) .append(" by ").append(userFactory.create(a.getAccountId()).getNameEmail()) .append("\n"); } } else { throw new AuthException("delete not permitted"); } } if (del.isEmpty()) { throw new ResourceNotFoundException(); } ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db); db.patchSetApprovals().delete(del); ChangeMessage changeMessage = new ChangeMessage(new ChangeMessage.Key(rsrc.getChange().getId(), ChangeUtil.messageUUID(db)), ((IdentifiedUser) control.getCurrentUser()).getAccountId(), TimeUtil.nowTs(), rsrc.getChange().currentPatchSetId()); changeMessage.setMessage(msg.toString()); db.changeMessages().insert(Collections.singleton(changeMessage)); db.commit(); } finally { db.rollback(); } indexer.index(rsrc.getChange()); return Response.none(); }
Source:
<code>public void showCoreContextMenu(Context context, View v) { PopupMenu popup = new PopupMenu(this, v); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(android.view.MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_core: showDialog(R.id.DIALOG_ADD_CORE); break; case R.id.menu_edit_core: if (dbHelper.hasCores()) { showDialog(R.id.DIALOG_EDIT_CORE); } break; case R.id.menu_delete_core: if (dbHelper.hasCores()) { showDialog(R.id.DIALOG_DELETE_CORE); } updateCoreSpinner(); break; } return false; } }); popup.inflate(R.menu.context_core); if (core.getCount()==0) { popup.getMenu().getItem(1).setEnabled(false); <START> popup.getMenu().getItem(2).setEnabled(false); <END> } popup.show(); }</code><technical_language>pretty brittle item position here, if menu layout changes this break</technical_language>

Target:
public void showCoreContextMenu(Context context, View v) { PopupMenu popup = new PopupMenu(this, v); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(android.view.MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_core: showDialog(R.id.DIALOG_ADD_CORE); break; case R.id.menu_edit_core: if (dbHelper.hasCores()) { showDialog(R.id.DIALOG_EDIT_CORE); } break; case R.id.menu_delete_core: if (dbHelper.hasCores()) { showDialog(R.id.DIALOG_DELETE_CORE); } updateCoreSpinner(); break; } return false; } }); popup.inflate(R.menu.context_core); if (core.getCount()==0) { popup.getMenu().findItem(R.id.menu_edit_core).setEnabled(false); popup.getMenu().findItem(R.id.menu_delete_core).setEnabled(false); } popup.show(); }
Source:
<code>public FilteredAggregatorFactory( @JsonProperty("name") String name, @JsonProperty("aggregator") AggregatorFactory delegate, @JsonProperty("filter") DimFilter filter ) { Preconditions.checkNotNull(delegate); Preconditions.checkNotNull(filter); Preconditions.checkArgument( <START> filter instanceof SelectorDimFilter || filter instanceof NotDimFilter, <END> "FilteredAggregator currently only supports filters of type selector and not" ); this.name = name; this.delegate = delegate; this.filter = filter; }</code><technical_language>need add a check notfilter contains a selector filter</technical_language>

Target:
public FilteredAggregatorFactory( @JsonProperty("name") String name, @JsonProperty("aggregator") AggregatorFactory delegate, @JsonProperty("filter") DimFilter filter ) { Preconditions.checkNotNull(delegate); Preconditions.checkNotNull(filter); Preconditions.checkArgument( filter instanceof SelectorDimFilter || (filter instanceof NotDimFilter && ((NotDimFilter) filter).getField() instanceof SelectorDimFilter), "FilteredAggregator currently only supports filters of type 'selector' and their negation" ); this.name = name; this.delegate = delegate; this.filter = filter; }
Source:
<code>public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("<LINK_0>"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { <START> throw new OvenException(); <END> } }</code><technical_language>include cause</technical_language>

Target:
public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("<LINK_0>"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { throw new OvenException(ex); } }
Source:
<code>public void findAll() throws Exception { final Operator operator = new Operator("id", "name", "description", "domainName", "friendlyName"); <START> final List<Operator> operators = Lists.newArrayList(operator); <END> context.checking(new Expectations() {{ oneOf(repository).findAll(); will(returnValue(operators)); }}); Reply<?> reply = service.findAll(); List<OperatorDTO> expected = Lists.newArrayList(new OperatorDTO("id", "name", "description", "domainName", "friendlyName")); assertThat(reply, containsValue(expected)); assertThat(reply, isOk()); }</code><technical_language>java final List<Operator> operators = Lists.newArrayList( new Operator("id", "name", "description", "domainName", "friendlyName"); );</technical_language>

Target:
public void findAll() throws Exception { final Operator operator = new Operator("id1", "name1", "description1", "domainName1", "friendlyName1"); final Operator anotherOperator = new Operator("id2", "name2", "description2", "domainName2", "friendlyName2"); final List<Operator> operators = Lists.newArrayList(operator, anotherOperator); context.checking(new Expectations() {{ oneOf(repository).findAll(); will(returnValue(operators)); }}); Reply<?> reply = service.findAll(); List<OperatorDTO> expected = Lists.newArrayList( new OperatorDTO("id1", "name1", "description1", "domainName1", "friendlyName1"), new OperatorDTO("id2", "name2", "description2", "domainName2", "friendlyName2") ); assertThat(reply, containsValue(expected)); assertThat(reply, isOk()); }
Source:
<code>private void refresh() { Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { com.google.gerrit.client.account.Util.ACCOUNT_SEC.myGroups(new GerritCallback<List<AccountGroup>>() { <START> public void onSuccess(List<AccountGroup> myGroups) { <END> boolean userHasOwnRight = Util.hasOwnRight(result, myGroups); enableForm(userHasOwnRight); saveProject.setVisible(userHasOwnRight); saveProject.setEnabled(false); display(result); } }); } }); }</code><technical_language>Again, please a recursive RPC here, instead add necessary data ProjectDetail object</technical_language>

Target:
private void refresh() { Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(result.canModifyData); saveProject.setVisible(result.canModifyData); saveProject.setEnabled(false); display(result); } }); }
Source:
<code>public Map<String, Set<MentionNotificationParameter>> getMentions() { return this.mentions; <START> } <END></code><technical_language>doc needs keys of map for. a quicklook I type of user sure</technical_language>

Target:
public Map<String, Set<MentionNotificationParameter>> getMentions() { return this.unmodifiableMentions; }
Source:
<code>public Builder(InternalEnvironment internalEnvironment) { this.internalEnvironment = internalEnvironment; <START> setType(TYPE); <END> }</code><technical_language>set type initialization</technical_language>

Target:
public Builder(InternalEnvironment internalEnvironment) { this.internalEnvironment = internalEnvironment; }
Source:
<code>public void testHostDiscoveryFromSourceCloses() throws Exception { Listenable<ConnectionStateListener> connectionStateListener = mock(Listenable.class); CuratorFramework curatorFramework = mock(CuratorFramework.class); <START> CuratorConnection connection = mock(CuratorConnection.class); <END> HostDiscoverySource closingHostDiscoverySource = mock(HostDiscoverySource.class); HostDiscovery closedHostDiscovery = mock(HostDiscovery.class); HostDiscoverySource nonClosingHostDiscoverySource = mock(HostDiscoverySource.class); HostDiscovery unclosedHostDiscovery = mock(HostDiscovery.class); when(curatorFramework.getState()).thenReturn(CuratorFrameworkState.STARTED); when(curatorFramework.getConnectionStateListenable()).thenReturn(connectionStateListener); when(connection.getCurator()).thenReturn(curatorFramework); when(closingHostDiscoverySource.forService(anyString())).thenReturn(closedHostDiscovery); when(nonClosingHostDiscoverySource.forService(anyString())).thenReturn(unclosedHostDiscovery); ServicePool<Service> servicePool = (ServicePool<Service>) ServicePoolBuilder.create(Service.class) .withServiceFactory(_serviceFactory) .withCachingPolicy(_cachingPolicy) .withHostDiscoverySource(closingHostDiscoverySource) .withHostDiscoverySource(nonClosingHostDiscoverySource) .withPartitionFilter(_partitionFilter) .build(); servicePool.close(); verify(closedHostDiscovery).close(); verify(unclosedHostDiscovery, never()).close(); }</code><technical_language>I feel changed tack some point that, I deleted declarations when() conditions them, test worked fine for me. totally done I mocked out a bunch of curator stuff I stopped NPEs, I necessary for some version of test (maybe creating a ZooKeeperHostDiscovery before?), unused in current incarnation</technical_language>

Target:
public void testHostDiscoveryFromSourceCloses() throws Exception { HostDiscoverySource closingHostDiscoverySource = mock(HostDiscoverySource.class); HostDiscovery closedHostDiscovery = mock(HostDiscovery.class); HostDiscoverySource nonClosingHostDiscoverySource = mock(HostDiscoverySource.class); HostDiscovery unclosedHostDiscovery = mock(HostDiscovery.class); when(closingHostDiscoverySource.forService(anyString())).thenReturn(closedHostDiscovery); when(nonClosingHostDiscoverySource.forService(anyString())).thenReturn(unclosedHostDiscovery); ServicePool<Service> servicePool = (ServicePool<Service>) ServicePoolBuilder.create(Service.class) .withServiceFactory(_serviceFactory) .withCachingPolicy(_cachingPolicy) .withHostDiscoverySource(closingHostDiscoverySource) .withHostDiscoverySource(nonClosingHostDiscoverySource) .withPartitionFilter(_partitionFilter) .build(); servicePool.close(); verify(closedHostDiscovery).close(); verify(unclosedHostDiscovery, never()).close(); }
Source:
<code>private static VdsNumaNode getNumaNodeWithLowerCpuIds(VdsNumaNode mostPinnedPnumaNode, VdsNumaNode currNode) { if (mostPinnedPnumaNode != null && <START> !mostPinnedPnumaNode.getCpuIds().isEmpty() <END> && Collections.min(currNode.getCpuIds()) < Collections.min(mostPinnedPnumaNode.getCpuIds())) { return currNode; } else { return mostPinnedPnumaNode; } }</code><technical_language>simpler handle this case right #927 - if numOfPinnedCpus block of #930-#931 is irrelevant #933-#934 is interesting</technical_language>

Target:
private static VdsNumaNode getNumaNodeWithLowerCpuIds(VdsNumaNode mostPinnedPnumaNode, VdsNumaNode currNode) { return Objects.compare(currNode.getCpuIds(), mostPinnedPnumaNode.getCpuIds(), Comparator.comparing(Collections::min)) < 0 ? currNode: mostPinnedPnumaNode; }
Source:
<code><START> private AutoCloseable setPageSetting(WizardProjectsImportPage wpip, String settingName, boolean settingValue) { <END> wpip.saveWidgetValues(); IDialogSettings dialogSettings = wpip.getWizard().getDialogSettings(); boolean originalValue = dialogSettings.getBoolean(settingName); dialogSettings.put(settingName, settingValue); wpip.restoreWidgetValues(); return () -> { dialogSettings.put(settingName, originalValue); wpip.restoreWidgetValues(); }; }</code><technical_language>Nice do this</technical_language>

Target:
private AutoCloseable setPageSetting(WizardProjectsImportPage wpip, String settingName, boolean settingValue) { IDialogSettings dialogSettings = wpip.getWizard().getDialogSettings(); wpip.saveWidgetValues(); boolean originalValue = dialogSettings.getBoolean(settingName); dialogSettings.put(settingName, settingValue); wpip.restoreWidgetValues(); return () -> { dialogSettings.put(settingName, originalValue); wpip.restoreWidgetValues(); }; }
Source:
<code>public boolean fetch( BuckEventBus eventBus, URI uri, Optional<PasswordAuthentication> authentication, Path output ) throws IOException { if (!("https".equals(uri.getScheme()) || "http".equals(uri.getScheme()))) { return false; } DownloadEvent.Started started = DownloadEvent.started(uri); eventBus.post(started); try { HttpURLConnection connection = createConnection(uri); if (authentication.isPresent()) { PasswordAuthentication p = authentication.get(); String authStr = p.getUserName() + ":" + new String(p.getPassword()); String authEncoded = BaseEncoding.base64().encode(authStr.getBytes()); <START> connection.addRequestProperty("Authorization", "Basic " + authEncoded); <END> } if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) { LOG.info("Unable to download %s: %s", uri, connection.getResponseMessage()); return false; } long contentLength = connection.getContentLengthLong(); try (InputStream is = new BufferedInputStream(connection.getInputStream()); OutputStream os = new BufferedOutputStream(Files.newOutputStream(output))) { long read = 0; while (true) { int r = is.read(); read++; if (r == -1) { break; } if (read % PROGRESS_REPORT_EVERY_N_BYTES == 0) { eventBus.post(new DownloadProgressEvent(uri, contentLength, read)); } os.write(r); } } return true; } finally { eventBus.post(DownloadEvent.finished(started)); } }</code><technical_language>add a check for connection HTTPS? Sending passwords in clear text sounds pretty wrong</technical_language>

Target:
public boolean fetch( BuckEventBus eventBus, URI uri, Optional<PasswordAuthentication> authentication, Path output ) throws IOException { if (!("https".equals(uri.getScheme()) || "http".equals(uri.getScheme()))) { return false; } DownloadEvent.Started started = DownloadEvent.started(uri); eventBus.post(started); try { HttpURLConnection connection = createConnection(uri); if (authentication.isPresent()) { if ("https".equals(uri.getScheme()) && connection instanceof HttpsURLConnection) { PasswordAuthentication p = authentication.get(); String authStr = p.getUserName() + ":" + new String(p.getPassword()); String authEncoded = BaseEncoding.base64().encode(authStr.getBytes()); connection.addRequestProperty("Authorization", "Basic " + authEncoded); } else { LOG.info("Refusing to send basic authentication over plain http."); return false; } } if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) { LOG.info("Unable to download %s: %s", uri, connection.getResponseMessage()); return false; } long contentLength = connection.getContentLengthLong(); try (InputStream is = new BufferedInputStream(connection.getInputStream()); OutputStream os = new BufferedOutputStream(Files.newOutputStream(output))) { long read = 0; while (true) { int r = is.read(); read++; if (r == -1) { break; } if (read % PROGRESS_REPORT_EVERY_N_BYTES == 0) { eventBus.post(new DownloadProgressEvent(uri, contentLength, read)); } os.write(r); } } return true; } finally { eventBus.post(DownloadEvent.finished(started)); } }
Source:
<code>public void addArtifact(Artifact artifact) { <START> Artifact artifactParent = Optional.of(artifact).map(a -> a.getHierarchyParent()).orElse(artifact); <END> artifacts.remove(artifactParent); artifacts.add(artifactParent); }</code><technical_language>Cosmetic: extract Optional.of(artifact).map(a -> a.getHierarchyParent()).orElse(artifact) a private method (i.e. private getArtifactHierarchyParent()?) re-use in removeArtifact avoid future issues this logic needs changed (i.e. forgetting apply change in removeArtifact)</technical_language>

Target:
public void addArtifact(Artifact artifact) { artifacts.remove(artifact); artifacts.add(artifact); }
Source:
<code>public void send(Interest<?, ?> interest, Object inventoryEvent) { InventoryEvent<?> message = InventoryEvent.from(interest.getAction(), inventoryEvent); try { <START> ProducerConnectionContext producerConnectionContext = init(); <END> Map<String, String> headers = toHeaders(interest); messageProcessor.send(producerConnectionContext, message, headers); Log.LOG.debugf("Sent message %s with headers %s to %s", message, headers, producerConnectionContext.getDestination()); } catch (JMSException | NamingException e) { LOG.failedToSendMessage(message.toString()); } }</code><technical_language>this leak connections something? sure, asking if re-initializing for message is want here</technical_language>

Target:
public void send(Interest<?, ?> interest, Object inventoryEvent) { InventoryEvent<?> message = InventoryEvent.from(interest.getAction(), inventoryEvent); try { init(); Map<String, String> headers = toHeaders(interest); messageProcessor.send(producerConnectionContext, message, headers); Log.LOG.debugf("Sent message %s with headers %s to %s", message, headers, producerConnectionContext.getDestination()); } catch (JMSException e) { LOG.failedToSendMessage(message.toString()); } }
Source:
<code>public ContainerHeartbeatResponse requestHeartbeat() { <START> String queryUrl = String.format(heartbeatEndpoint, coordinatorUrl, executionEnvContainerId); <END> ObjectMapper mapper = new ObjectMapper(); ContainerHeartbeatResponse response; String reply = ""; try { reply = httpGet(new URL(queryUrl)); log.debug("Container Heartbeat got response {}", reply); response = mapper.readValue(reply, ContainerHeartbeatResponse.class); return response; } catch (IOException e) { log.error("Error in container heart beat protocol. Query url: response: {}", queryUrl, reply); response = new ContainerHeartbeatResponse(); response.setAlive(false); return response; } }</code><technical_language>simpler do a one-shot initialization of queryUrl in constructor potentially a final variable</technical_language>

Target:
public ContainerHeartbeatResponse requestHeartbeat() { ObjectMapper mapper = new ObjectMapper(); ContainerHeartbeatResponse response; String reply = ""; try { reply = httpGet(new URL(heartbeatEndpoint)); LOG.debug("Container Heartbeat got response {}", reply); response = mapper.readValue(reply, ContainerHeartbeatResponse.class); return response; } catch (IOException e) { LOG.error("Error in container heart beat protocol. Query url: response: {}", heartbeatEndpoint, reply); } response = new ContainerHeartbeatResponse(false); return response; }
Source:
<code>protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); if (getVmTemplate().getUsbPolicy() != getVm().getUsbPolicy()) { getVmDeviceUtils().updateUsbSlots(getVmTemplate(), getVm().getStaticData()); <START> } <END> if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }</code><technical_language>part of VmDeviceUtils#copyVmDevices ? usb-specific handling for creating a vm based blank template. drawback I of is 'copyVmDevices' suggests is copying this method is polluted removal addition of devices I care aspect</technical_language>

Target:
protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }
Source:
<code>private StackPane getActivationPane(BibEntry entry) { StackPane activation = new StackPane(); activation.setId("citation-relation-tab"); VBox alignment = new VBox(); alignment.setId("activation-alignment"); alignment.setFillWidth(true); alignment.setAlignment(Pos.BASELINE_CENTER); Label infoLabel = new Label(Localization.lang("The search is currently deactivated")); Button activate = new Button(Localization.lang("Activate")); activate.setOnAction( event -> { <START> JabRefPreferences prefs = JabRefPreferences.getInstance(); <END> prefs.putBoolean(JabRefPreferences.ACTIVATE_CITATIONRELATIONS, true); dialogService.notify(Localization.lang("Please restart JabRef for preferences to take effect.")); bindToEntry(entry); }); activate.setDefaultButton(true); alignment.getChildren().addAll(infoLabel, activate); activation.getChildren().add(alignment); return activation; }</code><technical_language>Related Articles tab wrong. follow dependency infection principle, e.g. dependencies passed constructor. This allows mock in tests especially for preferences. For moment I leave is, currently working restructuring preferences/preferences service</technical_language>

Target:
private StackPane getActivationPane(BibEntry entry) { StackPane activation = new StackPane(); activation.setId("citation-relation-tab"); VBox alignment = new VBox(); alignment.setId("activation-alignment"); alignment.setFillWidth(true); alignment.setAlignment(Pos.BASELINE_CENTER); Label infoLabel = new Label(Localization.lang("The search is currently deactivated.")); Button activate = new Button(Localization.lang("Activate")); activate.setOnAction( event -> { JabRefPreferences prefs = JabRefPreferences.getInstance(); prefs.putBoolean(JabRefPreferences.ACTIVATE_CITATIONRELATIONS, true); dialogService.notify(Localization.lang("Please restart JabRef for preferences to take effect.")); bindToEntry(entry); }); activate.setDefaultButton(true); alignment.getChildren().addAll(infoLabel, activate); activation.getChildren().add(alignment); return activation; }
Source:
<code>@Before public void init() throws SQLException { StringBuilder url = new StringBuilder("jdbc:mysql://"); url.append(envOr("MYSQL_HOST", "127.0.0.1")); url.append(":").append(envOr("MYSQL_TCP_PORT", 3306)); String db = envOr("MYSQL_DB", null); if (db != null) url.append("/").append(db); url.append("?statementInterceptors=").append(TracingStatementInterceptor.class.getName()); url.append("&zipkinServiceName=").append("myservice"); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl(url.toString()); <START> dataSource.setUser(System.getenv("MYSQL_USER")); <END> assumeTrue("Minimally, the environment variable MYSQL_USER must be set", dataSource.getUser() != null); dataSource.setPassword(envOr("MYSQL_PASS", "")); connection = dataSource.getConnection(); spans.clear(); }</code><technical_language>ps try this? I CI (ex MYSQL_USER=root ./mvnw clean install)</technical_language>

Target:
@Before public void init() throws SQLException { StringBuilder url = new StringBuilder("jdbc:mysql://"); url.append(envOr("MYSQL_HOST", "127.0.0.1")); url.append(":").append(envOr("MYSQL_TCP_PORT", 3306)); String db = envOr("MYSQL_DB", null); if (db != null) url.append("/").append(db); url.append("?statementInterceptors=").append(TracingStatementInterceptor.class.getName()); url.append("&zipkinServiceName=").append("myservice"); url.append("&serverTimezone=").append("UTC"); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl(url.toString()); dataSource.setUser(System.getenv("MYSQL_USER")); assumeTrue("Minimally, the environment variable MYSQL_USER must be set", dataSource.getUser() != null); dataSource.setPassword(envOr("MYSQL_PASS", "")); connection = dataSource.getConnection(); spans.clear(); }
Source:
<code>private List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions) { int numReplicaGroups = instancePartitions.getNumReplicaGroups(); if (_isDimTable) { <START> <END> return SegmentAssignmentUtils.getInstancesForDimTable(instancePartitions); } if (numReplicaGroups == 1) { return SegmentAssignmentUtils .assignSegmentWithoutReplicaGroup(currentAssignment, instancePartitions, _replication); } else { int partitionId; if (_partitionColumn == null) { partitionId = 0; } else { OfflineSegmentZKMetadata segmentZKMetadata = ZKMetadataProvider .getOfflineSegmentZKMetadata(_helixManager.getHelixPropertyStore(), _offlineTableName, segmentName); Preconditions .checkState(segmentZKMetadata != null, "Failed to find segment ZK metadata for segment: %s of table: %s", segmentName, _offlineTableName); int segmentPartitionId = getPartitionId(segmentZKMetadata); int numPartitions = instancePartitions.getNumPartitions(); partitionId = segmentPartitionId % numPartitions; } return SegmentAssignmentUtils.assignSegmentWithReplicaGroup(currentAssignment, instancePartitions, partitionId); } }</code><technical_language>empty line</technical_language>

Target:
private List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions) { int numReplicaGroups = instancePartitions.getNumReplicaGroups(); if (numReplicaGroups == 1) { return SegmentAssignmentUtils .assignSegmentWithoutReplicaGroup(currentAssignment, instancePartitions, _replication); } else { int partitionId; if (_partitionColumn == null) { partitionId = 0; } else { OfflineSegmentZKMetadata segmentZKMetadata = ZKMetadataProvider .getOfflineSegmentZKMetadata(_helixManager.getHelixPropertyStore(), _offlineTableName, segmentName); Preconditions .checkState(segmentZKMetadata != null, "Failed to find segment ZK metadata for segment: %s of table: %s", segmentName, _offlineTableName); int segmentPartitionId = getPartitionId(segmentZKMetadata); int numPartitions = instancePartitions.getNumPartitions(); partitionId = segmentPartitionId % numPartitions; } return SegmentAssignmentUtils.assignSegmentWithReplicaGroup(currentAssignment, instancePartitions, partitionId); } }
Source:
<code>public void start(Stage primaryStage) throws Exception { <START> stage = primaryStage; <END> stage.setTitle(DNAINATOR); stage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); setDimensions(); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); stage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } stage.show(); }</code><technical_language>Right now, setting window screen's dimensions. This is a "truly maximized" window. try setting maximized setting window's dimensions</technical_language>

Target:
public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); setDimensions(primaryStage); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); }
Source:
<code>public void corruptedScoreRulesTest() { setSolverConfigCalculatorClass(TestdataCorruptedDifferentValuesCalculator.class); switch (environmentMode) { case FULL_ASSERT: case NON_INTRUSIVE_FULL_ASSERT: assertIllegalStateExceptionWhileSolving("not the uncorruptedScore"); break; case FAST_ASSERT: assertIllegalStateExceptionWhileSolving("Score corruption analysis could not be generated "); break; <START> case REPRODUCIBLE: <END> case NON_REPRODUCIBLE: case PRODUCTION: break; default: throw new AssertionError("Missing case for " + environmentMode); } }</code><technical_language>is a weird inconsistency. start String a capital letter, not</technical_language>

Target:
public void corruptedScoreRulesTest() { setSolverConfigCalculatorClass(TestdataCorruptedDifferentValuesCalculator.class); switch (environmentMode) { case FULL_ASSERT: case NON_INTRUSIVE_FULL_ASSERT: assertIllegalStateExceptionWhileSolving("not the uncorruptedScore"); break; case FAST_ASSERT: assertIllegalStateExceptionWhileSolving("Score corruption analysis could not be generated "); break; case REPRODUCIBLE: case NON_REPRODUCIBLE: case PRODUCTION: break; default: Assertions.fail("Environment mode not covered: " + environmentMode); } }
Source:
<code>public void saveAnswers(@Scope(OAuthScope.QUESTIONS_READ) final AccessToken accessToken, @QueryParam("account_question_id") final Long accountQuestionId, @Valid final List<Choice> choice) { LOGGER.debug("Saving answer for account id = {}", accessToken.accountId); <START> Optional<Integer> questionIdOptional = choice.get(0).questionId; <END> Integer questionId = 0; if (questionIdOptional.isPresent()) { questionId = questionIdOptional.get(); } this.questionProcessor.saveResponse(accessToken.accountId, questionId, accountQuestionId, choice); }</code><technical_language>final</technical_language>

Target:
public void saveAnswers(@Scope(OAuthScope.QUESTIONS_READ) final AccessToken accessToken, @QueryParam("account_question_id") final Long accountQuestionId, @Valid final List<Choice> choice) { LOGGER.debug("Saving answer for account id = {}", accessToken.accountId); final Optional<Integer> questionIdOptional = choice.get(0).questionId; Integer questionId = 0; if (questionIdOptional.isPresent()) { questionId = questionIdOptional.get(); } this.questionProcessor.saveResponse(accessToken.accountId, questionId, accountQuestionId, choice); }
Source:
<code>private String escapePlatformName(@NonNull String input) { <START> final String toEscape = "platform_name"; <END> return input.contains(toEscape) ? input.replaceAll(toEscape, getString(R.string.platform_name)) : input; }</code><technical_language>return input.replaceAll("platform_name", getString(R.string.platform_name)); more optimistic approach</technical_language>

Target:
private String escapePlatformName(@NonNull String input) { return input.replaceAll("platform_name", getString(R.string.platform_name)); }
Source:
<code>protected SWTBotEditor openRepresentation(Session session, String representationDescriptionName, final String representationName, Class<? extends DRepresentation> expectedRepresentationClass, boolean disableSnapToGridOnThisEditor) { DRepresentation representation = getRepresentationWithName(session, representationDescriptionName, representationName); TestCase.assertTrue("This representation should be a " + expectedRepresentationClass.getSimpleName(), expectedRepresentationClass.isInstance(representation)); IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation, new NullProgressMonitor()); SWTBotUtils.waitAllUiEvents(); SWTBotEditor swtBotEditor = null; <START> if (expectedRepresentationClass.equals(DDiagram.class)) { <END> swtBotEditor = SWTBotSiriusHelper.getSiriusDiagramEditor(editorPart.getTitle()); if (disableSnapToGridOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).disableSnapToGrid(); } } else { swtBotEditor = SWTBotSiriusHelper.getSiriusEditor(editorPart.getTitle()); } return swtBotEditor; }</code><technical_language>strict? SequenceDDiagram? Class#isAssignableFrom() instead</technical_language>

Target:
protected SWTBotEditor openRepresentation(Session session, String representationDescriptionName, final String representationName, Class<? extends DRepresentation> expectedRepresentationClass, boolean disableSnapToGridOnThisEditor) { DRepresentation representation = getRepresentationWithName(session, representationDescriptionName, representationName); TestCase.assertTrue("This representation should be a " + expectedRepresentationClass.getSimpleName(), expectedRepresentationClass.isInstance(representation)); IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation, new NullProgressMonitor()); SWTBotUtils.waitAllUiEvents(); SWTBotEditor swtBotEditor = null; if (DDiagram.class.isAssignableFrom(expectedRepresentationClass)) { swtBotEditor = SWTBotSiriusHelper.getSiriusDiagramEditor(editorPart.getTitle()); if (disableSnapToGridOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).disableSnapToGrid(); } } else { swtBotEditor = SWTBotSiriusHelper.getSiriusEditor(editorPart.getTitle()); } return swtBotEditor; }
Source:
<code>public void setEvent(boolean freshEvent) { try { if (freshEvent) { event = fresh.getParent().getParent().getParent().getParent() .getName(); } else { event = stale.getParent().getParent().getParent().getParent() .getName(); } <START> } catch (Exception e) { <END> e.printStackTrace(); event = ""; } }</code><technical_language>Please catch Exception. I removed compiles fine. If prevent NPEs this please replace if (null.. )</technical_language>

Target:
public void setEvent(boolean freshEvent) { TreeParent curElem = freshEvent ? fresh : stale; setEvent(curElem); }
Source:
<code>public void rawBytesPostTest() throws InterruptedException { Random random = new Random(); ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128)); HttpRequest postRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.wrappedBuffer(content)); HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest"); HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, content.remaining()); <START> postRequest = ReferenceCountUtil.retain(postRequest); <END> try { ByteBuffer receivedContent = doPostTest(postRequest, null); compareContent(receivedContent, Collections.singletonList(content)); } finally { ReferenceCountUtil.release(postRequest); } final int NUM_CONTENTS = 5; postRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null); List<ByteBuffer> contents = new ArrayList<ByteBuffer>(NUM_CONTENTS); int blobSize = 0; for (int i = 0; i < NUM_CONTENTS; i++) { ByteBuffer buffer = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128)); blobSize += buffer.remaining(); contents.add(i, buffer); } HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest"); HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, blobSize); ByteBuffer receivedContent = doPostTest(postRequest, contents); compareContent(receivedContent, contents); }</code><technical_language>do need retain release</technical_language>

Target:
public void rawBytesPostTest() throws InterruptedException { Random random = new Random(); ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128)); HttpRequest postRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.wrappedBuffer(content)); HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest"); HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, content.remaining()); postRequest = ReferenceCountUtil.retain(postRequest); ByteBuffer receivedContent = doPostTest(postRequest, null); compareContent(receivedContent, Collections.singletonList(content)); final int NUM_CONTENTS = 5; postRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null); List<ByteBuffer> contents = new ArrayList<ByteBuffer>(NUM_CONTENTS); int blobSize = 0; for (int i = 0; i < NUM_CONTENTS; i++) { ByteBuffer buffer = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128)); blobSize += buffer.remaining(); contents.add(i, buffer); } HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest"); HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, blobSize); receivedContent = doPostTest(postRequest, contents); compareContent(receivedContent, contents); }
Source:
<code>private void setInstancePropertiesForQuery(Object instance, List<Field> fields, Map<String, Object> properties) throws ActionHandlerException { for (Field field : fields) { Object value = properties.get(field.getName()); <START> if (value instanceof List) { <END> if (((List) value).size() > 0) { setInstanceProperty(instance, field, value); } } else if (null != value) { setInstanceProperty(instance, field, value); } } }</code><technical_language>put condition CollectionUtils.isNotEmpty() a casted _value_ object</technical_language>

Target:
private void setInstancePropertiesForQuery(Object instance, List<Field> fields, Map<String, Object> properties) throws ActionHandlerException { for (Field field : fields) { Object value = properties.get(field.getName()); if (value instanceof List && CollectionUtils.isNotEmpty((List) value)) { setInstanceProperty(instance, field, value); } else if (!(value instanceof List) && null != value) { setInstanceProperty(instance, field, value); } } }
Source:
<code>public FilterSupportStatus isFilterSupported( FilterAdapterContext context, FilterList filter) { List<FilterSupportStatus> unsupportedSubfilters = new ArrayList<>(); collectUnsupportedStatuses(context, filter, unsupportedSubfilters); <START> if (unsupportedSubfilters.size() == 0) { <END> return FilterSupportStatus.SUPPORTED; } else { return FilterSupportStatus.newCompositeNotSupported(unsupportedSubfilters); } }</code><technical_language>unsupportedSubfilters.isEmpty()</technical_language>

Target:
public FilterSupportStatus isFilterSupported( FilterAdapterContext context, FilterList filter) { List<FilterSupportStatus> unsupportedSubfilters = new ArrayList<>(); collectUnsupportedStatuses(context, filter, unsupportedSubfilters); if (!unsupportedSubfilters.isEmpty()) { return FilterSupportStatus.SUPPORTED; } else { return FilterSupportStatus.newCompositeNotSupported(unsupportedSubfilters); } }
Source:
<code><START> public void testGetDocContent_guidDocId() throws Exception { <END> adaptor.init(context); ByteArrayOutputStream baos = new ByteArrayOutputStream(); RecordingResponse response = new RecordingResponse(baos); adaptor.getDocContent( new MockRequest(new DocId("guid/{AAAAAAAA-0000-0000-0000-000000000004}")), response); assertEquals("text/plain", response.getContentType()); assertEquals("Hello from document {AAAAAAAA-0000-0000-0000-000000000004}", baos.toString("UTF-8")); }</code><technical_language>a test invalid GUID</technical_language>

Target:
public void testGetDocContent_guidDocId() throws Exception { adaptor.init(context); ByteArrayOutputStream baos = new ByteArrayOutputStream(); RecordingResponse response = new RecordingResponse(baos); adaptor.getDocContent( new MockRequest(newDocId("{AAAAAAAA-0000-0000-0000-000000000004}")), response); assertEquals("text/plain", response.getContentType()); assertEquals("Hello from document {AAAAAAAA-0000-0000-0000-000000000004}", baos.toString("UTF-8")); }
Source:
<code>private Metacard formMapper(Map map) { <START> LOGGER.debug("Starting form processing..."); <END> String title = safeGet(map, "title", String.class); String description = safeGet(map, "description", String.class); String filterTemplateFile = safeGet(map, "filterTemplateFile", String.class); if (anyNull(title, description, filterTemplateFile)) { LOGGER.debug("Invalid entry in forms.json"); return null; } File xmlFile = configDirectory.toPath().resolve(filterTemplateFile).toFile(); if (!xmlFile.exists()) { LOGGER.debug("Filter XML file does not exist: {}", filterTemplateFile); return null; } String filterXml = getFileContent(xmlFile); if (filterXml == null) { LOGGER.debug("Error while reading filter XML file: {}", filterTemplateFile); return null; } QueryTemplateMetacardImpl metacard = new QueryTemplateMetacardImpl(title, description); metacard.setFormsFilter(filterXml); return metacard; }</code><technical_language>trace</technical_language>

Target:
private Metacard formMapper(Map map) { String title = safeGet(map, Core.TITLE, String.class); String description = safeGet(map, Core.DESCRIPTION, String.class); String filterTemplateFile = safeGet(map, "filterTemplateFile", String.class); if (anyNull(title, description, filterTemplateFile)) { return null; } File xmlFile = configDirectory.toPath().resolve(filterTemplateFile).toFile(); if (!xmlFile.exists()) { LOGGER.warn("Filter XML file does not exist: {}", filterTemplateFile); return null; } String filterXml = getFileContent(xmlFile); if (filterXml == null) { return null; } QueryTemplateMetacard metacard = new QueryTemplateMetacard(title, description); metacard.setFormsFilter(filterXml); if (TemplateTransformer.invalidFormTemplate(metacard)) { LOGGER.warn("System forms configuration for template '{}' had one or more problems", title); return null; } return metacard; }
Source:
<code>private void processOrphanExclusivePIDs() { for (String orpahnPID : exclusivcePIDMap.getOrpahnPIDs()) { try { Configuration configuration = configAdmin.getConfiguration(orpahnPID, null); <START> configuration.delete(); <END> logger.debug("Deleting configuration for orphan pid {}", orpahnPID); } catch (IOException e) { logger.error("Error deleting configuration for orphan pid {}.", orpahnPID); } } }</code><technical_language>Is this a "silent" operation, if configuration exist all</technical_language>

Target:
private void processOrphanExclusivePIDs() { for (String orphanPID : exclusivePIDMap.getOrphanPIDs()) { try { Configuration configuration = configAdmin.getConfiguration(orphanPID, null); configuration.delete(); logger.debug("Deleting configuration for orphan pid {}", orphanPID); } catch (IOException e) { logger.error("Error deleting configuration for orphan pid {}.", orphanPID); } } }
Source:
<code>public static Condition<ExecutionEvent> event(Condition<? super ExecutionEvent>... conditions) { <START> return Assertions.allOf(conditions); <END> }</code><technical_language>Please move a separate "Polishing" PR</technical_language>

Target:
public static Condition<ExecutionEvent> event(Condition<? super ExecutionEvent>... conditions) { return Assertions.<ExecutionEvent> allOf(conditions); }