auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void search( @RequestParam(value = QUERY_PARAM, required = false) String query, HttpServletRequest request, HttpServletResponse response ) throws IOException { ResponseWriter writer = null; try { writer = writerResolver.writerFor(request, response); paramChecker.checkParameters(request); List<NamedParameter<?>> parameters = parse(request); SearchQuery.Builder queryBuilder; if (Strings.isNullOrEmpty(query)) { queryBuilder = SearchQuery.builder(); } else { queryBuilder = SearchQuery.getDefaultQuerySearcher(query); } for (NamedParameter<?> parameter : parameters) { if (parameter instanceof SearchParameter) { queryBuilder.addSearcher((SearchParameter)parameter); } else { <START> queryBuilder.addFilter((FilterParameter<?>)parameter); <END> } } Selection selection = selectionBuilder.build(request); SearchQuery searchQuery = queryBuilder .withLimit(selection.getLimit()) .withOffset(selection.getOffset()) .build(); QueryContext queryContext = QueryContext.create( applicationFetcher.applicationFor(request) .orElseThrow(InvalidParameterException::new), annotationsExtractor.extractFromSingleRequest(request), request ); QueryResult<Content> contentResult = searcher.search(searchQuery, queryContext); resultWriter.write(contentResult, writer); } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }</code><technical_language>Is this a safe cast? worth a check else if if add more subclasses of NamedParameter in future this break</technical_language>

Target:
public void search( @RequestParam(value = QUERY_PARAM, required = false) String query, HttpServletRequest request, HttpServletResponse response ) throws IOException { ResponseWriter writer = null; try { writer = writerResolver.writerFor(request, response); paramChecker.checkParameters(request); List<NamedParameter<?>> parameters = parse(request); SearchQuery.Builder queryBuilder; if (Strings.isNullOrEmpty(query)) { queryBuilder = SearchQuery.builder(); } else { queryBuilder = SearchQuery.getDefaultQuerySearcher(query); } for (NamedParameter<?> parameter : parameters) { if (parameter instanceof SearchParameter) { queryBuilder.addSearcher((SearchParameter)parameter); } else if (parameter instanceof FilterParameter) { queryBuilder.addFilter((FilterParameter<?>)parameter); } } Selection selection = selectionBuilder.build(request); SearchQuery searchQuery = queryBuilder .withLimit(selection.getLimit()) .withOffset(selection.getOffset()) .build(); QueryContext queryContext = QueryContext.create( applicationFetcher.applicationFor(request).orElse(DefaultApplication.create()), annotationsExtractor.extractFromSingleRequest(request), request ); QueryResult<Content> contentResult = searcher.search(searchQuery, queryContext); resultWriter.write(contentResult, writer); } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }
Source:
<code>public void authorizeEventTypeUpdate(final EventType eventType) throws ForbiddenAccessException, ServiceTemporaryUnavailableException { if (eventType.getAuthorization() == null) { return; } <START> final Resource resource = new EventTypeResource("/event-type", "event-type", <END> Collections.singletonMap(AuthorizationService.Operation.ADMIN, eventType.getAuthorization().getAdmins())); try { if (!authorizationService.isAuthorized(null, AuthorizationService.Operation.ADMIN, resource)) { throw new ForbiddenAccessException("Updating the `EventType` is only allowed for clients that " + "satisfy the authorization `admin` requirements"); } } catch (final PluginException e) { throw new ServiceTemporaryUnavailableException("Error calling authorization plugin", e); } }</code><technical_language>I event type name /event-type</technical_language>

Target:
public void authorizeEventTypeUpdate(final EventType eventType) throws ForbiddenAccessException, ServiceTemporarilyUnavailableException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), "event-type", Collections.singletonMap(AuthorizationService.Operation.ADMIN, eventType.getAuthorization().getAdmins())); try { if (!authorizationService.isAuthorized(null, AuthorizationService.Operation.ADMIN, resource)) { throw new ForbiddenAccessException("Updating the `EventType` is only allowed for clients that " + "satisfy the authorization `admin` requirements"); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }
Source:
<code>public String toString() { ToStringHelper helper = toStringHelper(this) .add("clientId", clientId) .add("name", name) .add("hiveType", hiveType) .add("hiveColumnIndex", hiveColumnIndex) .add("columnType", columnType); <START> comment.ifPresent(comment -> helper.add("comment", comment)); <END> return helper.toString(); }</code><technical_language>other handle this is <LINK_0> Optional.orElse(null). need break method call chain</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("clientId", clientId) .add("name", name) .add("hiveType", hiveType) .add("hiveColumnIndex", hiveColumnIndex) .add("columnType", columnType) .add("comment", comment.orElse(null)) .omitNullValues() .toString(); }
Source:
<code>public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<? extends SoftAssertionsProvider> type = getSupportedParameterType(parameterContext.getParameter()); if (type == null) { return false; <START> } <END> Executable executable = parameterContext.getDeclaringExecutable(); boolean isTestableMethod = executable instanceof Method && isAnnotated(executable, Testable.class); if (!isTestableMethod) { throw new ParameterResolutionException(format("Configuration error: cannot resolve SoftAssertionsProvider instances for [%s]. Only test methods are supported.", executable)); } if (Modifier.isAbstract(type.getModifiers())) { throw new ParameterResolutionException(format("Configuration error: cannot resolve abstract SoftAssertionsProvider instances [%s].", executable)); } return true; }</code><technical_language>I prefer isUnsupportedParameterType call Modifier.isAbstract(parameterContext.getParameter().getType() I need cast parameterContext.getParameter().getType() Class<? extends SoftAssertionsProvider> for this call</technical_language>

Target:
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { if (isUnsupportedParameterType(parameterContext.getParameter())) return false; Executable executable = parameterContext.getDeclaringExecutable(); boolean isTestableMethod = executable instanceof Method && isAnnotated(executable, Testable.class); if (!isTestableMethod) { throw new ParameterResolutionException(format("Configuration error: cannot resolve SoftAssertionsProvider instances for [%s]. Only test methods are supported.", executable)); } Class<?> type = parameterContext.getParameter().getType(); if (Modifier.isAbstract(type.getModifiers())) { throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] is abstract and cannot be instantiated.", executable)); } try { type.getDeclaredConstructor(); } catch (Exception e) { throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] has no default constructor and cannot be instantiated.", executable)); } return true; }
Source:
<code>private static String getUserId(Cause cause) { <START> if (cause instanceof UserIdCause) { <END> Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserId(); } return null; }</code><technical_language>Missing UserCause handling</technical_language>

