auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private JdbcReadOptions getJdbcReadOptions(ReadableConfig readableConfig) { final Optional<String> partitionColumnName = readableConfig.getOptional(READ_PARTITION_COLUMN); <START> final Optional<Long> partitionLower = readableConfig.getOptional(READ_PARTITION_LOWER_BOUND); final Optional<Long> partitionUpper = readableConfig.getOptional(READ_PARTITION_UPPER_BOUND); final Optional<Integer> numPartitions = readableConfig.getOptional(READ_PARTITION_NUM); <END> final JdbcReadOptions.Builder builder = JdbcReadOptions.builder(); if (partitionColumnName.isPresent()) { builder.setPartitionColumnName(partitionColumnName.get()); builder.setPartitionLowerBound(partitionLower.get()); builder.setPartitionUpperBound(partitionUpper.get()); builder.setNumPartitions(numPartitions.get()); } readableConfig.getOptional(READ_FETCH_SIZE).ifPresent(builder::setFetchSize); return builder.build(); }</code><technical_language>put 3 in partitionColumnName.isPresent() branch block, config.get(..) avoid warning</technical_language>

Target:
private JdbcReadOptions getJdbcReadOptions(ReadableConfig readableConfig) { final Optional<String> partitionColumnName = readableConfig.getOptional(SCAN_PARTITION_COLUMN); final JdbcReadOptions.Builder builder = JdbcReadOptions.builder(); if (partitionColumnName.isPresent()) { builder.setPartitionColumnName(partitionColumnName.get()); builder.setPartitionLowerBound(readableConfig.get(SCAN_PARTITION_LOWER_BOUND)); builder.setPartitionUpperBound(readableConfig.get(SCAN_PARTITION_UPPER_BOUND)); builder.setNumPartitions(readableConfig.get(SCAN_PARTITION_NUM)); } readableConfig.getOptional(SCAN_FETCH_SIZE).ifPresent(builder::setFetchSize); return builder.build(); }
Source:
<code>private void queryInterfaces() { VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(QueryType.GetVdsInterfacesByVdsId, params, new AsyncQuery<>((QueryReturnValue returnValue) -> { allExistingNics = returnValue.getReturnValue(); existingVlanDevicesByVlanId = mapVlanDevicesByVlanId(); initCreateOrUpdateBondParameters(); initNicLabelsParameters(); <START> queryTLVInformations(); <END> })); }</code><technical_language>need chain anymore: queryNetworkAttachments(); queryTLVInformations();</technical_language>

Target:
private void queryInterfaces() { VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(QueryType.GetVdsInterfacesByVdsId, params, new AsyncQuery<>((QueryReturnValue returnValue) -> { allExistingNics = returnValue.getReturnValue(); existingVlanDevicesByVlanId = mapVlanDevicesByVlanId(); initCreateOrUpdateBondParameters(); initNicLabelsParameters(); queryTLVInformations(); queryNetworkAttachments(); })); }
Source:
<code>public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = _getPowertools(); homes = _getHomes(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); teleportEnabled = _getTeleportEnabled(); godmode = _getGodModeEnabled(); muted = _getMuted(); muteTimeout = _getMuteTimeout(); <START> muteReason = _getMuteReason (); <END> jailed = _getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); lastLoginAddress = _getLastLoginAddress(); afk = _getAfk(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); isNPC = _isNPC(); arePowerToolsEnabled = _arePowerToolsEnabled(); kitTimestamps = _getKitTimestamps(); nickname = _getNickname(); ignoredPlayers = _getIgnoredPlayers(); logoutLocation = _getLogoutLocation(); lastAccountName = _getLastAccountName(); commandCooldowns = _getCommandCooldowns(); acceptingPay = _getAcceptingPay(); confirmPay = _getConfirmPay(); }</code><technical_language>Formatting again</technical_language>

Target:
public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = _getPowertools(); homes = _getHomes(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); teleportEnabled = _getTeleportEnabled(); godmode = _getGodModeEnabled(); muted = _getMuted(); muteTimeout = _getMuteTimeout(); muteReason = _getMuteReason(); jailed = _getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); lastLoginAddress = _getLastLoginAddress(); afk = _getAfk(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); isNPC = _isNPC(); arePowerToolsEnabled = _arePowerToolsEnabled(); kitTimestamps = _getKitTimestamps(); nickname = _getNickname(); ignoredPlayers = _getIgnoredPlayers(); logoutLocation = _getLogoutLocation(); lastAccountName = _getLastAccountName(); commandCooldowns = _getCommandCooldowns(); acceptingPay = _getAcceptingPay(); confirmPay = _getConfirmPay(); confirmClear = _getConfirmClear(); }
Source:
<code>public SavedHttpAttachment(String name, Map<String,Object> attachmentData, URI attachmentURI) throws IOException { super(name, (String)attachmentData.get("content_type"), Encoding.Plain); <START> Boolean stub = (Boolean) attachmentData.get("stub"); <END> Number length = (Number)attachmentData.get("length"); String digest = (String)attachmentData.get("digest"); String revpos = (String)attachmentData.get("revpos"); String data = (String)attachmentData.get("data"); if(!stub){ byte[] dataArray = data.getBytes(); InputStream is = Base64InputStreamFactory.get(new ByteArrayInputStream(dataArray)); this.data = IOUtils.toByteArray(is); } this.attachmentURI = attachmentURI; this.size = length.intValue(); }</code><technical_language>Is worth pulling out of properties? Some of</technical_language>

