auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public T deleteHostedVersion(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @ApiParam(value = "Entry to modify.", required = true) @PathParam("entryId") Long entryId, @ApiParam(value = "version", required = true) @QueryParam("version") String version) { T entry = getEntryDAO().findById(entryId); checkEntry(entry); checkUserCanUpdate(user, entry); checkHosted(entry); Optional<U> deleteVersion = entry.getWorkflowVersions().stream().filter(v -> Objects.equals(v.getName(), version)).findFirst(); <START> if (deleteVersion.isPresent() && deleteVersion.get().isFrozen()) { <END> throw new CustomWebApplicationException("Cannot delete a snapshotted version.", HttpStatus.SC_BAD_REQUEST); } if (entry.getActualDefaultVersion().getName().equals(version)) { Optional<U> max = entry.getWorkflowVersions().stream().filter(v -> !Objects.equals(v.getName(), version)) .max(Comparator.comparingLong(ver -> ver.getDate().getTime())); entry.setActualDefaultVersion(max.orElse(null)); } entry.getWorkflowVersions().removeIf(v -> Objects.equals(v.getName(), version)); PublicStateManager.getInstance().handleIndexUpdate(entry, StateManagerMode.UPDATE); return entry; }</code><technical_language>If version present, silently fail well. Fail severely bug fixing, I throw a 404 in case</technical_language>

Target:
public T deleteHostedVersion(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @ApiParam(value = "Entry to modify.", required = true) @PathParam("entryId") Long entryId, @ApiParam(value = "version", required = true) @QueryParam("version") String version) { T entry = getEntryDAO().findById(entryId); checkEntry(entry); checkUserCanUpdate(user, entry); checkHosted(entry); Optional<U> deleteVersion = entry.getWorkflowVersions().stream().filter(v -> Objects.equals(v.getName(), version)).findFirst(); if (deleteVersion.isEmpty()) { throw new CustomWebApplicationException("Cannot find version: " + version + " to delete", HttpStatus.SC_NOT_FOUND); } if (deleteVersion.get().isFrozen()) { throw new CustomWebApplicationException("Cannot delete a snapshotted version.", HttpStatus.SC_BAD_REQUEST); } if (entry.getActualDefaultVersion().getName().equals(version)) { Optional<U> max = entry.getWorkflowVersions().stream().filter(v -> !Objects.equals(v.getName(), version)) .max(Comparator.comparingLong(ver -> ver.getDate().getTime())); entry.setActualDefaultVersion(max.orElse(null)); } entry.getWorkflowVersions().removeIf(v -> Objects.equals(v.getName(), version)); PublicStateManager.getInstance().handleIndexUpdate(entry, StateManagerMode.UPDATE); return entry; }
Source:
<code>public static int getComponentIdentifier(String componentId) { <START> return Character.getNumericValue(componentId.charAt(componentId.length() - 2)); <END> }</code><technical_language>getNumericValue supports a lot of characters decimal digits (roman numerals, tamil numbers). suggest Character.digit(char, 10), checking return for -1</technical_language>

Target:
public static int getComponentIdentifier(String componentId) { final char ciChar = componentId.charAt(componentId.length() - 2); final int ci = Character.digit(ciChar, 10); if (ci == -1) { throw new IllegalArgumentException("Invalid component identifier " + ciChar); } return ci; }
Source:
<code>private Map<String, Boolean> getHealthStatusFromRest(String instance, List<String> partitions, RESTConfig restConfig, Map<String, String> customPayLoads) { MetricRegistry metrics = SharedMetricRegistries.getOrCreate(_namespace); Counter requestsTotal = metrics.counter(CUSTOM_PARTITION_CHECK_HTTP_REQUESTS_TOTAL); Counter errorRequestsTotal = metrics.counter(CUSTOM_PARTITION_CHECK_HTTP_REQUESTS_ERROR_TOTAL); <START> try (final Timer.Context timer = metrics.timer(CUSTOM_PARTITION_CHECK_HTTP_REQUEST_DURATION) <END> .time()) { requestsTotal.inc(); return _restClient.getPartitionStoppableCheck(restConfig.getBaseUrl(instance), partitions, customPayLoads); } catch (IOException e) { LOG.error("Failed to get partition status on instance {}, partitions: {}", instance, partitions, e); errorRequestsTotal.inc(); return Collections.emptyMap(); } }</code><technical_language>In case of exception, time counted in request duration, right? Is this in design? I this duration statistic accurate</technical_language>

Target:
private Map<String, Boolean> getHealthStatusFromRest(String instance, List<String> partitions, RESTConfig restConfig, Map<String, String> customPayLoads) { MetricRegistry metrics = SharedMetricRegistries.getOrCreate(_namespace); try (final Timer.Context timer = metrics.timer(CUSTOM_PARTITION_CHECK_HTTP_REQUESTS_DURATION) .time()) { return _restClient.getPartitionStoppableCheck(restConfig.getBaseUrl(instance), partitions, customPayLoads); } catch (IOException e) { LOG.error("Failed to get partition status on instance {}, partitions: {}", instance, partitions, e); metrics.counter(CUSTOM_PARTITION_CHECK_HTTP_REQUESTS_ERROR_TOTAL).inc(); return Collections.emptyMap(); } }
Source:
<code>public void testMult() { DoubleAD v1 = new DoubleAD(2.0, 4.0); DoubleAD v2 = new DoubleAD(3.0, 2.0); DoubleAD result = ADMath.mult(v1, v2); DoubleAD correctResult = new DoubleAD(6.0, 16.0); <START> testCompareValues(correctResult, result, 0.0); <END> }</code><technical_language>this class exact floating point calculations, I 0.0 is for allowed delta</technical_language>

