auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void broadcastEvent(AbstractEvent event, boolean isPriorityEvent) throws IOException { try (BufferConsumer eventBufferConsumer = EventSerializer.toBufferConsumer(event)) { for (int targetChannel = 0; targetChannel < numberOfChannels; targetChannel++) { tryFinishCurrentBufferBuilder(targetChannel); if (isPriorityEvent) { targetPartition.addPriorityEvent(event, targetChannel, eventBufferConsumer); } else { targetPartition.addBufferConsumer(eventBufferConsumer.copy(), targetChannel); <START> } <END> } if (flushAlways) { flushAll(); } } }</code><technical_language>eventBufferConsumer -> eventBufferConsumer.copy(), consistency action, avoid calling copy multiple times in ResultSubpartition#priorityEvent</technical_language>

Target:
public void broadcastEvent(AbstractEvent event, boolean isPriorityEvent) throws IOException { try (BufferConsumer eventBufferConsumer = EventSerializer.toBufferConsumer(event)) { for (int targetChannel = 0; targetChannel < numberOfChannels; targetChannel++) { tryFinishCurrentBufferBuilder(targetChannel); targetPartition.addBufferConsumer(eventBufferConsumer.copy(), targetChannel, isPriorityEvent); } if (flushAlways) { flushAll(); } } }
Source:
<code>private void validateMd5(String currentMd5, CloseableHttpResponse response, String agentContentMd5Header, String what) { final Header md5Header = response.getFirstHeader(agentContentMd5Header); LOGGER.debug("[Agent Upgrade Validate MD5] validating MD5 for {}, currentMD5:{}, responseMD5:{}, headerKey:{}", what, currentMd5, md5Header, agentContentMd5Header); if (md5Header == null) { <START> String message = String.format("[Agent Upgrade Validate MD5] Did not find %s MD5 header in response %s.", agentContentMd5Header, response); <END> LOGGER.debug(message); } if (!"".equals(currentMd5)) { if (!currentMd5.equals(md5Header.getValue())) { jvmExitter.jvmExit(what, currentMd5, md5Header.getValue()); } } }</code><technical_language>slf4j formatter, String.format</technical_language>

Target:
private void validateMd5(String currentMd5, CloseableHttpResponse response, String agentContentMd5Header, String what) { final Header md5Header = response.getFirstHeader(agentContentMd5Header); LOGGER.debug("[Agent Upgrade Validate MD5] validating MD5 for {}, currentMD5:{}, responseMD5:{}, headerKey:{}", what, currentMd5, md5Header, agentContentMd5Header); if (md5Header == null) { LOGGER.debug("[Agent Upgrade Validate MD5] Did not find MD5 header in response {}.", agentContentMd5Header, response); } if (!"".equals(currentMd5)) { if (!currentMd5.equals(md5Header.getValue())) { jvmExitter.jvmExit(what, currentMd5, md5Header.getValue()); } } }
Source:
<code>public void setInverted(boolean isInverted) { if (getInverted() != isInverted) { <START> for (CustomSpeedController motor : motors) { <END> motor.setInverted(!motor.getInverted()); } } this.isInverted = isInverted; }</code><technical_language>SpeedController CustomSpeedController</technical_language>

Target:
public void setInverted(boolean isInverted) { if (getInverted() != isInverted) { for (SpeedController motor : motors) { motor.setInverted(!motor.getInverted()); } } this.isInverted = isInverted; }
Source:
<code>private void addAztecAudioShortcodePlugin() { boolean foundAudioShortCodePlugin = false; for (IAztecPlugin plugin : mContent.getPlugins()) { if (plugin instanceof AudioShortcodePlugin) { <START> foundAudioShortCodePlugin = true; <END> break; } } if (!foundAudioShortCodePlugin) { mContent.getPlugins().add(new AudioShortcodePlugin()); } }</code><technical_language>Niptick: return here, avoid boolean foundAudioShortCodePlugin</technical_language>

Target:
private void addAztecAudioShortcodePlugin() { for (IAztecPlugin plugin : mContent.getPlugins()) { if (plugin instanceof AudioShortcodePlugin) { return; } } mContent.getPlugins().add(new AudioShortcodePlugin()); }
Source:
<code>private void initializeRefreshCallback() { repositoryManager.addCallbacks(categories -> { Platform.runLater(() -> { <START> this.getChildren().remove(this.overlay); <END> this.vBox.setDisable(false); }); }, error -> { }); }</code><technical_language>Alternatively use: java this.overlay.toBack();</technical_language>

Target:
private void initializeRefreshCallback() { repositoryManager.addCallbacks(categories -> { Platform.runLater(() -> { this.overlay.toBack(); this.vBox.setDisable(false); }); }, error -> { }); }
Source:
<code>private void onSuccess() { if (results.size() < callbacks.size()) { return; } Throwable caught = null; for (Object o : callbacks) { try { Object result = results.get(o); if (o instanceof AsyncCallback) { @SuppressWarnings("unchecked") AsyncCallback<Object> cb = (AsyncCallback<Object>) o; cb.onSuccess(result); } else { @SuppressWarnings("unchecked") com.google.gwtjsonrpc.common.AsyncCallback<Object> cb = (com.google.gwtjsonrpc.common.AsyncCallback<Object>) o; cb.onSuccess(result); } <START> } catch (Throwable t) { <END> if (caught == null) { caught = t; } } } propagate(caught); }</code><technical_language>This worth effort. If exception onSuccess call stack crash event loop</technical_language>