Target:
private static String getUserId(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserId(); } return ""; }
Source:
<code>private GerritIndexWriterConfig(Version version, Config cfg, String name) { luceneConfig = new IndexWriterConfig(version, new StandardAnalyzer(version, CharArraySet.EMPTY_SET)); luceneConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); double m = 1 << 20; luceneConfig.setRAMBufferSizeMB(cfg.getLong( "index", name, "ramBufferSize", (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB * m)) / m); luceneConfig.setMaxBufferedDocs(cfg.getInt( "index", name, "maxBufferedDocs", IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS)); try { if ((commitWithinMs = cfg.getLong("index", name, "commitWithin", 0)) >= 0) { <START> commitWithinMs = <END> ConfigUtil.getTimeUnit(cfg, "index", name, "commitWithin", MILLISECONDS.convert(5, MINUTES), MILLISECONDS); } } catch (IllegalArgumentException e) { commitWithinMs = ConfigUtil.getTimeUnit(cfg, "index", name, "commitWithin", MILLISECONDS.convert(5, MINUTES), MILLISECONDS); } }</code><technical_language>I paying attention Edwin's talk this a no-op: try { if (mayThrowIAE()) { commitWithinMs = foo(); } } catch (IAE) { commitWithinMs = foo(); } foo() is in cases end is if mayThrowIAE() returns false, in case commitWithinMs remains 0. end result is...ignore negative values if a time unit suffix. right? wrong just: commitWithMs = ConfigUtil.getTimeUnit(...) This set a number is negative, zero, positive, of is a time unit suffix</technical_language>

Target:
private GerritIndexWriterConfig(Version version, Config cfg, String name) { luceneConfig = new IndexWriterConfig(version, new StandardAnalyzer(version, CharArraySet.EMPTY_SET)); luceneConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); double m = 1 << 20; luceneConfig.setRAMBufferSizeMB(cfg.getLong( "index", name, "ramBufferSize", (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB * m)) / m); luceneConfig.setMaxBufferedDocs(cfg.getInt( "index", name, "maxBufferedDocs", IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS)); try { commitWithinMs = ConfigUtil.getTimeUnit(cfg, "index", name, "commitWithin", MILLISECONDS.convert(5, MINUTES), MILLISECONDS); } catch (IllegalArgumentException e) { commitWithinMs = cfg.getLong("index", name, "commitWithin", 0); } }
Source:
<code>public UserKeyRecord getRecordForCurrentUser() { try { return getSession().getUserKeyRecord(); } catch (SessionUnavailableException e) { <START> return null; <END> } }</code><technical_language>this ok? this throw a SessionUnavailableException part of method signature</technical_language>

Target:
public UserKeyRecord getRecordForCurrentUser() throws SessionUnavailableException { return getSession().getUserKeyRecord(); }
Source:
<code>protected GoodData(String hostname, String login, String password, int port, String protocol, GoodDataSettings settings) { notEmpty(hostname, "hostname"); notEmpty(login, "login"); notEmpty(password, "password"); notEmpty(protocol, "protocol"); <START> final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create() <END> .setUserAgent(getUserAgent()); applySettings(settings, httpClientBuilder); restTemplate = createRestTemplate(login, password, hostname, httpClientBuilder, port, protocol); accountService = new AccountService(getRestTemplate()); projectService = new ProjectService(getRestTemplate(), accountService); metadataService = new MetadataService(getRestTemplate()); modelService = new ModelService(getRestTemplate()); gdcService = new GdcService(getRestTemplate()); dataStoreService = new DataStoreService(httpClientBuilder, gdcService, new HttpHost(hostname, port, protocol).toURI(), login, password); datasetService = new DatasetService(getRestTemplate(), dataStoreService); reportService = new ReportService(getRestTemplate()); processService = new ProcessService(getRestTemplate(), accountService, dataStoreService); warehouseService = new WarehouseService(getRestTemplate(), hostname, port); connectorService = new ConnectorService(getRestTemplate(), projectService); }</code><technical_language>move this newly created createHttpClientBuilder method</technical_language>

