auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static ArrayList<ShortcutRecord> getShortcuts(Context context, String packageName) { ArrayList<ShortcutRecord> records = new ArrayList<>(); SQLiteDatabase db = getDatabase(context); Cursor cursor = db.query("shortcuts", new String[]{"name", "package", "icon", "intent_uri", "icon_blob"}, <START> "package LIKE ?", new String[]{"%" + packageName + "%"}, null, null, null); <END> cursor.moveToFirst(); while (!cursor.isAfterLast()) { ShortcutRecord entry = new ShortcutRecord(); entry.name = cursor.getString(0); entry.packageName = cursor.getString(1); entry.iconResource = cursor.getString(2); entry.intentUri = cursor.getString(3); entry.icon_blob = cursor.getBlob(4); records.add(entry); cursor.moveToNext(); } cursor.close(); return records; }</code><technical_language>Do need a here? I thought a simple = enough</technical_language>

Target:
public static ArrayList<ShortcutRecord> getShortcuts(Context context, String packageName) { ArrayList<ShortcutRecord> records = new ArrayList<>(); SQLiteDatabase db = getDatabase(context); Cursor cursor = db.query("shortcuts", new String[]{"name", "package", "icon", "intent_uri", "icon_blob"}, "package = ?", new String[]{packageName}, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { ShortcutRecord entry = new ShortcutRecord(); entry.name = cursor.getString(0); entry.packageName = cursor.getString(1); entry.iconResource = cursor.getString(2); entry.intentUri = cursor.getString(3); entry.icon_blob = cursor.getBlob(4); records.add(entry); cursor.moveToNext(); } cursor.close(); return records; }
Source:
<code>private void initUI() { VBox assigneeDialogBox = new VBox(); assignedAssigneePane = createAssignedAssigneeGroup(); matchingAssigneesBox = createMatchingAssigneeBox(); matchingAssigneePane = createMatchingAssigneePane(); textField = createTextField(); assigneeDialogBox.getChildren().add(new Label(ASSIGNED_ASSIGNEE)); assigneeDialogBox.getChildren().add(assignedAssigneePane); assigneeDialogBox.getChildren().add(textField); assigneeDialogBox.getChildren().add(new Label(ALL_ASSIGNEES)); <START> assigneeDialogBox.getChildren().add(matchingAssigneePane); <END> getDialogPane().setContent(assigneeDialogBox); refreshUI(state); Platform.runLater(textField::requestFocus); }</code><technical_language>This part addAll</technical_language>

Target:
private void initUI() { VBox assigneeDialogBox = new VBox(); assignedUserPane = createAssignedUserPane(); matchingUsersBox = createMatchingUsersBox(); ScrollPane matchingUsersPane = createMatchingUsersPane(); textField = createTextField(); assigneeDialogBox.getChildren().addAll(new Label(TITLE_ASSIGNED_USER), assignedUserPane, textField, new Label(TITLE_ALL_USERS), matchingUsersPane); getDialogPane().setContent(assigneeDialogBox); refreshUI(state); Platform.runLater(textField::requestFocus); }
Source:
<code>public static List<String> extractValues(Collection<StructuredProperty> source, FieldApprover fieldApprover) { return source.stream() .filter(x -> fieldApprover.approve(x.getDataInfo())) .map(StructuredProperty::getValue) <START> .filter(Objects::nonNull) <END> .collect(Collectors.toList()); }</code><technical_language>null check here, empty string through. check for blank strings</technical_language>

Target:
public static List<String> extractValues(Collection<StructuredProperty> source, FieldApprover fieldApprover) { return source.stream() .filter(x -> fieldApprover.approve(x.getDataInfo())) .map(StructuredProperty::getValue) .filter(StringUtils::isNotBlank) .collect(Collectors.toList()); }
Source:
<code>private boolean branchMatchWithFilter(String branch, String filter) { if (filter.startsWith("^")) { Pattern pattern = Pattern.compile(filter); return pattern.matcher(branch).matches(); <START> } else if (filter.endsWith("/*")) { <END> return branch.startsWith(filter.substring(0, filter.length() - 1)); } else { return branch.equals(filter); } }</code><technical_language>Nit: I dispense elses return in ifs</technical_language>

Target:
private boolean branchMatchWithFilter(String branch, String filter) { if (filter == null) { return false; } else if (filter.equals("*")) { return true; } else if (filter.startsWith("^")) { Pattern pattern = Pattern.compile(filter); return pattern.matcher(branch).matches(); } else if (filter.endsWith("/*")) { return branch.startsWith(filter.substring(0, filter.length() - 1)); } else { return branch.equals(filter); } }
Source:
<code>public void addColumn(Column column) { <START> ArrayList<Column> columnsToAdd = this.columnsToAdd; <END> if (columnsToAdd == null) { this.columnsToAdd = columnsToAdd = New.arrayList(); } columnsToAdd.add(column); }</code><technical_language>need for a local variable here, reference instance field</technical_language>

Target:
public void addColumn(Column column) { if (columnsToAdd == null) { columnsToAdd = New.arrayList(); } columnsToAdd.add(column); }
Source:
<code>private static void removeQuestionsAndResponsesWithoutComments( FeedbackResponseCommentSearchResultBundle frCommentSearchResults) { Iterator<Entry<String, List<FeedbackQuestionAttributes>>> fqsIter = frCommentSearchResults.questions.entrySet().iterator(); <START> while (fqsIter.hasNext()) { <END> fqsIter.next().getValue().removeIf(fq -> frCommentSearchResults.responses.get(fq.getId()).isEmpty()); } }</code><technical_language>Similarly here, fqsIter transformed for-loop map.forEach</technical_language>

Target:
private static void removeQuestionsAndResponsesWithoutComments( FeedbackResponseCommentSearchResultBundle frCommentSearchResults) { frCommentSearchResults.questions.forEach((fsName, questionList) -> questionList.removeIf(fq -> frCommentSearchResults.responses.get(fq.getId()).isEmpty())); }
Source:
<code>public boolean isContentTypeValid(HttpHeaders headers) { String contentType = headers.get(HttpHeaders.Names.CONTENT_TYPE); return (Strings.isNullOrEmpty(contentType) || <START> contentType.contains(MEDIA_TYPE_APPLICATION_JSON)); <END> }</code><technical_language>I send, application/JSON</technical_language>

Target:
public boolean isContentTypeValid(HttpHeaders headers) { String contentType = headers.get(HttpHeaders.Names.CONTENT_TYPE); return (Strings.isNullOrEmpty(contentType) || contentType.toLowerCase().contains(MEDIA_TYPE_APPLICATION_JSON)); }
Source:
<code>private void initialize() { initializeFields(); initializeDefaultColors(); for (String[] element : fAppearanceColorListModel) { fAppearanceColorList.add(element[0]); } fAppearanceColorList.getDisplay().asyncExec(() -> { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); }); <START> fDocCommentOwnerComposite.loadValues(null); <END> }</code><technical_language>Invoking null argument is evil, please provide another method arguments if sense</technical_language>