Target:
private void onSuccess() { if (results.size() < callbacks.size()) { return; } for (Object o : callbacks) { Object result = results.get(o); if (o instanceof AsyncCallback) { @SuppressWarnings("unchecked") AsyncCallback<Object> cb = (AsyncCallback<Object>) o; cb.onSuccess(result); } else { @SuppressWarnings("unchecked") com.google.gwtjsonrpc.common.AsyncCallback<Object> cb = (com.google.gwtjsonrpc.common.AsyncCallback<Object>) o; cb.onSuccess(result); } } }
Source:
<code>public void dispose() { ISelectionProvider provider = fSite.getSelectionProvider(); if (provider != null) { <START> ISelectionProvider currentProvider = fSpecialProvider != null ? fSpecialProvider : fSite.getSelectionProvider(); <END> disposeAction(fFindDeclarationsAction, currentProvider); disposeAction(fFindDeclarationsInProjectAction, currentProvider); disposeAction(fFindDeclarationsInHierarchyAction, currentProvider); disposeAction(fFindDeclarationsInWorkingSetAction, currentProvider); } fSpecialProvider = null; fFindDeclarationsAction = null; fFindDeclarationsInProjectAction = null; fFindDeclarationsInHierarchyAction = null; fFindDeclarationsInWorkingSetAction = null; updateGlobalActionHandlers(); super.dispose(); }</code><technical_language>this line if block check for currentProvider instead of for provider in if clause</technical_language>

Target:
public void dispose() { if (fRegisterInProvider) { unregisterActions(); } fSelectionProvider = null; fFindDeclarationsAction = null; fFindDeclarationsInProjectAction = null; fFindDeclarationsInHierarchyAction = null; fFindDeclarationsInWorkingSetAction = null; updateGlobalActionHandlers(); super.dispose(); }
Source:
<code>public void checkParameters(Command command, ExecutionHandlerContext context) { int numberOfArguments = command.getProcessedCommand().size(); if (numberOfArguments < 2) { throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); } else if (numberOfArguments == 2) { confirmKnownSubcommands(command); } else if (numberOfArguments == 3) { confirmArgumentsToGetSubcommand(command); <START> } else if (numberOfArguments > 3) { <END> throw new RedisParametersMismatchException( String.format(ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND, command.getStringKey())); } }</code><technical_language>I LGTM is suggesting this else, instead of else if</technical_language>

Target:
public void checkParameters(Command command, ExecutionHandlerContext context) { int numberOfArguments = command.getProcessedCommand().size(); if (numberOfArguments < 2) { throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); } else if (numberOfArguments == 2) { confirmKnownSubcommands(command); } else if (numberOfArguments == 3) { confirmArgumentsToGetSubcommand(command); } else { throw new RedisParametersMismatchException( String.format(ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND, command.getStringKey())); } }
Source:
<code>private static void checkBoundaries(double value) { if (value < 0 || value > 100) throw new IllegalArgumentException( <START> String.format("The percentage value <%s> should be between zero and hundred.", value)); <END> }</code><technical_language>.. 0 100., more user friendly</technical_language>