Target:
protected GoodData(String hostname, String login, String password, int port, String protocol, GoodDataSettings settings) { notEmpty(hostname, "hostname"); notEmpty(login, "login"); notEmpty(password, "password"); notEmpty(protocol, "protocol"); final HttpClientBuilder httpClientBuilder = createHttpClientBuilder(settings); restTemplate = createRestTemplate(login, password, hostname, httpClientBuilder, port, protocol); accountService = new AccountService(getRestTemplate()); projectService = new ProjectService(getRestTemplate(), accountService); metadataService = new MetadataService(getRestTemplate()); modelService = new ModelService(getRestTemplate()); gdcService = new GdcService(getRestTemplate()); dataStoreService = new DataStoreService(httpClientBuilder, gdcService, new HttpHost(hostname, port, protocol).toURI(), login, password); datasetService = new DatasetService(getRestTemplate(), dataStoreService); reportService = new ReportService(getRestTemplate()); processService = new ProcessService(getRestTemplate(), accountService, dataStoreService); warehouseService = new WarehouseService(getRestTemplate(), hostname, port); connectorService = new ConnectorService(getRestTemplate(), projectService); }
Source:
<code>public List<Descriptor<ListViewColumn>> getColumnsDescriptors() { StaplerRequest request = Stapler.getCurrentRequest(); <START> View view = request.findAncestorObject(clazz); <END> return view == null ? DescriptorVisibilityFilter.applyType(clazz, ListViewColumn.all()) : DescriptorVisibilityFilter.apply(view, ListViewColumn.all()); }</code><technical_language>request null</technical_language>

Target:
public List<Descriptor<ListViewColumn>> getColumnsDescriptors() { StaplerRequest request = Stapler.getCurrentRequest(); if (request != null) { View view = request.findAncestorObject(clazz); return view == null ? DescriptorVisibilityFilter.applyType(clazz, ListViewColumn.all()) : DescriptorVisibilityFilter.apply(view, ListViewColumn.all()); } return ListViewColumn.all(); }
Source:
<code>private Optional<Channel> channelFor(String guid) { long channelId = codec.decode(guid).longValue(); Optional<Channel> channelMaybe = channelResolver.fromId(channelId).toOptional(); if(!channelMaybe.isPresent()) { LOGGER.error("There is missing channel for this channel id: " + guid); <START> return Optional.empty(); <END> } return channelMaybe; }</code><technical_language>this a pointless extra line - optional, this if block is checking if !present log a message</technical_language>

Target:
private Optional<Channel> channelFor(String guid) { long channelId; try { channelId = codec.decode(guid).longValue(); } catch(IllegalArgumentException e) { LOGGER.error("{} was not valid for decoding", guid, e); return Optional.empty(); } Optional<Channel> channelMaybe = channelResolver.fromId(channelId).toOptional(); if(!channelMaybe.isPresent()) { LOGGER.error("There is missing channel for this channel id: {}", guid); return Optional.empty(); } return channelMaybe; }
Source:
<code>private boolean isTitleValid() { String templateTitle = this.template.getTitle(); if (StringUtils.isNotBlank(templateTitle)) { try { long count = ServiceManager.getTemplateService().countTemplatesWithTitleAndClient(templateTitle, ServiceManager.getUserService().getSessionClientId()); if (count > 1) { Helper.setErrorMessage(INCOMPLETE_DATA, TITLE_USED); return false; } else if (count == 1) { <START> if (Objects.nonNull(this.template.getId())) { <END> return true; } Helper.setErrorMessage(INCOMPLETE_DATA, TITLE_USED); return false; } return true; } catch (DAOException e) { Helper.setErrorMessage(INCOMPLETE_DATA, TITLE_USED); return false; } } Helper.setErrorMessage(INCOMPLETE_DATA, "templateTitleEmpty"); return false; }</code><technical_language>If I open existing template rename existing name, count is 1 template.id is null, I templates name</technical_language>

Target:
private boolean isTitleValid() { String templateTitle = this.template.getTitle(); if (StringUtils.isNotBlank(templateTitle)) { List<Template> templates = ServiceManager.getTemplateService().getTemplatesWithTitleAndClient(templateTitle, this.template.getClient().getId()); int count = templates.size(); if (count > 1) { Helper.setErrorMessage(INCOMPLETE_DATA, TITLE_USED); return false; } else if (count == 1) { Integer templateId = this.template.getId(); if (Objects.nonNull(templateId) && templates.get(0).getId().equals(templateId)) { return true; } Helper.setErrorMessage(INCOMPLETE_DATA, TITLE_USED); return false; } return true; } Helper.setErrorMessage(INCOMPLETE_DATA, "templateTitleEmpty"); return false; }
Source:
<code>private List<String> collectCommandReturnsFromHosts( List<CompletableFuture<CommandReturn>> futureList, List<String> hosts) { List<CommandReturn> results; try { results = collectAllFutures(futureList).get(); System.out.format("Results collected from %d hosts%n", results.size()); } catch (InterruptedException | ExecutionException e) { System.err.format("Failed to collect the results. Error is %s%n", e.getMessage()); LOG.error("Error: %s", e); return Collections.EMPTY_LIST; } if (results.size() != hosts.size()) { System.out.format("Error occurred while collecting information on %d/%d hosts%n", hosts.size() - results.size()); return Collections.EMPTY_LIST; } else { List<String> successfulHosts = new ArrayList<>(); for (int i = 0; i < hosts.size(); i++) { CommandReturn c = results.get(i); String host = hosts.get(i); if (c.getExitCode() != 0) { System.out.format("Execution failed on host %s%n", host); System.out.println(c.getFormattedOutput()); continue; } successfulHosts.add(host); } <START> System.out.format("Command successful on %d/%d hosts.%n", <END> successfulHosts.size(), hosts.size()); return successfulHosts; } }</code><technical_language>(nit) "Command executed successfully %d/%d hosts."</technical_language>

