auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Connection connect(String url, Properties info) throws SQLException { if (url.startsWith(LONG_PREFIX)) { url = url.substring(LONG_PREFIX.length()); } else if (url.startsWith(PREFIX)) { url = url.substring(PREFIX.length()); } else { return null; } CrateConnection connection; ClientHandleRegistry.ClientHandle handle = clientHandleRegistry.getHandle(url); if (url.equals("/")) { connection = new CrateConnection(handle, info); connection.connect(); } else { String[] pathAndParams = url.split("\\?"); connection = new CrateConnection(handle, info); connection.connect(); <START> try { <END> String[] urlParts = pathAndParams[0].split("/"); if (urlParts.length == 2) connection.setSchema(urlParts[1]); if (pathAndParams.length == 2) connection.setClientInfo(parseProperties(pathAndParams[1])); else if (urlParts.length > 2) { connection.close(); throw new SQLException("URL format is invalid. " + "Valid format is: [jdbc:]crate://[host1:port1][, host2:port2 ...][/schema][?property=value]"); } } catch (InvalidPropertiesFormatException e) { connection.close(); throw new SQLException(e.getMessage()); } } return connection; }</code><technical_language>wrap necessary code try catch</technical_language>

Target:
public Connection connect(String url, Properties info) throws SQLException { if (url.startsWith(LONG_PREFIX)) { url = url.substring(LONG_PREFIX.length()); } else if (url.startsWith(PREFIX)) { url = url.substring(PREFIX.length()); } else { return null; } try { url = parseUrl(url, info); } catch (IOException e) { throw new SQLException(e); } ClientHandleRegistry.ClientHandle handle = clientHandleRegistry.getHandle(url); CrateConnection connection = new CrateConnection(handle, info); connection.connect(); if (!url.equals("/")) { String[] urlParts = url.split("/"); if (urlParts.length == 2) { connection.setSchema(urlParts[1]); } else if (urlParts.length > 2) { connection.close(); throw new SQLException("URL format is invalid. " + "Valid format is: [jdbc:]crate://[host1:port1][, host2:port2 ...][/schema][?property=value]"); } connection.setClientInfo(info); } return connection; }
Source:
<code>public Object visit(ASTUserClass node, Object data) { List<ASTFieldDeclaration> fields = node.findDescendantsOfType(ASTFieldDeclaration.class); List<ASTMethod> methods = node.findDescendantsOfType(ASTMethod.class); Optional<NodeAndLocation> firstMethod = methods.stream() .filter(method -> method.hasRealLoc()) .map(method -> new NodeAndLocation(method)) <START> .min(Comparator.naturalOrder()); <END> if (!firstMethod.isPresent()) { return data; } for (ASTFieldDeclaration field : fields) { NodeAndLocation fieldPosition = new NodeAndLocation(field); if (fieldPosition.compareTo(firstMethod.get()) > 0) { addViolation(data, field, field.getName()); } } return data; }</code><technical_language>do min(nodeComparator), comparator defined, firstMethod Optional<ASTMethod></technical_language>

Target:
public Object visit(ASTUserClass node, Object data) { List<ASTField> fields = node.findChildrenOfType(ASTField.class); List<ApexNode<?>> nonFieldDeclarations = new ArrayList<>(); nonFieldDeclarations.addAll(getMethodNodes(node)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTUserClass.class)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTProperty.class)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTBlockStatement.class)); Optional<ApexNode<?>> firstNonFieldDeclaration = nonFieldDeclarations.stream() .filter(ApexNode::hasRealLoc) .min(NODE_BY_SOURCE_LOCATION_COMPARATOR); if (!firstNonFieldDeclaration.isPresent()) { return data; } for (ASTField field : fields) { if (NODE_BY_SOURCE_LOCATION_COMPARATOR.compare(field, firstNonFieldDeclaration.get()) > 0) { addViolation(data, field, field.getName()); } } return data; }
Source:
<code>public void givenTextContentTypeAtLowAlertThresholdThenAlertRaised() throws Exception { rule.setAlertThreshold(Plugin.AlertThreshold.LOW); <START> HttpMessage msg = createHttpMessageWithHeaders(new String[] {HEADER_TEXT}); <END> rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertContentSecurityPolicyAlertRaised(); }</code><technical_language>test HEADER_X_CSP HEADER_WEBKIT_CSP individually, assert of alert is raised</technical_language>

Target:
public void givenTextContentTypeAtLowAlertThresholdThenAlertRaised() throws Exception { rule.setAlertThreshold(Plugin.AlertThreshold.LOW); HttpMessage msg = createHttpMessageWithHeaders(HEADER_TEXT); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertContentSecurityPolicyAlertRaised(); }
Source:
<code>public void initialize() throws Exception { super.init(); endpointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL; storeURLHttp = getStoreURLHttp(); providerName = publisherContext.getContextTenant().getTenantUser(USER_KEY_USER2).getUserName(); User publisherUser1 = publisherContext.getContextTenant().getTenantUser(USER_KEY_USER2); apiPublisherClientCarbonSuperUser1 = new RestAPIPublisherImpl(publisherUser1.getUserNameWithoutDomain(), publisherUser1.getPassword(), publisherUser1.getUserDomain(), publisherURLHttps); userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(), createSession(keyManagerContext)); userManagementClient.addRole(ROLE, null, PERMISSIONS); userManagementClient.addUser(ALLOWED_USER, ALLOWED_USER_PASS, new String[] {ROLE}, null); apiStoreClientAllowedUser = new RestAPIStoreImpl(ALLOWED_USER, ALLOWED_USER_PASS, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, storeURLHttps); <START> anonymousRestAPIImpl = super.getRestAPIStoreForAnonymousUser(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); <END> }</code><technical_language>Do need super here</technical_language>