Target:
public SavedHttpAttachment(String name, Map<String,Object> attachmentData, URI attachmentURI) throws IOException { super(name, (String)attachmentData.get("content_type"), Encoding.Plain); Boolean stub = (Boolean) attachmentData.get("stub"); Number length = (Number)attachmentData.get("length"); String data = (String)attachmentData.get("data"); if(!stub){ byte[] dataArray = data.getBytes(); InputStream is = Base64InputStreamFactory.get(new ByteArrayInputStream(dataArray)); this.data = IOUtils.toByteArray(is); } this.attachmentURI = attachmentURI; this.size = length.intValue(); }
Source:
<code>public List<Object> next() { try { if (!resultSet.next()) { return null; } <START> getObjects(results); <END> return Arrays.asList(results); } catch (SQLException ex) { throw new DatabaseException("Failed to fetch next rows", ex); } }</code><technical_language>return Arrays.asList(results) shares instance variableObject[] results internally. instantiate a new Object[] for a return value</technical_language>

Target:
public List<Object> next() { try { if (!resultSet.next()) { return null; } return getObjects(); } catch (SQLException ex) { throw new DatabaseException("Failed to fetch next rows", ex); } }
Source:
<code>public String getStandardLeafName( String nodeName, HttpMessage msg, List<NameValuePair> params) { <START> StringBuilder sb = new StringBuilder(); String method = msg.getRequestHeader().getMethod(); sb.append(method); sb.append(":"); sb.append(nodeName); sb.append(Session.getParamDisplayString(params, NameValuePair.TYPE_QUERY_STRING)); if (method.equalsIgnoreCase(HttpRequestHeader.POST)) { String contentType = msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE); if (contentType != null && contentType.startsWith("multipart/form-data")) { sb.append("(multipart/form-data)"); } else { sb.append(Session.getParamDisplayString(params, NameValuePair.TYPE_POST_DATA)); } } return sb.toString(); <END> }</code><technical_language>This replaced a call session, duplicating existing logic</technical_language>

