auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testFindPrimaryReferenceSingleChildOfSpanContext() { Tracer tracer = new APMTracer(); Map<String, String> headers = new HashMap<>(); headers.put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID); headers.put(Constants.HAWKULAR_APM_ID, TEST_APM_ID1); headers.put(Constants.HAWKULAR_APM_TXN, TEST_TXN); <START> SpanContext spanCtx = tracer.extract(Format.Builtin.TEXT_MAP, <END> new TextMapExtractAdapter(headers)); Reference ref = new Reference(References.CHILD_OF, spanCtx); assertEquals(ref, APMSpan.findPrimaryReference(Arrays.asList(ref))); }</code><technical_language>please span.context() instead of calling extract method tracer</technical_language>

Target:
public void testFindPrimaryReferenceSingleChildOfSpanContext() { Tracer tracer = new APMTracer(); SpanContext spanCtx = extractSpanContext(tracer, TEST_APM_ID1); Reference ref = new Reference(References.CHILD_OF, spanCtx); assertEquals(ref, APMSpan.findPrimaryReference(Arrays.asList(ref))); }
Source:
<code>List<IResource> getRelevantResources() { List<IResource> resourcesInScope = new ArrayList<IResource>(); ResourceTraversal[] traversals = getScope().getTraversals(); <START> for (ResourceTraversal resourceTraversal : traversals) { <END> resourcesInScope.addAll(Arrays.asList(resourceTraversal .getResources())); } return resourcesInScope; }</code><technical_language>style nit: braces single line block</technical_language>

Target:
List<IResource> getRelevantResources() { List<IResource> resourcesInScope = new ArrayList<IResource>(); ResourceTraversal[] traversals = getScope().getTraversals(); for (ResourceTraversal resourceTraversal : traversals) resourcesInScope.addAll(Arrays.asList(resourceTraversal .getResources())); return resourcesInScope; }
Source:
<code>private String getStorageId(final ZooKeeperHolder zooKeeperHolder, final Environment environment) { final CuratorFramework curator = zooKeeperHolder.get(); try { curator.create().creatingParentsIfNeeded() .forPath(StorageService.ZK_TIMELINES_DEFAULT_STORAGE, null); <START> } catch (final Exception e) { <END> LOGGER.debug("Node is already there", StorageService.ZK_TIMELINES_DEFAULT_STORAGE); } try { final byte[] storageIdBytes = curator.getData() .forPath(StorageService.ZK_TIMELINES_DEFAULT_STORAGE); if (storageIdBytes != null) { return new String(storageIdBytes); } } catch (final Exception e) { LOGGER.warn("Init of default storage from zk failed, will use default from env", e); } return environment.getProperty("nakadi.timelines.storage.default"); }</code><technical_language>I catch more specific exception (I NodeExistsException that)</technical_language>

Target:
private String getStorageId(final ZooKeeperHolder zooKeeperHolder, final Environment environment) { final CuratorFramework curator = zooKeeperHolder.get(); try { curator.create().creatingParentsIfNeeded() .forPath(StorageService.ZK_TIMELINES_DEFAULT_STORAGE, null); } catch (final KeeperException.NodeExistsException e) { LOGGER.trace("Node already is there", StorageService.ZK_TIMELINES_DEFAULT_STORAGE); } catch (final Exception e) { LOGGER.error("Zookeeper access error {}", e.getMessage(), e); } try { final byte[] storageIdBytes = curator.getData() .forPath(StorageService.ZK_TIMELINES_DEFAULT_STORAGE); if (storageIdBytes != null) { return new String(storageIdBytes, Charsets.UTF_8); } } catch (final Exception e) { LOGGER.warn("Init of default storage from zk failed, will use default from env", e); } return environment.getProperty("nakadi.timelines.storage.default"); }
Source:
<code>public void runAll(AuthenticationInfo authenticationInfo, boolean blocking) { for (Paragraph p : getParagraphs()) { if (!p.isEnabled()) { continue; } if (authenticationInfo != null) { p.setAuthenticationInfo(authenticationInfo); } else if (p.getUser() != null){ p.setAuthenticationInfo(new AuthenticationInfo((p.getUser()))); } else { <START> p.setAuthenticationInfo(AuthenticationInfo.ANONYMOUS); <END> } if (!run(p.getId(), blocking)) { logger.warn("Skip running the remain notes because paragraph fails", p.getId()); break; } } }</code><technical_language>ok, is authenticationInfo is set scheduling cronjob</technical_language>

Target:
public void runAll(AuthenticationInfo authenticationInfo, boolean blocking) { for (Paragraph p : getParagraphs()) { if (!p.isEnabled()) { continue; } p.setAuthenticationInfo(authenticationInfo); if (!run(p.getId(), blocking)) { logger.warn("Skip running the remain notes because paragraph fails", p.getId()); break; } } }
Source:
<code>public CharSequence toXML() { <START> XmlStringBuilder xml = new XmlStringBuilder(); <END> xml.halfOpenElement(this); xml.attribute("node", node); xml.rightAngleBracket(); xml.halfOpenElement("affiliation"); xml.attribute("jid", userJid); xml.attribute("affiliation", "none"); xml.closeEmptyElement(); xml.closeElement(this); return xml; }</code><technical_language>new XmlStringbuilder(this) possible. XML is qualified a namespace. This is case in current code halfOpenElement() is add xmlns. extra reduces LOC count halfOpenElement() is required</technical_language>