Target:
private static void checkBoundaries(double value) { if (value < 0 || value > 100) throw new IllegalArgumentException( String.format("The percentage value <%s> should be between 0 and 100.", value)); }
Source:
<code>private void checkFilesAreOpened() { try { projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/WEB-INF"); } catch (TimeoutException ex) { <START> fail("Known issue <LINK_0>"); <END> } projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/WEB-INF/jsp"); projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/index.jsp"); projectExplorer.waitItem( PROJECT_NAME + "/src/main/java/org/eclipse/qa/examples/AppController.java"); editor.waitTabIsPresent("index.jsp"); editor.waitTabIsPresent("AppController"); editor.waitTabIsPresent("qa-spring-sample"); }</code><technical_language>Please, express if is permanent random in error message: permanent failure <LINK_1></technical_language>

Target:
private void checkFilesAreOpened() { try { projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/WEB-INF"); } catch (TimeoutException ex) { fail("Known random failure <LINK_0>"); } projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/WEB-INF/jsp"); projectExplorer.waitItem(PROJECT_NAME + "/src/main/webapp/index.jsp"); projectExplorer.waitItem( PROJECT_NAME + "/src/main/java/org/eclipse/qa/examples/AppController.java"); editor.waitTabIsPresent("index.jsp"); editor.waitTabIsPresent("AppController"); editor.waitTabIsPresent("qa-spring-sample"); }
Source:
<code>public void mergeLicenses( List<String> licenseMerges, LicenseMap licenseMap ) throws MojoFailureException { Set<String> licenseFound = new HashSet<>(); if ( !CollectionUtils.isEmpty( licenseMerges ) ) { Map<String, Set<String>> mergedLicenses = new HashMap<>(); for ( String merge : licenseMerges ) { merge = merge.trim(); String[] split = merge.split( "\\s*\\|\\s*" ); String mainLicense = split[0]; Set<String> mergeList; if ( mergedLicenses.containsKey( mainLicense ) ) { mergeList = mergedLicenses.get( mainLicense ); } else { mergeList = new HashSet<>(); } for ( int i = 0; i < split.length; i++ ) { String licenseToAdd = split[i]; if ( i == 0 ) { continue; } if ( mergeList.contains( licenseToAdd ) || licenseFound.contains( licenseToAdd ) || mainLicense.equals( licenseToAdd ) ) { throw new MojoFailureException( "The license " + licenseToAdd + " was already registered in the " + "configuration, please use only one such entry as described in the example " + "<LINK_0>" + "example-thirdparty.html#Merge_licenses" ); } mergeList.add( licenseToAdd ); licenseFound.add( licenseToAdd ); } mergedLicenses.put( mainLicense, mergeList ); } for ( Map.Entry<String, Set<String>> entry : mergedLicenses.entrySet() ) { String mainLicense = entry.getKey(); Set<String> mergedLicense = entry.getValue(); if ( verbose ) { <START> LOG.info( "Will merge to *" + mainLicense + "*, licenses: " + mergedLicense ); <END> } thirdPartyTool.mergeLicenses( licenseMap, mainLicense, mergedLicense ); } } }</code><technical_language>{} instead of string concat</technical_language>

Target:
public void mergeLicenses( List<String> licenseMerges, LicenseMap licenseMap ) throws MojoFailureException { Set<String> licenseFound = new HashSet<>(); if ( !CollectionUtils.isEmpty( licenseMerges ) ) { Map<String, Set<String>> mergedLicenses = new HashMap<>(); for ( String merge : licenseMerges ) { merge = merge.trim(); String[] split = merge.split( "\\s*\\|\\s*" ); String mainLicense = split[0]; Set<String> mergeList; if ( mergedLicenses.containsKey( mainLicense ) ) { mergeList = mergedLicenses.get( mainLicense ); } else { mergeList = new HashSet<>(); } for ( int i = 0; i < split.length; i++ ) { String licenseToAdd = split[i]; if ( i == 0 ) { continue; } if ( mergeList.contains( licenseToAdd ) || licenseFound.contains( licenseToAdd ) || mainLicense.equals( licenseToAdd ) ) { throw new MojoFailureException( "The license " + licenseToAdd + " was already registered in the " + "configuration, please use only one such entry as described in the example " + "<LINK_0>" + "example-thirdparty.html#Merge_licenses" ); } mergeList.add( licenseToAdd ); licenseFound.add( licenseToAdd ); } mergedLicenses.put( mainLicense, mergeList ); } for ( Map.Entry<String, Set<String>> entry : mergedLicenses.entrySet() ) { String mainLicense = entry.getKey(); Set<String> mergedLicense = entry.getValue(); if ( verbose ) { LOG.info( "Will merge to '{}', licenses: {}", mainLicense, mergedLicense ); } thirdPartyTool.mergeLicenses( licenseMap, mainLicense, mergedLicense ); } } }
Source:
<code>public static File prepareAbsoluteOutputDirPath(MojoParameters params, String dir, String path) { <START> return prepareAbsolutePath(params, new File(new File(params.getProject().getBuild().getDirectory(), params.getOutputDirectory()), dir).toString(), path); <END> }</code><technical_language>get this line: If params.getOutputDirectory() is absolute path (it think, this is this PR is support) I want append another directory</technical_language>

Target:
public static File prepareAbsoluteOutputDirPath(MojoParameters params, String dir, String path) { return prepareAbsolutePath(params, new File(params.getOutputDirectory(), dir), path); }
Source:
<code>public void folderContains_shouldReturnTrueWhenFolderContainsFileWithGivenName() { String path = System.getProperty("user.dir"); File folder = new File(path+"/folder"); folder.mkdir(); <START> File file = new File(path+"/folder/file"); <END> try { file.createNewFile(); assertTrue(OpenmrsUtil.folderContains(folder,"file")); file.delete(); } catch (Exception e) { } folder.delete(); }</code><technical_language>this file path work OSs! work properly windows? Java's abstraction get system's file separator</technical_language>

Target:
public void folderContains_shouldReturnTrueWhenFolderContainsFileWithGivenName() { File folder = createFileInUserDirectory("folder"); folder.mkdir(); File file = createFileInUserDirectory("folder" + separator + "file"); try { file.createNewFile(); assertTrue(OpenmrsUtil.folderContains(folder, "file")); file.delete(); } catch (IOException e) {Assert.fail("Unable to create file");} folder.delete(); }
Source:
<code>protected Result pushDownDereferences(Context context, ProjectNode projectNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { <START> ImmutableMap<VariableReferenceExpression, RowExpression> <END> dereferencesMap = expressions.inverse().entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); return Result.ofPlanNode( new ProjectNode(context.getIdAllocator().getNextId(), projectNode.getSource(), Assignments.builder().putAll(projectNode.getAssignments()).putAll(dereferencesMap).build())); }</code><technical_language>formatting Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); return Result.ofPlanNode( new ProjectNode(context.getIdAllocator().getNextId(), projectNode.getSource(), Assignments.builder() .putAll(projectNode.getAssignments()) .putAll(dereferencesMap) .build()));</technical_language>

Target:
protected Result pushDownDereferences(Context context, ProjectNode projectNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); return Result.ofPlanNode( new ProjectNode(context.getIdAllocator().getNextId(), projectNode.getSource(), Assignments.builder() .putAll(projectNode.getAssignments()) .putAll(dereferencesMap) .build())); }
Source:
<code>public void deleteQueue(String queueName) throws QueueManagerException { try { UserRegistry userRegistry = Utils.getUserRegistry(); String resourcePath = QueueManagementConstants.MB_QUEUE_STORAGE_PATH + "/" + queueName; if (QueueManagementBeans.queueExists(queueName)) { QueueManagementBeans.getInstance().deleteQueue(queueName); userRegistry.delete(resourcePath); } <START> removeRoleCreateForLoggedInUser(queueName); <END> } catch (RegistryException e) { throw new QueueManagerException("Failed to delete queue : " + queueName, e); } }</code><technical_language>removeRoleCreateForLoggedInUser 'removeRoleCreatedForLoggedInUser'</technical_language>

Target:
public void deleteQueue(String queueName) throws QueueManagerException { try { UserRegistry userRegistry = Utils.getUserRegistry(); String resourcePath = QueueManagementConstants.MB_QUEUE_STORAGE_PATH + "/" + queueName; if (QueueManagementBeans.queueExists(queueName)) { QueueManagementBeans.getInstance().deleteQueue(queueName); userRegistry.delete(resourcePath); } removeRoleCreatedForLoggedInUser(queueName); } catch (RegistryException e) { throw new QueueManagerException("Failed to delete queue : " + queueName, e); } }
Source:
<code>public Session openSession(URI sessionResourceURI, IProgressMonitor monitor, UICallBack uiCallback) { SubMonitor subMonitor = SubMonitor.convert(monitor, 100); Session session = <START> SessionManager.INSTANCE.getSession(sessionResourceURI, <END> subMonitor.newChild(30)); if (session != null && !session.isOpen()) { try { session.open(subMonitor.newChild(70)); } catch (AirdResourceVersionMismatchException e) { session = null; if (uiCallback != null && uiCallback.askSessionReopeningWithResourceVersionMismatch(e)) { try { MigrationUtil.ignoreVersionMismatch = true; session = SessionManager.INSTANCE.getSession(sessionResourceURI, new NullProgressMonitor()); session.open(new NullProgressMonitor()); } finally { MigrationUtil.ignoreVersionMismatch = false; } } else { throw e; } } } subMonitor.done(); return session; }</code><technical_language>this</technical_language>