Target:
private List<String> collectCommandReturnsFromHosts( List<CompletableFuture<CommandReturn>> futureList, List<String> hosts) { List<CommandReturn> results; try { results = collectAllFutures(futureList).get(); System.out.format("Results collected from %d hosts%n", results.size()); } catch (InterruptedException | ExecutionException e) { System.err.format("Failed to collect the results. Error is %s%n", e.getMessage()); LOG.error("Error: %s", e); return Collections.EMPTY_LIST; } if (results.size() != hosts.size()) { System.out.format("Error occurred while collecting information on %d/%d hosts%n", hosts.size() - results.size()); return Collections.EMPTY_LIST; } else { List<String> successfulHosts = new ArrayList<>(); for (int i = 0; i < hosts.size(); i++) { CommandReturn c = results.get(i); String host = hosts.get(i); if (c.getExitCode() != 0) { System.out.format("Execution failed on host %s%n", host); System.out.println(c.getFormattedOutput()); continue; } successfulHosts.add(host); } System.out.format("Command executed successfully on %d/%d hosts.", successfulHosts.size(), hosts.size()); return successfulHosts; } }
Source:
<code>public static void main( String[] args ) throws InterruptedException, IOException { FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); <START> File indexFile = new File( "index" ); <END> Runtime.getRuntime().addShutdownHook( new Thread( () -> fs.deleteFile( indexFile ) ) ); new GBPTreePlayground( fs, indexFile ).run(); }</code><technical_language>I if args if length > 0 if grab arg file (could absolute). I ran this out. print file (absolute path) working starting up. delete file in end, always? if want try out restarts, generations that</technical_language>

Target:
public static void main( String[] args ) throws InterruptedException, IOException { File indexFile; if ( args.length > 0 ) { indexFile = new File( args[0] ); } else { indexFile = new File( "index" ); } FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); new GBPTreePlayground( fs, indexFile ).run(); }
Source:
<code>public SASTokenProvider getSASTokenProvider() throws AzureBlobFileSystemException { AuthType authType = getEnum(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.SharedKey); if (authType != AuthType.SAS) { throw new SASTokenProviderException(String.format( "Invalid auth type: %s is being used, expecting SAS", authType)); } try { String configKey = FS_AZURE_SAS_TOKEN_PROVIDER_TYPE; Class<? extends SASTokenProvider> sasTokenProviderClass = getClass(configKey, null, SASTokenProvider.class); <START> if (sasTokenProviderClass == null) { <END> throw new IllegalArgumentException( String.format("The configuration value for \"%s\" is invalid.", configKey)); } SASTokenProvider sasTokenProvider = ReflectionUtils .newInstance(sasTokenProviderClass, rawConfig); if (sasTokenProvider == null) { throw new IllegalArgumentException("Failed to initialize " + sasTokenProviderClass); } LOG.trace("Initializing {}", sasTokenProviderClass.getName()); sasTokenProvider.initialize(rawConfig, accountName); LOG.trace("{} init complete", sasTokenProviderClass.getName()); return sasTokenProvider; } catch(IllegalArgumentException e) { throw e; } catch (Exception e) { throw new TokenAccessProviderException("Unable to load SAS token provider class: " + e, e); } }</code><technical_language>do need do that? increases LOC maintenance costs</technical_language>

Target:
public SASTokenProvider getSASTokenProvider() throws AzureBlobFileSystemException { AuthType authType = getEnum(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.SharedKey); if (authType != AuthType.SAS) { throw new SASTokenProviderException(String.format( "Invalid auth type: %s is being used, expecting SAS", authType)); } try { String configKey = FS_AZURE_SAS_TOKEN_PROVIDER_TYPE; Class<? extends SASTokenProvider> sasTokenProviderClass = getClass(configKey, null, SASTokenProvider.class); Preconditions.checkArgument(sasTokenProviderClass != null, String.format("The configuration value for \"%s\" is invalid.", configKey)); SASTokenProvider sasTokenProvider = ReflectionUtils .newInstance(sasTokenProviderClass, rawConfig); Preconditions.checkArgument(sasTokenProvider != null, String.format("Failed to initialize %s", sasTokenProviderClass)); LOG.trace("Initializing {}", sasTokenProviderClass.getName()); sasTokenProvider.initialize(rawConfig, accountName); LOG.trace("{} init complete", sasTokenProviderClass.getName()); return sasTokenProvider; } catch (Exception e) { throw new TokenAccessProviderException("Unable to load SAS token provider class: " + e, e); } }
Source:
<code>public static String encodeFileUri(String fileUriStr, String fileChecksum, String encodedSubDir) throws IOException { <START> if (instance == null) { <END> throw new IOException("Uninitialized ReplChangeManager instance."); } String encodedUri = fileUriStr; if ((fileChecksum != null) && (cmroot != null)) { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + fileChecksum + URI_FRAGMENT_SEPARATOR + FileUtils.makeQualified(cmroot, conf); } else { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + URI_FRAGMENT_SEPARATOR; } encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + ((encodedSubDir != null) ? encodedSubDir : ""); LOG.debug("Encoded URI: " + encodedUri); return encodedUri; }</code><technical_language>assert expect caller instantiate ReplChangeManager invoking this method. Also, if think, exception is better, IllegalStateException relevant</technical_language>