Target:
public String getStandardLeafName( String nodeName, HttpMessage msg, List<NameValuePair> params) { return Model.getSingleton() .getSession() .getLeafName( nodeName, msg.getRequestHeader().getMethod(), msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE), params); }
Source:
<code>public @NonNull TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> <START> fetchTooltip(@NonNull <END> SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { ITmfStateSystem ss = getAnalysisModule().getStateSystem(); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<@NonNull Integer> quarks = entries.values(); long start = filter.getStart(); if (ss == null || quarks.size() != 1 || !getAnalysisModule().isQueryable(start)) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } int quark = quarks.iterator().next(); try { Map<String, String> retMap = null; ITmfStateInterval state = ss.querySingleState(start, quark); Object object = state.getValue(); if (object instanceof String) { retMap = Collections.singletonMap("value", object.toString()); } else { retMap = Collections.emptyMap(); } return new TmfModelResponse<>(retMap, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } catch (StateSystemDisposedException e) { return new TmfModelResponse<>(null, ITmfResponse.Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } }</code><technical_language>yet, I add some basic tooltips merging this</technical_language>

Target:
public @NonNull TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> fetchTooltip(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
<code>public boolean visit(MethodInvocation node) { if (isMethod(node, "android.view.View", "findViewById", "int")) { <START> FindViewByIdItem item = new FindViewByIdItem(node); <END> items.add(item); } return VISIT_SUBTREE; }</code><technical_language>inline local variable</technical_language>

Target:
public boolean visit(MethodInvocation node) { if (isMethod(node, "android.view.View", "findViewById", "int")) { FindViewByIdItem item = new FindViewByIdItem(); if (item.setAssignment(node)) { items.add(item); } } return VISIT_SUBTREE; }
Source:
<code>protected void commit(Expression expr) { Operation op = (Operation) input; Class container = (Class) input.eContainer(); if (op.getMethods().isEmpty()) { OpaqueBehavior ob = (OpaqueBehavior) ModelUtils.create(container, UMLPackage.Literals.OPAQUE_BEHAVIOR); ob.getBodies().add(expr.getBody()); ob.getLanguages().add(expr.getLanguage()); container.getOwnedBehaviors().add(ob); op.getMethods().add(ob); } else { OpaqueBehavior ob = (OpaqueBehavior) op.getMethods().get(0); int index = ob.getLanguages().indexOf(expr.getLanguage()); if (index == -1) { ob.getLanguages().add(expr.getLanguage()); ob.getBodies().add(expr.getBody()); } else { <START> ob.getBodies().set(index, <END> expr.getBody()); } } }</code><technical_language>Thanks. But, guarantee 'index' is a valid index in body list. If more languages bodies, this seek end of list fail exception. need able add body if language previously existed body. needs padded out nulls blanks. else in UI broken horribly in case, get this point</technical_language>

Target:
protected void commit(Expression expr) { Operation op = (Operation) input; Class container = (Class) input.eContainer(); if (op.getMethods().isEmpty()) { OpaqueBehavior ob = (OpaqueBehavior) ModelUtils.create(container, UMLPackage.Literals.OPAQUE_BEHAVIOR); ob.getBodies().add(expr.getBody()); ob.getLanguages().add(expr.getLanguage()); container.getOwnedBehaviors().add(ob); op.getMethods().add(ob); } else { OpaqueBehavior ob = (OpaqueBehavior) op.getMethods().get(0); int index = ob.getLanguages().indexOf(expr.getLanguage()); if (index == -1) { ob.getLanguages().add(expr.getLanguage()); index = ob.getLanguages().size() - 1; } int numFillBody = ob.getLanguages().size() - ob.getBodies().size(); while (numFillBody-- > 0) { ob.getBodies().add(""); } ob.getBodies().set(index, expr.getBody()); } }
Source:
<code><START> public <C> Stream<Match> match(Object object, Captures captures, C context) <END> { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }</code><technical_language>final</technical_language>

Target:
public final <C> Stream<Match> match(Object object, Captures captures, C context) { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }
Source:
<code>void doneWithIt() { <START> synchronized (refCounts) { <END> if (refCounts == 0) { pollingCache.close(); } refCounts -= 1; } }</code><technical_language>Synchronize get replaced</technical_language>

Target:
void doneWithIt() { synchronized (refCounts) { if (refCounts.get() == 0) { pollingCache.close(); } refCounts.decrementAndGet(); } }
Source:
<code>public QueryContext parseContext(HttpServletRequest request) throws QueryParseException { return new QueryContext( <START> configFetcher.sourcesFor(request).or(ApplicationSources.DEFAULT_SOURCES), <END> annotationExtractor.extractFromRequest(request), selectionBuilder.build(request) ); }</code><technical_language>a method called defaults() similar please</technical_language>

Target:
public QueryContext parseContext(HttpServletRequest request) throws QueryParseException { return new QueryContext( configFetcher.sourcesFor(request).or(ApplicationSources.defaults()), annotationExtractor.extractFromRequest(request), selectionBuilder.build(request) ); }
Source:
<code>private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); <START> sleepForOneSecond(); <END> Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }</code><technical_language>move sleepForOneSecond method clickFollow? I understood previous discussion, explicit wait is necessary in case of a post. request includes tests</technical_language>

Target:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }
Source:
<code>protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { try { <START> abvs.reset(); <END> abvs.getDataOutput().write(ValueTag.JS_NULL_TAG); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } }</code><technical_language>XDMConstants.setJsNull(result) here</technical_language>

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { XDMConstants.setJsNull(result); }
Source:
<code>void pollQueue() { int emitted = 0; do { counter.set(1); long produced = 0; <START> long r = requested.get(); <END> for (;;) { if (child.isUnsubscribed()) return; Throwable error; if (finished) { if ((error = this.error) != null) { queue.clear(); child.onError(error); return; } else if (queue.isEmpty()) { child.onCompleted(); return; } } if (r > 0) { Object o = queue.poll(); if (o != null) { child.onNext(on.getValue(o)); r--; emitted++; produced++; } else { break; } } else { break; } } if (produced > 0 && requested.get() != Long.MAX_VALUE) { requested.addAndGet(-produced); } } while (counter.decrementAndGet() > 0); if (emitted > 0) { request(emitted); } }</code><technical_language>requested counter read local variables loop</technical_language>

Target:
void pollQueue() { int emitted = 0; final AtomicLong localRequested = this.requested; final AtomicLong localCounter = this.counter; do { localCounter.set(1); long produced = 0; long r = localRequested.get(); for (;;) { if (child.isUnsubscribed()) return; Throwable error; if (finished) { if ((error = this.error) != null) { queue.clear(); child.onError(error); return; } else if (queue.isEmpty()) { child.onCompleted(); return; } } if (r > 0) { Object o = queue.poll(); if (o != null) { child.onNext(on.getValue(o)); r--; emitted++; produced++; } else { break; } } else { break; } } if (produced > 0 && localRequested.get() != Long.MAX_VALUE) { localRequested.addAndGet(-produced); } } while (localCounter.decrementAndGet() > 0); if (emitted > 0) { request(emitted); } }
Source:
<code>public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the launched MR jobs on the cluster"); String azExecId = jobProps.getString("azkaban.flow.execid"); final String logFilePath = <START> String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, <END> getId()); info("log file path is: " + logFilePath); HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }</code><technical_language>"%s/_job.%s.%s.log" is in cancel methods. a constant for ? good create getLogFilePath(workingDir, execId, getId) is common</technical_language>

Target:
public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the launched MR jobs on the cluster"); String azExecId = jobProps.getString(CommonJobProperties.EXEC_ID); final String logFilePath = String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, getId()); info("log file path is: " + logFilePath); HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }
Source:
<code><START> protected void validateRackAwareness() { <END> if (dataNodes.size() > 0) { Iterator<DataNode> dataNodeIter = dataNodes.iterator(); boolean lastHasRackId = dataNodeIter.next().hasRackId(); while (dataNodeIter.hasNext()) { boolean currHasRackId = dataNodeIter.next().hasRackId(); if (lastHasRackId != currHasRackId) { throw new IllegalStateException("dataNodes in datacenter must all have defined rack IDs or none at all"); } lastHasRackId = currHasRackId; } this.rackAware = lastHasRackId; } }</code><technical_language>doc</technical_language>