Target:
public CharSequence toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); xml.attribute("node", node); xml.rightAngleBracket(); xml.halfOpenElement("affiliation"); xml.attribute("jid", userJid); xml.attribute("affiliation", "none"); xml.closeEmptyElement(); xml.closeElement(this); return xml; }
Source:
<code>private boolean handleDefinedNestedTargetMapping(Set<String> handledTargets) { NestedTargetPropertyMappingHolder holder = new NestedTargetPropertyMappingHolder.Builder() .mappingContext( ctx ) .method( method ) .existingVariableNames( existingVariableNames ) .build(); unprocessedSourceParameters.removeAll( holder.getProcessedSourceParameters() ); propertyMappings.addAll( holder.getPropertyMappings() ); handledTargets.addAll( holder.getHandledTargets() ); for ( Entry<PropertyEntry, List<Mapping>> entry : holder.getUnprocessedDefinedTarget().entrySet() ) { if ( entry.getValue().isEmpty() ) { continue; } unprocessedDefinedTargets.put( entry.getKey().getName(), entry.getValue() ); } <START> return holder.isErrorOccurred(); <END> }</code><technical_language>hasErrorOccured</technical_language>

Target:
private boolean handleDefinedNestedTargetMapping(Set<String> handledTargets) { NestedTargetPropertyMappingHolder holder = new NestedTargetPropertyMappingHolder.Builder() .mappingContext( ctx ) .method( method ) .existingVariableNames( existingVariableNames ) .build(); unprocessedSourceParameters.removeAll( holder.getProcessedSourceParameters() ); propertyMappings.addAll( holder.getPropertyMappings() ); handledTargets.addAll( holder.getHandledTargets() ); for ( Entry<PropertyEntry, List<Mapping>> entry : holder.getUnprocessedDefinedTarget().entrySet() ) { if ( entry.getValue().isEmpty() ) { continue; } unprocessedDefinedTargets.put( entry.getKey().getName(), entry.getValue() ); } return holder.hasErrorOccurred(); }
Source:
<code>public BaseResponseDto generateWithdrawRequest(@RequestBody WithdrawOperateRequestDto requestDto) { requestDto.getBaseParam().setUserId(getLoginName()); String loginName = getLoginName(); if (blacklistService.userIsInBlacklist(loginName)) { BaseResponseDto<BaseResponseDataDto> baseResponseDto = new BaseResponseDto<>(); baseResponseDto.setCode(ReturnMessage.WITHDRAW_IN_BLACKLIST.getCode()); <START> baseResponseDto.setMessage("操作失败(错误代码:YM001), 请联系客服"); <END> return baseResponseDto; } return mobileAppWithDrawService.generateWithdrawRequest(requestDto); }</code><technical_language>message in returnMessage</technical_language>

Target:
public BaseResponseDto generateWithdrawRequest(@RequestBody WithdrawOperateRequestDto requestDto) { requestDto.getBaseParam().setUserId(getLoginName()); return mobileAppWithDrawService.generateWithdrawRequest(requestDto); }
Source:
<code><START> ClusterTierManagerPassiveEntity(ClusterTierManagerConfiguration config, <END> EhcacheStateService ehcacheStateService, Management management) throws ConfigurationException { if (config == null) { throw new ConfigurationException("ClusterTierManagerConfiguration cannot be null"); } this.ehcacheStateService = ehcacheStateService; if (ehcacheStateService == null) { throw new AssertionError("Server failed to retrieve EhcacheStateService."); } try { ehcacheStateService.configure(); this.management = management; } catch (ConfigurationException e) { ehcacheStateService.destroy(); throw e; } }</code><technical_language>visibility change</technical_language>

Target:
public ClusterTierManagerPassiveEntity(ClusterTierManagerConfiguration config, EhcacheStateService ehcacheStateService, Management management) throws ConfigurationException { if (config == null) { throw new ConfigurationException("ClusterTierManagerConfiguration cannot be null"); } this.ehcacheStateService = ehcacheStateService; if (ehcacheStateService == null) { throw new AssertionError("Server failed to retrieve EhcacheStateService."); } try { ehcacheStateService.configure(); this.management = management; } catch (ConfigurationException e) { ehcacheStateService.destroy(); throw e; } }
Source:
<code>private Object exec(Object message) { if (message instanceof List) { return ((List) message).parallelStream().map(this::exec).collect(Collectors.toList()); } <START> <END> if (!(message instanceof Map)) { return invalid(); } Map msg = (Map) message; if (!msg.containsKey("id")) { return fail(null, invalid("Required key `id` missing")); } Object id = msg.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { return fail(null, invalid("Key `id` not string or number or null")); } if (!msg.containsKey("jsonrpc")) { return fail(id, invalid("Required key `jsonrpc` missing")); } if (!VERSION.equals(msg.get("jsonrpc"))) { return fail(id, invalid("Key `jsonrpc` not equal to `2.0`")); } if (!msg.containsKey("method")) { return fail(id, invalid("Required key `method` missing")); } if (!(msg.get("method") instanceof String)) { return fail(id, invalid("Key `method` not string")); } if (!methods.containsKey(msg.get("method"))) { return fail("id", METHOD_NOT_FOUND); } Object params = msg.get("params"); if (params != null && !(params instanceof List || params instanceof Map)) { return fail(id, invalidParams("Parameters must be a structured value")); } try { return success(id, methods.get(msg.get("method")).apply(params)); } catch (IllegalArgumentException ex) { return fail(id, invalidParams(ex.getMessage())); } catch (Exception ex) { return fail(id, INTERNAL_ERROR); } }</code><technical_language>other global fork join pool for operations I remember do built in parallelStream top of head. If PR adding cyclops-react in SimpleReact allows pass a custom pool arg(<LINK_0> in yet</technical_language>

Target:
private Object exec(Object message) { if (!(message instanceof Map)) { return response(null, invalid("message must be a map", message)); } Map msg = (Map) message; if (!msg.containsKey("id")) { return response(null, invalid("required key `id` missing")); } Object id = msg.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { return response(null, invalid("key `id` not string or number or null", id)); } if (!msg.containsKey(JSONRPC)) { return response(id, invalid("required key `jsonrpc` missing")); } if (!VERSION.equals(msg.get(JSONRPC))) { return response(id, invalid("key `jsonrpc` not equal to `2.0`", msg.get(JSONRPC))); } if (!msg.containsKey(METHOD)) { return response(id, invalid("required key `method` missing")); } if (!(msg.get(METHOD) instanceof String)) { return response(id, invalid("key `method` not string", msg.get(METHOD))); } String method = (String) msg.get(METHOD); if (!methods.containsKey(method)) { return response(id, error(METHOD_NOT_FOUND, String.format("method `%s` not found", method))); } Object params = msg.get("params"); if (params != null && !(params instanceof List || params instanceof Map)) { return response(id, invalidParams("parameters must be a structured value", params)); } try { return response(id, methods.get(method).apply(params)); } catch (RuntimeException e) { return response(id, JsonRpc.error(INTERNAL_ERROR, "Internal Error")); } }
Source:
<code>protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() <START> && vdsGroup.getcompatibility_version() != null <END> && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }</code><technical_language>Minor - Version's compareTo a null check, need vdsGroup.getcompatibility_version() != null</technical_language>