Target:
private void initialize() { initializeFields(); initializeDefaultColors(); for (String[] element : fAppearanceColorListModel) { fAppearanceColorList.add(element[0]); } fAppearanceColorList.getDisplay().asyncExec(() -> { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); }); fDocCommentOwnerComposite.loadValues(); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LocationImpl)) return false; LocationImpl location = (LocationImpl)o; <START> return (lineNumber != location.lineNumber || <END> externalResource != location.externalResource || Objects.equals(resourcePath ,location.resourcePath) || externalResourceId != location.externalResourceId || Objects.equals(resourceProjectPath, location.resourceProjectPath) && !(target != null ? !target.equals(location.target) : location.target != null)); }</code><technical_language>this implementation of equals is correct</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LocationImpl)) return false; LocationImpl location = (LocationImpl)o; return lineNumber == location.lineNumber && externalResourceId == location.externalResourceId && externalResource == location.externalResource && Objects.equals(resourcePath ,location.resourcePath) && Objects.equals(resourceProjectPath, location.resourceProjectPath) && !(target != null ? !target.equals(location.target) : location.target != null); }
Source:
<code>public int clear() { int numOfEntriesDeleted = 0; int numOfValuesDeleted = 0; Collection<Data> locks = lockStore != null ? lockStore.getLockedKeys() : Collections.<Data>emptySet(); for (Data key : multiMapValues.keySet()) { if (!locks.contains(key)) { MultiMapValue value = multiMapValues.remove(key); if (value != null) { numOfEntriesDeleted++; numOfValuesDeleted += value.size(); } } <START> } <END> decrementSize(numOfValuesDeleted); return numOfEntriesDeleted; }</code><technical_language>Due threading model, other operation this MultiMapContainer executed. need worry e.g. concurrent adds in combination clear. I need increased complexity for clear</technical_language>

Target:
public int clear() { Collection<Data> locks = lockStore != null ? lockStore.getLockedKeys() : Collections.<Data>emptySet(); Map<Data, MultiMapValue> lockedKeys = createHashMap(locks.size()); int lockedValuesSize = 0; for (Data key : locks) { MultiMapValue multiMapValue = multiMapValues.get(key); if (multiMapValue != null) { lockedKeys.put(key, multiMapValue); lockedValuesSize += multiMapValue.size(); } } int numberOfAffectedEntries = multiMapValues.size() - lockedKeys.size(); multiMapValues.clear(); multiMapValues.putAll(lockedKeys); size = lockedValuesSize; return numberOfAffectedEntries; }
Source:
<code>public Builder addAnnotations(Collection<AnnotationSpec> annotationSpecs) { <START> checkArgument(annotationSpecs != null, "field annotations must not be null."); <END> this.annotations.addAll(annotationSpecs); return this; }</code><technical_language>consistent, this (and others) be: java checkNotNull(annotationSpecs, "annotationSpecs == null");</technical_language>

Target:
public Builder addAnnotations(Collection<AnnotationSpec> annotationSpecs) { checkArgument(annotationSpecs != null, "annotationSpecs == null"); this.annotations.addAll(annotationSpecs); return this; }
Source:
<code>public void registered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker == null) { <START> LOGGER.info("The ChannelService is registered, starting TasksBlueprintApplicationContextTracker"); <END> ChannelService channelService = (ChannelService) service; tracker = new TasksBlueprintApplicationContextTracker(bundleContext, channelService); tracker.open(true); } }</code><technical_language>sounded</technical_language>