Target:
private void validateRackAwareness() { if (dataNodes.size() > 0) { Iterator<DataNode> dataNodeIter = dataNodes.iterator(); boolean hasRackId = (dataNodeIter.next().getRackId() >= 0); while (dataNodeIter.hasNext()) { if (hasRackId != (dataNodeIter.next().getRackId() >= 0)) { throw new IllegalStateException("dataNodes in datacenter: " + name + " must all have defined rack IDs or none at all"); } } this.rackAware = hasRackId; } }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { if (!(node instanceof AggregationNode)) { return Optional.empty(); } AggregationNode parent = (AggregationNode) node; Map<Symbol, AggregationNode.Aggregation> assignments = parent.getAggregations(); if (assignments.size() == 0 || assignments.size() > 1) { return Optional.empty(); } for (Map.Entry<Symbol, AggregationNode.Aggregation> entry : assignments.entrySet()) { AggregationNode.Aggregation aggregation = entry.getValue(); requireNonNull(aggregation, "aggregation is null"); Signature signature = aggregation.getSignature(); FunctionCall functionCall = aggregation.getCall(); if (!"count".equals(signature.getName()) || !functionCall.getArguments().isEmpty()) { return Optional.empty(); } } PlanNode child = lookup.resolve(parent.getSource()); <START> if (!(child instanceof AggregationNode)) { <END> return Optional.empty(); } if (ScalarQueryUtil.isScalar(child, lookup)) { return Optional.of(new ValuesNode(node.getId(), node.getOutputSymbols(), ImmutableList.of(ImmutableList.of(new LongLiteral("1"))))); } return Optional.empty(); }</code><technical_language>if ScalarQueryUtil need this if block</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { AggregationNode parent = (AggregationNode) node; Map<Symbol, AggregationNode.Aggregation> assignments = parent.getAggregations(); if (parent.hasDefaultOutput() && assignments.size() != 1) { return Optional.empty(); } for (Map.Entry<Symbol, AggregationNode.Aggregation> entry : assignments.entrySet()) { AggregationNode.Aggregation aggregation = entry.getValue(); requireNonNull(aggregation, "aggregation is null"); Signature signature = aggregation.getSignature(); FunctionCall functionCall = aggregation.getCall(); if (!"count".equals(signature.getName()) || !functionCall.getArguments().isEmpty()) { return Optional.empty(); } } if (!assignments.isEmpty() && isScalar(parent.getSource(), lookup)) { return Optional.of(new ValuesNode(node.getId(), node.getOutputSymbols(), ImmutableList.of(ImmutableList.of(new LongLiteral("1"))))); } return Optional.empty(); }
Source:
<code>public void broadcastIntent(Intent intent, String permission) throws IOException, JadbException { List<String> args = new ArrayList<>(); args.add("broadcast"); intent.generate(args); if(permission != null){ args.add("--receiver-permission"); args.add(permission); } InputStream stream = device.executeShell("am", args.toArray(new String[args.size()])); int i; do{ i = stream.read(); <START> } while (i != -1); <END> stream.close(); }</code><technical_language>reading entire stream closing? close here, do need read entire stream? In case, move out a function. a Stream class a static method skipAll something</technical_language>

Target:
public void broadcastIntent(Intent intent, String permission) throws IOException, JadbException { List<String> args = new ArrayList<>(); args.add("broadcast"); intent.generate(args); if (permission != null) { args.add("--receiver-permission"); args.add(permission); } try (InputStream stream = device.executeShell("am", args.toArray(new String[args.size()]))) { Stream.flushRead(stream); } }
Source:
<code>public void should_get_black_cat_count_by_using_group_by_and_having() { final long expectedBlackCatCount = 6L; final long actualBlackCatCount = query().from(cat) .select(catEntity.name.count()) .groupBy(catEntity.color) <START> .having(catEntity.name.count().goe(1)) <END> .fetchOne(); assertEquals(expectedBlackCatCount, actualBlackCatCount); }</code><technical_language>This clause is entropy reducing, if handled correctly, query proper result</technical_language>

Target:
public void should_get_black_cat_count_by_using_group_by_and_having() { final long expectedTabbyCatCount = 2L; final Cat tabbyColorCatFoo = new Cat("Foo", 7, Color.TABBY); final Cat tabbyColorCatBar = new Cat("Bar", 8, Color.TABBY); insertEntitiesForTest(Arrays.asList(tabbyColorCatFoo, tabbyColorCatBar)); final long actualTabbyCatCount = query().from(cat) .select(catEntity.name.count()) .groupBy(catEntity.color) .having(catEntity.name.count().eq(2L)) .fetchOne(); removeEntitiesForTest(Arrays.asList(tabbyColorCatFoo, tabbyColorCatBar)); assertEquals(expectedTabbyCatCount, actualTabbyCatCount); }
Source:
<code>public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { ISaveablePart saveablePart = getSite().getPage().getActiveEditor(); <START> if (saveablePart instanceof ISaveablesSource) { <END> return ((ISaveablesSource) saveablePart).getSaveables(); } } return super.getSaveables(); }</code><technical_language>handle case of editor a ISaveablesSource? if (saveablePart instanceof ISaveablesSource) { ... } else { return new ISaveable[] { new DefaultSaveable(saveablePart) }; }</technical_language>