Target:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }
Source:
<code>private void reloadJenkinsConfigurationViaCliAndWait() throws Exception { final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER).invoke(); assertThat(result, succeededSilently()); boolean sleep = true; while (sleep) { sleep = false; <START> for (Thread t : Thread.getAllStackTraces().keySet()) { <END> if (t.getName().equals("Jenkins config reload thread")) { System.out.println("Reloading thread is active and performing reload operation, sleeping 1s..."); sleep = true; Thread.sleep(1000); break; } } } }</code><technical_language>Waiting for j.jenkins.servletContext.getAttribute("app") instanceof Jenkins is cleaner</technical_language>

Target:
private void reloadJenkinsConfigurationViaCliAndWait() throws Exception { final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER).invoke(); assertThat(result, succeededSilently()); while (!(j.jenkins.servletContext.getAttribute("app") instanceof Jenkins)) { System.out.println("Jenkins reload operation is performing, sleeping 1s..."); Thread.sleep(1000); } }
Source:
<code>public void should_not_return_tags_of_foreign_organization() throws IOException { <START> OrganizationDto organization_with_specific_tags = dbTester.organizations().insert(); <END> OrganizationDto myOrganization = dbTester.organizations().insert(); RuleDefinitionDto rule = dbTester.rules().insert(setSystemTags("system1", "system2")); insertMetadata(organization_with_specific_tags, rule, setTags("tag1", "tag2")); indexRules(); SearchResponse result = ws.newRequest() .setParam("facets", "tags") .setParam("f", "tags") .setParam("organization", myOrganization.getKey()) .executeProtobuf(SearchResponse.class); assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString()); assertThat(result.getFacets().getFacets(0).getValuesList()) .extracting(v -> tuple(v.getVal(), v.getCount())) .containsExactly( tuple("system1", 1L), tuple("system2", 1L) ); }</code><technical_language>Please camel case for variables</technical_language>

Target:
public void should_not_return_tags_of_foreign_organization() throws IOException { OrganizationDto organizationWithSpecificTags = dbTester.organizations().insert(); OrganizationDto myOrganization = dbTester.organizations().insert(); RuleDefinitionDto rule = dbTester.rules().insert(setSystemTags("system1", "system2")); insertMetadata(organizationWithSpecificTags, rule, setTags("tag1", "tag2")); indexRules(); SearchResponse result = ws.newRequest() .setParam("facets", "tags") .setParam("f", "tags") .setParam("organization", myOrganization.getKey()) .executeProtobuf(SearchResponse.class); assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString()); assertThat(result.getFacets().getFacets(0).getValuesList()) .extracting(v -> tuple(v.getVal(), v.getCount())) .containsExactly( tuple("system1", 1L), tuple("system2", 1L) ); }
Source:
<code>protected Object doGetValue() { Object value = null; <START> if (source instanceof ShapeImpl) { <END> for (Object child : source.getChildren()) { if (child instanceof DecorationNodeImpl && FLOATING_LABEL.equals(NotationTypesMap.instance.getHumanReadableType((View) child))) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } } } } } return value; }</code><technical_language>is interface for Shape</technical_language>