Target:
public static String encodeFileUri(String fileUriStr, String fileChecksum, String encodedSubDir) throws IOException { if (instance == null) { throw new IllegalStateException("Uninitialized ReplChangeManager instance."); } String encodedUri = fileUriStr; if ((fileChecksum != null) && (cmroot != null)) { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + fileChecksum + URI_FRAGMENT_SEPARATOR + FileUtils.makeQualified(cmroot, conf); } else { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + URI_FRAGMENT_SEPARATOR; } encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + ((encodedSubDir != null) ? encodedSubDir : ""); LOG.debug("Encoded URI: " + encodedUri); return encodedUri; }
Source:
<code>private InterpreterResult getMetaData(String propertyKey, String cmd, InterpreterContext interpreterContext) { Connection connection; String user = interpreterContext.getAuthenticationInfo().getUser(); DatabaseMetaData dataBaseMetaData; ResultSet resultSet = null; ResultSetMetaData resultSetMetaData = null; String tableName = cmd.substring(7).trim(); String results; try { connection = getConnection(propertyKey, interpreterContext); if (connection == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } try { dataBaseMetaData = connection.getMetaData(); if (tableName.equals("")) { resultSet = dataBaseMetaData.getTables(null, null, "%", TABLE_TYPES); } else { resultSet = dataBaseMetaData.getColumns(null, null, tableName, null); } results = getResults(resultSet, true); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } } if (connection != null) { try { connection.close(); } catch (SQLException e) { } } } return new InterpreterResult(Code.SUCCESS, results); } catch (Exception e) { logger.error("Cannot fetch metadata.", e); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); <START> String errorMsg = new String(baos.toByteArray(), StandardCharsets.UTF_8); <END> try { closeDBPool(user, propertyKey); } catch (SQLException e1) { e1.printStackTrace(); } return new InterpreterResult(Code.ERROR, errorMsg); } }</code><technical_language>I remember, org.apache.commons.lang3.exception.ExceptionUtils#getStackTrace</technical_language>

Target:
private InterpreterResult getMetaData(String propertyKey, String cmd, InterpreterContext interpreterContext) { Connection connection; String user = interpreterContext.getAuthenticationInfo().getUser(); DatabaseMetaData dataBaseMetaData; ResultSet resultSet = null; String tableName = null; String results; if (cmd.split(" +").length > 1) { tableName = cmd.split(" +")[1]; } try { connection = getConnection(propertyKey, interpreterContext); if (connection == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } try { dataBaseMetaData = connection.getMetaData(); if (tableName == null) { resultSet = dataBaseMetaData.getTables(null, null, "%", TABLE_TYPES); } else { resultSet = dataBaseMetaData.getColumns(null, null, tableName, null); } results = getResults(resultSet, true); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } } if (connection != null) { try { connection.close(); } catch (SQLException e) { } } } return new InterpreterResult(Code.SUCCESS, results); } catch (Exception e) { logger.error("Cannot fetch metadata.", e); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); String errorMsg = new String(baos.toByteArray(), StandardCharsets.UTF_8); try { closeDBPool(user, propertyKey); } catch (SQLException e1) { e1.printStackTrace(); } return new InterpreterResult(Code.ERROR, errorMsg); } }
Source:
<code>public AjaxTinyMCEPage() { <START> ta = new TextArea("ta"); <END> ta.setVisible(false); ta.setOutputMarkupPlaceholderTag(true); ta.add(new TinyMceBehavior()); add(ta); add(new AjaxLink<Void>("toggle") { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { visible = !visible; ta.setVisible(visible); target.add(ta); } }); }</code><technical_language>diamond operator</technical_language>

Target:
public AjaxTinyMCEPage() { ta = new TextArea<>("ta"); ta.setVisible(false); ta.setOutputMarkupPlaceholderTag(true); ta.add(new TinyMceBehavior()); add(ta); add(new AjaxLink<Void>("toggle") { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { visible = !visible; ta.setVisible(visible); target.add(ta); } }); }
Source:
<code>private void handleLogRequest(VoltMessage message) { Iv2RepairLogRequestMessage req = (Iv2RepairLogRequestMessage)message; int deadHostId = req.getDeadHostId(); if (deadHostId != Integer.MAX_VALUE) { if (m_messenger.canCompleteRepair(deadHostId)) { req.disableDeadHostCheck(); deliver(message); } else { if (req.getRepairRetryCount() > 100 && req.getRepairRetryCount() % 100 == 0) { hostLog.warn("Repair Request for dead host " + deadHostId + " has not been processed yet because connection has not closed"); <START> if (req.getRepairRetryCount() == 60 * 100) { <END> hostLog.warn("Connection to dead host " + deadHostId + " has not been closed for 60 seconds, stop blocking repair request."); m_messenger.markPicoZombieHost(deadHostId); } } Runnable retryRepair = new Runnable() { @Override public void run() { InitiatorMailbox.this.deliver(message); } }; VoltDB.instance().scheduleWork(retryRepair, 10, -1, TimeUnit.MILLISECONDS); } return; } List<Iv2RepairLogResponseMessage> logs = m_repairLog.contents(req.getRequestId(), req.isMPIRequest()); if (req.isMPIRequest()) { m_scheduler.cleanupTransactionBacklogOnRepair(); } for (Iv2RepairLogResponseMessage log : logs) { send(message.m_sourceHSId, log); } }</code><technical_language>This conditional check executed line 591 avoid delay more 60 seconds</technical_language>

Target:
private void handleLogRequest(VoltMessage message) { Iv2RepairLogRequestMessage req = (Iv2RepairLogRequestMessage)message; int deadHostId = req.getDeadHostId(); if (deadHostId != Integer.MAX_VALUE) { if (req.getRepairRetryCount() == 60 * 100) { hostLog.warn("Connection to dead host " + deadHostId + " has not been closed for 60 seconds, stop blocking repair request."); m_messenger.markPicoZombieHost(deadHostId); } if (m_messenger.canCompleteRepair(deadHostId)) { req.disableDeadHostCheck(); deliver(message); } else { if (req.getRepairRetryCount() > 100 && req.getRepairRetryCount() % 100 == 0) { hostLog.warn("Repair Request for dead host " + deadHostId + " has not been processed yet because connection has not closed"); } Runnable retryRepair = new Runnable() { @Override public void run() { InitiatorMailbox.this.deliver(message); } }; VoltDB.instance().scheduleWork(retryRepair, 10, -1, TimeUnit.MILLISECONDS); } return; } List<Iv2RepairLogResponseMessage> logs = m_repairLog.contents(req.getRequestId(), req.isMPIRequest()); if (req.isMPIRequest()) { m_scheduler.cleanupTransactionBacklogOnRepair(); } for (Iv2RepairLogResponseMessage log : logs) { send(message.m_sourceHSId, log); } }
Source:
<code>private void flipQA (JSONObject template) { try { String qfmt = template.getString("qfmt"); String afmt = template.getString("afmt"); Matcher m = Pattern.compile("(?s)(.+)<hr id=answer>(.+)").matcher(afmt); if (!m.find()) { template.put("qfmt", afmt.replace("{{FrontSide}}","")); } else { template.put("qfmt",m.group(2).trim()); <START> } <END> template.put("afmt","{{FrontSide}}\n\n<hr id=answer>\n\n" + qfmt); } catch (JSONException e) { throw new RuntimeException(e); } }</code><technical_language>This DeckTask is unused</technical_language>