Target:
public void testMult() { DoubleAD v1 = new DoubleAD(2.0, 4.0); DoubleAD v2 = new DoubleAD(3.0, 2.0); DoubleAD result = ADMath.mult(v1, v2); DoubleAD correctResult = new DoubleAD(6.0, 16.0); assertEquals(correctResult, result); }
Source:
<code>private GitResourceVariantTreeProvider createTreeProviderWithAdditions() throws Exception { testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.checkoutBranch(MASTER); file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new <START> NameConflictTreeWalk(repo); <END> tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }</code><technical_language>a NameConflictTreeWalk</technical_language>

Target:
private GitResourceVariantTreeProvider createTreeProviderWithAdditions() throws Exception { testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.checkoutBranch(MASTER); file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new TreeWalk(repo); tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }
Source:
<code>protected void updateContent(TargetBean data) { _pageContent.removeClassName("hide"); _targetNameBox.setValue(data.getName()); _descriptionBox.setValue(data.getDescription()); <START> for (int i = 0; i < _targetType.getItemCount(); i++) { <END> if (_targetType.getValue(i) != null && _targetType.getValue(i).equals(data.getType().getValue())) { _targetType.setSelectedIndex(i); break; } } _classifiersTable.setValue(data.getClassifiers()); refreshTargetForm(data); if (_uuid == null || _uuid.equals("")) { _resetButton.setVisible(false); } }</code><technical_language>able call setValue() _targetType here. No</technical_language>

Target:
protected void updateContent(TargetBean data) { _pageContent.removeClassName("hide"); _targetNameBox.setValue(data.getName()); _descriptionBox.setValue(data.getDescription()); _targetType.setValue(data.getType().getValue()); _classifiersTable.setValue(data.getClassifiers()); refreshTargetForm(data); if (_uuid == null || _uuid.equals("")) { _resetButton.setVisible(false); } }
Source:
<code>public Version getVersion(IProgressMonitor monitor) { Optional<Version> version = Optional.empty(); if (path != null) { try { ProcessBuilder builder = new ProcessBuilder(path, "version"); Process process = builder.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!monitor.isCanceled() && (!version.isPresent()) && ((line = reader.readLine()) != null)) { version = parseVersion(line); } } <START> } catch (IOException e) { <END> } } return version.orElse(Version.emptyVersion); }</code><technical_language>Shouldnt log this error console instead of muting it</technical_language>

Target:
public Version getVersion(IProgressMonitor monitor) { Optional<Version> version = Optional.empty(); if (path != null) { try { ProcessBuilder builder = new ProcessBuilder(path, "version"); Process process = builder.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!monitor.isCanceled() && (!version.isPresent()) && ((line = reader.readLine()) != null)) { version = parseVersion(line); } } } catch (IOException e) { OpenShiftCoreActivator.logError(e.getLocalizedMessage(), e); } } return version.orElse(Version.emptyVersion); }
Source:
<code>public ImmutableSetMultimap<String, String> getValues(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getValues); b.bindUris("entityList", entityIds); b.bind("uris.value", uris.value()); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return <START> rdfClient.resultToMap(rdfClient.query(b.toString()), <END> "entity", "s"); }</code><technical_language>this selectToMap</technical_language>

Target:
public ImmutableSetMultimap<String, String> getValues(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getValues); b.bindUris("entityList", entityIds); b.bind("uris.value", uris.value()); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return rdfClient.selectToMap(b.toString(), "entity", "s"); }
Source:
<code>public storage_pool getForVds(Guid vds, Guid userID, boolean isFiltered) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vdsId", vds); <START> <END> ParameterizedRowMapper<storage_pool> mapper = new ParameterizedRowMapper<storage_pool>() { @Override public storage_pool mapRow(ResultSet rs, int rowNum) throws SQLException { storage_pool entity = new storage_pool(); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs.getString("id"))); entity.setname(rs.getString("name")); entity.setstorage_pool_type(StorageType.forValue(rs .getInt("storage_pool_type"))); entity.setstatus(StoragePoolStatus.forValue(rs.getInt("status"))); entity.setmaster_domain_version(rs .getInt("master_domain_version")); entity.setspm_vds_id(NGuid.createGuidFromString(rs .getString("spm_vds_id"))); entity.setcompatibility_version(new Version(rs .getString("compatibility_version"))); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setStoragePoolFormatType(getStorageFormatTypeForPool(rs)); return entity; } }; return getCallsHandler().executeRead("Getstorage_poolsByVdsId", mapper, parameterSource); }</code><technical_language>forgot pass userID isFiltered parameters DAO</technical_language>

Target:
public storage_pool getForVds(Guid vds, Guid userID, boolean isFiltered) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vdsId", vds).addValue("user_id", userID).addValue("is_filtered", isFiltered); ParameterizedRowMapper<storage_pool> mapper = new ParameterizedRowMapper<storage_pool>() { @Override public storage_pool mapRow(ResultSet rs, int rowNum) throws SQLException { storage_pool entity = new storage_pool(); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs.getString("id"))); entity.setname(rs.getString("name")); entity.setstorage_pool_type(StorageType.forValue(rs .getInt("storage_pool_type"))); entity.setstatus(StoragePoolStatus.forValue(rs.getInt("status"))); entity.setmaster_domain_version(rs .getInt("master_domain_version")); entity.setspm_vds_id(NGuid.createGuidFromString(rs .getString("spm_vds_id"))); entity.setcompatibility_version(new Version(rs .getString("compatibility_version"))); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setStoragePoolFormatType(getStorageFormatTypeForPool(rs)); return entity; } }; return getCallsHandler().executeRead("Getstorage_poolsByVdsId", mapper, parameterSource); }
Source:
<code>private void applyRename(List<RenameProject> projects) { List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>(); for (RenameProject project : projects) { project.getTextDocumentEdits().forEach(edit -> edits.add(Either.forLeft(edit))); <START> ; <END> } workspaceEditAction.applyWorkspaceEdit(new WorkspaceEdit(edits)); }</code><technical_language>Unnecessary line</technical_language>