Target:
protected Object doGetValue() { Object value = null; if (source instanceof View) { source.getChildren().iterator(); Iterator<?> iterator = source.getChildren().iterator(); while (iterator.hasNext() && value == null) { Object child = (Object) iterator.next(); if (child instanceof DecorationNodeImpl && FLOATING_LABEL.equals(NotationTypesMap.instance.getHumanReadableType((View) child))) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } } } } } return value; }
Source:
<code>public boolean checkUnsortedEncodedKeyComponentsEqual(@Nullable Double lhs, @Nullable Double rhs) { <START> return Objects.equals(lhs, rhs); <END> }</code><technical_language>If decide null totally equivalent zero, nullToZero(lhs).equals(nullToZero(rhs). null match zero</technical_language>

Target:
public boolean checkUnsortedEncodedKeyComponentsEqual(@Nullable Double lhs, @Nullable Double rhs) { return DimensionHandlerUtils.nullToZero(lhs).equals(DimensionHandlerUtils.nullToZero(rhs)); }
Source:
<code>public Map<String, Statistic<?, ?>> collectStatistics(Context context, Collection<String> statisticNames) { Map<String, Statistic<?, ?>> statistics = new TreeMap<>(); AbstractExposedStatistics<T> exposedObject = (AbstractExposedStatistics<T>) findExposedObject(context); if (exposedObject != null) { if (statisticNames == null || statisticNames.isEmpty()) { statistics.putAll(exposedObject.queryStatistics()); } else { for (String statisticName : statisticNames) { try { statistics.put(statisticName, exposedObject.queryStatistic(statisticName)); <START> } catch (IllegalArgumentException ignored) { <END> } } } } return statistics; }</code><technical_language>modify prevent a business flow handling exceptions</technical_language>

Target:
public Map<String, Statistic<?, ?>> collectStatistics(Context context, Collection<String> statisticNames) { Map<String, Statistic<?, ?>> statistics = new TreeMap<>(); AbstractExposedStatistics<T> exposedObject = (AbstractExposedStatistics<T>) findExposedObject(context); if (exposedObject != null) { if (statisticNames == null || statisticNames.isEmpty()) { statistics.putAll(exposedObject.queryStatistics()); } else { for (String statisticName : statisticNames) { Statistic<?, ?> statistic = exposedObject.queryStatistic(statisticName); if (statistic != null) { statistics.put(statisticName, statistic); } } } } return statistics; }
Source:
<code><START> static void ensureInitialized() { <END> if (sExecutorService == null) { sExecutorService = Executors.newCachedThreadPool(); } }</code><technical_language>this public class is package protected is public is visible package</technical_language>

Target:
public static void ensureInitialized() { if (sExecutorService == null) { sExecutorService = Executors.newCachedThreadPool(); } }
Source:
<code>LedgerMetadataFormat buildProtoFormat(boolean withPassword) { LedgerMetadataFormat.Builder builder = LedgerMetadataFormat.newBuilder(); builder.setQuorumSize(writeQuorumSize).setAckQuorumSize(ackQuorumSize) .setEnsembleSize(ensembleSize).setLength(length) .setState(state).setLastEntryId(lastEntryId); if (storeSystemtimeAsLedgerCreationTime) { <START> builder.setCtime(ctime); <END> } builder.setDigestType(digestType); if (hasPassword && withPassword) { builder.setPassword(ByteString.copyFrom(password)); } if (customMetadata != null) { LedgerMetadataFormat.cMetadataMapEntry.Builder cMetadataBuilder = LedgerMetadataFormat.cMetadataMapEntry.newBuilder(); for (Map.Entry<String, byte[]> entry : customMetadata.entrySet()) { cMetadataBuilder.setKey(entry.getKey()).setValue(ByteString.copyFrom(entry.getValue())); builder.addCustomMetadata(cMetadataBuilder.build()); } } for (Map.Entry<Long, ArrayList<BookieSocketAddress>> entry : ensembles.entrySet()) { LedgerMetadataFormat.Segment.Builder segmentBuilder = LedgerMetadataFormat.Segment.newBuilder(); segmentBuilder.setFirstEntryId(entry.getKey()); for (BookieSocketAddress addr : entry.getValue()) { segmentBuilder.addEnsembleMember(addr.toString()); } builder.addSegment(segmentBuilder.build()); } return builder.build(); }</code><technical_language>I initially for BC, put password digesttype in metadata long time ago. introduced, password digesttype added time. reason digest is skipped. I version introduced, 4.1.0 4.2.0. I suggest keeping logic before. if (hasPassword) { builder.setDigestType(digestType); if (withPassword) { ... } } a separate issues clean BC related legacy code enforce EOL of releases</technical_language>

Target:
LedgerMetadataFormat buildProtoFormat(boolean withPassword) { LedgerMetadataFormat.Builder builder = LedgerMetadataFormat.newBuilder(); builder.setQuorumSize(writeQuorumSize).setAckQuorumSize(ackQuorumSize) .setEnsembleSize(ensembleSize).setLength(length) .setState(state).setLastEntryId(lastEntryId); if (storeSystemtimeAsLedgerCreationTime) { builder.setCtime(ctime); } if (hasPassword) { builder.setDigestType(digestType); if (withPassword) { builder.setPassword(ByteString.copyFrom(password)); } } if (customMetadata != null) { LedgerMetadataFormat.cMetadataMapEntry.Builder cMetadataBuilder = LedgerMetadataFormat.cMetadataMapEntry.newBuilder(); for (Map.Entry<String, byte[]> entry : customMetadata.entrySet()) { cMetadataBuilder.setKey(entry.getKey()).setValue(ByteString.copyFrom(entry.getValue())); builder.addCustomMetadata(cMetadataBuilder.build()); } } for (Map.Entry<Long, ArrayList<BookieSocketAddress>> entry : ensembles.entrySet()) { LedgerMetadataFormat.Segment.Builder segmentBuilder = LedgerMetadataFormat.Segment.newBuilder(); segmentBuilder.setFirstEntryId(entry.getKey()); for (BookieSocketAddress addr : entry.getValue()) { segmentBuilder.addEnsembleMember(addr.toString()); } builder.addSegment(segmentBuilder.build()); } return builder.build(); }
Source:
<code>private Object getService(String clazz, String filter) { BundleContext bundleContext = getBundleContext(); ServiceReference<?>[] ref; try { ref = bundleContext.getServiceReferences(clazz, filter); if (ref.length > 1) throw new InvalidSyntaxException("Multiple service references found", filter); if (ref.length < 1) throw new InvalidSyntaxException("No service references found", filter); return bundleContext.getService(ref[0]); } catch (InvalidSyntaxException e) { <START> LOGGER.error(String.format("Invalid filter: %s", filter)); <END> } catch (NullPointerException e) { LOGGER.debug( String.format("Service Reference for class %s not found. Returning NULL", clazz)); } return null; }</code><technical_language>[parameterized logging](<LINK_0> Also, error is right level this exception system break</technical_language>

Target:
private Object getService(String clazz, String filter) { BundleContext bundleContext = getBundleContext(); ServiceReference<?>[] refs; try { refs = bundleContext.getServiceReferences(clazz, filter); if (refs != null) { if (refs.length > 1) { LOGGER.warn( "More than one service references are found with class: {}, and filter: {}\n" + "Ignoring rest of service references except for the first of the below list:", clazz, filter); Arrays.stream(refs).forEachOrdered(ref -> LOGGER.warn(ref.toString())); } return bundleContext.getService(refs[0]); } } catch (InvalidSyntaxException e) { LOGGER.warn("Invalid filter: {}", filter); } return null; }
Source:
<code>@Override public void bundleChanged( BundleEvent event ) { switch ( event.getType() ) { case BundleEvent.UNINSTALLED: case BundleEvent.INSTALLED: if ( event.getBundle().getSymbolicName().startsWith( COMMON_UI_BUNDLE ) ) { String bundleStr = event.getBundle().getHeaders().get( "Bundle-Name" ) + event.getBundle().getHeaders().get( "Bundle-Version" ); <START> log.info( "Received Bundle event : {}", bundleStr <END> + ( ( event.getType() == BundleEvent.INSTALLED ) ? "Installed" : "Uninstalled" ) ); bundleStateManager.setState( bundleStr, event.getBundle().getState() ); } break; } }</code><technical_language>deploy transformed platform plugins some custom header Bundle-PlatformPluginName determine if need store state in bundleStateManager? avoid maintaining whitelist solution applies immediately platform plugins deployed in OSGi</technical_language>

Target:
@Override public void bundleChanged( BundleEvent event ) { switch ( event.getType() ) { case BundleEvent.UNINSTALLED: case BundleEvent.INSTALLED: if ( event.getBundle().getHeaders().get( "Bundle-PlatformPluginName" ) != null ) { String bundleStr = event.getBundle().getHeaders().get( "Bundle-Name" ) + event.getBundle().getHeaders().get( "Bundle-Version" ); log.info( "Received Bundle event : {}", bundleStr + ( ( event.getType() == BundleEvent.INSTALLED ) ? "Installed" : "Uninstalled" ) ); bundleStateManager.setState( bundleStr, event.getType() ); } break; } }
Source:
<code>public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { <START> return initScore < other.getInitScore() ? -1 : 1; <END> } else { return Integer.compare(score, other.getScore()); } }</code><technical_language>Nitpick: return Integer.compare(initScore, other.getInitScore());</technical_language>

Target:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { return Integer.compare(initScore, other.getInitScore()); } else { return Integer.compare(score, other.getScore()); } }
Source:
<code>public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); <START> linesOfText = null; <END> correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }</code><technical_language>above, prefer a blank entry null</technical_language>