Target:
public void initialize() throws Exception { super.init(); endpointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL; storeURLHttp = getStoreURLHttp(); providerName = publisherContext.getContextTenant().getTenantUser(USER_KEY_USER2).getUserName(); User publisherUser1 = publisherContext.getContextTenant().getTenantUser(USER_KEY_USER2); apiPublisherClientCarbonSuperUser1 = new RestAPIPublisherImpl(publisherUser1.getUserNameWithoutDomain(), publisherUser1.getPassword(), publisherUser1.getUserDomain(), publisherURLHttps); userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(), createSession(keyManagerContext)); userManagementClient.addRole(ROLE, null, PERMISSIONS); userManagementClient.addUser(ALLOWED_USER, ALLOWED_USER_PASS, new String[] {ROLE}, null); apiStoreClientAllowedUser = new RestAPIStoreImpl(ALLOWED_USER, ALLOWED_USER_PASS, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, storeURLHttps); anonymousRestAPIImpl = getRestAPIStoreForAnonymousUser(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); }
Source:
<code>public FileInfo[] listDir(){ try { return Files.list(p).map( path -> new PathInfo(path) ).toArray(PathInfo[]::new); } catch (IOException e) { <START> e.printStackTrace(); <END> return null; } }</code><technical_language>I do that, instead I throw a RuntimeException and/or logging mechanism log exception. IIRC printStackTrace writes stderr inline logging framework</technical_language>

Target:
public FileInfo[] listDir() throws IOException { return Files.list(p).map( path -> new PathInfo(path) ).toArray(PathInfo[]::new); }
Source:
<code><START> public void setRyaStreamsConfiguration(final String ryaInstance, final RyaStreamsDetails streamsDetails) throws InstanceDoesNotExistException, RyaClientException{ <END> requireNonNull(streamsDetails); if(!instanceExists.exists(ryaInstance)) { throw new InstanceDoesNotExistException("There is no Rya instance named '" + ryaInstance + "' in this storage."); } final RyaDetailsRepository repo = getRyaDetailsRepo(ryaInstance); try { new RyaDetailsUpdater(repo).update(oldDetails -> { final RyaDetails.Builder builder = RyaDetails.builder(oldDetails); builder.setRyaStreamsDetails(streamsDetails); return builder.build(); }); } catch (CouldNotApplyMutationException | RyaDetailsRepositoryException e) { throw new RyaClientException("Unable to update which Rya Streams subsystem is used by the '" + ryaInstance + "' Rya instance.", e); } }</code><technical_language>Null check ryaInstance</technical_language>

Target:
public void setRyaStreamsConfiguration(final String ryaInstance, final RyaStreamsDetails streamsDetails) throws InstanceDoesNotExistException, RyaClientException{ requireNonNull(ryaInstance); requireNonNull(streamsDetails); if(!instanceExists.exists(ryaInstance)) { throw new InstanceDoesNotExistException("There is no Rya instance named '" + ryaInstance + "' in this storage."); } final RyaDetailsRepository repo = getRyaDetailsRepo(ryaInstance); try { new RyaDetailsUpdater(repo).update(oldDetails -> { final RyaDetails.Builder builder = RyaDetails.builder(oldDetails); builder.setRyaStreamsDetails(streamsDetails); return builder.build(); }); } catch (CouldNotApplyMutationException | RyaDetailsRepositoryException e) { throw new RyaClientException("Unable to update which Rya Streams subsystem is used by the '" + ryaInstance + "' Rya instance.", e); } }
Source:
<code>private void uploadPersonalNote() { final SimpleCancellableHandler myHandler = new SimpleCancellableHandler(CacheDetailActivity.this, progress); final Message cancelMessage = myHandler.cancelMessage(res.getString(R.string.cache_personal_note_upload_cancelled)); progress.show(CacheDetailActivity.this, res.getString(R.string.cache_personal_note_uploading), res.getString(R.string.cache_personal_note_uploading), true, cancelMessage); myHandler.unsubscribeIfCancelled(AndroidRxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { final IConnector con = ConnectorFactory.getConnector(cache); if (con.supportsPersonalNote()) { final boolean success = con.uploadPersonalNote(cache); final Message msg = Message.obtain(); final Bundle bundle = new Bundle(); if (success) { bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, CgeoApplication.getInstance().getString(R.string.cache_personal_note_upload_done)); } else { bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, CgeoApplication.getInstance().getString(R.string.cache_personal_note_upload_error)); } <START> msg.setData(bundle); <END> myHandler.sendMessage(msg); } } })); }</code><technical_language>I simply written: java bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, CgeoApplication().getInstance().getString(success ? R.string.cache_personal_note_upload_done : R.string.cache_personal_note_upload_error)); avoid repeating code</technical_language>

Target:
private void uploadPersonalNote() { final SimpleCancellableHandler myHandler = new SimpleCancellableHandler(CacheDetailActivity.this, progress); final Message cancelMessage = myHandler.cancelMessage(res.getString(R.string.cache_personal_note_upload_cancelled)); progress.show(CacheDetailActivity.this, res.getString(R.string.cache_personal_note_uploading), res.getString(R.string.cache_personal_note_uploading), true, cancelMessage); myHandler.unsubscribeIfCancelled(AndroidRxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { final IConnector con = ConnectorFactory.getConnector(cache); final boolean success = con.uploadPersonalNote(cache); final Message msg = Message.obtain(); final Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, CgeoApplication.getInstance().getString(success ? R.string.cache_personal_note_upload_done : R.string.cache_personal_note_upload_error)); msg.setData(bundle); myHandler.sendMessage(msg); } })); }
Source:
<code><START> private UpdatedObservableAdapter<EditableConfiguration> setAsObservableConfigModel(ForwardingObservable<EditableConfiguration> model) { <END> Optional.ofNullable(observableConfigModel).ifPresent(UpdatedObservableAdapter::close); observableConfigModel = new UpdatedObservableAdapter<>(model); groupEditorViewModel.updateModel(observableConfigModel); return observableConfigModel; }</code><technical_language>This is groups break in a new config. Reproduce: 1. current config a group 1. Creare a new config 1. groups page click group 1. Exception raise This is is in groups</technical_language>