Target:
private void applyRename(List<RenameProject> projects) { List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>(); for (RenameProject project : projects) { project.getTextDocumentEdits().forEach(edit -> edits.add(Either.forLeft(edit))); } workspaceEditAction.applyWorkspaceEdit(new WorkspaceEdit(edits)); }
Source:
<code>void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { if (clientCtx.getConf().disableEnsembleChangeFeature.isAvailable()) { if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(getCurrentEnsemble(), failedBookies.keySet()); return; } if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot perform ensemble change with write flags {}. " + "Failed bookies for ledger {}.", writeFlags, failedBookies, ledgerId); } handleUnrecoverableErrorDuringAdd(WriteException); return; } synchronized (metadataLock) { if (changingEnsemble) { <START> delayedWriteFailedBookies.putAll(failedBookies); <END> } else { changingEnsemble = true; Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); toReplace.putAll(failedBookies); List<BookieSocketAddress> origEnsemble = getCurrentEnsemble(); ensembleChangeLoop(origEnsemble, toReplace); } } }</code><technical_language>this change potentially a side effect causing a longer pause ensemble changes. I is a good idea completely block waiting previous ensemble done. matter is need ensure update local copy of metadata ensemble changes completed, no? explain performance difference current approach previous approach</technical_language>

Target:
void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { if (clientCtx.getConf().disableEnsembleChangeFeature.isAvailable()) { if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(getCurrentEnsemble(), failedBookies.keySet()); return; } if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot perform ensemble change with write flags {}. " + "Failed bookies for ledger {}.", writeFlags, failedBookies, ledgerId); } handleUnrecoverableErrorDuringAdd(WriteException); return; } boolean triggerLoop = false; Map<Integer, BookieSocketAddress> toReplace = null; List<BookieSocketAddress> origEnsemble = null; synchronized (metadataLock) { if (changingEnsemble) { delayedWriteFailedBookies.putAll(failedBookies); } else { changingEnsemble = true; triggerLoop = true; toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); toReplace.putAll(failedBookies); origEnsemble = getCurrentEnsemble(); } } if (triggerLoop) { ensembleChangeLoop(origEnsemble, toReplace); } }
Source:
<code>private synchronized void tickClock(final String workerId) { <START> assert (workerClockMap.containsKey(workerId)); <END> int workerClock = workerClockMap.get(workerId).intValue(); workerClock++; workerClockMap.put(workerId, workerClock); if (minimumClockWorkers.contains(workerId)) { minimumClockWorkers.remove(workerId); if (minimumClockWorkers.size() == 0) { globalMinimumClock++; broadcastGlobalMinimumClock(); } } else if (workerClock == globalMinimumClock) { minimumClockWorkers.add(workerId); } }</code><technical_language>throwing RuntimeException instead of assertion codebase former</technical_language>

Target:
private synchronized void tickClock(final String workerId) { Integer workerClock = workerClockMap.get(workerId); if (workerClock == null) { throw new RuntimeException(String.format("Uninitialized worker %s sent tick message", workerId)); } workerClock++; workerClockMap.put(workerId, workerClock); if (minimumClockWorkers.remove(workerId)) { if (minimumClockWorkers.size() == 0) { globalMinimumClock++; broadcastGlobalMinimumClock(); } } }
Source:
<code>public VariableBatchStrategy(Ordering<T> ordering, <START> List<Integer> maxActiveGroups, <END> boolean rollingForward) { this.ordering = Objects.requireNonNull(ordering); this.rollingForward = rollingForward; maxActiveGroups.forEach(x -> Preconditions.checkArgument(x > 0)); this.maxActiveGroups = ImmutableList.copyOf(maxActiveGroups); this.totalModInstanceCount = Optional.empty(); }</code><technical_language>max in variable name is a misleading. Suggest groupSizes</technical_language>

Target:
public VariableBatchStrategy( Ordering<T> ordering, List<Integer> maxActiveGroups, boolean rollingForward) { this.ordering = Objects.requireNonNull(ordering); this.rollingForward = rollingForward; maxActiveGroups.forEach(x -> Preconditions.checkArgument(x > 0)); this.groupSizes = ImmutableList.copyOf(maxActiveGroups); this.totalModInstanceCount = Optional.empty(); }
Source:
<code>private static void sendWithRest(MessageChannel channel) { IntStream.range(1, 10).forEach(i -> { channel.send(MessageBuilder.withPayload(createEvent()).build()); <START> }); <END> }</code><technical_language>reason Streams here. simple for (int i = 0; i < 10; i++) enough</technical_language>

Target:
private static void sendWithRest(MessageChannel channel) { for (int i = 0; i < 10; i++) { channel.send(MessageBuilder.withPayload(createEvent()).build()); } }
Source:
<code>public String getTag() { if (tags == null || tags.isEmpty()) { return null; } <START> return tags.iterator().next(); <END> }</code><technical_language>fields pick List<> if null empty return getTag()</technical_language>

Target:
public String getTag() { return tag; }
Source:
<code>void streamingPut(ByteArray key, Versioned<byte[]> value) { <START> if(overwrite == false) { <END> dstStreamingClient.streamingPut(key, value); } else { VectorClock denseClock = VectorClockUtils.makeClockWithCurrentTime(dstServerIds); Versioned<byte[]> updatedValue = new Versioned<byte[]>(value.getValue(), denseClock); dstStreamingClient.streamingPut(key, updatedValue); } entriesForkLifted++; if(entriesForkLifted % progressOps == 0) { logger.info(workName + " fork lifted " + entriesForkLifted + " entries successfully"); } }</code><technical_language>switch order of if -else clauses.. I dont contrapositive ( if !overwrite) if clauses :)</technical_language>

Target:
void streamingPut(ByteArray key, Versioned<byte[]> value) { if(overwrite) { VectorClock denseClock = VectorClockUtils.makeClockWithCurrentTime(dstServerIds); Versioned<byte[]> updatedValue = new Versioned<byte[]>(value.getValue(), denseClock); dstStreamingClient.streamingPut(key, updatedValue); } else { dstStreamingClient.streamingPut(key, value); } entriesForkLifted++; if(entriesForkLifted % progressOps == 0) { logger.info(workName + " fork lifted " + entriesForkLifted + " entries successfully"); } }
Source:
<code>private void onSerialOwnershipRequested(Object data) { try { throw new Exception(); } catch (Exception e) { StackTraceElement[] elems = e.getStackTrace(); String requester = elems[elems.length - 4].getClassName(); synchronized (this) { this.notify(); } close(); String myPackage = this.getClass().getPackage().getName(); if (requester.startsWith(myPackage)) requester = "another AT connection"; <START> logger.debug("Connection for port canceled due to ownership request from {}.", port, requester); <END> } }</code><technical_language>debug warnings? This a good place log a warning</technical_language>

Target:
private void onSerialOwnershipRequested(Object data) { try { throw new Exception(); } catch (Exception e) { StackTraceElement[] elems = e.getStackTrace(); String requester = elems[elems.length - 4].getClassName(); synchronized (this) { this.notify(); } close(); String myPackage = this.getClass().getPackage().getName(); if (requester.startsWith(myPackage)) requester = "another AT connection"; logger.warn("Connection for port canceled due to ownership request from {}.", port, requester); } }
Source:
<code>private ChannelHandlerContext findCtx() throws ClosedChannelException { ChannelHandlerContext ctx = this.multiplexCtx; if (ctx != null && !ctx.isRemoved()) { return ctx; } <START> ctx = channel.pipeline().context(Http2MultiplexCodec.class); <END> if (ctx == null) { ctx = channel.pipeline().context(Http2MultiplexHandler.class); } if (ctx == null) { if (channel.isActive()) { throw new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) + " must be in the ChannelPipeline of Channel " + channel); } else { throw new ClosedChannelException(); } } this.multiplexCtx = ctx; return ctx; }</code><technical_language>2 calls channel.pipeline() moved a variable</technical_language>