Target:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); linesOfText = new String[]{}; correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }
Source:
<code>public void testConvertToDataModelTypeWithoutFiles() { <START> uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter(); <END> Variant converted = converter.convert(mongoVariant); assertEquals(variant, converted); }</code><technical_language>Full qualification is needed</technical_language>

Target:
public void testConvertToDataModelTypeWithoutFiles() { DBObjectToVariantConverter converter = new DBObjectToVariantConverter(); Variant converted = converter.convert(mongoVariant); assertEquals(variant, converted); }
Source:
<code>public static void setForceLogs(String userId, boolean forceLogs) { PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()) .edit() <START> .putBoolean(userId + "_" + FORCE_LOGS, forceLogs) <END> .apply(); }</code><technical_language>nit: this key (userId+"_"+FORCE_LOGS) is in places, drift unexpectedly sides, I good for in helper function</technical_language>

Target:
public static void setForceLogs(String userId, boolean forceLogs) { PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()) .edit() .putBoolean(getUserSpecificKey(userId, FORCE_LOGS), forceLogs) .apply(); }
Source:
<code>public void createSnapshotTest_invalidIndex(){ String indexName = "live_xxxxxxxxx"; File snapshot = null; try { snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); <START> assertNull(snapshot); <END> } catch (DotStateException | IllegalArgumentException | IOException e) { e.printStackTrace(); } }</code><technical_language>assertNull needed if expecting exception</technical_language>

Target:
public void createSnapshotTest_invalidIndex() throws IOException{ String indexName = "live_xxxxxxxxx"; esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); }
Source:
<code>public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); PageDTO page = (PageDTO) request.getAttribute(PageHandlerMapping.PAGE_ATTRIBUTE_NAME); assert page != null; model.addObject(MODEL_ATTRIBUTE_NAME, page); model.addObject("pageFields", page.getPageFields()); model.addObject("BLC_PAGE_TYPE", "page"); String plainTextStr = (String) page.getPageFields().get("plainText"); if (!StringUtils.isEmpty(plainTextStr)) { if (Boolean.valueOf(plainTextStr)) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); } } String templatePath = page.getTemplatePath(); ExtensionResultHolder<String> erh = new ExtensionResultHolder<String>(); Boolean internalValidateFindPreviouslySet = false; ExtensionResultStatusType extResult; try { if (!BroadleafRequestContext.getBroadleafRequestContext().getInternalValidateFind()) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); internalValidateFindPreviouslySet = true; } extResult = templateOverrideManager.getProxy().getOverrideTemplate(erh, page); } finally { if (internalValidateFindPreviouslySet) { <START> BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); <END> } } if (extResult != ExtensionResultStatusType.NOT_HANDLED) { templatePath = erh.getResult(); } model.setViewName(templatePath); addDeepLink(model, deepLinkService, page); return model; }</code><technical_language>again, false if previously set true in this scope? Otherwise, true</technical_language>