Target:
private void setAsObservableConfigModel(ForwardingObservable<EditableConfiguration> model) { Optional.ofNullable(observableConfigModel).ifPresent(UpdatedObservableAdapter::close); observableConfigModel = new UpdatedObservableAdapter<>(model); groupEditorViewModel.updateModel(observableConfigModel); }
Source:
<code>public void testExpiredEntriesCleared() { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i,-1, null, i, TimeUnit.MILLISECONDS); } <START> timeService.advance(SIZE / 2); <END> cache.clear(); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); }</code><technical_language>Do need test more 1 entry</technical_language>

Target:
public void testExpiredEntriesCleared() { for (int i = 0; i < 2; i++) { cache.put("key-" + i, "value-" + i,-1, null, i, TimeUnit.MILLISECONDS); } timeService.advance(1); cache.clear(); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); }
Source:
<code>public void onMediaDeleted(String localMediaId) { if (!TextUtils.isEmpty(localMediaId)) { if (mShowAztecEditor && !mShowGutenbergEditor) { <START> mAztecBackspaceDeletedOrGbBlockDeletedMediaItemIds.add(localMediaId); <END> UploadService.setDeletedMediaItemIds(mAztecBackspaceDeletedOrGbBlockDeletedMediaItemIds); cancelMediaUpload(StringUtils.stringToInt(localMediaId), false); } else if (mShowGutenbergEditor) { MediaModel mediaModel = mMediaStore.getMediaWithLocalId(StringUtils.stringToInt(localMediaId)); if (mediaModel == null) { return; } mAztecBackspaceDeletedOrGbBlockDeletedMediaItemIds.add(localMediaId); UploadService.setDeletedMediaItemIds(mAztecBackspaceDeletedOrGbBlockDeletedMediaItemIds); if (mediaModel.getUploadState() != null && MediaUtils.isLocalFile(mediaModel.getUploadState().toLowerCase(Locale.ROOT)) && !UploadService.isPendingOrInProgressMediaUpload(mediaModel)) { mDispatcher.dispatch(MediaActionBuilder.newRemoveMediaAction(mediaModel)); } } } }</code><technical_language>put 2 lines of code in some method call blocks of code order increase reusability</technical_language>

Target:
public void onMediaDeleted(String localMediaId) { if (!TextUtils.isEmpty(localMediaId)) { if (mShowAztecEditor && !mShowGutenbergEditor) { setDeletedMediaIdOnUploadService(localMediaId); cancelMediaUpload(StringUtils.stringToInt(localMediaId), false); } else if (mShowGutenbergEditor) { MediaModel mediaModel = mMediaStore.getMediaWithLocalId(StringUtils.stringToInt(localMediaId)); if (mediaModel == null) { return; } setDeletedMediaIdOnUploadService(localMediaId); if (mediaModel.getUploadState() != null && MediaUtils.isLocalFile(mediaModel.getUploadState().toLowerCase(Locale.ROOT)) && !UploadService.isPendingOrInProgressMediaUpload(mediaModel)) { mDispatcher.dispatch(MediaActionBuilder.newRemoveMediaAction(mediaModel)); } } } }
Source:
<code>private String createMailMessage(QueryContext queryContext) { StringBuilder msgBuilder = new StringBuilder(); switch(queryContext.getStatus().getStatus()){ case SUCCESSFUL: msgBuilder.append("Result available at "); String baseURI = conf.get(GrillConfConstants.GRILL_SERVER_BASE_URL, GrillConfConstants.DEFAULT_GRILL_SERVER_BASE_URL); msgBuilder.append(baseURI); msgBuilder.append("queryapi/queries/"); msgBuilder.append(queryContext.getQueryHandle()); <START> msgBuilder.append("/resultset"); <END> break; case FAILED: msgBuilder.append(queryContext.getStatus().getErrorMessage()); break; case CANCELED: case CLOSED: default: break; } return msgBuilder.toString(); }</code><technical_language>passing /httpresultset is downloadable instead of /resultset</technical_language>

Target:
private String createMailMessage(QueryContext queryContext) { StringBuilder msgBuilder = new StringBuilder(); switch(queryContext.getStatus().getStatus()){ case SUCCESSFUL: msgBuilder.append("Result available at "); String baseURI = conf.get(GrillConfConstants.GRILL_SERVER_BASE_URL, GrillConfConstants.DEFAULT_GRILL_SERVER_BASE_URL); msgBuilder.append(baseURI); msgBuilder.append("queryapi/queries/"); msgBuilder.append(queryContext.getQueryHandle()); msgBuilder.append("/httpresultset"); break; case FAILED: msgBuilder.append(queryContext.getStatus().getErrorMessage()); break; case CANCELED: case CLOSED: default: break; } return msgBuilder.toString(); }
Source:
<code>public InvalidParameterValueException(Class expected, Class<? extends Object> actual) { <START> super(MSG_PREFIX+expected.getName()+" but actual class was "+actual.getName()); <END> }</code><technical_language>I prefer String.format, is true I C, formatted messages more readable concatenations</technical_language>

Target:
public InvalidParameterValueException(Class expected, Class<? extends Object> actual) { super(format(MSG, expected.getName(), actual.getName())); }
Source:
<code>public boolean removeVMFromBackupOffering(final VirtualMachine vm) { final VeeamClient client = getClient(vm.getDataCenterId()); final VmwareDatacenter vmwareDC = findVmwareDatacenterForVM(vm); try { if (!client.removeVMFromVeeamJob(vm.getBackupExternalId(), vm.getInstanceName(), vmwareDC.getVcenterHost())) { LOG.warn("Failed to remove VM from Veeam Job id: " + vm.getBackupExternalId()); } } catch (CloudRuntimeException e) { LOG.debug("VM was removed from the job so could not remove again, trying to delete the veeam job now.", e); } final String clonedJobName = getGuestBackupName(vm.getInstanceName(), vm.getUuid()); if (!client.deleteJobAndBackup(clonedJobName)) { LOG.warn("Failed to remove Veeam job and backup for job: " + clonedJobName); throw new CloudRuntimeException("Failed to delete Veeam B&R job and backup, an operation may be in progress. Please try again after some time."); } <START> for (final Backup backup: backupDao.listByVmId(null, vm.getId())) { <END> backupDao.remove(backup.getId()); } return true; }</code><technical_language>this moved BackupManagerImpl successful operation</technical_language>