Target:
public Session openSession(URI sessionResourceURI, IProgressMonitor monitor, UICallBack uiCallback) { SubMonitor subMonitor = SubMonitor.convert(monitor, 100); Session session = this.getSession(sessionResourceURI, subMonitor.newChild(30)); if (session != null && !session.isOpen()) { try { session.open(subMonitor.newChild(70)); } catch (AirdResourceVersionMismatchException e) { session = null; if (uiCallback != null && uiCallback.askSessionReopeningWithResourceVersionMismatch(e)) { try { MigrationUtil.ignoreVersionMismatch = true; session = this.getSession(sessionResourceURI, new NullProgressMonitor()); session.open(new NullProgressMonitor()); } finally { MigrationUtil.ignoreVersionMismatch = false; } } else { throw e; } } } subMonitor.done(); return session; }
Source:
<code>private <E> E executePrincipalQuery(QueryConfiguration configuration, ResultSetCallback<E> resultSetCallback) { String sql = configuration.getSql(); if (log.isDebugEnabled()) { log.debug("Executing principalQuery..."); } <START> if (log.isTraceEnabled()) { <END> log.tracef("principalQuery ==> \"%s\" using \"%s\" as value", sql, name); } try ( Connection connection = getConnection(configuration); PreparedStatement preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, name); try ( ResultSet resultSet = preparedStatement.executeQuery() ) { return resultSetCallback.handle(resultSet); } } catch (SQLException e) { throw log.couldNotExecuteQuery(sql, e); } catch (Exception e) { throw log.unexpectedErrorWhenProcessingAuthenticationQuery(sql, e); } }</code><technical_language>conditions useless, if generating of tracef/debug parameters is cheap operation. (But sense if is for example String.join(", ", array), is expensive operation omitted trace is enabled.)</technical_language>

Target:
private <E> E executePrincipalQuery(QueryConfiguration configuration, ResultSetCallback<E> resultSetCallback) { String sql = configuration.getSql(); log.tracef("Executing principalQuery %s with value %s", sql, name); try ( Connection connection = getConnection(configuration); PreparedStatement preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, name); try ( ResultSet resultSet = preparedStatement.executeQuery() ) { return resultSetCallback.handle(resultSet); } } catch (SQLException e) { throw log.couldNotExecuteQuery(sql, e); } catch (Exception e) { throw log.unexpectedErrorWhenProcessingAuthenticationQuery(sql, e); } }
Source:
<code>public void testGetCachedBranches() throws GerritException { if (!isVersion28OrLater()) { return; } GerritClient client = reviewHarness.getClient(); NullProgressMonitor monitor = new NullProgressMonitor(); NameKey project = client.getChange(reviewHarness.getShortId(), monitor) .getChangeDetail() .getChange() .getProject(); assertNull(client.getCachedBranches(project)); client.refreshConfigOnce(project, monitor); Set<String> branches = client.getCachedBranches(project); assertNotNull(branches); assertTrue(branches.contains("refs/heads/master")); String newBranch = "branch-" + System.currentTimeMillis(); String newBranchRef = "refs/heads/" + newBranch; try { createBranchIfNonExistent(newBranch); assertFalse(client.getCachedBranches(project).contains(newBranchRef)); client.refreshConfigOnce(project, monitor); assertFalse(client.getCachedBranches(project).contains(newBranchRef)); client.refreshConfig(monitor); assertTrue(client.getCachedBranches(project).contains(newBranchRef)); <START> System.out.println(newBranchRef); <END> } finally { deleteBranch(newBranch); } }</code><technical_language>Remove this</technical_language>

Target:
public void testGetCachedBranches() throws GerritException { if (!isVersion28OrLater()) { return; } GerritClient client = reviewHarness.getClient(); NullProgressMonitor monitor = new NullProgressMonitor(); NameKey project = client.getChange(reviewHarness.getShortId(), monitor) .getChangeDetail() .getChange() .getProject(); assertNull(client.getCachedBranches(project)); client.refreshConfigOnce(project, monitor); Set<String> branches = client.getCachedBranches(project); assertNotNull(branches); assertTrue(branches.contains("refs/heads/master")); String newBranch = "branch-" + System.currentTimeMillis(); String newBranchRef = "refs/heads/" + newBranch; try { createBranchIfNonExistent(newBranch); assertFalse(client.getCachedBranches(project).contains(newBranchRef)); client.refreshConfigOnce(project, monitor); assertFalse(client.getCachedBranches(project).contains(newBranchRef)); client.refreshConfig(monitor); assertTrue(client.getCachedBranches(project).contains(newBranchRef)); } finally { deleteBranch(newBranch); } }
Source:
<code>default ITag<?> getInternal(MCTag<T> theTag) { <START> return getTagCollection().getIDTagMap().get(theTag.getIdInternal()); <END> }</code><technical_language>While I is override ITagCollection's default implementation, this more sense getTagCollection().get(theTag.getIdInternal()), is a bit more readable, if is thing</technical_language>

Target:
default ITag<?> getInternal(MCTag<T> theTag) { return getTagCollection().get(theTag.getIdInternal()); }
Source:
<code>private synchronized short updateLibraryId(final String library) { Short libraryId = this.libraryIds.get(library); if (libraryId == null) { <START> libraryId = this.nextLibraryId++; <END> this.libraryIds.put(library, libraryId); } return libraryId; }</code><technical_language>too, this done computeIfAbsent</technical_language>