Target:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); PageDTO page = (PageDTO) request.getAttribute(PageHandlerMapping.PAGE_ATTRIBUTE_NAME); assert page != null; model.addObject(MODEL_ATTRIBUTE_NAME, page); model.addObject("pageFields", page.getPageFields()); model.addObject("BLC_PAGE_TYPE", "page"); String plainTextStr = (String) page.getPageFields().get("plainText"); if (!StringUtils.isEmpty(plainTextStr)) { if (Boolean.valueOf(plainTextStr)) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); } } String templatePath = page.getTemplatePath(); ExtensionResultHolder<String> erh = new ExtensionResultHolder<String>(); Boolean internalValidateFindPreviouslySet = false; ExtensionResultStatusType extResult; try { if (!BroadleafRequestContext.getBroadleafRequestContext().getInternalValidateFind()) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); internalValidateFindPreviouslySet = true; } extResult = templateOverrideManager.getProxy().getOverrideTemplate(erh, page); } finally { if (internalValidateFindPreviouslySet) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(false); } } if (extResult != ExtensionResultStatusType.NOT_HANDLED) { templatePath = erh.getResult(); } model.setViewName(templatePath); addDeepLink(model, deepLinkService, page); return model; }
Source:
<code>public String getErrorMessage() { String message = null; switch(resolvedError) { case AmbryUnavailable: message += "Insufficient DataNodes replied to complete operation " + context + ":" + operationPolicy; break; case BlobDoesNotExist: message += "BlobDoesNotExist to perform the operation " + context + ":" + operationPolicy; break; case BlobDeleted: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob is deleted "; break; case BlobExpired: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob expired "; break; default: <START> message += "Experienced an unexpected internal error for operation " + context + ":" + operationPolicy; <END> } return message; }</code><technical_language>include resolvedError in this message is on</technical_language>

Target:
public String getErrorMessage() { String message = null; switch(resolvedError) { case AmbryUnavailable: message += "Insufficient DataNodes replied to complete operation " + context + ":" + operationPolicy + "resulting in AmbryUnavailable"; break; case BlobDoesNotExist: message += "BlobDoesNotExist to perform the operation " + context + ":" + operationPolicy; break; case BlobDeleted: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob is deleted "; break; case BlobExpired: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob expired "; break; default: message += "Experienced an unexpected internal "+ resolvedError +" error for operation " + context + ":" + operationPolicy; } return message; }
Source:
<code>protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException, InterruptedException { try { List<P4Head> heads = getHeads(listener); for (P4Head head : heads) { if (criteria == null) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } else { String base = head.getPath(); ClientHelper p4 = new ClientHelper(credential, listener, hack, charset); SCMSourceCriteria.Probe probe = new P4Probe(p4, base); if (criteria.isHead(probe, listener)) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } } } <START> } catch (Exception e) { <END> String err = "P4: Unable add streams to observer."; logger.severe(err); listener.error(err); throw new InterruptedException(e.getMessage()); } }</code><technical_language>Upgrade scm api 2.0.4 released propagate IOExceptions</technical_language>

Target:
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException, InterruptedException { try { List<P4Head> heads = getHeads(listener); for (P4Head head : heads) { if (criteria == null) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } else { String base = head.getPath(); SCMSourceCriteria.Probe probe = new P4Probe(credential, listener, charset, base); if (criteria.isHead(probe, listener)) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } } checkInterrupt(); } } catch (Exception e) { throw new IOException(e.getMessage()); } }
Source:
<code>public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity player) { <START> target.playSound(sound, 1.0F, 1.0F); <END> return super.hitEntity(stack, target, player); }</code><technical_language>putting volume pitch fields well</technical_language>

Target:
public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity player) { target.playSound(sound.get(), volume, pitch); return super.hitEntity(stack, target, player); }
Source:
<code>protected void comparePlans(String sql) { <START> comparePlans(sql, null); <END> }</code><technical_language>Please empty map instead. avoid a NPE errors in future. comparePlans(sql, Collections.emptyMap());</technical_language>

Target:
protected void comparePlans(String sql) { comparePlans(sql, Collections.emptyMap()); }
Source:
<code>public String getAvatarUrl() { if(chatMember == null) { return null; } if (!(chatMember instanceof ChatRoomMemberJabberImpl)) { return null; } ChatRoomMemberJabberImpl memberJabber = ((ChatRoomMemberJabberImpl) this.chatMember); String url; if((url = (String) memberJabber.getData( ChatRoomMemberPresenceExtensionReader .IDENTITY_AVATAR_URL)) != null) { return url; } else if((url = memberJabber.getAvatarUrl()) != null) { return url; } String email; if((email = getEmail()) != null) { return String.format(GRAVARAR_URL_FORMAT, Util.stringToMD5hash(email)); } String avatarId; if((avatarId = (String) memberJabber.getData( ChatRoomMemberPresenceExtensionReader.AVATAR_ID)) != null) { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(avatarId)); } <START> return null; <END> }</code><technical_language>return a valid random avatar based user id if else is missing</technical_language>