Target:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { IEditorPart saveablePart = getSite().getPage().getActiveEditor(); return saveablePart instanceof ISaveablesSource ? ((ISaveablesSource) saveablePart).getSaveables() : new Saveable[] { new DefaultSaveable(saveablePart) }; } return super.getSaveables(); }
Source:
<code>public boolean shouldDisplay() throws IOException, ServletException { if (!Functions.hasPermission(Jenkins.ADMINISTER)) { return false; } if (getActiveAdministrativeMonitorsCount() == 0) { return false; } <START> StaplerRequest req = Stapler.getCurrentRequest(); <END> if (req == null) { return false; } List<Ancestor> ancestors = req.getAncestors(); if (ancestors == null || ancestors.size() == 0) { return false; } Ancestor a = ancestors.get(ancestors.size() - 1); Object o = a.getObject(); if (o instanceof HudsonIsLoading) { return false; } if (o instanceof HudsonIsRestarting) { return false; } if (o instanceof Jenkins) { String url = a.getRestOfUrl(); if (ignoredJenkinsRestOfUrls.contains(url)) { return false; } } return true; }</code><technical_language>NIT: checked if is required</technical_language>

Target:
public boolean shouldDisplay() throws IOException, ServletException { if (!Functions.hasPermission(Jenkins.ADMINISTER)) { return false; } StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { return false; } List<Ancestor> ancestors = req.getAncestors(); if (ancestors == null || ancestors.size() == 0) { return false; } Ancestor a = ancestors.get(ancestors.size() - 1); Object o = a.getObject(); if (o instanceof HudsonIsLoading) { return false; } if (o instanceof HudsonIsRestarting) { return false; } if (o instanceof Jenkins) { String url = a.getRestOfUrl(); if (ignoredJenkinsRestOfUrls.contains(url)) { return false; } } if (getActiveAdministrativeMonitorsCount() == 0) { return false; } return true; }
Source:
<code>public Response getAllSchemaVersions(@PathParam("schemaName") String schemaName, @Context SecurityContext securityContext) { try { LOG.info("Get all versions for schema : {}", schemaName); Collection<SchemaVersionInfo> schemaVersionInfos = schemaRegistryClient.getAllVersions(schemaName); Collection<String> schemaVersions = new ArrayList<>(); if (schemaVersionInfos != null && !schemaVersionInfos.isEmpty()) { LOG.debug("######### Received schema versions from schema registry: {}", schemaVersionInfos); for (SchemaVersionInfo schemaVersionInfo: schemaVersionInfos) { schemaVersions.add(schemaVersionInfo.getVersion().toString()); } return WSUtils.respondEntities(schemaVersions, OK); } else { LOG.debug("######### Received null response for schema versions from schema registry for schema: {}", schemaName); return WSUtils.respondEntity(schemaVersions, NOT_FOUND); } } catch (SchemaNotFoundException e) { LOG.error("Schema not found: [{}]", schemaName, e); <START> throw EntityNotFoundException.byId(schemaName); <END> } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>This EntityNotFoundException#byName instead of EntityNotFoundException#byId</technical_language>

Target:
public Response getAllSchemaVersions(@PathParam("schemaName") String schemaName, @Context SecurityContext securityContext) { try { LOG.info("Get all versions for schema : {}", schemaName); Collection<SchemaVersionInfo> schemaVersionInfos = schemaRegistryClient.getAllVersions(schemaName); Collection<String> schemaVersions = new ArrayList<>(); if (schemaVersionInfos != null && !schemaVersionInfos.isEmpty()) { LOG.debug("######### Received schema versions from schema registry: {}", schemaVersionInfos); for (SchemaVersionInfo schemaVersionInfo: schemaVersionInfos) { schemaVersions.add(schemaVersionInfo.getVersion().toString()); } return WSUtils.respondEntities(schemaVersions, OK); } else { LOG.debug("######### Received null response for schema versions from schema registry for schema: {}", schemaName); return WSUtils.respondEntity(schemaVersions, NOT_FOUND); } } catch (SchemaNotFoundException e) { LOG.error("Schema not found: [{}]", schemaName, e); throw EntityNotFoundException.byName(schemaName); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public MessageChannel getDiscardChannel() { <START> String channelName = this.discardChannelName; <END> if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } return this.discardChannel; }</code><technical_language>exit early if this.discardChannel is null, need store this local variable in case</technical_language>

Target:
public MessageChannel getDiscardChannel() { if (this.discardChannel == null) { String channelName = this.discardChannelName; if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } } return this.discardChannel; }
Source:
<code>public void setPictureAs(OCFile file) { if (file != null){ if (file.isDown()) { File externalFile = new File(file.getStoragePath()); Uri sendUri = Uri.fromFile(externalFile); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(sendUri, file.getMimetype()); intent.putExtra("mimeType", file.getMimetype()); <START> mFileActivity.startActivityForResult(Intent.createChooser(intent, "Set As"), 200); <END> } else { } } else { Log_OC.wtf(TAG, "Trying to send a NULL OCFile"); } }</code><technical_language>"Set As" get fetched string resources</technical_language>

Target:
public void setPictureAs(OCFile file) { if (file != null){ if (file.isDown()) { File externalFile = new File(file.getStoragePath()); Uri sendUri = Uri.fromFile(externalFile); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(sendUri, file.getMimetype()); intent.putExtra("mimeType", file.getMimetype()); mFileActivity.startActivityForResult(Intent.createChooser(intent, mFileActivity.getString(R.string.set_as)), 200); } else { } } else { Log_OC.wtf(TAG, "Trying to send a NULL OCFile"); } }
Source:
<code>public void protocolTypesTestCase() throws IOException, InterruptedException, InternalServerException { BrokerManagerService brokerManagerService = mock(BrokerManagerService.class); List<String> protocolsList = new ArrayList<>(); <START> protocolsList.add("amqp-v1.0"); <END> protocolsList.add("mqtt-v3.1.1"); Protocols protocols = new Protocols(); protocols.setProtocol(protocolsList); when(brokerManagerService.getSupportedProtocols()).thenReturn(protocols); mbRESTService.setBrokerManagerService(brokerManagerService); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(Constants.BASE_URL + "/protocol-types"); getRequest.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); String content = StringUtils.EMPTY; if (responseEntity != null) { content = EntityUtils.toString(responseEntity); } Assert.assertTrue(content != null && content.contains("amqp-v1.0") && content.contains("mqtt-v3.1.1"), "Unexpected protocols"); Assert.assertEquals(response.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "200 not received"); httpClient.getConnectionManager().shutdown(); }</code><technical_language>is amqp version marked 1.0 ? 0.91</technical_language>