Target:
private short updateLibraryId(final String library) { return this.libraryIds.computeIfAbsent(library, (s) -> this.nextLibraryId++); }
Source:
<code><START> public String getDefaultMetaVariable() { <END> T[] enumConstants = enumType.getEnumConstants(); List<String> items = new ArrayList<>(enumConstants.length); for (Enum<T> item : enumConstants) { try { if (enumType.getField(item.name()).getAnnotation(Deprecated.class) == null) { items.add(item.name()); } } catch (NoSuchFieldException e) { throw new AssertionError(); } catch (SecurityException e) { items.add(item.name()); LoggerFactory.getLogger() .info( "A SecurityException occured while getting field '" + item.name() + "' from enum '" + enumType.getName() + "': " + e.getMessage()); } } return new StringBuffer() .append('[') .append(Joiner.on(" | ").join(items)) .append(']') .toString(); }</code><technical_language>case</technical_language>

Target:
public String getDefaultMetaVariable() { T[] enumConstants = enumType.getEnumConstants(); List<String> items = new ArrayList<>(enumConstants.length); for (Enum<T> item : enumConstants) { try { if (enumType.getField(item.name()).getAnnotation(Deprecated.class) == null) { items.add(item.name().toLowerCase()); } } catch (NoSuchFieldException e) { throw new AssertionError(); } catch (SecurityException e) { items.add(item.name()); LoggerFactory.getLogger() .info( "A SecurityException occured while getting field '" + item.name() + "' from enum '" + enumType.getName() + "': " + e.getMessage()); } } return new StringBuffer() .append('[') .append(Joiner.on(" | ").join(items)) .append(']') .toString(); }
Source:
<code>public void onStart() { super.onStart(); <START> if (TextUtils.getTrimmedLength(lastSearchedText) > 0) { <END> forceStartSearch(lastSearchedText); } }</code><technical_language>crashes lastSearchedText is null launch. check for isEmpty</technical_language>

Target:
public void onStart() { super.onStart(); if (isValidQuery(lastSearchedText)) { forceStartSearch(lastSearchedText); } }
Source:
<code>private Comparable findPropertyValueByName(IProperty property, String valueIn) { Optional<Comparable> value = property.parseValue(valueIn); if (value.isPresent()) { return value.get(); } else { for (Object v : property.getAllowedValues()) { if (isValueEqualTo(property, (Comparable) v, valueIn)) { return (Comparable) v; } } <START> ; <END> } return null; }</code><technical_language>;</technical_language>

Target:
private Comparable findPropertyValueByName(IProperty property, String valueIn) { Optional<Comparable> value = property.parseValue(valueIn); if (value.isPresent()) { return value.get(); } else { for (Object v : property.getAllowedValues()) { if (isValueEqualTo(property, (Comparable) v, valueIn)) { return (Comparable) v; } } } return null; }
Source:
<code>public DivolteConfiguration configuration() { <START> if (exceptions.size() > 0) { <END> throw new IllegalStateException("Attempt to access invalid configuration."); } return divolteConfiguration; }</code><technical_language>isEmpty() (PMD complain this?)</technical_language>

Target:
public DivolteConfiguration configuration() { if (!exceptions.isEmpty()) { throw new IllegalStateException("Attempt to access invalid configuration."); } return divolteConfiguration; }
Source:
<code>private void patchParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { <START> String paragraphId = (String) fromMessage.get("id"); <END> if (paragraphId == null) { return; } String noteId = getOpenNoteId(conn); if (noteId == null) { noteId = (String) fromMessage.get("noteId"); } if (!hasParagraphWriterPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "write")) { return; } final Note note = notebook.getNote(noteId); Paragraph p = note.getParagraph(paragraphId); DiffMatchPatch dmp = new DiffMatchPatch(); String patchText = (String) fromMessage.get("patch"); patchText = patchText.replace(",@@", "@@"); LinkedList<DiffMatchPatch.Patch> patches = (LinkedList<DiffMatchPatch.Patch>) dmp.patchFromText(patchText); String paragraphText = p.getText(); paragraphText = (String) dmp.patchApply(patches, paragraphText)[0]; p.setText(paragraphText); Message message = new Message(OP.PATCH_PARAGRAPH).put("patch", patchText) .put("paragraphId", p.getId()); broadcastExcept(note.getId(), message, conn); }</code><technical_language>I, absolutely, cases kinds of usages need fix of them. occur ClassCaseException</technical_language>

Target:
private void patchParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { if (!collaborativeModeEnable) { return; } String paragraphId = fromMessage.getType("id", LOG); if (paragraphId == null) { return; } String noteId = getOpenNoteId(conn); if (noteId == null) { noteId = fromMessage.getType("noteId", LOG); if (noteId == null) { return; } } if (!hasParagraphWriterPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "write")) { return; } final Note note = notebook.getNote(noteId); if (note == null) { return; } Paragraph p = note.getParagraph(paragraphId); if (p == null) { return; } DiffMatchPatch dmp = new DiffMatchPatch(); String patchText = fromMessage.getType("patch", LOG); if (patchText == null) { return; } LinkedList<DiffMatchPatch.Patch> patches = null; try { patches = (LinkedList<DiffMatchPatch.Patch>) dmp.patchFromText(patchText); } catch (ClassCastException e) { LOG.error("Failed to parse patches", e); } if (patches == null) { return; } String paragraphText = p.getText() == null ? "" : p.getText(); paragraphText = (String) dmp.patchApply(patches, paragraphText)[0]; p.setText(paragraphText); Message message = new Message(OP.PATCH_PARAGRAPH).put("patch", patchText) .put("paragraphId", p.getId()); broadcastExcept(note.getId(), message, conn); }
Source:
<code>private Level resolveLogLevelOnClose() { <START> if (!serverContext.isActive()) { <END> return Level.FINEST; } if (closeCause == null || closeCause instanceof EOFException || closeCause instanceof CancelledKeyException) { if (connectionType.equals(ConnectionType.REST_CLIENT) || connectionType.equals(ConnectionType.MEMCACHE_CLIENT)) { return Level.FINE; } else { return Level.INFO; } } else { return Level.WARNING; } }</code><technical_language>read right, active/inactive context</technical_language>