Target:
public void registered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker == null) { LOGGER.info("ChannelService registered, starting TasksBlueprintApplicationContextTracker"); ChannelService channelService = (ChannelService) service; tracker = new TasksBlueprintApplicationContextTracker(bundleContext, channelService); tracker.open(true); } }
Source:
<code><START> public void recognizeEntitiesTooManyDocuments() { <END> recognizeEntitiesTooManyDocumentsRunner(inputs -> { StepVerifier.create(client.recognizeEntitiesBatch(inputs)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); }</code><technical_language>this supported in endpoints, deployed linked entities one</technical_language>

Target:
public void recognizeEntitiesTooManyDocuments() { recognizeEntitiesTooManyDocumentsRunner(inputs -> { StepVerifier.create(client.recognizeEntitiesBatch(inputs)) .verifyErrorSatisfies(ex -> { HttpResponseException exception = (HttpResponseException) ex; assertEquals(HttpResponseException.class, exception.getClass()); assertEquals(EXCEEDED_ALLOWED_DOCUMENTS_LIMITS_MESSAGE, exception.getMessage()); assertEquals(INVALID_DOCUMENT_BATCH, exception.getValue().toString()); }); }); }
Source:
<code>public TopologyServiceMultiRetryStrategy( long delayInMillis, long retries, LogProvider logProvider ) { <START> super( delayInMillis, retries, logProvider, millis -> <END> { try { Thread.sleep( millis ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } ); }</code><technical_language>of it, this read a bit if lambda a method reference, e.g. super( delayInMillis, retries, logProvider, this::sleep )</technical_language>

Target:
public TopologyServiceMultiRetryStrategy( long delayInMillis, long retries, LogProvider logProvider ) { super( delayInMillis, retries, logProvider, TopologyServiceMultiRetryStrategy::sleep ); }
Source:
<code>public void dragFinished(DragSourceEvent event) { super.dragFinished(event); <START> handleSwtDragFinished(); <END> }</code><technical_language>sense reset m_swtTransferables here</technical_language>

Target:
public void dragFinished(DragSourceEvent event) { super.dragFinished(event); handleSwtDragFinished(); m_swtTransferables = null; }
Source:
<code>public PersistedStreamingMap(@NonNull Path dataPath, @NonNull Options options, @NonNull ISerializer serializer, @NonNull CorfuRuntime corfuRuntime) { try { <START> FileUtils.deleteDirectory(dataPath.toFile()); <END> this.rocksDb = RocksDB.open(options, dataPath.toFile().getAbsolutePath()); } catch (RocksDBException | IOException e) { throw new UnrecoverableCorfuError(e); } this.serializer = serializer; this.corfuRuntime = corfuRuntime; }</code><technical_language>RIP. This recursively delete files one-by-one java "can't" delete a directory empty. Alternatively, call DbDestroy if path exists, underlying implementation more efficient, sure. Need investigate</technical_language>

Target:
public PersistedStreamingMap(@NonNull Path dataPath, @NonNull Options options, @NonNull ISerializer serializer, @NonNull CorfuRuntime corfuRuntime) { try { RocksDB.destroyDB(dataPath.toFile().getAbsolutePath(), options); this.rocksDb = RocksDB.open(options, dataPath.toFile().getAbsolutePath()); } catch (RocksDBException e) { throw new UnrecoverableCorfuError(e); } this.serializer = serializer; this.corfuRuntime = corfuRuntime; }
Source:
<code>private boolean hasClientServerSocket() { if (!config.getAdvancedNetworkConfig().isEnabled()) { return true; } Map<EndpointQualifier, EndpointConfig> endpointConfigs = config.getAdvancedNetworkConfig().getEndpointConfigs(); EndpointConfig clientEndpointConfig = endpointConfigs.get(CLIENT); <START> return clientEndpointConfig instanceof ServerSocketEndpointConfig; <END> }</code><technical_language>clientEndpointConfig != null enough here</technical_language>

Target:
private boolean hasClientServerSocket() { if (!config.getAdvancedNetworkConfig().isEnabled()) { return true; } Map<EndpointQualifier, EndpointConfig> endpointConfigs = config.getAdvancedNetworkConfig().getEndpointConfigs(); EndpointConfig clientEndpointConfig = endpointConfigs.get(CLIENT); return clientEndpointConfig != null; }
Source:
<code>public void bindView(View view, Context context, Cursor cursor) { final ThemeViewHolder themeViewHolder = (ThemeViewHolder) view.getTag(); final String screenshotURL = cursor.getString(cursor.getColumnIndex("screenshot")); final String name = cursor.getString(cursor.getColumnIndex("name")); final String price = cursor.getString(cursor.getColumnIndex("price")); themeViewHolder.nameView.setText(name); themeViewHolder.priceView.setText(price); ScreenshotHolder urlHolder = (ScreenshotHolder) themeViewHolder.imageView.getTag(); if (urlHolder == null) { urlHolder = new ScreenshotHolder(); urlHolder.requestURL = screenshotURL; themeViewHolder.imageView.setTag(urlHolder); } if (!urlHolder.requestURL.equals(screenshotURL)) { themeViewHolder.imageView.setImageBitmap(null); urlHolder.requestURL = screenshotURL; } <START> themeViewHolder.imageView.setImageUrl(screenshotURL + "?w=" + 500, WordPress.imageLoader); <END> }</code><technical_language>Hard-coded width</technical_language>

Target:
public void bindView(View view, Context context, Cursor cursor) { final ThemeViewHolder themeViewHolder = (ThemeViewHolder) view.getTag(); final String screenshotURL = cursor.getString(cursor.getColumnIndex("screenshot")); final String name = cursor.getString(cursor.getColumnIndex("name")); final String price = cursor.getString(cursor.getColumnIndex("price")); themeViewHolder.nameView.setText(name); themeViewHolder.priceView.setText(price); ScreenshotHolder urlHolder = (ScreenshotHolder) themeViewHolder.imageView.getTag(); if (urlHolder == null) { urlHolder = new ScreenshotHolder(); urlHolder.requestURL = screenshotURL; themeViewHolder.imageView.setDefaultImageResId(R.drawable.light_grey); themeViewHolder.imageView.setTag(urlHolder); } if (!urlHolder.requestURL.equals(screenshotURL)) { themeViewHolder.imageView.setImageBitmap(null); urlHolder.requestURL = screenshotURL; } themeViewHolder.imageView.setImageUrl(screenshotURL + "?w=" + mGridView.getWidth(), WordPress.imageLoader); }
Source:
<code>public List<Clip> getClips(String pid, String uri) { PidReference pidReference = new PidReference(); pidReference.setPid(pid); pidReference.setHref(uri); List<Clip> clips; try { <START> clips = clipsAdapter.clipsFor(pidReference); <END> } catch (NitroException e) { throw Throwables.propagate(e); } return clips; }</code><technical_language>simplify try { return clipsAdapter.clipsFor(pidReference); ..</technical_language>

Target:
public List<Clip> getClips(String pid, String uri) { PidReference pidReference = new PidReference(); pidReference.setPid(pid); pidReference.setHref(uri); try { return clipsAdapter.clipsFor(pidReference); } catch (NitroException e) { throw Throwables.propagate(e); } }
Source:
<code>private void deleteObsoleteHistoryData() throws SQLException { if (prop.getInteger(NotificationProperties.DAYS_TO_KEEP_HISTORY) > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -prop.getInteger(NotificationProperties.DAYS_TO_KEEP_HISTORY)); Timestamp startDeleteFrom = new Timestamp(cal.getTimeInMillis()); Connection connection = null; PreparedStatement deleteStmt = null; int deletedRecords; try { connection = ds.getConnection(); <START> deleteStmt = connection.prepareStatement("DELETE FROM event_notification_hist WHERE sent_at < ?"); <END> deleteStmt.setTimestamp(1, startDeleteFrom); deletedRecords = deleteStmt.executeUpdate(); } finally { if (deleteStmt != null) { deleteStmt.close(); } if (connection != null) { connection.close(); } } if (deletedRecords > 0) { log.debug(deletedRecords + " records were deleted from \"event_notification_hist\" table."); } } }</code><technical_language>Is this change related patch</technical_language>

Target:
private void deleteObsoleteHistoryData() throws SQLException { if (prop.getInteger(NotificationProperties.DAYS_TO_KEEP_HISTORY) > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -prop.getInteger(NotificationProperties.DAYS_TO_KEEP_HISTORY)); Timestamp startDeleteFrom = new Timestamp(cal.getTimeInMillis()); Connection connection = null; PreparedStatement deleteStmt = null; int deletedRecords; try { connection = ds.getConnection(); deleteStmt = connection.prepareStatement("delete from event_notification_hist where sent_at < ?"); deleteStmt.setTimestamp(1, startDeleteFrom); deletedRecords = deleteStmt.executeUpdate(); } finally { if (deleteStmt != null) { deleteStmt.close(); } if (connection != null) { connection.close(); } } if (deletedRecords > 0) { log.debug(deletedRecords + " records were deleted from \"event_notification_hist\" table."); } } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append(fFailedTest + ": " + fThrownException.getMessage()); <START> return sb.toString(); <END> }</code><technical_language>If continue a StringBuilder here, in a sense</technical_language>

Target:
public String toString() { return fFailedTest + ": " + fThrownException.getMessage(); }
Source:
<code>public static void shareLink(Context context, String subject, String text) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); <START> i.putExtra(Intent.EXTRA_SUBJECT, subject); <END> i.putExtra(Intent.EXTRA_TEXT, text); context.startActivity(Intent.createChooser(i, context.getString(R.string.share_url_label))); }</code><technical_language>safer put EXTRA_SUBJECT if !TextUtils.isEmpty(subject)</technical_language>

Target:
public static void shareLink(Context context, String subject, String text) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, text); if (!TextUtils.isEmpty(subject)) { i.putExtra(Intent.EXTRA_SUBJECT, subject); } context.startActivity(Intent.createChooser(i, context.getString(R.string.share_url_label))); }
Source:
<code>public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler cbh) throws SaslException { final long timeout; if (props.containsKey(WildFlySasl.AUTHENTICATION_TIMEOUT)) { timeout = Long.parseLong((String) props.get(WildFlySasl.AUTHENTICATION_TIMEOUT)); } else { timeout = DEFAULT_TIMEOUT; } final NameAssignedCallbackHandler nameAssignedCallbackHandler = new NameAssignedCallbackHandler(cbh); final SaslServer delegateSaslServer = delegate.createSaslServer(mechanism, protocol, serverName, props, nameAssignedCallbackHandler); return delegateSaslServer == null ? null : new AbstractDelegatingSaslServer(delegateSaslServer) { private final AtomicBoolean complete = new AtomicBoolean(); private final AtomicBoolean nameAssigned = new AtomicBoolean(); private volatile ScheduledThreadPoolExecutor executor; private volatile ScheduledFuture<Void> timeoutTask; @Override public byte[] evaluateResponse(final byte[] response) throws SaslException { try { final byte[] challenge = delegate.evaluateResponse(response); if (nameAssignedCallbackHandler.isNameAssigned() && nameAssigned.compareAndSet(false, true)) { <START> executor = createExecutor(); <END> timeoutTask = executor.schedule(() -> { dispose(); return null; }, timeout, TimeUnit.SECONDS); } if (isComplete() && complete.compareAndSet(false, true)) { cancelTimeoutTask(); } return challenge; } catch (SaslException | RuntimeException | Error e) { if (isComplete() && complete.compareAndSet(false, true)) { cancelTimeoutTask(); } throw e; } } @Override public void dispose() throws SaslException { try { super.dispose(); } finally { ScheduledThreadPoolExecutor stpe = executor; executor = null; timeoutTask = null; if (stpe != null) { stpe.shutdownNow(); } } } private ScheduledThreadPoolExecutor createExecutor() { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); executor.setRemoveOnCancelPolicy(true); executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return executor; } private void cancelTimeoutTask() { if (timeoutTask != null) { timeoutTask.cancel(true); } } }; }</code><technical_language>Ideally a shared executor here, configured in SecurityDomain (and in WildFly, injected a single shared source). This done enhancement later, urgent creating a thread for concurrent authentication severely problematic for real-world cases</technical_language>