Target:
public void protocolTypesTestCase() throws IOException, InterruptedException, InternalServerException { BrokerManagerService brokerManagerService = mock(BrokerManagerService.class); List<String> protocolsList = new ArrayList<>(); protocolsList.add("amqp-v0.91"); Protocols protocols = new Protocols(); protocols.setProtocol(protocolsList); when(brokerManagerService.getSupportedProtocols()).thenReturn(protocols); mbRESTService.setBrokerManagerService(brokerManagerService); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(Constants.BASE_URL + "/protocol-types"); getRequest.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); String content = StringUtils.EMPTY; if (responseEntity != null) { content = EntityUtils.toString(responseEntity); } Assert.assertTrue(content != null && content.contains("amqp-v0.91"), "Unexpected protocols"); Assert.assertEquals(response.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "200 not received"); httpClient.getConnectionManager().shutdown(); }
Source:
<code>protected void executeSPMMergeCommand(VDSCommandType vdsCommandType) { <START> getParameters().setEntityInfo(new EntityInfo(VdcObjectType.Disk, getParameters().getSubchainInfo().getBaseImageId())); <END> SPMColdMergeVDSCommandParameters parameters = new SPMColdMergeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getSubchainInfo()); VDSReturnValue vdsReturnValue = runVdsCommand(vdsCommandType, parameters); if (vdsReturnValue.getSucceeded()) { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); getTaskIdList().add(createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); setSucceeded(true); } }</code><technical_language>getParameters().getSubchainInfo().getImageGroupId()</technical_language>

Target:
protected void executeSPMMergeCommand(VDSCommandType vdsCommandType) { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.Disk, getParameters().getSubchainInfo().getImageGroupId())); SPMColdMergeVDSCommandParameters parameters = new SPMColdMergeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getSubchainInfo()); VDSReturnValue vdsReturnValue = runVdsCommand(vdsCommandType, parameters); if (vdsReturnValue.getSucceeded()) { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); getTaskIdList().add(createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); setSucceeded(true); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> Realm.init(getApplicationContext()); <END> setContentView(R.layout.activity_realm_example); RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build(); Realm.deleteRealm(realmConfiguration); realm = Realm.getInstance(realmConfiguration); }</code><technical_language>Is OK here? init called multiple times</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_realm_example); RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build(); Realm.deleteRealm(realmConfiguration); realm = Realm.getInstance(realmConfiguration); }
Source:
<code>protected void processDescriptionPropertiesRecursively(SIRIUS processedDescription, SIRIUS originalDescription, TransformationCache cache) { SIRIUS currentDescription = originalDescription; while (currentDescription != null) { <START> for (EStructuralFeature feature : currentDescription.eClass().getEAllStructuralFeatures()) { this.processDescriptionFeature(feature, processedDescription, currentDescription, cache); } <END> currentDescription = getParentOf(currentDescription); } }</code><technical_language>java8-isation [forEach]</technical_language>

Target:
protected void processDescriptionPropertiesRecursively(SIRIUS processedDescription, SIRIUS originalDescription, TransformationCache cache) { Optional<SIRIUS> currentDescription = Optional.of(originalDescription); while (currentDescription.isPresent()) { for (EStructuralFeature feature : currentDescription.get().eClass().getEAllStructuralFeatures()) { this.processDescriptionFeature(feature, processedDescription, currentDescription.get(), cache); } currentDescription = this.getParentOf(currentDescription.get()); } }
Source:
<code>public boolean getBooleanDeviceConfig(final String nameSpace, final String flagName) { return <START> Boolean.parseBoolean(NetworkStackUtils.getDeviceConfigProperty(nameSpace, <END> flagName, "false" )); }</code><technical_language>a getDeviceConfigPropertyBoolean function in NetworkStackUtils</technical_language>