Target:
private Level resolveLogLevelOnClose() { if (!serverContext.isNodeActive()) { return Level.FINEST; } if (closeCause == null || closeCause instanceof EOFException || closeCause instanceof CancelledKeyException) { if (connectionType.equals(ConnectionType.REST_CLIENT) || connectionType.equals(ConnectionType.MEMCACHE_CLIENT)) { return Level.FINE; } else { return Level.INFO; } } else { return Level.WARNING; } }
Source:
<code>public void convertsToXml() throws Exception { final Memo memo = new MkMemo(); memo.update( new Directives() .xpath("/memo") .add("uri").set("fake.thindeck.com").up() .addIf("domains") .addIf("domain").set("domain.thindeck.com") ); final StringWriter writer = new StringWriter(); <START> JAXBContext.newInstance(JxMemo.class) <END> .createMarshaller() .marshal(new JxMemo(memo), writer); MatcherAssert.assertThat( writer.toString(), XhtmlMatchers.hasXPaths( " " ) ); }</code><technical_language>Try JaxbConverter instead, jcabi-matchers</technical_language>

Target:
public void convertsToXml() throws Exception { final Memo memo = new MkMemo(); memo.update( new Directives() .xpath("/memo") .add("uri").set("fake.thindeck.com").up() .addIf("domains") .addIf("domain").set("domain.thindeck.com") ); MatcherAssert.assertThat( JaxbConverter.the(new JxMemo(memo)), XhtmlMatchers.hasXPaths( " " ) ); }
Source:
<code>private Optional<ImageInfoV4Response> selectLatestImageFromCandidates(List<ImageInfoV4Response> upgradeCandidates) { <START> ImageInfoV4Response imageInfoV4Response = upgradeCandidates.stream().max(ImageInfoV4Response.creationBasedComparator()).orElseThrow(); <END> LOGGER.debug("Choosing latest image as either upgrade request is empty or lockComponents is true", imageInfoV4Response); return Optional.of(imageInfoV4Response); }</code><technical_language>orElseThrow() omitted here,</technical_language>

Target:
private Optional<ImageInfoV4Response> selectLatestImageFromCandidates(List<ImageInfoV4Response> upgradeCandidates) { Optional<ImageInfoV4Response> imageInfoV4Response = upgradeCandidates.stream().max(ImageInfoV4Response.creationBasedComparator()); LOGGER.debug("Choosing latest image as either upgrade request is empty or lockComponents is true", imageInfoV4Response); return imageInfoV4Response; }
Source:
<code>public WatsonService(final String name) { this.name = name; String iamApiKey = CredentialUtils.getIAMKey(name); if (iamApiKey != null) { tokenManager = new IamTokenManager(new IamOptions.Builder().apiKey(iamApiKey).build()); } <START> apiKey = CredentialUtils.getAPIKey(name); <END> String url = CredentialUtils.getAPIUrl(name); if ((url != null) && !url.isEmpty()) { setEndPoint(url); } client = configureHttpClient(); }</code><technical_language>iam_url? running stage1 need a IAM server</technical_language>

Target:
public WatsonService(final String name) { this.name = name; String iamApiKey = CredentialUtils.getIAMKey(name); String iamUrl = CredentialUtils.getIAMUrl(name); if (iamApiKey != null) { IamOptions iamOptions = new IamOptions.Builder() .apiKey(iamApiKey) .url(iamUrl) .build(); tokenManager = new IamTokenManager(iamOptions); } apiKey = CredentialUtils.getAPIKey(name); String url = CredentialUtils.getAPIUrl(name); if ((url != null) && !url.isEmpty()) { setEndPoint(url); } client = configureHttpClient(); }
Source:
<code><START> public List<ObservationDto> getSampleObservations(final int studyId, final List<Integer> instanceIds, <END> final Integer selectionVariableId) { final SQLQuery createSQLQuery = this.session.createSQLQuery(measurementQuery.getSampleObservationQuery()); createSQLQuery.addScalar("nd_experiment_id", new IntegerType()); createSQLQuery.addScalar("preferred_name", new StringType()); createSQLQuery.addScalar("value", new IntegerType()); createSQLQuery.setParameter("studyId", studyId); createSQLQuery.setParameter("selectionVariableId", selectionVariableId); createSQLQuery.setParameterList("instanceIds", instanceIds); return this.mapSampleObservations(createSQLQuery.list()); }</code><technical_language>I find tests for this function</technical_language>

Target:
public List<ObservationDto> getSampleObservations(final int studyId, final List<Integer> instanceIds, final Integer selectionVariableId) { final SQLQuery createSQLQuery = this.session.createSQLQuery(this.measurementQuery.getSampleObservationQuery()); createSQLQuery.addScalar("nd_experiment_id", new IntegerType()); createSQLQuery.addScalar("preferred_name", new StringType()); createSQLQuery.addScalar("value", new StringType()); createSQLQuery.setParameter("studyId", studyId); createSQLQuery.setParameter("selectionVariableId", selectionVariableId); createSQLQuery.setParameterList("instanceIds", instanceIds); return this.mapSampleObservations(createSQLQuery.list()); }
Source:
<code>public void asyncReadLastConfirmed(final ReadLastConfirmedCallback cb, final Object ctx) { <START> if (clientCtx.getConf().useExplicitLacForReads) { <END> asyncReadExplicitLastConfirmed(cb, ctx); } else { asyncReadLastConfirmedInternal(cb, ctx); } }</code><technical_language>I a flag is choice here. bookkeeper client *smart* figure out reading explicit lac piggybacked lac</technical_language>