Target:
public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler cbh) throws SaslException { final long timeout; if (props.containsKey(WildFlySasl.AUTHENTICATION_TIMEOUT)) { timeout = Long.parseLong((String) props.get(WildFlySasl.AUTHENTICATION_TIMEOUT)); } else { timeout = DEFAULT_TIMEOUT; } final SaslServer delegateSaslServer = delegate.createSaslServer(mechanism, protocol, serverName, props, cbh); return (delegateSaslServer == null) ? null : new DelegatingTimeoutSaslServer(delegateSaslServer, scheduledExecutorService, timeout); }
Source:
<code>private void populateColumns(JsonNode propertiesNode, List<String> arrays, List<ElasticsearchColumn> columns) { StringComparator comparator = new StringComparator(); TreeMap<String, Type> fieldsMap = new TreeMap<>(comparator); for (String columnMetadata : getColumnMetadata(null, propertiesNode)) { int delimiterIndex = columnMetadata.lastIndexOf(":"); if (delimiterIndex == -1 || delimiterIndex == columnMetadata.length() - 1) { LOG.debug("Invalid column path format: %s", columnMetadata); continue; } String fieldName = columnMetadata.substring(0, delimiterIndex); String typeName = columnMetadata.substring(delimiterIndex + 1); if (!fieldName.endsWith(".type")) { LOG.debug("Ignoring column with no type info: %s", columnMetadata); continue; } String propertyName = fieldName.substring(0, fieldName.lastIndexOf('.')); String nestedName = propertyName.replaceAll("properties\\.", ""); if (nestedName.contains(".")) { fieldsMap.put(nestedName, getPrestoType(typeName)); } else { <START> boolean newNestedColumn = columns.stream() <END> .noneMatch(column -> column.getName().equalsIgnoreCase(nestedName)); if (newNestedColumn) { columns.add(new ElasticsearchColumn(nestedName, getPrestoType(typeName), nestedName, typeName, arrays.contains(nestedName), -1)); } } } processNestedFields(fieldsMap, columns, arrays); }</code><technical_language>name boolean isNonNestedColumn, difference here</technical_language>