Target:
public boolean removeVMFromBackupOffering(final VirtualMachine vm) { final VeeamClient client = getClient(vm.getDataCenterId()); final VmwareDatacenter vmwareDC = findVmwareDatacenterForVM(vm); try { if (!client.removeVMFromVeeamJob(vm.getBackupExternalId(), vm.getInstanceName(), vmwareDC.getVcenterHost())) { LOG.warn("Failed to remove VM from Veeam Job id: " + vm.getBackupExternalId()); } } catch (Exception e) { LOG.debug("VM was removed from the job so could not remove again, trying to delete the veeam job now.", e); } final String clonedJobName = getGuestBackupName(vm.getInstanceName(), vm.getUuid()); if (!client.deleteJobAndBackup(clonedJobName)) { LOG.warn("Failed to remove Veeam job and backup for job: " + clonedJobName); throw new CloudRuntimeException("Failed to delete Veeam B&R job and backup, an operation may be in progress. Please try again after some time."); } return true; }
Source:
<code>private Optional<SystemTable> getPropertiesSystemTable(ConnectorSession connectorSession, SchemaTableName tableName, SchemaTableName sourceTableName) { Optional<Table> table = metastore.getTable(sourceTableName.getSchemaName(), sourceTableName.getTableName()); if (!table.isPresent() || table.get().getTableType().equals(TableType.VIRTUAL_VIEW.name())) { throw new TableNotFoundException(tableName); } Map<String, String> properties = table.get().getParameters(); List<ColumnMetadata> columns = properties.keySet().stream().map(key -> new ColumnMetadata(key, VarcharType.VARCHAR)).collect(toImmutableList()); <START> ImmutableList<Type> types = columns.stream().map(columnMetadata -> columnMetadata.getType()).collect(toImmutableList()); <END> Iterable<List<Object>> propertyValues = singletonList(ImmutableList.copyOf(properties.values())); SystemTable propertiesSystemTable = new SystemTable() { @Override public Distribution getDistribution() { return Distribution.SINGLE_COORDINATOR; } @Override public ConnectorTableMetadata getTableMetadata() { return new ConnectorTableMetadata(sourceTableName, columns); } @Override public RecordCursor cursor(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint) { return new InMemoryRecordSet(types, propertyValues).cursor(); } }; return Optional.of(propertiesSystemTable); }</code><technical_language>Nit: declare variable List<...>. Also, lambda simplified a method reference: java List<Type> types = columns.stream().map(ColumnMetadata::getType).collect(toImmutableList());</technical_language>

Target:
private Optional<SystemTable> getPropertiesSystemTable(ConnectorSession connectorSession, SchemaTableName tableName, SchemaTableName sourceTableName) { Optional<Table> table = metastore.getTable(sourceTableName.getSchemaName(), sourceTableName.getTableName()); if (!table.isPresent() || table.get().getTableType().equals(TableType.VIRTUAL_VIEW.name())) { throw new TableNotFoundException(tableName); } List<Map.Entry<String, String>> sortedEntries = table.get().getParameters().entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).collect(toImmutableList()); List<ColumnMetadata> columns = sortedEntries.stream().map(Map.Entry::getKey).map(key -> new ColumnMetadata(key, VarcharType.VARCHAR)).collect(toImmutableList()); List<Type> types = columns.stream().map(ColumnMetadata::getType).collect(toImmutableList()); Iterable<List<Object>> propertyValues = ImmutableList.of(ImmutableList.copyOf(sortedEntries.stream().map(Map.Entry::getValue).collect(toImmutableList()))); SystemTable propertiesSystemTable = new SystemTable() { @Override public Distribution getDistribution() { return Distribution.SINGLE_COORDINATOR; } @Override public ConnectorTableMetadata getTableMetadata() { return new ConnectorTableMetadata(sourceTableName, columns); } @Override public RecordCursor cursor(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint) { return new InMemoryRecordSet(types, propertyValues).cursor(); } }; return Optional.of(propertiesSystemTable); }
Source:
<code>public DatastreamTaskImpl() { _partitions = new ArrayList<>(); _partitionsV2 = new ArrayList<>(); _dependencies = new ArrayList<>(); <START> computeHash(); <END> }</code><technical_language>While I understand concern, daunting error-prone call computeHash() in (almost) single method mutate this object (but of them). Precomputing hashcode is useful type is immutable. I more straightforward compute hashcode demand, especially - if of - Brooklin's code is CPU bound anyways</technical_language>