Target:
public void asyncReadLastConfirmed(final ReadLastConfirmedCallback cb, final Object ctx) { if (clientCtx.getConf().useExplicitLacForReads) { asyncReadExplicitLastConfirmed(cb, ctx); } else { asyncReadPiggybackLastConfirmed(cb, ctx); } }
Source:
<code>synchronized public void send(PlainCommand command) { if (socket == null) { try { socket = recreateSocket(); <START> socketStream = socket.getOutputStream(); <END> } catch (IOException e) { throw new AtsdClientException("Error while connecting to ATSD", e); } } try { socketStream.write(command.compose().getBytes("UTF8")); if (clientConfiguration.isAutoflush()) { socketStream.flush(); } return; } catch (Exception e) { log.warn("Error while sending commands to ATSD. Trying to reconnect", e); } try { socket = recreateSocket(); socketStream = socket.getOutputStream(); socketStream.write(command.compose().getBytes("UTF8")); if (clientConfiguration.isAutoflush()) { socketStream.flush(); } } catch (Exception e) { throw new AtsdClientException("Error while sending command to ATSD", e); } }</code><technical_language>need enforce TCP connect timeout read timeout, apply reasonable defaults, timeouts configurable</technical_language>

Target:
synchronized public void send(PlainCommand command) { send(command.compose()); }
Source:
<code>public void throwsForNonParcelableProperty() throws Exception { TypeElement type = elements.getTypeElement(SampleTypeWithNonSerializable.class.getCanonicalName()); AutoValueExtension.Context context = createContext(type); extension.generateClass(context, "Test_AnnotatedType", "SampleTypeWithNonSerializable", true); <START> fail(); <END> }</code><technical_language>need call this expected =, JUnit fail if exception is thrown</technical_language>

Target:
@Test public void throwsForNonParcelableProperty() throws Exception { TypeElement type = elements.getTypeElement(SampleTypeWithNonSerializable.class.getCanonicalName()); AutoValueExtension.Context context = createContext(type); try { extension.generateClass(context, "Test_AnnotatedType", "SampleTypeWithNonSerializable", true); fail(); } catch (AutoParcelException e) }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } oldPool = getVmPoolDao().get(getVmPool().getVmPoolId()); if (oldPool == null) { return failValidation(EngineMessage.VM_POOL_CANNOT_UPDATE_POOL_NOT_FOUND); } if (getParameters().getVmsCount() < 0) { return failValidation(EngineMessage.VM_POOL_CANNOT_DECREASE_VMS_FROM_POOL); } if (oldPool.getVmPoolType() != getParameters().getVmPool().getVmPoolType() || oldPool.isStateful() != getParameters().getVmPool().isStateful()) { <START> return failValidation(EngineMessage.VM_POOL_CANNOT_CHANGE_POOL_TYPE); <END> } return true; }</code><technical_language>difficult for user correlate 'pool type' stateful option? weird error for properties</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } oldPool = getVmPoolDao().get(getVmPool().getVmPoolId()); if (oldPool == null) { return failValidation(EngineMessage.VM_POOL_CANNOT_UPDATE_POOL_NOT_FOUND); } if (getParameters().getVmsCount() < 0) { return failValidation(EngineMessage.VM_POOL_CANNOT_DECREASE_VMS_FROM_POOL); } if (oldPool.getVmPoolType() != getParameters().getVmPool().getVmPoolType()) { return failValidation(EngineMessage.VM_POOL_CANNOT_CHANGE_POOL_TYPE); } if (oldPool.isStateful() != getParameters().getVmPool().isStateful()) { return failValidation(EngineMessage.VM_POOL_CANNOT_CHANGE_POOL_STATEFUL_OPTION); } return true; }
Source:
<code>public DatastreamRestClient(String zkAddr, String clusterName) { <START> Validate.notEmpty(zkAddr, "invalid ZooKeeper address"); <END> Validate.notEmpty(zkAddr, "invalid cluster name"); _httpClient = null; String basePath = String.format("/%s/d2", clusterName); D2Client d2Client = new D2ClientBuilder() .setZkHosts(zkAddr) .setBasePath(basePath) .build(); try { FutureCallback<None> future = new FutureCallback<>(); d2Client.start(future); future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS); _restClient = new RestClient(d2Client, "d2://"); } catch (Exception e) { String errMsg = String.format("Failed to start D2 client, zk=%s, cluster=%s", zkAddr, clusterName); LOG.error(errMsg, e); throw new DatastreamRuntimeException(errMsg, e); } _builders = new DatastreamRequestBuilders(); _bootstrapBuilders = new BootstrapRequestBuilders(); }</code><technical_language>add a log in other constructor if already</technical_language>

Target:
public DatastreamRestClient(String zkAddr, String clusterName) { Validate.notEmpty(zkAddr, "invalid ZooKeeper address"); Validate.notEmpty(clusterName, "invalid cluster name"); _httpClient = null; String basePath = String.format("/%s/d2", clusterName); D2Client d2Client = new D2ClientBuilder() .setZkHosts(zkAddr) .setBasePath(basePath) .build(); try { FutureCallback<None> future = new FutureCallback<>(); d2Client.start(future); future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS); _restClient = new RestClient(d2Client, "d2://"); } catch (Exception e) { String errMsg = String.format("Failed to start D2 client, zk=%s, cluster=%s", zkAddr, clusterName); LOG.error(errMsg, e); throw new DatastreamRuntimeException(errMsg, e); } _builders = new DatastreamRequestBuilders(); _bootstrapBuilders = new BootstrapRequestBuilders(); LOG.info(String.format("Successfully created Datastream REST client, zk=%s, cluster=%s", zkAddr, clusterName)); }
Source:
<code>public void onCoursePaymentSuccessful() { final Activity activity = getActivity(); if( activity != null) { activity.finish(); } final Bundle arguments = getArguments(); if (arguments != null) { final EnrolledCoursesResponse courseData = (EnrolledCoursesResponse) arguments.getSerializable(Router.EXTRA_COURSE_DATA); EventBus.getDefault().postSticky(new CourseUpgradedEvent(courseData.getCourse().getId())); <START> final Serializable serializable = arguments.getSerializable(Router.EXTRA_COURSE_UNIT); CourseComponent courseUnit; if (serializable != null) { courseUnit = (CourseComponent) serializable; analyticsRegistry.trackCourseUpgradeSuccess(courseUnit.getId(), courseData.getCourse().getId(), courseUnit.getBlockId()); } else { analyticsRegistry.trackCourseUpgradeSuccess(null, <END> courseData.getCourse().getId(), null); } } else { EventBus.getDefault().postSticky(new CourseUpgradedEvent(null)); } }</code><technical_language>replaced // Fire analytics final CourseComponent courseUnit = (CourseComponent) arguments.getSerializable(Router.EXTRA_COURSE_UNIT); if (courseUnit != null) { analyticsRegistry.trackCourseUpgradeSuccess(courseUnit.getId(), courseData.getCourse().getId(), courseUnit.getBlockId()); } else { analyticsRegistry.trackCourseUpgradeSuccess(null, courseData.getCourse().getId(), null); }</technical_language>