Target:
private void populateColumns(JsonNode propertiesNode, List<String> arrays, List<ElasticsearchColumn> columns) { FieldNestingComparator comparator = new FieldNestingComparator(); TreeMap<String, Type> fieldsMap = new TreeMap<>(comparator); for (String columnMetadata : getColumnMetadata(Optional.empty(), propertiesNode)) { int delimiterIndex = columnMetadata.lastIndexOf(":"); if (delimiterIndex == -1 || delimiterIndex == columnMetadata.length() - 1) { LOG.debug("Invalid column path format: %s", columnMetadata); continue; } String fieldName = columnMetadata.substring(0, delimiterIndex); String typeName = columnMetadata.substring(delimiterIndex + 1); if (!fieldName.endsWith(".type")) { LOG.debug("Ignoring column with no type info: %s", columnMetadata); continue; } String propertyName = fieldName.substring(0, fieldName.lastIndexOf('.')); String nestedName = propertyName.replaceAll("properties\\.", ""); if (nestedName.contains(".")) { fieldsMap.put(nestedName, getPrestoType(typeName)); } else { boolean newColumnFound = columns.stream() .noneMatch(column -> column.getName().equalsIgnoreCase(nestedName)); if (newColumnFound) { columns.add(new ElasticsearchColumn(nestedName, getPrestoType(typeName), nestedName, typeName, arrays.contains(nestedName), -1)); } } } processNestedFields(fieldsMap, columns, arrays); }
Source:
<code>private static int cmdList(Context context, String[] argv) { try { for (EPerson person : ePersonService.findAll(context, EPerson.EMAIL)) { System.out.printf("%s\t%s/%s\t%s, %s\n", <START> person.getID(), <END> person.getEmail(), person.getNetid(), person.getLastName(), person.getFirstName()); } } catch (SQLException ex) { System.err.println(ex.getMessage()); return 1; } return 0; }</code><technical_language>need .toString() well</technical_language>

Target:
private static int cmdList(Context context, String[] argv) { try { for (EPerson person : ePersonService.findAll(context, EPerson.EMAIL)) { System.out.printf("%s\t%s/%s\t%s, %s\n", person.getID().toString(), person.getEmail(), person.getNetid(), person.getLastName(), person.getFirstName()); } } catch (SQLException ex) { System.err.println(ex.getMessage()); return 1; } return 0; }
Source:
<code><START> public Set<MaterialConfig> getSchedulableDependencyMaterials() { <END> HashSet<MaterialConfig> dependencyMaterials = new HashSet<>(); for (MaterialConfig materialConfig : getSchedulableMaterials()) { if (materialConfig instanceof DependencyMaterialConfig) { dependencyMaterials.add(materialConfig); } } return dependencyMaterials; }</code><technical_language>Set<DependencyMaterialConfig>? Stops casts places used</technical_language>

Target:
public Set<DependencyMaterialConfig> getSchedulableDependencyMaterials() { HashSet<DependencyMaterialConfig> dependencyMaterials = new HashSet<>(); for (MaterialConfig materialConfig : getSchedulableMaterials()) { if (materialConfig instanceof DependencyMaterialConfig) { dependencyMaterials.add((DependencyMaterialConfig) materialConfig); } } return dependencyMaterials; }
Source:
<code>public void moveAxis(Object elementToMove, int newIndex) { if (!isDynamic() && elementToMove instanceof IAxis) { final TransactionalEditingDomain domain = getTableEditingDomain(); <START> if (domain == null) { <END> return; } final List<Object> newAxisOrder = new ArrayList<Object>(getRepresentedContentProvider().getAxis()); newAxisOrder.remove(elementToMove); newAxisOrder.add(newIndex, elementToMove); domain.getCommandStack().execute(getSetNewAxisOrderCommand(newAxisOrder)); } }</code><technical_language>null operand</technical_language>

Target:
public void moveAxis(Object elementToMove, int newIndex) { if (!isDynamic() && elementToMove instanceof IAxis) { final TransactionalEditingDomain domain = getTableEditingDomain(); if (null != domain) { final List<Object> newAxisOrder = new ArrayList<Object>(getRepresentedContentProvider().getAxis()); newAxisOrder.remove(elementToMove); newAxisOrder.add(newIndex, elementToMove); domain.getCommandStack().execute(getSetNewAxisOrderCommand(newAxisOrder)); } } }
Source:
<code>public void onLifespanExecutionFinished(Iterable<Lifespan> newlyCompletelyExecutedDriverGroups) { checkState(initialScheduled); SettableFuture<?> newDriverGroupReady; <START> synchronized (this) { <END> for (Lifespan newlyCompletelyExecutedDriverGroup : newlyCompletelyExecutedDriverGroups) { checkArgument(!newlyCompletelyExecutedDriverGroup.isTaskWide()); availableTasks.enqueue(taskByDriverGroup[newlyCompletelyExecutedDriverGroup.getId()]); totalLifespanExecutionFinished++; int driverGroupId = newlyCompletelyExecutedDriverGroup.getId(); runningDriverGroupIdsByTask[taskByDriverGroup[driverGroupId]].remove(driverGroupId); } newDriverGroupReady = this.newDriverGroupReady; } newDriverGroupReady.set(null); }</code><technical_language>nit: move 2 lines up, reuse it</technical_language>