Target:
public String getAvatarUrl() { if (chatMember == null) { return null; } if (!(chatMember instanceof ChatRoomMemberJabberImpl)) { return null; } ChatRoomMemberJabberImpl memberJabber = ((ChatRoomMemberJabberImpl) this.chatMember); IdentityPacketExtension ipe = getIdentityExtensionOrNull( memberJabber.getLastPresence()); String url; if (ipe != null && (url = ipe.getUserAvatarUrl()) != null) { return url; } else if ((url = memberJabber.getAvatarUrl()) != null) { return url; } String email; if ((email = getEmail()) != null) { return String.format(GRAVARAR_URL_FORMAT, Util.stringToMD5hash(email)); } AvatarIdPacketExtension avatarIdExtension = getAvatarIdExtensionOrNull( memberJabber.getLastPresence()); String avatarId; if (ipe != null && (avatarId = avatarIdExtension.getAvatarId()) != null) { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(avatarId)); } else { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(identifier)); } }
Source:
<code>public List<OpenTransaction> startTransactions(List<? extends PreCommitCondition> conditions) { if (conditions.isEmpty()) { return ImmutableList.of(); } List<StartIdentifiedAtlasDbTransactionResponse> responses = timelockService.startIdentifiedAtlasDbTransactionBatch(conditions.size()); Preconditions.checkState(conditions.size() == responses.size(), "Different number of responses and conditions"); try { long immutableTs = Collections.max(responses.stream() .map(response -> response.immutableTimestamp().getImmutableTimestamp()) <START> .collect(Collectors.toList())); <END> recordImmutableTimestamp(immutableTs); cleaner.punch(responses.get(0).startTimestampAndPartition().timestamp()); return Streams.zip( responses.stream(), conditions.stream(), (response, condition) -> { LockToken immutableTsLock = response.immutableTimestamp().getLock(); Supplier<Long> startTimestampSupplier = Suppliers.ofInstance( response.startTimestampAndPartition().timestamp()); Transaction transaction = createTransaction( immutableTs, startTimestampSupplier, immutableTsLock, condition); return new OpenTransactionImpl(transaction, immutableTsLock); }).collect(Collectors.toList()); } catch (Throwable t) { timelockService.tryUnlock( responses.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet())); throw Throwables.rewrapAndThrowUncheckedException(t); } }</code><technical_language>non-actionable: I guess this is matter, collecting a list is kind of unnecessary</technical_language>

Target:
public List<OpenTransaction> startTransactions(List<? extends PreCommitCondition> conditions) { if (conditions.isEmpty()) { return ImmutableList.of(); } List<StartIdentifiedAtlasDbTransactionResponse> responses = timelockService.startIdentifiedAtlasDbTransactionBatch(conditions.size()); Preconditions.checkState(conditions.size() == responses.size(), "Different number of responses and conditions"); try { long immutableTs = responses.stream() .mapToLong(response -> response.immutableTimestamp().getImmutableTimestamp()) .max().getAsLong(); recordImmutableTimestamp(immutableTs); cleaner.punch(responses.get(0).startTimestampAndPartition().timestamp()); return Streams.zip( responses.stream(), conditions.stream(), (response, condition) -> { LockToken immutableTsLock = response.immutableTimestamp().getLock(); Supplier<Long> startTimestampSupplier = Suppliers.ofInstance( response.startTimestampAndPartition().timestamp()); Transaction transaction = createTransaction( immutableTs, startTimestampSupplier, immutableTsLock, condition); return new OpenTransactionImpl(transaction, immutableTsLock); }).collect(Collectors.toList()); } catch (Throwable t) { timelockService.tryUnlock( responses.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet())); throw Throwables.rewrapAndThrowUncheckedException(t); } }
Source:
<code>public String marshall(Object input, Map<String, Object> parameters) { try { if (parameters.containsKey(MARSHALLER_PARAMETER_STRICT)) { <START> jsonContext.get().setWrap((boolean) parameters.get(MARSHALLER_PARAMETER_STRICT)); <END> } if (NOT_NULL.equals(parameters.get(FIELDS))) { jsonContext.get().setWriteNull(false); } return marshall(input); } finally { jsonContext.get().reset(); } }</code><technical_language>This casting boolean is failing receiving a String parameter (true) due changes for invoking _buildParameters_ instead of _isStrictType_ . Failing test is _IdentifierJbpmRestIntegrationTest.testBasicJbpmRequest_ If receives a String, be: suggestion jsonContext.get().setWrap(Boolean.parseBoolean((string) parameters.get(MARSHALLER_PARAMETER_STRICT)));</technical_language>

Target:
public String marshall(Object input, Map<String, Object> parameters) { try { if (parameters.containsKey(MARSHALLER_PARAMETER_STRICT)) { jsonContext.get().setWrap(Boolean.parseBoolean((String) parameters.get(MARSHALLER_PARAMETER_STRICT))); } if (NOT_NULL.equals(parameters.get(FIELDS))) { jsonContext.get().setWriteNull(false); } return marshall(input); } finally { jsonContext.get().reset(); } }
Source:
<code>public NewsItem getNewsItemById(Long id) { return newsItemRepository.findById(id) <START> .orElseThrow(() -> new RestException("Not found", 404)); <END> }</code><technical_language>HttpServletResponse.SC_NOT_FOUND</technical_language>

Target:
public NewsItem getNewsItemById(Long id) { return newsItemRepository.findById(id) .orElseThrow(() -> new RestException("Not found", HttpServletResponse.SC_NOT_FOUND)); }
Source:
<code>private boolean maybeDrainPendingCall(Call call, long now) { try { Node node = call.nodeProvider.provide(); if (node != null) { log.trace("Assigned to node {}", call, node); call.curNode = node; getOrCreateListValue(callsToSend, node).add(call); return true; } else { log.trace("Unable to assign to a node.", call); return false; } } catch (Throwable t) { log.debug("Unable to choose node for {}", call, t); <START> if (t instanceof RetriableException) { <END> call.retry(call, t); } else { call.fail(now, t); } return true; } }</code><technical_language>this logic of checking type of t is in multiple places, consolidate this logic call.retry(), passing throwable instance. rename method a bit more encompassing, attemptToRetry something</technical_language>