Target:
private void flipQA (JSONObject template) { String qfmt = template.getString("qfmt"); String afmt = template.getString("afmt"); Matcher m = Pattern.compile("(?s)(.+)<hr id=answer>(.+)").matcher(afmt); if (!m.find()) { template.put("qfmt", afmt.replace("{{FrontSide}}","")); } else { template.put("qfmt",m.group(2).trim()); } template.put("afmt","{{FrontSide}}\n\n<hr id=answer>\n\n" + qfmt); }
Source:
<code><START> public static < A, B > RandomAccessiblePair< A, B > pair( <END> final RandomAccessible< A > sourceA, final RandomAccessible< B > sourceB ) { return new RandomAccessiblePair< A, B >( sourceA, sourceB ); }</code><technical_language>I suggest return type RandomAccessible<Pair<A, B>> RandomAccessible<? extends Pair<A, B>>, if is strong need for _exactly_ RandomAccessiblePair<A, B>. I imagine want add other variants implementing this later</technical_language>

Target:
public static < A, B > RandomAccessible< Pair< A, B > > pair( final RandomAccessible< A > sourceA, final RandomAccessible< B > sourceB ) { return new RandomAccessiblePair< A, B >( sourceA, sourceB ); }
Source:
<code>public String getSubjectKeyID() { <START> if (subjectKeyID == null) { <END> byte[] subjectKeyId = x509Cert.getExtensionValue(SUBJECT_KEY_ID); try { if (subjectKeyId != null) { DERDecoder extVal = new DERDecoder(subjectKeyId); extVal.expect(DERDecoder.TYPE_OCTET_STRING); extVal.getLength(); extVal.expect(DERDecoder.TYPE_OCTET_STRING); int keyIDLen = extVal.getLength(); subjectKeyID = Hex.encodeHexString(extVal.getBytes(keyIDLen)); } } catch (WSSecurityException e) { LOG.error("Unable to convert SKI into human readable {}", e.getLocalizedMessage(), e); } } return StringUtils.isEmpty(subjectKeyID) ? EMPTY_FIELD : subjectKeyID; }</code><technical_language>Add this logic certificatemanagerserviceImpl class</technical_language>

Target:
public String getSubjectKeyID() { return subjectKeyID; }
Source:
<code>public URI getURI() { <START> return this.uri; <END> }</code><technical_language>this try create a URI logic null for retro compatibility</technical_language>

Target:
public URI getURI() { if (this.uri == null) { this.uri = URI.create(String.format("%s:%s", getScheme(), getReference())); } return this.uri; }
Source:
<code>public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener, String instanceName) throws Exception { PropertyKey propertyKey = _dataAccessor.keyBuilder().customizedStatesRoot(instanceName); <START> if (_zkclient.exists(propertyKey.getPath())) { addListener(listener, new Builder(_clusterName).customizedStatesRoot(instanceName), ChangeType.CUSTOMIZED_STATE_ROOT, new EventType[]{EventType.NodeChildrenChanged}); } <END> }</code><technical_language>Do useful log (warn) if this evaluates false</technical_language>

Target:
public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener, String instanceName) throws Exception { addListener(listener, new Builder(_clusterName).customizedStatesRoot(instanceName), ChangeType.CUSTOMIZED_STATE_ROOT, new EventType[]{EventType.NodeChildrenChanged}); }
Source:
<code>public String getHeader(CharSequence headerName) { <START> return headers().get(headerName.toString()); <END> }</code><technical_language>toString()</technical_language>

Target:
public String getHeader(CharSequence headerName) { return headers().get(headerName); }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getTitle().hashCode(); <START> result = prime * result + super.hashCode(); <END> return result; }</code><technical_language>suggest consider conventional hashCode implementation is consistent equals method - entity title account, of null: final int prime = 31; int result = super.hashCode(); result = prime * result + ((getEntity() == null) ? 0 : getEntity().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); return result; (If objects equal equals method, calling hashCode method of objects produce integer result.)</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((getEntity() == null) ? 0 : getEntity().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); return result; }
Source:
<code>public boolean testDouble(double value) { if (!lowerUnbounded) { if (value < lower) { return false; } if (lowerExclusive && lower == value) { return false; } } if (!upperUnbounded) { if (value > upper) { return false; } if (upperExclusive && value == upper) { return false; } } <START> return !Double.isNaN(value) && !Double.isNaN(lower) && !Double.isNaN(upper); <END> }</code><technical_language>@bhhari Is reason test this fix queries? extend com.facebook.presto.orc.TestTupleDomainFilter#testDoubleRange unit test</technical_language>