Target:
public void onLifespanExecutionFinished(Iterable<Lifespan> newlyCompletelyExecutedDriverGroups) { checkState(initialScheduled, "onLifespanExecutionFinished should only be called after initial scheduling finished"); SettableFuture<?> newDriverGroupReady; synchronized (this) { for (Lifespan newlyCompletelyExecutedDriverGroup : newlyCompletelyExecutedDriverGroups) { checkArgument(!newlyCompletelyExecutedDriverGroup.isTaskWide()); int driverGroupId = newlyCompletelyExecutedDriverGroup.getId(); availableTasks.enqueue(taskByDriverGroup[driverGroupId]); totalLifespanExecutionFinished++; runningDriverGroupIdsByTask[taskByDriverGroup[driverGroupId]].remove(driverGroupId); } newDriverGroupReady = this.newDriverGroupReady; } newDriverGroupReady.set(null); }
Source:
<code>public void serializeText(Text text) throws XMLStreamException { if(text != null && text.getData() != null) <START> serializer.writeCharacters(text.getData()); <END> }</code><technical_language>Checking text is null properly defensive. If text is null, I text.getData() is guaranteed null, part of check is unnecessary</technical_language>

Target:
public void serializeText(Text text) throws XMLStreamException { if(text != null) serializer.writeCharacters(text.getData()); }
Source:
<code>boolean method1(Nums k, String string) { switch (k) { case ONE -> { Stream.of(string.split(" ")) .anyMatch(Word -> "in".equals(Word)); <START> System.out.println(1); <END> System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); System.out.println(1); } default -> Stream.of(string.split(" ")) .anyMatch(Word -> "in".equals(Word)); } return true; }</code><technical_language>please line number of lamba in argument of method , is cool idea more visual</technical_language>

Target:
boolean method1(Nums k, String string) { switch (k) { case ONE -> { System.out.println(2); System.out.println(3); System.out.println(4); System.out.println(5); System.out.println(6); System.out.println(7); System.out.println(8); System.out.println(9); System.out.println(10); System.out.println(11); } default -> Stream.of(string.split(" ")) .anyMatch(Word -> "in".equals(Word)); } return true; }
Source:
<code>private void bindAttrOrRelation(AccessibleObject fieldOrMethod) { boolean isRelation = RELATIONSHIP_TYPES.stream().anyMatch(fieldOrMethod::isAnnotationPresent); String fieldName = getFieldName(fieldOrMethod); Class<?> fieldType = getFieldType(entityClass, fieldOrMethod); <START> if (fieldName == null || "class".equals(fieldName) <END> || OBJ_METHODS.contains(fieldOrMethod)) { return; } if (fieldOrMethod instanceof Method) { Method method = (Method) fieldOrMethod; requestScopeableMethods.put(method, isRequestScopeableMethod(method)); } if (isRelation) { bindRelation(fieldOrMethod, fieldName, fieldType); } else { bindAttr(fieldOrMethod, fieldName, fieldType); } }</code><technical_language>"id" is reserved in JSON-API. JSON-API spec: > In other words, a resource attribute relationship name, attribute relationship named type id. Based this, original code is correct</technical_language>

Target:
private void bindAttrOrRelation(AccessibleObject fieldOrMethod) { boolean isRelation = RELATIONSHIP_TYPES.stream().anyMatch(fieldOrMethod::isAnnotationPresent); String fieldName = getFieldName(fieldOrMethod); Class<?> fieldType = getFieldType(entityClass, fieldOrMethod); if (fieldName == null || "id".equals(fieldName) || "class".equals(fieldName) || OBJ_METHODS.contains(fieldOrMethod)) { return; } if (fieldOrMethod instanceof Method) { Method method = (Method) fieldOrMethod; requestScopeableMethods.put(method, isRequestScopeableMethod(method)); } if (isRelation) { bindRelation(fieldOrMethod, fieldName, fieldType); } else { bindAttr(fieldOrMethod, fieldName, fieldType); } }
Source:
<code>private static void migrateDB() { if(PropertyUtil.getOptional("db.flyway", true) == false) { log.warn("Skipping flyway migration! Remove 'db.flyway' property or set it to 'true' to enable migration"); return; } <START> boolean ingoreMigrationFailures = PropertyUtil.getOptional("db.ingoreMigrationFailures", false); <END> log.info("Oskari-map checking DB status"); try { FlywaydbMigrator.migrate(DS_HELPER.getDataSource()); log.info("Oskari core DB migrated successfully"); } catch (Exception e) { log.error("DB migration for Oskari core failed!"); if(!ingoreMigrationFailures) { throw e; } } final String[] additionalPools = DS_HELPER.getAdditionalModules(); for(String module : additionalPools) { final String poolName = DS_HELPER.getOskariDataSourceName(module); try { FlywaydbMigrator.migrate(DS_HELPER.getDataSource(poolName), module); log.info(module + " DB migrated successfully"); } catch (Exception e) { log.error("DB migration for module " + module + " failed!", e); if(!ingoreMigrationFailures) { throw e; } } } }</code><technical_language>Lets fix ingore -> ignore naming. good</technical_language>

Target:
private static void migrateDB() { if(PropertyUtil.getOptional("db.flyway", true) == false) { log.warn("Skipping flyway migration! Remove 'db.flyway' property or set it to 'true' to enable migration"); return; } boolean ignoreMigrationFailures = PropertyUtil.getOptional("db.ignoreMigrationFailures", false); log.info("Oskari-map checking DB status"); try { FlywaydbMigrator.migrate(DS_HELPER.getDataSource()); log.info("Oskari core DB migrated successfully"); } catch (Exception e) { log.error("DB migration for Oskari core failed!"); if(!ignoreMigrationFailures) { throw e; } } final String[] additionalPools = DS_HELPER.getAdditionalModules(); for(String module : additionalPools) { final String poolName = DS_HELPER.getOskariDataSourceName(module); try { FlywaydbMigrator.migrate(DS_HELPER.getDataSource(poolName), module); log.info(module + " DB migrated successfully"); } catch (Exception e) { log.error("DB migration for module " + module + " failed!", e); if(!ignoreMigrationFailures) { throw e; } } } }
Source:
<code>protected void split() { log.trace("splitting {}", this); double width = (area.getWidth() / 2); double height = (area.getHeight() / 2); double x = area.getX(); double y = area.getY(); int childLevel = level + 1; SpatialQuadTree<N> ne = new SpatialQuadTree<>(layoutModel, childLevel, x + width, y, width, height); SpatialQuadTree<N> nw = new SpatialQuadTree<>(layoutModel, childLevel, x, y, width, height); SpatialQuadTree<N> sw = new SpatialQuadTree<>(layoutModel, childLevel, x, y + height, width, height); SpatialQuadTree<N> se = new SpatialQuadTree<>(layoutModel, childLevel, x + width, y + height, width, height); synchronized (lock) { children = <START> new ImmutableMap.Builder<Quadrant, SpatialQuadTree<N>>() <END> .put(NE, ne) .put(NW, nw) .put(SW, sw) .put(SE, se) .build(); } }</code><technical_language>Note do this instead: children = ImmutableMap.of(NE, ne, NW, nw, SW, sw, SE, se); I create ImmutableMap of size 5 of() in this way</technical_language>