Target:
private boolean maybeDrainPendingCall(Call call, long now) { try { Node node = call.nodeProvider.provide(); if (node != null) { log.trace("Assigned to node {}", call, node); call.curNode = node; getOrCreateListValue(callsToSend, node).add(call); return true; } else { log.trace("Unable to assign to a node.", call); return false; } } catch (Throwable t) { log.debug("Unable to choose node for {}", call, t); call.retryOrFail(call, t, now); return true; } }
Source:
<code>public Builder id(String id) { <START> this.id = field1; <END> return getSelf(); }</code><technical_language>This fix kept; incorrect PR fixed part of a commit reverted. suggestion this.id = id;</technical_language>

Target:
public Builder id(String id) { this.id = id; return getSelf(); }
Source:
<code>public static HeaderBuffer create(final ReadableByteChannel channel, final long capacity, final int maxPageBytes) throws IOException { if (maxPageBytes < MAX_GET_ELEMENT_SIZE) { throw new IllegalArgumentException("Page size must be at least " + MAX_GET_ELEMENT_SIZE); } HeaderChannelBuffer channelBuffer = new HeaderChannelBuffer(channel, capacity, maxPageBytes); channelBuffer.fill(); if (channelBuffer.capacity <= maxPageBytes) { <START> return new HeaderInMemoryBuffer(channelBuffer.buffer); <END> } return channelBuffer; }</code><technical_language>return HeaderInMemoryBuffer creating a new HeaderChannelBuffer if capacity maxPageBytes small enough</technical_language>

Target:
public static HeaderBuffer create(final ReadableByteChannel channel, final long capacity, final int maxPageBytes) throws IOException { if (maxPageBytes < MAX_GET_ELEMENT_SIZE) { throw new IllegalArgumentException("Page size must be at least " + MAX_GET_ELEMENT_SIZE); } if (capacity <= maxPageBytes) { ByteBuffer buf = ByteBuffer.allocate((int) capacity).order(ByteOrder.LITTLE_ENDIAN); IOUtils.readFully(channel, buf); buf.flip(); return new HeaderInMemoryBuffer(buf); } HeaderChannelBuffer channelBuffer = new HeaderChannelBuffer(channel, capacity, maxPageBytes); channelBuffer.fill(); return channelBuffer; }
Source:
<code>@Override public String toDruidExpression( RexNode rexNode, RelDataType rowType, DruidQuery query) { final RexCall call = (RexCall) rexNode; final RexLiteral flag = (RexLiteral) call.getOperands().get(0); final TimeUnitRange calciteUnit = (TimeUnitRange) flag.getValue(); final RexNode arg = call.getOperands().get(1); final String input = DruidExpressions.toDruidExpression(arg, rowType, query); if (input == null) { return null; } final String druidUnit = EXTRACT_UNIT_MAP.get(calciteUnit); if (druidUnit == null) { return null; } final TimeZone tz; if (arg.getType().getSqlTypeName() <START> == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) { <END> tz = TimeZone.getTimeZone(query.getConnectionConfig().timeZone()); } else { tz = DateTimeUtils.UTC_ZONE; } return DruidExpressions.applyTimeExtract(input, druidUnit, tz); }</code><technical_language>this line</technical_language>

Target:
@Override public String toDruidExpression( RexNode rexNode, RelDataType rowType, DruidQuery query) { final RexCall call = (RexCall) rexNode; final RexLiteral flag = (RexLiteral) call.getOperands().get(0); final TimeUnitRange calciteUnit = (TimeUnitRange) flag.getValue(); final RexNode arg = call.getOperands().get(1); final String input = DruidExpressions.toDruidExpression(arg, rowType, query); if (input == null) { return null; } final String druidUnit = EXTRACT_UNIT_MAP.get(calciteUnit); if (druidUnit == null) { return null; } final TimeZone tz = arg.getType().getSqlTypeName() == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? TimeZone.getTimeZone(query.getConnectionConfig().timeZone()) : DateTimeUtils.UTC_ZONE; return DruidExpressions.applyTimeExtract(input, druidUnit, tz); }
Source:
<code>public void testgetBiGaussianValue() throws MSDKException { MultiKeyMap<Integer, Triplet> horizontalSlice = objSliceSparseMatrix.getHorizontalSlice(140.1037, 1, 9); BiGaussianSimilarityTest objBiGaussian = new BiGaussianSimilarityTest(); boolean goodPeak = objBiGaussian.execute(horizontalSlice, 1, 9, 140.1037); <START> Assert.assertEquals(true, goodPeak); <END> }</code><technical_language>assertTrue</technical_language>

Target:
public void testgetBiGaussianValue() throws MSDKException { MultiKeyMap<Integer, Triplet> horizontalSlice = objSliceSparseMatrix.getHorizontalSlice(140.1037, 1, 9); BiGaussianSimilarityTest objBiGaussian = new BiGaussianSimilarityTest(); boolean goodPeak = objBiGaussian.execute(horizontalSlice, 1, 9, 140.1037); Assert.assertTrue(goodPeak); }
Source:
<code>public static Properties loadProperties(String path){ String propertiesFilePath = System.getProperty(path); <START> M_log.debug("ccm props: " + propertiesFilePath); <END> if (!propertiesFilePath.isEmpty()) { return PropertiesUtilities.getPropertiesObjectFromURL(propertiesFilePath); } M_log.error("File path for (" + path + ") is not provided"); return null; }</code><technical_language>put ccm in message this tied ccm in important way</technical_language>

Target:
public static Properties loadProperties(String path){ String propertiesFilePath = System.getProperty(path); M_log.debug(path + " : " + propertiesFilePath); if (!propertiesFilePath.isEmpty()) { return PropertiesUtilities.getPropertiesObjectFromURL(propertiesFilePath); } M_log.error("File path for (" + path + ") is not provided"); return null; }