Target:
private ChannelHandlerContext findCtx() throws ClosedChannelException { ChannelHandlerContext ctx = this.multiplexCtx; if (ctx != null && !ctx.isRemoved()) { return ctx; } ChannelPipeline pipeline = channel.pipeline(); ctx = pipeline.context(Http2MultiplexCodec.class); if (ctx == null) { ctx = pipeline.context(Http2MultiplexHandler.class); } if (ctx == null) { if (channel.isActive()) { throw new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) + " or " + StringUtil.simpleClassName(Http2MultiplexHandler.class) + " must be in the ChannelPipeline of Channel " + channel); } else { throw new ClosedChannelException(); } } this.multiplexCtx = ctx; return ctx; }
Source:
<code>private static byte[] serializeContent(Content content) throws CacheDatabaseException { try { String type = content.getType(); switch (type) { case "text": return serializeTextContent((TextContent) content); case "image": return serializeImageContent((ImageContent) content); default: throw new ContentException("No such content exists !"); } } catch (CacheDatabaseException exception) { Log.d(TAG, "Could not serialize content !", exception); <START> throw new CacheDatabaseException("Could not serialize Content !"); <END> } }</code><technical_language>throw exception is enough rethrow exception abroad. is better, log abroad</technical_language>

Target:
private static byte[] serializeContent(Content content) throws CacheDatabaseException { Objects.requireNonNull(content); try { String type = content.getType(); switch (type) { case "text": return serializeTextContent((TextContent) content); case "image": return serializeImageContent((ImageContent) content); default: throw new ContentException("No such content exists !"); } } catch (CacheDatabaseException exception) { Log.d(TAG, "Could not serialize content !", exception); throw exception; } }
Source:
<code>public boolean isHygrometerNotifying() { TiSensorTagGattResources resource = this.gattResources.get(HUMIDITY); <START> if (resource != null) { <END> return resource.getGattValueCharacteristic().isNotifying(); } else { return false; } }</code><technical_language>this externalised a method code for types of sensors</technical_language>

Target:
public boolean isHygrometerNotifying() { return isNotifying(HUMIDITY); }
Source:
<code>public void onMetadataChanged(@NonNull MediaItem item) { final MediaSessionImplBase session = getSession(); if (session == null) { return; } SessionPlayer player = session.getPlayer(); if (player.getCurrentMediaItem() == item) { if (!updateCurrentMediaItemMetadataWithDuration(player)) { <START> notifyCurrentMediaItemChanged(item); <END> } } }</code><technical_language>need notify event duration is changed others changed</technical_language>