Target:
protected void split() { log.trace("splitting {}", this); double width = (area.getWidth() / 2); double height = (area.getHeight() / 2); double x = area.getX(); double y = area.getY(); int childLevel = level + 1; SpatialQuadTree<N> ne = new SpatialQuadTree<>(layoutModel, childLevel, x + width, y, width, height); SpatialQuadTree<N> nw = new SpatialQuadTree<>(layoutModel, childLevel, x, y, width, height); SpatialQuadTree<N> sw = new SpatialQuadTree<>(layoutModel, childLevel, x, y + height, width, height); SpatialQuadTree<N> se = new SpatialQuadTree<>(layoutModel, childLevel, x + width, y + height, width, height); synchronized (lock) { children = ImmutableMap.of(NE, ne, NW, nw, SW, sw, SE, se); } }
Source:
<code>public static void setSslVerification(Repository repo, HttpURLConnection conn) throws IOException { if ("https".equals(conn.getURL().getProtocol())) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; <START> if (repo.getConfig().getBoolean("http", "sslVerify", true)) { END> try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); httpsConn.setSSLSocketFactory(ctx.getSocketFactory()); httpsConn.setHostnameVerifier(trustAllHostNames); } catch (KeyManagementException e) { throw new IOException(e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException(e.getMessage()); } } } }</code><technical_language>if sslVerify is false want enter this block this read: if (!repo.getConfig().getBoolean("http", "sslVerify", true))</technical_language>

Target:
public static void setSslVerification(Repository repo, HttpURLConnection conn) throws IOException { if ("https".equals(conn.getURL().getProtocol())) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; if (!repo.getConfig().getBoolean("http", "sslVerify", true)) { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); httpsConn.setSSLSocketFactory(ctx.getSocketFactory()); httpsConn.setHostnameVerifier(trustAllHostNames); } catch (KeyManagementException e) { throw new IOException(e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException(e.getMessage()); } } } }
Source:
<code>public void start() { try { Map<String, MonitorConfig> monitorConfigs = getMonitorConfigs(config); for (Map.Entry<String, MonitorConfig> entry : monitorConfigs.entrySet()) { String monitorName = entry.getKey(); MonitorConfig monitorConfig = entry.getValue(); if (!Strings.isNullOrEmpty(monitorConfig.getMonitorFactoryClass())) { int schedulingIntervalInMs = monitorConfig.getSchedulingIntervalInMs(); <START> LOGGER.info("Scheduling monitor to run every ms", monitorName, schedulingIntervalInMs); <END> if (monitorConfig.isJitterEnabled()) { SecureRandom secureRandom = new SecureRandom(); schedulingIntervalInMs += secureRandom.nextInt(schedulingIntervalInMs + 1); } scheduler.schedule(getRunnable(instantiateMonitor(monitorName, monitorConfig, metricsRegistry)), schedulingIntervalInMs); } else { LOGGER.warn("Not scheduling the monitor: to run, since monitor factory class is not set in config.", monitorName); } } } catch (InstantiationException e) { LOGGER.error("Exception when instantiating the monitor : ", e); throw new SamzaException(e); } }</code><technical_language>This log message is incorrect now</technical_language>