Target:
public DatastreamTaskImpl() { _partitions = new ArrayList<>(); _partitionsV2 = new ArrayList<>(); _dependencies = new ArrayList<>(); }
Source:
<code>public String getServerPublicKey(String serverName) { <START> PublicKey pk = null; <END> EngineSSHDialog dialog = getEngineSSHDialog(); try { dialog.setHost(serverName); dialog.connect(); dialog.useDefaultKeyPair(); PublicKey pk = dialog.getPublicKey } catch (Throwable e) { log.errorFormat("Could not ssh public key of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { dialog.disconnect(); } return pk.toString(); }</code><technical_language>tab</technical_language>

Target:
public String getServerPublicKey(String serverName) { PublicKey pk = null; EngineSSHDialog dialog = getEngineSSHDialog(); try { dialog.setHost(serverName); dialog.connect(); dialog.useDefaultKeyPair(); pk = dialog.getPublicKey(); } catch (Throwable e) { log.errorFormat("Could not fetch ssh public key of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { dialog.disconnect(); } return pk.toString(); }
Source:
<code>public Integer getDistinctCount(SearchCriteria<T> sc, String[] distinctColumns) { String clause = sc != null ? sc.getWhereClause() : null; <START> if (clause != null && clause.length() == 0) { <END> clause = null; } final StringBuilder str = createDistinctSelect(sc, clause != null, distinctColumns); if (clause != null) { str.append(clause); } Collection<JoinBuilder<SearchCriteria<?>>> joins = null; if (sc != null) { joins = sc.getJoins(); if (joins != null) { addJoins(str, joins); } } final TransactionLegacy txn = TransactionLegacy.currentTxn(); final String sql = "SELECT COUNT(*) FROM (" + str.toString() + ") AS tmp"; PreparedStatement pstmt = null; try { pstmt = txn.prepareAutoCloseStatement(sql); int i = 1; if (clause != null) { for (final Pair<Attribute, Object> value : sc.getValues()) { prepareAttribute(i++, pstmt, value.first(), value.second()); } } if (joins != null) { i = addJoinAttributes(i, pstmt, joins); } final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { return rs.getInt(1); } return 0; } catch (final SQLException e) { throw new CloudRuntimeException("DB Exception on: " + pstmt, e); } catch (final Throwable e) { throw new CloudRuntimeException("Caught: " + pstmt, e); } }</code><technical_language>This replaced Strings.isNullOrEmpty()</technical_language>

Target:
public Integer getDistinctCount(SearchCriteria<T> sc, String[] distinctColumns) { String clause = sc != null ? sc.getWhereClause() : null; if (Strings.isNullOrEmpty(clause)) { clause = null; } final StringBuilder str = createDistinctSelect(sc, clause != null, distinctColumns); if (clause != null) { str.append(clause); } Collection<JoinBuilder<SearchCriteria<?>>> joins = null; if (sc != null) { joins = sc.getJoins(); if (joins != null) { addJoins(str, joins); } } final TransactionLegacy txn = TransactionLegacy.currentTxn(); final String sql = "SELECT COUNT(*) FROM (" + str.toString() + ") AS tmp"; try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql)) { int i = 1; if (clause != null) { for (final Pair<Attribute, Object> value : sc.getValues()) { prepareAttribute(i++, pstmt, value.first(), value.second()); } } if (joins != null) { i = addJoinAttributes(i, pstmt, joins); } final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { return rs.getInt(1); } return 0; } catch (final SQLException e) { throw new CloudRuntimeException("DB Exception in executing: " + sql, e); } catch (final Throwable e) { throw new CloudRuntimeException("Caught exception in : " + sql, e); } }
Source:
<code>public void testEventLookup() { assertTrue(fixture.hasEvent("sched_switch")); assertFalse(fixture.hasEvent("Sched_switch")); <START> String[] events = {"sched_switch", "sched_wakeup", "timer_init"}; <END> assertTrue(fixture.hasAllEvents(events)); assertTrue(fixture.hasEvents(events)); String[] names = {"inexistent", "sched_switch", "SomeThing"}; assertTrue(fixture.hasEvents(names)); assertFalse(fixture.hasAllEvents(names)); }</code><technical_language>formatting-OCD tells spaces { }</technical_language>

Target:
public void testEventLookup() { assertTrue(fixture.hasEvent("sched_switch")); assertFalse(fixture.hasEvent("Sched_switch")); String[] events = { "sched_switch", "sched_wakeup", "timer_init" }; assertTrue(fixture.hasAllEvents(events)); assertTrue(fixture.hasAtLeastOneOfEvents(events)); String[] names = { "inexistent", "sched_switch", "SomeThing" }; assertTrue(fixture.hasAtLeastOneOfEvents(names)); assertFalse(fixture.hasAllEvents(names)); }
Source:
<code>private void highlightViewOnUiThread() { final View viewToHighlight = mViewToHighlight.getAndSet(null); if (viewToHighlight == mHighlightedView) { return; } if (mHighlightedView != null) { for (ColorDrawable drawable : mHighlightDrawables) { mHighlightedView.getOverlay().remove(drawable); } } if (viewToHighlight != null && <START> viewToHighlight.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { <END> mHighlightDrawables = newViewHighlightDrawablesArray(viewToHighlight); for (ColorDrawable drawable : mHighlightDrawables) { viewToHighlight.getOverlay().add(drawable); } mHighlightedView = viewToHighlight; } }</code><technical_language>This right me. if this view is in a context parent MarginLayoutParams? is highlightable, no, this new margin highlighting</technical_language>

Target:
private void highlightViewOnUiThread() { final View viewToHighlight = mViewToHighlight.getAndSet(null); if (viewToHighlight == mHighlightedView) { return; } if (mHighlightedView != null) { mHighlightOverlays.removeHighlight(mHighlightedView); } if (viewToHighlight != null) { mHighlightOverlays.highlightView(viewToHighlight, mContentColor.get()); mHighlightedView = viewToHighlight; } }
Source:
<code>public Publisher<Integer> createFlowPublisher(long elements) { <START> return ReactiveStreamsFlowBridge.toFlow( <END> new AsyncIterablePublisher<>(Collections.emptyList(), ex) ); }</code><technical_language>I subprojects target 6 diamond work: <LINK_0></technical_language>

Target:
public Publisher<Integer> createFlowPublisher(long elements) { return ReactiveStreamsFlowBridge.toFlowPublisher( new AsyncIterablePublisher<Integer>(Collections.<Integer>emptyList(), ex) ); }
Source:
<code>public void testAlwaysHealthy() throws Exception { final AtomicLong successfulRuns = new AtomicLong(0); final List<Thread> taskThreads = Collections.synchronizedList(new ArrayList<>()); final DurableScheduledService service = new DurableScheduledService("testAlwaysHealthy", RUN_FREQUENCY, RUN_TIMEOUT, RUN_TIMEOUT) { @Override protected void startUp() { LOG.info(Thread.currentThread().getName() + " startUp"); } @Override protected void runOneIteration() { LOG.info(Thread.currentThread().getName() + " runOneIteration"); synchronized (taskThreads) { if (!taskThreads.contains(Thread.currentThread())) { taskThreads.add(Thread.currentThread()); } } successfulRuns.incrementAndGet(); } @Override protected void shutDown() { LOG.info(Thread.currentThread().getName() + " shutDown"); } }; service.startAsync().awaitRunning(); long numRuns = 10 * ((RUN_TIMEOUT.toMillis() / RUN_FREQUENCY.toMillis()) + 1); Duration runDuration = RESTART_TIMEOUT.multipliedBy(numRuns); Instant expiration = Instant.now().plus(runDuration); while (successfulRuns.get() < numRuns && Instant.now().isBefore(expiration)) { Thread.sleep(RUN_FREQUENCY.toMillis()); } service.stopAsync().awaitTerminated(); Assert.assertTrue(numRuns <= successfulRuns.get()); <START> Assert.assertTrue(successfulRuns.get() - numRuns <= 1); <END> Assert.assertTrue(taskThreads.stream().noneMatch(Thread::isAlive)); Assert.assertEquals(taskThreads.size(), 1); }</code><technical_language>Is for this assert flaky in PCL loaded machines. I dont a good suggestion for difference be, concerns get a more successful runs expected. (more 1)</technical_language>

Target:
public void testAlwaysHealthy() throws Exception { final AtomicLong runsCompleted = new AtomicLong(0); final List<Thread> taskThreads = Collections.synchronizedList(new ArrayList<>()); final DurableScheduledService service = new DurableScheduledService("testAlwaysHealthy", RUN_FREQUENCY, RUN_TIMEOUT, RUN_TIMEOUT) { @Override protected void startUp() { LOG.info(Thread.currentThread().getName() + " startUp"); } @Override protected void runOneIteration() { LOG.info(Thread.currentThread().getName() + " runOneIteration"); synchronized (taskThreads) { if (!taskThreads.contains(Thread.currentThread())) { taskThreads.add(Thread.currentThread()); } } runsCompleted.incrementAndGet(); } @Override protected void shutDown() { LOG.info(Thread.currentThread().getName() + " shutDown"); } }; service.startAsync().awaitRunning(); long numRuns = 2 * ((RUN_TIMEOUT.toMillis() / RUN_FREQUENCY.toMillis()) + 1); Duration runDuration = RESTART_TIMEOUT.multipliedBy(numRuns); Instant expiration = Instant.now().plus(runDuration); while (runsCompleted.get() < numRuns && Instant.now().isBefore(expiration)) { Thread.sleep(RUN_FREQUENCY.toMillis()); } service.stopAsync().awaitTerminated(); Assert.assertTrue(numRuns <= runsCompleted.get()); Assert.assertTrue(taskThreads.stream().noneMatch(Thread::isAlive)); Assert.assertEquals(taskThreads.size(), 1); }
Source:
<code>public static void main(String args[]) { try { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); DumpIndexTool dumpIndexTool = new DumpIndexTool(verifiableProperties); dumpIndexTool.doOperation(); } catch (Exception e) { <START> logger.error("Closed with exception ", e); <END> } }</code><technical_language>exception need caught</technical_language>

Target:
public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); DumpIndexTool dumpIndexTool = new DumpIndexTool(verifiableProperties); dumpIndexTool.doOperation(); }
Source:
<code>public Domain updateDomain(UpdateDomainCmd cmd) { <START> return _managementService.updateDomain(cmd); <END> }</code><technical_language>Instead of changing method is called, missing in search query added updateDomain method in managementserviceimpl is in use. removed</technical_language>

Target:
public Domain updateDomain(UpdateDomainCmd cmd) { return _domainMgr.updateDomain(cmd); }
Source:
<code>private StreamExecutionEnvironment getExecutionEnvironment() { Configuration config = new Configuration(); config.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); <START> config.set(CoreOptions.DEFAULT_PARALLELISM, 1); <END> config.set(ExecutionCheckpointingOptions.CHECKPOINTING_INTERVAL, Duration.ofMillis(42)); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment( config); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(10, Time.milliseconds(1))); return env; }</code><technical_language>prefer config.set(CoreOptions.DEFAULT_PARALLELISM, 1); env.setParallelism(1)</technical_language>