Target:
public void onMetadataChanged(@NonNull MediaItem item) { final MediaSessionImplBase session = getSession(); if (session == null) { return; } SessionPlayer player = session.getPlayer(); if (player.getCurrentMediaItem() == item) { boolean notified = updateCurrentMediaItemMetadataWithDuration(player); if (!notified) { notifyCurrentMediaItemChanged(item); } } }
Source:
<code>public int visit(IASTExpression expr) { if (!shouldReportInMacro() && enclosedInMacroExpansion(expr)) return PROCESS_SKIP; <START> if (expr instanceof IASTFunctionCallExpression) { <END> IASTFunctionCallExpression func = (IASTFunctionCallExpression) expr; IASTExpression functionNameExpression = func.getFunctionNameExpression(); IASTNode parent = func.getParent(); if (!(func.getParent() instanceof IASTExpressionStatement) && func.getPropertyInParent() != IASTExpressionList.NESTED_EXPRESSION) { while (parent instanceof IASTUnaryExpression) { int operator = ((IASTUnaryExpression) parent).getOperator(); if (operator != IASTUnaryExpression.op_bracketedPrimary) { return PROCESS_CONTINUE; } parent = parent.getParent(); } if (!(parent instanceof IASTExpressionStatement)) { return PROCESS_CONTINUE; } } IASTName name; if (functionNameExpression instanceof IASTIdExpression) { name = ((IASTIdExpression) functionNameExpression).getName(); } else if (functionNameExpression instanceof IASTFieldReference) { name = ((IASTFieldReference) functionNameExpression).getFieldName(); } else { return PROCESS_CONTINUE; } IBinding binding = name.resolveBinding(); if (checkNestedRightSide(func, binding, name)) { return PROCESS_CONTINUE; } if (binding instanceof IFunction && ((IFunction) binding).isNoDiscard()) { reportProblem(ER_ID, expr, name); } else if (binding instanceof ICPPClassType && expr instanceof ICPPASTExpression && checkEvaluation((ICPPASTExpression) expr)) { reportProblem(ER_ID, expr, name); } return PROCESS_CONTINUE; } else if (expr instanceof ICPPASTCastExpression) { ICPPASTCastExpression cast = (ICPPASTCastExpression) expr; if (cast.getOperator() != ICPPASTCastExpression.op_static_cast) { return PROCESS_CONTINUE; } if (checkEvaluation(cast)) { reportProblem(ER_ID, expr, cast.getTypeId()); } } return PROCESS_CONTINUE; }</code><technical_language>Oh, evaluations handle C case. I guess need a fall function name expression all. (I wish evaluations for C well. simplify things.) Feel free consider of suggestions optional if more difficult :)</technical_language>

Target:
public int visit(IASTExpression expr) { if (!shouldReportInMacro() && enclosedInMacroExpansion(expr)) return PROCESS_SKIP; if (isDiscardedValueExpression(expr) && isCallToNodiscardFunction(expr, res)) { reportProblem(ER_ID, expr, res[0]); res[0] = null; } return PROCESS_CONTINUE; }
Source:
<code>private ScheduledQueryMaintenanceRequestType translateAstType(int type) throws SemanticException { switch (type) { case HiveParser.TOK_CREATE_SCHEDULED_QUERY: <START> return ScheduledQueryMaintenanceRequestType.INSERT; <END> case HiveParser.TOK_ALTER_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.UPDATE; case HiveParser.TOK_DROP_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.DELETE; default: throw new SemanticException("Can't handle: " + type); } }</code><technical_language>call _CREATE_, _ALTER_, _DROP_? I end result is _INSERT_, _UPDATE_, _DELETE_ in metastore, respectively; however, is a bit misleading immediately SQL DML operations</technical_language>

Target:
private ScheduledQueryMaintenanceRequestType translateAstType(int type) throws SemanticException { switch (type) { case HiveParser.TOK_CREATE_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.CREATE; case HiveParser.TOK_ALTER_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.ALTER; case HiveParser.TOK_DROP_SCHEDULED_QUERY: return ScheduledQueryMaintenanceRequestType.DROP; default: throw new SemanticException("Can't handle: " + type); } }
Source:
<code>public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { <START> synchronized (JobWrapper.class) { <END> if (cachedMethods.containsKey(methodKey)) { methodToRun = cachedMethods.get(methodKey); } else { methodToRun = getMethodToRun(instance, methodName); if (methodToRun == null) { log.error("could not find the required method '{}' on instance of {}", methodName, instance.getClass().getSimpleName()); return; } cachedMethods.put(methodKey, methodToRun); } } } else { methodToRun = cachedMethods.get(methodKey); } OnTimerMethodAnnotation annotation = methodToRun.getAnnotation(OnTimerMethodAnnotation.class); if (annotation.transactional()) { Exception e = TransactionSupport.executeInNewTransaction(new TransactionMethod<Exception>() { @Override public Exception runInTransaction() { try { methodToRun.invoke(instance, methodParams); } catch (Exception e) { return e; } return null; } }); if (e != null) { throw e; } } else { methodToRun.invoke(instance, methodParams); } } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } }</code><technical_language>simplified to: cachedMethods.putIfAbscent(methodKey, getMethodToRun(instance, methodName)) ? instead of synchronized block</technical_language>

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { cachedMethods.putIfAbsent(methodKey, getMethodToRun(instance, methodName)); } methodToRun = cachedMethods.get(methodKey); invokeMethod(instance, methodToRun, methodParams); } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } }
Source:
<code>public void process(JSONRequestContext requestContext) { StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); Long commentId = requestContext.getLong("commentId"); <START> StudentGroupContactLogEntryComment comment = entryCommentDAO.findById(commentId); <END> entryCommentDAO.archive(comment); }</code><technical_language>null-check</technical_language>