Target:
public void onCoursePaymentSuccessful() { final Activity activity = getActivity(); if( activity != null) { activity.finish(); } final Bundle arguments = getArguments(); if (arguments != null) { final EnrolledCoursesResponse courseData = (EnrolledCoursesResponse) arguments.getSerializable(Router.EXTRA_COURSE_DATA); EventBus.getDefault().postSticky(new CourseUpgradedEvent(courseData.getCourse().getId())); final CourseComponent courseUnit = (CourseComponent) arguments.getSerializable(Router.EXTRA_COURSE_UNIT); if (courseUnit != null) { analyticsRegistry.trackCourseUpgradeSuccess(courseUnit.getId(), courseData.getCourse().getId(), courseUnit.getBlockId()); } else { analyticsRegistry.trackCourseUpgradeSuccess(null, courseData.getCourse().getId(), null); } } else { EventBus.getDefault().postSticky(new CourseUpgradedEvent(null)); } }
Source:
<code>public void close() throws IOException { IOException first = null; for (int index = keyMaterials.length - 1; index >= 0; index--) { try { if (keyMaterials[index] != null) { keyMaterials[index].close(); } <START> } catch (IOException ioe) { <END> first = first == null ? ioe : first; } } if (first != null) { throw first; } }</code><technical_language>I think</technical_language>

Target:
public void close() throws IOException { Throwable first = null; for (int index = keyMaterials.length - 1; index >= 0; index--) { try { if (keyMaterials[index] != null) { keyMaterials[index].close(); } } catch (IOException e) { first = first == null ? e : first; } catch (RuntimeException e) { first = first == null ? e : first; } catch (Throwable e) { first = first == null ? e : first; } } if (first != null) { if (first instanceof IOException) { throw (IOException) first; } else if (first instanceof RuntimeException) { throw (RuntimeException) first; } else { throw new IOException("Error closing credentials.", first); } } }
Source:
<code>private static List<String> getExpectedOutput(int retentionPeriod, RETENTION_UNITS retentionUnit, FEED_TYPE feedType, DateTime endDateUTC, List<String> inputData) { DateTimeFormatter formatter = DateTimeFormat.forPattern(TimeUtil.getFormatStringForFeedType(feedType)); List<String> finalData = new ArrayList<String>(); final String endLimit = formatter.print(getEndLimit(retentionPeriod, retentionUnit, endDateUTC)); for (String testDate : inputData) { <START> if (!testDate.equalsIgnoreCase("somethingRandom")) { <END> if (testDate.compareTo(endLimit) >= 0) { finalData.add(testDate); } } else { finalData.add(testDate); } } return finalData; }</code><technical_language>Is this for a negative check</technical_language>

Target:
private static List<String> getExpectedOutput(int retentionPeriod, RETENTION_UNITS retentionUnit, FEED_TYPE feedType, DateTime endDateUTC, List<String> inputData) { DateTimeFormatter formatter = DateTimeFormat.forPattern(TimeUtil.getFormatStringForFeedType(feedType)); List<String> finalData = new ArrayList<String>(); final String endLimit = formatter.print(getEndLimit(retentionPeriod, retentionUnit, endDateUTC)); for (String testDate : inputData) { if (testDate.compareTo(endLimit) >= 0) { finalData.add(testDate); } } return finalData; }
Source:
<code>public String toString() { <START> return String.format("COORD[%s,%s]", X, Y); <END> }</code><technical_language>X Y primitives, %s %d here</technical_language>

Target:
public String toString() { return String.format("COORD(%s,%s)", X, Y); }
Source:
<code>private CompletableFuture<byte[]> sendAndReceive(String subject, byte[] payload, NodeId toNodeId) { Node node = cluster.getNode(toNodeId); if (node == null) { <START> return Futures.exceptionalFuture(new ConnectException()); <END> } return messagingService.sendAndReceive(node.endpoint(), subject, payload); }</code><technical_language>omit stacktrace for performance</technical_language>

Target:
private CompletableFuture<byte[]> sendAndReceive(String subject, byte[] payload, NodeId toNodeId) { Node node = cluster.getNode(toNodeId); if (node == null) { return Futures.exceptionalFuture(CONNECT_EXCEPTION); } return messagingService.sendAndReceive(node.endpoint(), subject, payload); }
Source:
<code>public void start() throws Exception { LOG.info("Starting split enumerator for source {}.", operatorName); coordinatorExecutor.execute(() -> { try { enumerator.start(); <START> } catch (Exception e) { <END> LOG.error("Failed to start the enumerator of operator due to", operatorName, e); context.failJob(e); } }); started = true; }</code><technical_language>change this Throwable? catch issues dependencies, classpaths. is other parts of Flink do is important. job wrong dependencies kills a shared cluster</technical_language>

Target:
public void start() throws Exception { LOG.info("Starting split enumerator for source {}.", operatorName); coordinatorExecutor.execute(() -> { try { enumerator.start(); } catch (Throwable e) { LOG.error("Failed to start the enumerator of operator due to", operatorName, e); context.failJob(e); ExceptionUtils.rethrowIfFatalErrorOrOOM(e); } }); started = true; }