Target:
private StreamExecutionEnvironment getExecutionEnvironment() { Configuration config = new Configuration(); config.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment( config); env.setParallelism(1); env.enableCheckpointing(42); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(10, Time.milliseconds(1))); return env; }
Source:
<code><START> public Optional<String> getAgreementId() { <END> return Optional.ofNullable(agreementId); }</code><technical_language>create on-demand Direct Debit payment request agreement ID</technical_language>

Target:
public String getAgreementId() { return agreementId; }
Source:
<code>public void init(Configuration conf) { String schemaFileType = conf.get( ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE_TYPE); String schemaFile = conf.get( ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE, ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE_DEFAULT); NodeSchemaLoadResult result; try { <START> if (schemaFileType.compareTo("yaml") == 0) { <END> result = NodeSchemaLoader.getInstance().loadSchemaFromYaml(schemaFile); } else { result = NodeSchemaLoader.getInstance().loadSchemaFromFile(schemaFile); } allSchema = result.getSchemaList(); enforcePrefix = result.isEnforePrefix(); maxLevel = allSchema.size(); } catch (Throwable e) { String msg = "Fail to load schema file:" + schemaFile + ", error:" + e.getMessage(); LOG.error(msg); throw new RuntimeException(msg); } }</code><technical_language>schema type string case insensitive</technical_language>