Target:
public void process(JSONRequestContext requestContext) { StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); Long commentId = requestContext.getLong("commentId"); if (commentId == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, "CommentId was not defined."); StudentGroupContactLogEntryComment comment = entryCommentDAO.findById(commentId); entryCommentDAO.archive(comment); }
Source:
<code>public DataSet<ExecRow> write() throws StandardException{ long start = System.currentTimeMillis(); CountFunction countFunction = new CountFunction<>(); KafkaStreamer kafkaStreamer = new KafkaStreamer(rdd.getNumPartitions(), topicName, schema); JavaRDD streamed = rdd.map(countFunction).mapPartitionsWithIndex(kafkaStreamer, true); streamed.collect(); Long count = countFunction.getCount().value(); if(count == 0) { try { kafkaStreamer.noData(); <START> } catch(Exception e) { <END> throw StandardException.newException("", e); } } long end = System.currentTimeMillis(); ValueRow valueRow=new ValueRow(2); valueRow.setColumn(1,new SQLLongint(count)); valueRow.setColumn(2,new SQLLongint(end-start)); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); }</code><technical_language>this is necessary</technical_language>

Target:
public DataSet<ExecRow> write() throws StandardException{ long start = System.currentTimeMillis(); CountFunction countFunction = new CountFunction<>(); KafkaStreamer kafkaStreamer = new KafkaStreamer(rdd.getNumPartitions(), topicName); JavaRDD streamed = rdd.map(countFunction).mapPartitionsWithIndex(kafkaStreamer, true); streamed.collect(); Long count = countFunction.getCount().value(); if(count == 0) { try { kafkaStreamer.noData(); } catch(Exception e) { throw StandardException.newException("", e); } } long end = System.currentTimeMillis(); ValueRow valueRow=new ValueRow(2); valueRow.setColumn(1,new SQLLongint(count)); valueRow.setColumn(2,new SQLLongint(end-start)); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); }
Source:
<code>public LightblueBulkDataResponse getBulkResponse() { <START> return bulkResponse; <END> }</code><technical_language>Do is in this returning a collection of successful responses</technical_language>

Target:
public LightblueBulkDataErrorResponse getBulkResponse() { return bulkResponse; }
Source:
<code>private LongSupplier committingIdSupplier() throws IOException { if ( transactionIdStore != null ) { <START> return () -> transactionIdStore.committingTransactionId(); <END> } if ( fileBasedOperationsOnly ) { return () -> { throw new UnsupportedOperationException( "Current version of log files can't perform any " + "operation that require availability of transaction id store. Please build full version of log files " + "to be able to use them." ); }; } if ( readOnly ) { requireNonNull( pageCache, "Read only log files require page cache to be able to read commited " + "transaction info from store store." ); requireNonNull( storeDirectory, "Store directory is required." ); ReadOnlyTransactionIdStore transactionIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDirectory ); return transactionIdStore::committingTransactionId; } else { requireNonNull( dependencies, TransactionIdStore.class.getSimpleName() + " is required. " + "Please provide an instance or a dependencies where it can be found." ); return () -> resolveDependency( TransactionIdStore.class ).committingTransactionId(); } }</code><technical_language>I method references instead, captures target object instance, instead of capturing this builder object referencing transactionIdStore field call. This applies dependency resolver based lambda bellow, in lastCommittedIdSupplier method above</technical_language>

Target:
private LongSupplier committingIdSupplier() throws IOException { if ( transactionIdStore != null ) { return transactionIdStore::committingTransactionId; } if ( fileBasedOperationsOnly ) { return () -> { throw new UnsupportedOperationException( "Current version of log files can't perform any " + "operation that require availability of transaction id store. Please build full version of log files " + "to be able to use them." ); }; } if ( readOnly ) { requireNonNull( pageCache, "Read only log files require page cache to be able to read commited " + "transaction info from store store." ); requireNonNull( storeDirectory, "Store directory is required." ); ReadOnlyTransactionIdStore transactionIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDirectory ); return transactionIdStore::committingTransactionId; } else { requireNonNull( dependencies, TransactionIdStore.class.getSimpleName() + " is required. " + "Please provide an instance or a dependencies where it can be found." ); return () -> resolveDependency( TransactionIdStore.class ).committingTransactionId(); } }
Source:
<code>public void visit(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case FUNCTION: JSDocInfo bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && (bestJSDocInfo.isConstructor() || bestJSDocInfo.isInterface())) { convertConstructorToClass(n, bestJSDocInfo); } break; case CALL: if ("goog.defineClass".equals(n.getFirstChild().getQualifiedName())) { convertDefineClassToClass(n); } break; case GETPROP: case NAME: case VAR: case LET: case CONST: boolean needToExport = false; JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(n); if (jsdoc != null && jsdoc.hasTypedefType()) { String name; if (n.getToken() == Token.NAME) { name = n.getString(); } else if (n.getToken() == Token.GETPROP) { needToExport = true; name = n.getSecondChild().getString(); } else { name = n.getFirstChild().getString(); } Node typeDef = Node.newString(Token.TYPE_ALIAS, name); types.put(name, typeDef); typeDef.setJSDocInfo(jsdoc); if (needToExport) { typesToRename.put( <START> n.getFirstChild().getString() + "." + n.getSecondChild().getString(), name); <END> typeDef = new Node(Token.EXPORT, typeDef); } if (parent.getToken() == Token.EXPR_RESULT) { parent.getParent().replaceChild(parent, typeDef); } else if (parent.getToken() == Token.ASSIGN) { parent.getGrandparent().replaceChild(parent.getParent(), typeDef); } else { parent.replaceChild(n, typeDef); } } break; default: break; } }</code><technical_language>is this n.getQualifiedName()</technical_language>