Target:
public boolean getBooleanDeviceConfig(final String nameSpace, final String flagName) { return NetworkStackUtils.getDeviceConfigPropertyBoolean(nameSpace, flagName, false ); }
Source:
<code><START> public void clearAll(CommCarePlatform platform) { <END> cleanup(); Stack<Resource> s = this.getResourceStack(); int count = 0; while (!s.isEmpty()) { Resource r = s.pop(); try { r.getInstaller().uninstall(r, platform); count++; } catch (UnresolvedResourceException e) { } } if (count > 0) { Logger.log(LogTypes.TYPE_RESOURCES, "Cleaned up " + count + " records from table"); } storage.removeAll(); }</code><technical_language>This is close I merge if resulting method more complex</technical_language>

Target:
public void clearAll(CommCarePlatform platform) { clearByStatus(platform, RESOURCE_STATUS_ALL_RESOURCES); storage.removeAll(); }
Source:
<code>private boolean permissionCheck(Resource resource, Action action, Map<String, Object> permission) { ResourceAction permissionResourceAction = (ResourceAction) permission.get("resourceAction"); if (action != permissionResourceAction.getAction()) { return false; } Resource permissionResource = permissionResourceAction.getResource(); if (permissionResource.getType() != resource.getType()) { return false; } String permissionResourceName = permissionResource.getName(); Pattern resourceNamePattern = Pattern.compile(permissionResourceName); Matcher resourceNameMatcher = resourceNamePattern.matcher(resource.getName()); <START> return resourceNameMatcher.matches(); <END> }</code><technical_language>Hmm, do performance benchmark result? this is fast enough</technical_language>

Target:
private boolean permissionCheck(Resource resource, Action action, Map<String, Object> permission) { ResourceAction permissionResourceAction = (ResourceAction) permission.get("resourceAction"); if (action != permissionResourceAction.getAction()) { return false; } Resource permissionResource = permissionResourceAction.getResource(); if (permissionResource.getType() != resource.getType()) { return false; } String permissionResourceName = permissionResource.getName(); Pattern resourceNamePattern = permissionPatternCache.get(permissionResourceName); Matcher resourceNameMatcher = resourceNamePattern.matcher(resource.getName()); return resourceNameMatcher.matches(); }
Source:
<code>protected static void writeProperties(JsonGenerator jg, DocumentModel doc, String schema, ServletRequest request) throws IOException { Collection<Property> properties = doc.getPropertyObjects(schema); if (properties.isEmpty()) { return; } SchemaManager schemaManager = Framework.getService(SchemaManager.class); String prefix = schemaManager.getSchema(schema).getNamespace().prefix; if (prefix == null || prefix.length() == 0) { prefix = schema; } <START> JSONPropertyWriter currentWriter = writer.prefix(prefix); <END> if (request != null) { DownloadService downloadService = Framework.getService(DownloadService.class); String blobUrlPrefix = VirtualHostHelper.getBaseURL(request) + downloadService.getDownloadUrl(doc, null, null) + "/"; currentWriter = currentWriter.filesBaseUrl(blobUrlPrefix); } for (Property p : properties) { currentWriter.writeProperty(jg, p); } }</code><technical_language>a prefix creates a new JSONPropertyWriter object ditch static (rarely a good idea) create a new JSONPropertyWriter bother fluent methods return new instances</technical_language>

Target:
protected static void writeProperties(JsonGenerator jg, DocumentModel doc, String schema, ServletRequest request) throws IOException { Collection<Property> properties = doc.getPropertyObjects(schema); if (properties.isEmpty()) { return; } SchemaManager schemaManager = Framework.getService(SchemaManager.class); String prefix = schemaManager.getSchema(schema).getNamespace().prefix; if (prefix == null || prefix.length() == 0) { prefix = schema; } JSONPropertyWriter writer = JSONPropertyWriter.create().writeNull(false).writeEmpty(false).prefix(prefix); if (request != null) { DownloadService downloadService = Framework.getService(DownloadService.class); String blobUrlPrefix = VirtualHostHelper.getBaseURL(request) + downloadService.getDownloadUrl(doc, null, null) + "/"; writer.filesBaseUrl(blobUrlPrefix); } for (Property p : properties) { writer.writeProperty(jg, p); } }
Source:
<code><START> String getReadable(long val) { <END> String unit[] = {"", "KB", "MB", "GB", "TB" }; int cnt = 0; double d = val; while (d > 1000 && cnt < unit.length-1) { d = d/1000; cnt++; } DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.DOWN); return cnt > 0 ? "(" + df.format(d) + unit[cnt] + ")" : unit[cnt]; }</code><technical_language>this 'static'</technical_language>