Target:
public void start() { try { Map<String, MonitorConfig> monitorConfigs = getMonitorConfigs(config); for (Map.Entry<String, MonitorConfig> entry : monitorConfigs.entrySet()) { String monitorName = entry.getKey(); MonitorConfig monitorConfig = entry.getValue(); if (!Strings.isNullOrEmpty(monitorConfig.getMonitorFactoryClass())) { int schedulingIntervalInMs = monitorConfig.getSchedulingIntervalInMs(); int monitorSchedulingJitterInMs = (int) (RANDOM.nextInt(schedulingIntervalInMs + 1) * (monitorConfig.getSchedulingJitterPercent() / 100.0)); schedulingIntervalInMs += monitorSchedulingJitterInMs; LOGGER.info("Scheduling the monitor: to run every ms.", monitorName, schedulingIntervalInMs); scheduler.schedule(getRunnable(instantiateMonitor(monitorName, monitorConfig, metricsRegistry)), schedulingIntervalInMs); } else { LOGGER.warn("Not scheduling the monitor: to run, since monitor factory class is not set in config.", monitorName); } } } catch (InstantiationException e) { LOGGER.error("Exception when instantiating the monitor : ", e); throw new SamzaException(e); } }
Source:
<code>public String getDeleteUserErrorMessages(AuthenticatedUser au) { String retVal = ""; if (!dvObjSvc.findByAuthenticatedUserId(au).isEmpty()) { retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.dvobjects"); } if (!roleAssigneeSvc.getAssignmentsFor(au.getIdentifier()).isEmpty()) { if (!retVal.isEmpty()) { retVal += "; "; } retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.roleAssignments"); } if (!gbRespSvc.findByAuthenticatedUserId(au).isEmpty()) { if (!retVal.isEmpty()) { retVal += "; "; } retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.gbResps"); } if (!datasetVersionService.getDatasetVersionUsersByAuthenticatedUser(au).isEmpty()) { if (!retVal.isEmpty()) { retVal += "; "; } retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.versionUser"); } if (!explicitGroupService.findGroups(au).isEmpty()) { if (!retVal.isEmpty()) { retVal += "; "; } retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.groupMember"); } <START> if (userHasPendingAccessRequests(au)) { <END> if (!retVal.isEmpty()) { retVal += "; "; } retVal += BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.pendingRequests"); } if (!retVal.isEmpty()) { retVal = BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.prefix", Arrays.asList(au.getIdentifier())) + " " + retVal + "."; } return retVal; }</code><technical_language>Currently, access request is acted on, delete, I fair delete requests delete user (instead of failing). question is talk of storing for historical purposes. If/when do, want a) allow delete of user b) anonymize requests. c) delete them, of course, I need of case. said, sense change delete cascading now</technical_language>

Target:
public String getDeleteUserErrorMessages(AuthenticatedUser au) { String retVal = ""; List<String> reasons= new ArrayList(); if (!dvObjSvc.findByAuthenticatedUserId(au).isEmpty()) { reasons.add(BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.dvobjects")); } if (!roleAssigneeSvc.getAssignmentsFor(au.getIdentifier()).isEmpty()) { reasons.add(BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.roleAssignments")); } if (!gbRespSvc.findByAuthenticatedUserId(au).isEmpty()) { reasons.add( BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.gbResps")); } if (!datasetVersionService.getDatasetVersionUsersByAuthenticatedUser(au).isEmpty()) { reasons.add(BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.versionUser")); } if (!reasons.isEmpty()) { retVal = BundleUtil.getStringFromBundle("admin.api.deleteUser.failure.prefix", Arrays.asList(au.getIdentifier())); retVal += " " + reasons.stream().collect(Collectors.joining("; ")) + "."; } return retVal; }
Source:
<code>public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { Template t = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); <START> assertTrue(t==null); <END> } catch(NullPointerException e) { assertTrue("getting non-existant working template should not throw an NPE", false); } }</code><technical_language>user assertNull</technical_language>

Target:
public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { final Template template = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); assertNull(template); } catch(NullPointerException e) { Logger.error(this, "getting non-existant template should not throw an NPE", e); assertTrue("getting non-existant template should not throw an NPE", false); } }
Source:
<code>public void testSimple() { <START> final KafkaProducer<String, String> producer = mock(KafkaProducer.class); <END> KafkaBolt<String, String> bolt = makeBolt(producer); OutputCollector collector = mock(OutputCollector.class); TopologyContext context = mock(TopologyContext.class); Map<String, Object> conf = new HashMap<>(); bolt.prepare(conf, context, collector); MkTupleParam param = new MkTupleParam(); param.setFields("key", "message"); Tuple testTuple = Testing.testTuple(Arrays.asList("KEY", "VALUE"), param); bolt.execute(testTuple); verify(producer).send(argThat(new ArgumentMatcher<ProducerRecord<String, String>>() { @Override public boolean matches(ProducerRecord<String, String> arg) { LOG.info("GOT ->", arg); LOG.info(" {}", arg.topic(), arg.key(), arg.value()); return "MY_TOPIC".equals(arg.topic()) && "KEY".equals(arg.key()) && "VALUE".equals(arg.value()); } }), any(Callback.class)); verify(collector).ack(testTuple); }</code><technical_language>wondering if <LINK_0> stubbing ends some weird things, e.g. returning null send</technical_language>

Target:
public void testSimple() { MockProducer<String, String> producer = new MockProducer<>(Cluster.empty(), false, null, null, null); KafkaBolt<String, String> bolt = makeBolt(producer); OutputCollector collector = mock(OutputCollector.class); TopologyContext context = mock(TopologyContext.class); Map<String, Object> conf = new HashMap<>(); bolt.prepare(conf, context, collector); String key = "KEY"; String value = "VALUE"; Tuple testTuple = createTestTuple(key, value); bolt.execute(testTuple); assertThat(producer.history().size(), is(1)); ProducerRecord<String, String> arg = producer.history().get(0); LOG.info("GOT ->", arg); LOG.info("{}, {}, {}", arg.topic(), arg.key(), arg.value()); assertThat(arg.topic(), is("MY_TOPIC")); assertThat(arg.key(), is(key)); assertThat(arg.value(), is(value)); producer.completeNext(); verify(collector).ack(testTuple); }
Source:
<code>public CompletableFuture<PhysicalSlot> requestNewAllocatedSlot(@Nonnull SlotRequestId slotRequestId, @Nonnull ResourceProfile resourceProfile, @Nullable Time timeout) { assertRunningInMainThread(); LOG.debug("Request new allocated slot with slot request id and resource profile {}", slotRequestId, resourceProfile); final PendingRequest pendingRequest = PendingRequest.createNormalRequest(slotRequestId, resourceProfile); if (timeout != null) { FutureUtils .orTimeout( pendingRequest.getSlotFuture(), timeout.toMilliseconds(), TimeUnit.MILLISECONDS, componentMainThreadExecutor) <START> .whenCompleteAsync((physicalSlot, throwable) -> { if (throwable instanceof TimeoutException) { timeoutPendingSlotRequest(slotRequestId); } }, componentMainThreadExecutor); <END> } return internalRequestNewAllocatedSlot(pendingRequest); }</code><technical_language>offline discussion Chesnay concluded this is fix for problem. Instead try expose futures other dependents this lead violating main thread guarantee waiting this future of main thread (get() try complete future's dependents)</technical_language>

Target:
public CompletableFuture<PhysicalSlot> requestNewAllocatedSlot(@Nonnull SlotRequestId slotRequestId, @Nonnull ResourceProfile resourceProfile, @Nullable Time timeout) { assertRunningInMainThread(); LOG.debug("Request new allocated slot with slot request id and resource profile {}", slotRequestId, resourceProfile); final PendingRequest pendingRequest = PendingRequest.createNormalRequest(slotRequestId, resourceProfile); return internalRequestNewSlot(pendingRequest, timeout); }