Target:
public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo bestJSDocInfo = null; switch (n.getToken()) { case FUNCTION: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && (bestJSDocInfo.isConstructor() || bestJSDocInfo.isInterface())) { convertConstructorToClass(n, bestJSDocInfo); } break; case CALL: if ("goog.defineClass".equals(n.getFirstChild().getQualifiedName())) { convertDefineClassToClass(n); } break; case GETPROP: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && bestJSDocInfo.hasTypedefType()) { String interfaceName = n.getSecondChild().getString(); Node interfaceMember = Node.newString(Token.INTERFACE_MEMBERS, interfaceName); typesToRename.put(n.getQualifiedName(), interfaceName); types.put(interfaceName, interfaceMember); interfaceMember.setJSDocInfo(bestJSDocInfo); Node interfaceNode = new Node(Token.INTERFACE, IR.empty(), IR.empty(), interfaceMember); Node nameNode = Node.newString(Token.NAME, interfaceName); nameNode.addChildToBack(interfaceNode); Node exportNode = new Node(Token.EXPORT, new Node(Token.CONST, nameNode)); replaceExpressionOrAssignment(n, parent, exportNode); } break; case NAME: case VAR: case LET: case CONST: bestJSDocInfo = NodeUtil.getBestJSDocInfo(n); if (bestJSDocInfo != null && bestJSDocInfo.hasTypedefType()) { String name; if (n.getToken() == Token.NAME) { name = n.getString(); } else { name = n.getFirstChild().getString(); } Node typeDef = Node.newString(Token.TYPE_ALIAS, name); types.put(name, typeDef); typeDef.setJSDocInfo(bestJSDocInfo); replaceExpressionOrAssignment(n, parent, typeDef); } break; default: break; } }
Source:
<code>private void markAllBelowAsRead() { if (listView.getSelectedIndex() >= 0) { for (int i = listView.getSelectedIndex(); i < listView.getItems().size(); i++) { TurboIssue issue = listView.getItems().get(i).getIssue(); issue.markAsRead(UI.prefs); } parentPanelControl.refresh(); } <START> } <END></code><technical_language>methods similar. reuse</technical_language>

Target:
private void markAllBelowAsRead() { Optional<GuiElement> item = listView.getSelectedItem(); if (item.isPresent()) { for(int i = listView.getSelectedIndex(); i < listView.getItems().size(); i++){ TurboIssue issue = listView.getItems().get(i).getIssue(); issue.markAsRead(UI.prefs); } parentPanelControl.refresh(); } }
Source:
<code>private static void parse( String filename, InputStream inputStream, AnnotatedTypeFactory atypeFactory, ProcessingEnvironment processingEnv, StubAnnotations stubAnnos, boolean isJdkAsStub) { <START> AnnotationFileParser sp = <END> new AnnotationFileParser(filename, atypeFactory, processingEnv, isJdkAsStub); try { sp.parseStubUnit(inputStream); sp.process(stubAnnos); } catch (ParseProblemException e) { StringJoiner message = new StringJoiner(LINE_SEPARATOR); message.add( e.getProblems().size() + " problems while parsing stub file " + filename + ":"); for (Problem p : e.getProblems()) { message.add(p.getVerboseMessage()); } sp.warn(message.toString()); } }</code><technical_language>Rename sp afp parser</technical_language>

Target:
private static void parse( String filename, InputStream inputStream, AnnotatedTypeFactory atypeFactory, ProcessingEnvironment processingEnv, StubAnnotations stubAnnos, boolean isJdkAsStub) { AnnotationFileParser afp = new AnnotationFileParser(filename, atypeFactory, processingEnv, isJdkAsStub); try { afp.parseStubUnit(inputStream); afp.process(stubAnnos); } catch (ParseProblemException e) { StringJoiner message = new StringJoiner(LINE_SEPARATOR); message.add( e.getProblems().size() + " problems while parsing stub file " + filename + ":"); for (Problem p : e.getProblems()) { message.add(p.getVerboseMessage()); } afp.warn(message.toString()); } }
Source:
<code>public static String getUniqueHostName(VDS host) { <START> return host.getHostName() + "-" + new String(DigestUtils.md5Hex(host.getId().toByteArray())).substring(0, 6); <END> }</code><technical_language>if md5Hex returns string, do need new String? if new String byte array... explicit encoding</technical_language>

Target:
public static String getUniqueHostName(VDS host) { return host.getHostName() + "-" + DigestUtils.md5Hex(host.getId().toByteArray()).substring(0, 6); }
Source:
<code>private void checkRange(CubeMap cubeMap, int lowerBound, int upperBound) { Set<Cube> range = new HashSet<>(); cubeMap.cubes(lowerBound, upperBound).forEach(cube -> { <START> assertFalse(range.contains(cube)); END> range.add(cube); }); cubeMap.all().forEach(cube -> { if (cube.getY() >= lowerBound && cube.getY() <= upperBound) { assertTrue(range.contains(cube)); } else { assertFalse(range.contains(cube)); } }); int alwaysLower = Integer.MIN_VALUE; for(Cube cube : cubeMap.cubes(lowerBound, upperBound)) { assertThat(cube.getY(), is(greaterThan(alwaysLower))); alwaysLower = cube.getY(); } }</code><technical_language>assertThat possible... provides nicer output fails. assertThat(range, hasItem(cube))</technical_language>