Target:
public boolean testDouble(double value) { if (Double.isNaN(value)) { return false; } if (!lowerUnbounded) { if (value < lower) { return false; } if (lowerExclusive && lower == value) { return false; } } if (!upperUnbounded) { if (value > upper) { return false; } if (upperExclusive && value == upper) { return false; } } return true; }
Source:
<code>public NullStatisticsReporter() { <START> super( FileUtils.getFile( FileUtils.getTempDirectory(), RandomStringUtils.randomAlphabetic( 24 ) ) ); <END> }</code><technical_language>nice protected no-arg constructor of StatisticsReporter for purposes null variables of File RunEntryStatisticsMap, etc. necessary create new objects if unused</technical_language>

Target:
private NullStatisticsReporter() { super( null, null, null ); }
Source:
<code>public void sendMessageToElastic() throws Exception { Server server = Server.builder().setHost("host").setPort("123").build(); Query query = Query.builder().build(); Result result = new Result(1, "attributeName", "className", "objDomain", "classNameAlias", "typeName", ImmutableMap.of("key", (Object)1)); ElasticWriter writer = createElasticWriter(); when(mockClient.execute(Matchers.isA(IndicesExists.class))).thenReturn(jestResultFalse); when(mockClient.execute(Matchers.isA(PutMapping.class))).thenReturn(jestResultTrue); writer.setJestClient(mockClient); writer.start(); writer.doWrite(server, query, ImmutableList.of(result)); writer.stop(); Mockito.verify(mockClient, atLeast(2)).execute(Matchers.<Action<JestResult>>any()); <START> <END> }</code><technical_language>verify call Elastic sends data is contains results inputs. In end, important action of class, tested</technical_language>

Target:
public void sendMessageToElastic() throws Exception { when(mockClient.execute(Matchers.isA(IndicesExists.class))).thenReturn(jestResultFalse); when(mockClient.execute(Matchers.isA(PutMapping.class))).thenReturn(jestResultTrue); when(mockClient.execute(Matchers.isA(Index.class))).thenReturn(jestResultTrue); writer.start(); writer.doWrite(server, query, ImmutableList.of(result)); writer.stop(); Mockito.verify(mockClient, times(4)).execute(Matchers.<Action<JestResult>>any()); }
Source:
<code>public static void getModel(String projectId, String computeRegion, String modelId) <START> throws IOException { <END> try (AutoMlClient client = AutoMlClient.create()) { ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId); Model model = client.getModel(modelFullId); System.out.format("Model name: %s%n", model.getName()); System.out.format( "Model Id: %s\n", model.getName().split("/")[model.getName().split("/").length - 1]); System.out.format("Model display name: %s%n", model.getDisplayName()); System.out.format("Dataset Id: %s%n", model.getDatasetId()); System.out.println("Tables Model Metadata: "); System.out.format( "\tTraining budget: %s%n", model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()); System.out.format( "\tTraining cost: %s%n", model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); String createTime = dateFormat.format(new java.util.Date(model.getCreateTime().getSeconds() * 1000)); System.out.format("Model create time: %s%n", createTime); System.out.format("Model deployment state: %s%n", model.getDeploymentState()); for (TablesModelColumnInfo info : model.getTablesModelMetadata().getTablesModelColumnInfoList()) { System.out.format( "Column: %s - Importance: %.2f%n", info.getColumnDisplayName(), info.getFeatureImportance()); } } }</code><technical_language>this include more specific exceptions beside IOException, io.grpc. StatusRuntimeException, io.grpc.StatusException, com.google.protobuf.InvalidProtocolBufferException users diagnose on</technical_language>