Target:
String getReadable(long val) { String unit[] = {"", "KB", "MB", "GB", "TB" }; int cnt = 0; double d = val; while (d >= 1000 && cnt < unit.length-1) { d = d/1000; cnt++; } DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.DOWN); return cnt > 0 ? "(" + df.format(d) + unit[cnt] + ")" : unit[cnt]; }
Source:
<code>protected Consumer<ConditionInspector> getConditionParser() { return c -> { final FieldCondition cond = (FieldCondition) c.getCondition(); final Operator op = resolve(cond.getOperator()); <START> switch (op) { <END> case LESS_OR_EQUAL: case LESS_THAN: upperBound = ((Number) cond.getValues().iterator().next()).doubleValue(); break; case GREATER_THAN: case GREATER_OR_EQUAL: lowerBound = ((Number) cond.getValues().iterator().next()).doubleValue(); break; } }; }</code><technical_language>do cover EQUALS (like IntegerRange?)</technical_language>

Target:
protected Consumer<ConditionInspector> getConditionParser() { return c -> { final FieldCondition cond = (FieldCondition) c.getCondition(); final Operator op = resolve(cond.getOperator()); switch (op) { case LESS_OR_EQUAL: case LESS_THAN: upperBound = ((Number) cond.getValues().iterator().next()).doubleValue(); break; case GREATER_THAN: case GREATER_OR_EQUAL: lowerBound = ((Number) cond.getValues().iterator().next()).doubleValue(); break; case EQUALS: lowerBound = ((Number) cond.getValues().iterator().next()).doubleValue(); upperBound = ((Number) cond.getValues().iterator().next()).doubleValue(); break; } }; }
Source:
<code><START> public final Integer getUnstableReturn() { <END> return unstableReturn; }</code><technical_language>Add CheckForNull</technical_language>

Target:
public final Integer getUnstableReturn() { return new Integer(0).equals(unstableReturn) ? null : unstableReturn; }
Source:
<code>public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { <START> logger.info("loadScript Loading Script " + file.getName()); <END> String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); if(extension != null){ engine = factory.getEngineByExtension(extension); } if (engine != null) { logger.info("EngineName: " + engine.getFactory().getEngineName()); initializeSciptGlobals(); engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } }</code><technical_language>this addition sense</technical_language>

Target:
public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { logger.info("Loading Script " + file.getName()); String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(extension); if (engine != null) { logger.info("EngineName: " + engine.getFactory().getEngineName()); initializeSciptGlobals(); engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } }
Source:
<code>private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:"; <START> if (modelResponse.getModelInfo().getModelName() != null) { <END> formType = formType + modelResponse.getModelInfo().getModelName(); } else { formType = formType + composedTrainResultItem.getModelId().toString(); } Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; }</code><technical_language>find a modelName for composed submodels service return this in train result</technical_language>

Target:
private static List<CustomFormSubmodel> getComposedSubmodels(Model modelResponse) { List<CustomFormSubmodel> subModelList = new ArrayList<>(); for (TrainResult composedTrainResultItem : modelResponse.getComposedTrainResults()) { String formType = "custom:" + composedTrainResultItem.getModelId().toString(); Map<String, CustomFormModelField> fieldMap = new TreeMap<>(); composedTrainResultItem.getFields() .forEach(formFieldsReport -> fieldMap.put( formFieldsReport.getFieldName(), new CustomFormModelField( null, formFieldsReport.getFieldName(), formFieldsReport.getAccuracy()))); CustomFormSubmodel customFormSubmodel = new CustomFormSubmodel( composedTrainResultItem.getAverageModelAccuracy(), fieldMap, formType); PrivateFieldAccessHelper.set(customFormSubmodel, "modelId", composedTrainResultItem.getModelId().toString()); subModelList.add(customFormSubmodel); } return subModelList; }
Source:
<code>public static void main(String[] args) { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ReceiveMode.PEEK_LOCK) .isLockAutoRenewed(true) .queueName("<<queue-name>>") .isAutoComplete(false) .maxAutoLockRenewalDuration(Duration.ofSeconds(2)) .buildAsyncClient(); Disposable subscription = receiverAsyncClient.receive() .flatMap(message -> { boolean messageProcessed = false; if (messageProcessed) { return receiverAsyncClient.complete(message) .doFinally(signalType -> { <START> System.out.println("Message completed."); <END> }).then(); } else { return receiverAsyncClient.abandon(message) .doFinally(signalType -> { System.out.println("Message Abandoned."); }).then(); } }).subscribe(); try { Thread.sleep(Duration.ofSeconds(60).toMillis()); } catch (InterruptedException ignored) { } subscription.dispose(); receiverAsyncClient.close(); }</code><technical_language>Remove debug statements dofinally</technical_language>

Target:
public static void main(String[] args) { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ReceiveMode.PEEK_LOCK) .isLockAutoRenewed(true) .queueName("<<queue-name>>") .isAutoComplete(false) .maxAutoLockRenewalDuration(Duration.ofSeconds(2)) .buildAsyncClient(); Disposable subscription = receiverAsyncClient.receive() .flatMap(message -> { boolean messageProcessed = false; if (messageProcessed) { return receiverAsyncClient.complete(message).then(); } else { return receiverAsyncClient.abandon(message).then(); } }).subscribe(); try { Thread.sleep(Duration.ofSeconds(60).toMillis()); } catch (InterruptedException ignored) { } subscription.dispose(); receiverAsyncClient.close(); }