Target:
private void checkRange(CubeMap cubeMap, int lowerBound, int upperBound) { Iterable<Cube> range = cubeMap.cubes(lowerBound, upperBound); Set<Cube> rangeSet = new HashSet<>(); range.forEach(cube -> { rangeSet.add(cube); }); assertThat(range, hasDistinctElements()); cubeMap.all().forEach(cube -> { if (cube.getY() >= lowerBound && cube.getY() <= upperBound) { assertThat(rangeSet, hasItem(cube)); } else { assertThat(rangeSet, not(hasItem(cube))); } }); int alwaysLower = Integer.MIN_VALUE; for(Cube cube : range) { assertThat(cube.getY(), is(greaterThan(alwaysLower))); alwaysLower = cube.getY(); } }
Source:
<code>public int readdirCallback(String path, long bufaddr, FuseFillDir filter, long offset, ByteBuffer fi) { try { <START> return readdir(path, bufaddr, filter, offset, new FuseFileInfo(fi)); <END> } catch (Exception e) { e.printStackTrace(); return -ErrorCodes.EIO(); } }</code><technical_language>LOG.error("Failed readdir {}, offset {}: ", path, offset, e)</technical_language>

Target:
public int readdirCallback(String path, long bufaddr, FuseFillDir filter, long offset, ByteBuffer fi) { try { return readdir(path, bufaddr, filter, offset, new FuseFileInfo(fi)); } catch (Exception e) { LOG.error("Failed to readdir {}, offset {}: ", path, offset, e); return -ErrorCodes.EIO(); } }
Source:
<code>public void moveDown(){ <START> setY(getY() + 2.2); <END> setX(getX() - 0.7); }</code><technical_language>2.2 is downspeed of bullet class If downspeed 'protected' instead of 'private' one</technical_language>

Target:
public void moveDown(){ setY(getY() + downspeed); setX(getX() - 0.7); }
Source:
<code>public void shouldCreateAPaymentRequest() throws Exception { GatewayAccountEntity gatewayAccount = new GatewayAccountEntity( defaultTestAccount.getPaymentProvider(), new HashMap<>(), TEST); gatewayAccount.setId(defaultTestAccount.getAccountId()); PaymentRequestEntity paymentRequestEntity = aValidPaymentRequestEntity() <START> .withId(null) <END> .withGatewayAccountEntity(gatewayAccount) .build(); assertThat(paymentRequestEntity.getId(), is(nullValue())); paymentRequestDao.persist(paymentRequestEntity); assertThat(paymentRequestEntity.getId(), is(notNullValue())); assertThat(paymentRequestEntity.getCreatedDate().getNano() % 1000000, is(0)); }</code><technical_language>remove withId() method, auto-incrementing this now</technical_language>

Target:
public void shouldCreateAPaymentRequest() throws Exception { GatewayAccountEntity gatewayAccount = new GatewayAccountEntity( defaultTestAccount.getPaymentProvider(), new HashMap<>(), TEST); gatewayAccount.setId(defaultTestAccount.getAccountId()); PaymentRequestEntity paymentRequestEntity = aValidPaymentRequestEntity() .withGatewayAccountEntity(gatewayAccount) .build(); paymentRequestDao.persist(paymentRequestEntity); assertThat(paymentRequestEntity.getId(), is(notNullValue())); assertThat(paymentRequestEntity.getCreatedDate().getNano() % 1000000, is(0)); }
Source:
<code>private void initButtonsPart() { yesNoButtons = new HLayout(); yesNoButtons.setMargin(10); yesNoButtons.setMembersMargin(5); yesNoButtons.setHeight(30); yesNoButtons.setWidth100(); yesNoButtons.setAlign(Alignment.RIGHT); yesButton = new IButton("Yes"); yesButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { <START> String url = "/automation-dashboard/#/portal/job-planner-calendar-def-workflows"; <END> com.google.gwt.user.client.Window.open(url, url, ""); PlanWindow.this.window.hide(); PlanWindow.this.destroy(); } }); noButton = new IButton("No"); noButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { PlanWindow.this.window.hide(); PlanWindow.this.destroy(); } }); yesNoButtons.setMembers(yesButton, noButton); rootPage.addMember(yesNoButtons); }</code><technical_language>URL a constant defined top of class</technical_language>

Target:
private void initButtonsPart() { yesNoButtons = new HLayout(); yesNoButtons.setMargin(10); yesNoButtons.setMembersMargin(5); yesNoButtons.setHeight(30); yesNoButtons.setWidth100(); yesNoButtons.setAlign(Alignment.RIGHT); yesButton = new IButton("Yes"); yesButton.addClickHandler(clickEvent -> { com.google.gwt.user.client.Window.open(JPP_URL, JPP_URL, ""); PlanWindow.this.window.hide(); PlanWindow.this.destroy(); }); noButton = new IButton("No"); noButton.addClickHandler(clickEvent -> { PlanWindow.this.window.hide(); PlanWindow.this.destroy(); }); yesNoButtons.setMembers(yesButton, noButton); rootPage.addMember(yesNoButtons); }