Target:
public static void getModel(String projectId, String computeRegion, String modelId) throws IOException, StatusRuntimeException { try (AutoMlClient client = AutoMlClient.create()) { ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId); Model model = client.getModel(modelFullId); System.out.format("Model name: %s%n", model.getName()); System.out.format( "Model Id: %s\n", model.getName().split("/")[model.getName().split("/").length - 1]); System.out.format("Model display name: %s%n", model.getDisplayName()); System.out.format("Dataset Id: %s%n", model.getDatasetId()); System.out.println("Tables Model Metadata: "); System.out.format( "\tTraining budget: %s%n", model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()); System.out.format( "\tTraining cost: %s%n", model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); String createTime = dateFormat.format(new java.util.Date(model.getCreateTime().getSeconds() * 1000)); System.out.format("Model create time: %s%n", createTime); System.out.format("Model deployment state: %s%n", model.getDeploymentState()); for (TablesModelColumnInfo info : model.getTablesModelMetadata().getTablesModelColumnInfoList()) { System.out.format( "Column: %s - Importance: %.2f%n", info.getColumnDisplayName(), info.getFeatureImportance()); } } }
Source:
<code>public static String extractTelecom(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7Parser201305.ExtractTelecom method..."); String telecom = null; if (CollectionUtils.isNotEmpty(params.getPatientTelecom()) && params.getPatientTelecom().get(0) != null) { PRPAMT201306UV02PatientTelecom patientTelecom = params.getPatientTelecom().get(0); if (CollectionUtils.isNotEmpty(patientTelecom.getValue()) && patientTelecom.getValue().get(0) != null) { TELExplicit telecomValue = patientTelecom.getValue().get(0); LOG.info("Found patientTelecom in query parameters = " + telecomValue.getValue()); telecom = telecomValue.getValue(); <START> if (telecom != null && !telecom.startsWith("tel:")) { <END> telecom = null; LOG.info("Found patientTelecom in query parameters is not in the correct uri format"); } } else { LOG.info("message does not contain a patientTelecom"); } } else { LOG.info("message does not contain a patientTelecom"); } LOG.trace("Exiting HL7Parser201305.ExtractTelecom method..."); return telecom; }</code><technical_language>Suggest replacing null check NullChecker.notNullish(telecom)</technical_language>

Target:
public static String extractTelecom(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7Parser201305.ExtractTelecom method..."); String telecom = null; if (CollectionUtils.isNotEmpty(params.getPatientTelecom()) && params.getPatientTelecom().get(0) != null) { PRPAMT201306UV02PatientTelecom patientTelecom = params.getPatientTelecom().get(0); if (CollectionUtils.isNotEmpty(patientTelecom.getValue()) && patientTelecom.getValue().get(0) != null) { TELExplicit telecomValue = patientTelecom.getValue().get(0); LOG.info("Found patientTelecom in query parameters = " + telecomValue.getValue()); telecom = telecomValue.getValue(); if (!StringUtils.startsWith(telecom, "tel:")) { telecom = null; LOG.info("Found patientTelecom in query parameters is not in the correct uri format"); } } else { LOG.info("message does not contain a patientTelecom"); } } else { LOG.info("message does not contain a patientTelecom"); } LOG.trace("Exiting HL7Parser201305.ExtractTelecom method..."); return telecom; }
Source:
<code>public static void setUp() throws IOException, TimeoutException, InterruptedException { createFileHandler(FILE_HANDLER_ADDRESS, "tests_hal1.log"); <START> administration.reloadIfRequired(); <END> createFileHandler(FILE_HANDLER_TB_REMOVED_ADDRESS, "tests_hal2.log"); administration.reloadIfRequired(); }</code><technical_language>consecutive reloads necessary reload end sufficient</technical_language>

Target:
public static void setUp() throws IOException, TimeoutException, InterruptedException { createFileHandler(FILE_HANDLER_ADDRESS, "tests_hal1.log"); createFileHandler(FILE_HANDLER_TB_REMOVED_ADDRESS, "tests_hal2.log"); administration.reloadIfRequired(); }
Source:
<code>public Response doImport(Action action) { validateParameters(action, "storageDomain.id|name"); ImportRepoImageParameters importParameters = new ImportRepoImageParameters(); importParameters.setSourceRepoImageId(id); importParameters.setSourceStorageDomainId(getStorageDomainId()); importParameters.setStoragePoolId(getDataCenterId(getStorageDomainId(action))); importParameters.setStorageDomainId(getStorageDomainId(action)); if (action.isSetImportAsTemplate()) { if (action.isImportAsTemplate()) { validateParameters(action, "cluster.id|name"); importParameters.setClusterId(getClusterId(action)); if (action.isSetTemplate() && action.getTemplate().isSetName()) { importParameters.setTemplateName(action.getTemplate().getName()); } } importParameters.setImportAsTemplate(action.isImportAsTemplate()); } if (action.isSetDisk()) { if (action.getDisk().isSetAlias()) { importParameters.setDiskAlias(action.getDisk().getAlias()); } <START> if (action.getDisk().isSetName()) { <END> importParameters.setDiskAlias(action.getDisk().getName()); } } return doAction(VdcActionType.ImportRepoImage, importParameters, action); }</code><technical_language>if "name" "alias" set, alias effect, no</technical_language>

Target:
public Response doImport(Action action) { validateParameters(action, "storageDomain.id|name"); ImportRepoImageParameters importParameters = new ImportRepoImageParameters(); importParameters.setSourceRepoImageId(id); importParameters.setSourceStorageDomainId(getStorageDomainId()); importParameters.setStoragePoolId(getDataCenterId(getStorageDomainId(action))); importParameters.setStorageDomainId(getStorageDomainId(action)); if (action.isSetImportAsTemplate()) { if (action.isImportAsTemplate()) { validateParameters(action, "cluster.id|name"); importParameters.setClusterId(getClusterId(action)); if (action.isSetTemplate() && action.getTemplate().isSetName()) { importParameters.setTemplateName(action.getTemplate().getName()); } } importParameters.setImportAsTemplate(action.isImportAsTemplate()); } if (action.isSetDisk()) { if (action.getDisk().isSetName()) { importParameters.setDiskAlias(action.getDisk().getName()); } if (action.getDisk().isSetAlias()) { importParameters.setDiskAlias(action.getDisk().getAlias()); } } return doAction(VdcActionType.ImportRepoImage, importParameters, action); }
Source:
<code><START> default void checkCanCreateViewWithSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) <END> { denyCreateViewWithSelect(tableName.toString()); }</code><technical_language>@deprecated {@link #checkCanCreateViewWithSelectFromColumns} instead</technical_language>

Target:
default void checkCanCreateViewWithSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) { checkCanCreateViewWithSelectFromColumns(transactionHandle, identity, tableName, emptySet()); }
Source:
<code>public void testLogMessage() throws IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Method m = ReflectionUtils.getStaticTestMethod(Logger.class, "getLogMessage", String.class, String.class, ADALError.class); <START> String msg = (String)m.invoke(null, "a", "b", ADALError.AUTH_FAILED); <END> assertEquals("Empty message is expected", ADALError.AUTH_FAILED.name()+":a b", msg); msg = (String)m.invoke(null, "a", null, ADALError.AUTH_FAILED); assertEquals("Empty message is expected", ADALError.AUTH_FAILED.name()+":a", msg); }</code><technical_language>I curious. a b here</technical_language>

Target:
public void testLogMessage() throws IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Method m = ReflectionUtils.getStaticTestMethod(Logger.class, "getLogMessage", String.class, String.class, ADALError.class); String msg = (String)m.invoke(null, "logMsg", "logAdditionalMsg", ADALError.AUTH_FAILED); assertEquals("Empty message is expected", ADALError.AUTH_FAILED.name()+":logMsg logAdditionalMsg", msg); msg = (String)m.invoke(null, "logMsg", null, ADALError.AUTH_FAILED); assertEquals("Empty message is expected", ADALError.AUTH_FAILED.name()+":logMsg", msg); }