Target:
public void init(Configuration conf) { String schemaFileType = conf.get( ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE_TYPE); String schemaFile = conf.get( ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE, ScmConfigKeys.OZONE_SCM_NETWORK_TOPOLOGY_SCHEMA_FILE_DEFAULT); NodeSchemaLoadResult result; try { if (schemaFileType.toLowerCase().compareTo("yaml") == 0) { result = NodeSchemaLoader.getInstance().loadSchemaFromYaml(schemaFile); } else { result = NodeSchemaLoader.getInstance().loadSchemaFromXml(schemaFile); } allSchema = result.getSchemaList(); enforcePrefix = result.isEnforePrefix(); maxLevel = allSchema.size(); } catch (Throwable e) { String msg = "Fail to load schema file:" + schemaFile + ", error:" + e.getMessage(); LOG.error(msg); throw new RuntimeException(msg); } }
Source:
<code>protected void processTuple(KeyValPair<byte[], byte[]> tuple) { if (ExeMode.UpdateAsync == exeMode) { updateAsync(tuple); return; } <START> Slice key = new Slice(tuple.getKey()); <END> if (ExeMode.UpdateSync == exeMode) { store.getSync(bucketId, key); } insertValueToStore(tuple); }</code><technical_language>move if block</technical_language>

Target:
protected void processTuple(KeyValPair<byte[], byte[]> tuple) { switch (execMode) { case UPDATEASYNC: updateAsync(tuple); break; case UPDATESYNC: store.getSync(getTimeByKey(tuple.getKey()), new Slice(tuple.getKey())); insertValueToStore(tuple); break; default: insertValueToStore(tuple); } }
Source:
<code>@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_webview, container, false); webView = (WebView) view.findViewById(R.id.webview); mLayout = (ViewGroup) view; <START> markers = new HashMap<>(); <END> WebSettings webViewSettings = webView.getSettings(); webViewSettings.setSupportZoom(true); webViewSettings.setBuiltInZoomControls(false); webViewSettings.setJavaScriptEnabled(true); webViewSettings.setGeolocationEnabled(true); webView.setWebChromeClient(new GeoWebChromeClient()); AirMapType mapType = AirMapType.fromBundle(getArguments()); webView.loadDataWithBaseURL(mapType.getDomain(), mapType.getMapData(getResources()), "text/html", "base64", null); webView.addJavascriptInterface(new MapsJavaScriptInterface(), "AirMapView"); return view; }</code><technical_language>initialize inline in line 45 final</technical_language>

Target:
@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_webview, container, false); webView = (WebView) view.findViewById(R.id.webview); mLayout = (ViewGroup) view; WebSettings webViewSettings = webView.getSettings(); webViewSettings.setSupportZoom(true); webViewSettings.setBuiltInZoomControls(false); webViewSettings.setJavaScriptEnabled(true); webViewSettings.setGeolocationEnabled(true); webView.setWebChromeClient(new GeoWebChromeClient()); AirMapType mapType = AirMapType.fromBundle(getArguments()); webView.loadDataWithBaseURL(mapType.getDomain(), mapType.getMapData(getResources()), "text/html", "base64", null); webView.addJavascriptInterface(new MapsJavaScriptInterface(), "AirMapView"); return view; }
Source:
<code><START> ParamDef mockParamDef(String name, String type) { <END> ParamDef paramDef = mock(ParamDef.class); when(paramDef.getName()).thenReturn(name); when(paramDef.getType()).thenReturn(type); return paramDef; }</code><technical_language>This method private</technical_language>

Target:
private ParamDef mockParamDef(String name, String type) { ParamDef paramDef = mock(ParamDef.class); when(paramDef.getName()).thenReturn(name); when(paramDef.getType()).thenReturn(type); return paramDef; }
Source:
<code>public Object invoke(String currentPath, PathRef parent, Object model, EvaluationContext ctx, List<Parameter> parameters) { StringBuffer result = new StringBuffer(); if(ctx.configuration().jsonProvider().isArray(model)){ Iterable<?> objects = ctx.configuration().jsonProvider().toIterable(model); for (Object obj : objects) { if (obj instanceof String) { result.append(obj.toString()); } } } if (parameters != null) { for (Parameter param : parameters) { if (param.getValue() != null) { <START> result.append(param.getValue().toString()); <END> } } } return result.toString(); }</code><technical_language>evaluating ILateBindingValue here</technical_language>

Target:
public Object invoke(String currentPath, PathRef parent, Object model, EvaluationContext ctx, List<Parameter> parameters) { StringBuffer result = new StringBuffer(); if(ctx.configuration().jsonProvider().isArray(model)){ Iterable<?> objects = ctx.configuration().jsonProvider().toIterable(model); for (Object obj : objects) { if (obj instanceof String) { result.append(obj.toString()); } } } if (parameters != null) { for (Parameter param : parameters) { Object value = param.getValue(); if (value != null) { result.append(value.toString()); } } } return result.toString(); }
Source:
<code><START> public synchronized ListenableFuture<?> reserveRevocable(QueryId queryId, long bytes) <END> { checkArgument(bytes >= 0, "bytes is negative"); ListenableFuture<?> result; if (bytes != 0) { queryMemoryRevocableReservations.merge(queryId, bytes, Long::sum); } reservedRevocableBytes += bytes; if (getFreeBytes() <= 0) { if (future == null) { future = NonCancellableMemoryFuture.create(); } checkState(!future.isDone(), "future is already completed"); result = future; } else { result = NOT_BLOCKED; } onMemoryReserved(); return result; }</code><technical_language>update this reserve? reserving revocable slow improved regular reserve. knowledge experience right do correctly harder more confusing for coming in try figure out safely improve it</technical_language>

Target:
public ListenableFuture<?> reserveRevocable(QueryId queryId, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); ListenableFuture<?> result; if (bytes != 0) { queryMemoryRevocableReservations.merge(queryId, bytes, Long::sum); } synchronized (this) { reservedRevocableBytes += bytes; if (getFreeBytes() <= 0) { if (future == null) { future = NonCancellableMemoryFuture.create(); } checkState(!future.isDone(), "future is already completed"); result = future; } else { result = NOT_BLOCKED; } } onMemoryReserved(); return result; }
Source:
<code>public int calcTotalPages(int totalResults) { int returnVal = (int) Math.ceil(totalResults / (double) this.getPageSize()); <START> if (returnVal == 0) { returnVal = 1; } <END> return returnVal; }</code><technical_language><LINK_0> suggestion if (returnVal == 0) { returnVal = 1; }</technical_language>

Target:
public int calcTotalPages(int totalResults) { int returnVal = (int) Math.ceil(totalResults / (double) this.getPageSize()); return Math.max(returnVal, 1); }
Source:
<code>String readProcessorData(String fullPath) { try { return zkClient.readData(fullPath, false); } catch (Exception e) { String errorMsg = String.format("Cannot read ZK node: %s", fullPath); <START> LOG.error(errorMsg, e); <END> throw new SamzaException(errorMsg, e); } }</code><technical_language>log re-throw? caller of this method handling/logging exception</technical_language>

Target:
String readProcessorData(String fullPath) { try { String data = zkClient.readData(fullPath, false); metrics.reads.inc(); return data; } catch (Exception e) { throw new SamzaException(String.format("Cannot read ZK node: %s", fullPath), e); } }
Source:
<code>private PokemonInfo getCurrentActivePokemon() { int idx = 0; PokemonInfo currentPokemon = null; <START> for (PokemonInfo pokemonInfo : getPlayer1Team()) { <END> if (pokemonInfo.isActive()) { if (idx == mCurrentActivePokemon) { currentPokemon = pokemonInfo; break; } else { idx++; } } } return currentPokemon; }</code><technical_language>Wth. Arent simply checking if playerTeam[mCurrentActive].isActive</technical_language>

Target:
private PokemonInfo getCurrentActivePokemon() { return getPlayer1Team().get(mCurrentActivePokemon); }
Source:
<code>public State convertToState(int[] data, ComfoAirCommandType commandType) { int[] get_reply_data_pos = commandType.getGetReplyDataPos(); int get_reply_data_bits = commandType.getGetReplyDataBits(); <START> if (get_reply_data_pos[0] < data.length) { <END> boolean result = (data[get_reply_data_pos[0]] & get_reply_data_bits) == get_reply_data_bits; return (result) ? new DecimalType(1) : new DecimalType(0); } else { return null; } }</code><technical_language>This method needs protect parameters null (data commandType)</technical_language>

Target:
public State convertToState(int[] data, ComfoAirCommandType commandType) { if (data == null || commandType == null) { logger.trace("\"DataTypeBoolean\" class \"convertToState\" method parameter: null"); return null; } else { int[] get_reply_data_pos = commandType.getGetReplyDataPos(); int get_reply_data_bits = commandType.getGetReplyDataBits(); if (get_reply_data_pos[0] < data.length) { boolean result = (data[get_reply_data_pos[0]] & get_reply_data_bits) == get_reply_data_bits; return (result) ? new DecimalType(1) : new DecimalType(0); } else { return null; } } }
Source:
<code>public boolean isResourceExpired(SamzaResource resource) { return System.currentTimeMillis() - resource.getTimestamp() + Duration.ofMinutes(1).toMillis() <START> > YarnConfiguration.DEFAULT_RM_CONTAINER_ALLOC_EXPIRY_INTERVAL_MS; <END> }</code><technical_language>DEFAULT_RM_CONTAINER_ALLOC_EXPIRY_INTERVAL_MS a Duration? Duration.between(resource.getTS, Instant.now()).compareTo(DEFAULT_RM_CONTAINER_ALLOC_EXPIRY_INTERVAL_MS) > 0;</technical_language>

Target:
public boolean isResourceExpired(SamzaResource resource) { Duration yarnAllocatedResourceExpiry = Duration.ofMinutes(YarnConfiguration.DEFAULT_RM_CONTAINER_ALLOC_EXPIRY_INTERVAL_MS) .minus(Duration.ofSeconds(30)); return System.currentTimeMillis() - resource.getTimestamp() > yarnAllocatedResourceExpiry.toMillis(); }
Source:
<code>public ResultSet getUninterruptibly() { <START> return null; <END> }</code><technical_language>return Uninterruptibles.getUninterruptibly(this)</technical_language>

Target:
public ResultSet getUninterruptibly() { try { return Uninterruptibles.getUninterruptibly(this); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } }
Source:
<code>private static boolean checkArgumentIndex( @NotNull ProblemsHolder holder, @NotNull GoExpression placeholder, @NotNull GoCallExpr callExpr, @NotNull Placeholder fmtPlaceholder, int callArgsNum) { int argNum = fmtPlaceholder.getPosition(); if (argNum < 0) return false; if (argNum == 0) { holder.registerProblem(placeholder, "Index value [0] is not allowed", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return false; } if (argNum <= callArgsNum) return true; if (GoPsiImplUtil.hasVariadic(callExpr.getArgumentList())) return false; <START> if (argNum <= callArgsNum) return true; <END> int arg = fmtPlaceholder.getPosition(); String message = String.format("Got %d placeholder(s) for %d arguments(s)", arg, callArgsNum); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return false; }</code><technical_language>typo</technical_language>

Target:
private static boolean checkArgumentIndex(@NotNull ProblemsHolder holder, @NotNull GoExpression placeholder, @NotNull GoCallExpr callExpr, @NotNull Placeholder fmtPlaceholder, int callArgsNum) { int argNum = fmtPlaceholder.getPosition(); if (argNum < 0) return false; if (argNum == 0) { TextRange range = TextRange.create(fmtPlaceholder.getStartPos() + 3, fmtPlaceholder.getStartPos() + 4); holder.registerProblem(placeholder, "Index value [0] is not allowed #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); return false; } if (argNum < callArgsNum) return true; if (GoPsiImplUtil.hasVariadic(callExpr.getArgumentList())) return false; if (argNum == callArgsNum) return true; int arg = fmtPlaceholder.getPosition(); String message = String.format("Got %d placeholder(s) for %d arguments(s)", arg, callArgsNum); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return false; }