auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String getTooltip(MergeMode mode) { String tooltip; switch (mode) { case LEFT_TO_RIGHT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.right.tooltip"); break; case RIGHT_TO_LEFT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.left.tooltip"); break; case ACCEPT: tooltip = EMFCompareDiagramEditMessages.getString("accept.change.tooltip"); break; case REJECT: tooltip = EMFCompareDiagramEditMessages.getString("reject.change.tooltip"); break; default: <START> throw new IllegalStateException(); <END> } return tooltip; }</code><technical_language>state of this class invalid, parameter. relevant exception in a case is IllegalArgumentException</technical_language>

Target:
public String getTooltip(MergeMode mode) throws IllegalArgumentException { String tooltip; switch (mode) { case LEFT_TO_RIGHT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.right.tooltip"); break; case RIGHT_TO_LEFT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.left.tooltip"); break; case ACCEPT: tooltip = EMFCompareDiagramEditMessages.getString("accept.change.tooltip"); break; case REJECT: tooltip = EMFCompareDiagramEditMessages.getString("reject.change.tooltip"); break; default: throw new IllegalArgumentException(); } return tooltip; }
Source:
<code>private Credentials getUserCredentials(HttpServletRequest request) { String header = request.getHeader(SSOUtils.HEADER_AUTHORIZATION).substring("Basic".length()); Credentials credentials = null; if (StringUtils.isNotEmpty(header)) { String[] creds = new String( Base64.decodeBase64(request.getHeader(SSOUtils.HEADER_AUTHORIZATION).substring("Basic".length())), Charset.forName("UTF-8") ).split(":", 2); <START> credentials = translateUser(creds[0], creds[1]); <END> } return credentials; }</code><technical_language>please check creds.length() is 2 access, do allow exception in this case</technical_language>

Target:
private Credentials getUserCredentials(HttpServletRequest request) { String header = request.getHeader(SSOUtils.HEADER_AUTHORIZATION); Credentials credentials = null; if (StringUtils.isNotEmpty(header)) { String[] creds = new String( Base64.decodeBase64(header.substring("Basic".length())), Charset.forName("UTF-8") ).split(":", 2); if (creds.length == 2) { credentials = translateUser(creds[0], creds[1]); } } return credentials; }
Source:
<code>public static MetricKey<ASTAnyTypeDeclaration> of(final Metric<ASTAnyTypeDeclaration> metric, final String name) { return new MetricKey<ASTAnyTypeDeclaration>() { @Override public String name() { return name; } @Override public Metric<ASTAnyTypeDeclaration> getCalculator() { return metric; } @Override public boolean supports(ASTAnyTypeDeclaration node) { return metric.supports(node); } @Override public boolean equals(Object obj) { <START> return obj == this; <END> } @Override public int hashCode() { return (metric != null ? metric.hashCode() * 31 : 0) + (name != null ? name.hashCode() : 0); } }; }</code><technical_language>Is this correct? potentially create another key instance name+metric. This method returns a new instance, this fail: Metric metric = new CycloClassMetric(); String name = "Cyclo"; assert JavaClassMetricKey.of(metric, name) .equals(JavaClassMetricKey.of(metric, name));</technical_language>

Target:
public static MetricKey<ASTAnyTypeDeclaration> of(final Metric<ASTAnyTypeDeclaration> metric, final String name) { return new MetricKey<ASTAnyTypeDeclaration>() { @Override public String name() { return name; } @Override public Metric<ASTAnyTypeDeclaration> getCalculator() { return metric; } @Override public boolean supports(ASTAnyTypeDeclaration node) { return metric.supports(node); } @Override public boolean equals(Object obj) { return obj != null && getClass() == obj.getClass() && Objects.equals(name(), getClass().cast(obj).name()) && Objects.equals(getCalculator(), getClass().cast(obj).getCalculator()); } @Override public int hashCode() { return (metric != null ? metric.hashCode() * 31 : 0) + (name != null ? name.hashCode() : 0); } }; }
Source:
<code>public void testSetVisibleSizeAndRefresh() { uiModel.setVisibleSizeAndRefresh(0, 0); <START> verify(delegate).setVisibleSizeAndRefresh(eq(0), eq(0)); <END> }</code><technical_language>IMO values, e.g. 0 1 sure, for example, "delegated" method is simply parameter twice..</technical_language>

Target:
public void testSetVisibleSizeAndRefresh() { uiModel.setVisibleSizeAndRefresh(0, 1); verify(delegate).setVisibleSizeAndRefresh(eq(0), eq(1)); }
Source:
<code>public void testReadViaFluentAPI() { FooBarPGType result = (FooBarPGType) handle.createQuery("SELECT get_foo_bar(1)") <START> .map(new PGObjectColumnMapper()) <END> .findOnly(); assertThat(result).isEqualTo(new FooBarPGType(1, "foo1", "bar1")); }</code><technical_language>if mapTo(FooBarPGType.class) instead of cast. I column mapper needs a column mapper factory for that</technical_language>

Target:
public void testReadViaFluentAPI() { FooBarPGType result = handle.createQuery("SELECT get_foo_bar(1)") .mapTo(FooBarPGType.class) .findOnly(); assertThat(result).isEqualTo(new FooBarPGType(1, "foo1", "bar1")); }
Source:
<code><START> public static URI toURI(IPath path) throws CoreException { <END> if (path.isUNC()) { IRemoteServicesManager manager = RemoteCorePlugin.getService(IRemoteServicesManager.class); String[] parts = path.segment(0).split(":"); IRemoteConnectionType services = null; String connName = null; if (parts.length == 2) { services = manager.getConnectionType(parts[0]); connName = parts[1]; } else if (parts.length == 1) { String id = Preferences.getString(IRemotePreferenceConstants.PREF_REMOTE_SERVICES_ID); if (id != null) { services = manager.getConnectionType(id); } connName = parts[0]; } IRemoteConnection conn = null; if (services != null) { conn = services.getConnection(connName); } else if (connName != null) { for (IRemoteConnectionType s : manager.getAllConnectionTypes()) { if (s != null) { conn = s.getConnection(connName); if (conn != null) { break; } } } } if (conn != null) { String scheme = conn.getConnectionType().getScheme(); String filePath = path.removeFirstSegments(1).makeAbsolute().toString(); try { return new URI(scheme, connName, filePath, null, null); } catch (URISyntaxException e) { } } } return null; }</code><technical_language>I reason throw CoreException here</technical_language>

Target:
public static URI toURI(IPath path) { if (path.isUNC()) { IRemoteServicesManager manager = RemoteCorePlugin.getService(IRemoteServicesManager.class); String[] parts = path.segment(0).split(":"); IRemoteConnectionType services = null; String connName = null; if (parts.length == 2) { services = manager.getConnectionType(parts[0]); connName = parts[1]; } else if (parts.length == 1) { String id = Preferences.getString(IRemotePreferenceConstants.PREF_REMOTE_SERVICES_ID); if (id != null) { services = manager.getConnectionType(id); } connName = parts[0]; } IRemoteConnection conn = null; if (services != null) { conn = services.getConnection(connName); } else if (connName != null) { for (IRemoteConnectionType s : manager.getAllConnectionTypes()) { if (s != null) { conn = s.getConnection(connName); if (conn != null) { break; } } } } if (conn != null) { String scheme = conn.getConnectionType().getScheme(); String filePath = path.removeFirstSegments(1).makeAbsolute().toString(); try { return new URI(scheme, connName, filePath, null, null); } catch (URISyntaxException e) { } } } return null; }
Source:
<code><START> private Iterable<ITask> getTasksAssosciatedWithReviewTask(ITask reviewTask) { <END> String lookupUrl = reviewTask.getUrl(); String taskUrl = "http://someurl"; AbstractRepositoryConnector repository = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl); String taskId = repository.getTaskIdFromTaskUrl(taskUrl); String repositoryUrl = repository.getRepositoryUrlFromTaskUrl(taskUrl); ITask assosciatedTask = taskList.getTask(repositoryUrl, taskId); if (assosciatedTask == null) { return Collections.emptyList(); } return ImmutableSet.of(assosciatedTask); }</code><technical_language>task</technical_language>

Target:
private ITask getTasksAssosciatedWithReviewTask(ITask reviewTask) { String lookupUrl = reviewTask.getUrl(); String taskUrl = "http://someurl"; AbstractRepositoryConnector repository = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl); String taskId = repository.getTaskIdFromTaskUrl(taskUrl); String repositoryUrl = repository.getRepositoryUrlFromTaskUrl(taskUrl); ITask assosciatedTask = taskList.getTask(repositoryUrl, taskId); return assosciatedTask; }
Source:
<code>static ConnectionSettingsFilter optional(final String... settingNames) { return (ConnectionSettings inputSettings) -> { ConnectionSettings outputSettings = inputSettings.clone(); for (final String settingName : settingNames) { <START> if (outputSettings.hasSetting(settingName)) { <END> outputSettings.removeSetting(settingName); } } return outputSettings; }; }</code><technical_language>call remove here? Do need check for existing in map removing</technical_language>

Target:
static ConnectionSettingsFilter optional(final String... settingNames) { return (ConnectionSettings inputSettings) -> { ConnectionSettings outputSettings = inputSettings.clone(); for (final String settingName : settingNames) { outputSettings.removeSetting(settingName); } return outputSettings; }; }
Source:
<code>public Page getOutput() { if (!finishing) { return null; } QueryInfo queryInfo = queryPerformanceFetcher.getQueryInfo(operatorContext.getDriverContext().getTaskId().getQueryId()); checkState(queryInfo.getOutputStage().isPresent(), "Output stage is missing"); checkState(queryInfo.getOutputStage().get().getSubStages().size() == 1, "Expected one sub stage of explain node"); if (!hasFinalStageInfo(queryInfo.getOutputStage().get())) { return null; } <START> String plan = textDistributedPlan(queryInfo.getOutputStage().get().getSubStages().get(0), metadata, statsCalculator, costCalculator, operatorContext.getSession(), verbose); <END> BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1); VARCHAR.writeString(builder, plan); outputConsumed = true; return new Page(builder.build()); }</code><technical_language>Is a case stages? for some DDL</technical_language>

Target:
public Page getOutput() { if (!finishing) { return null; } QueryInfo queryInfo = queryPerformanceFetcher.getQueryInfo(operatorContext.getDriverContext().getTaskId().getQueryId()); checkState(queryInfo.getOutputStage().isPresent(), "Output stage is missing"); checkState(queryInfo.getOutputStage().get().getSubStages().size() == 1, "Expected one sub stage of explain node"); if (!hasFinalStageInfo(queryInfo.getOutputStage().get())) { return null; } String plan = textDistributedPlan(queryInfo.getOutputStage().get().getSubStages().get(0), functionRegistry, statsCalculator, costCalculator, operatorContext.getSession(), verbose); BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1); VARCHAR.writeString(builder, plan); outputConsumed = true; return new Page(builder.build()); }
Source:
<code>protected void setUpTestData(SystemTestData testData) throws Exception { testData.setUpSecurity(); System.setProperty("DefaultCatalogStore", "org.geoserver.csw.store.simple.GeoServerSimpleCatalogStore"); <START> System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true"); <END> File root = testData.getDataDirectoryRoot(); File catalog = new File(root, "catalog"); File records = new File("./src/test/resources/org/geoserver/csw/records"); FileUtils.copyDirectory(records, catalog); }</code><technical_language>set in base test class, cleaned end of test</technical_language>

Target:
protected void setUpTestData(SystemTestData testData) throws Exception { testData.setUpSecurity(); System.setProperty("DefaultCatalogStore", "org.geoserver.csw.store.simple.GeoServerSimpleCatalogStore"); File root = testData.getDataDirectoryRoot(); File catalog = new File(root, "catalog"); File records = new File("./src/test/resources/org/geoserver/csw/records"); FileUtils.copyDirectory(records, catalog); }
Source:
<code>public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); for(String currentSubscription: subscriptions) { if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) { if (currentSubscription.length() < 10) <START> throw new IllegalArgumentException("GUS subjectId is incorrect."); <END> } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.EMAIL.getName())) { if (!currentSubscription.matches("[a-zA-Z0-9\\-\\_\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}")) throw new IllegalArgumentException("Email Address is incorrect."); } } if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } }</code><technical_language>this is subjectId chatter group id right</technical_language>

Target:
public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); if(subscriptions == null) return; for(String currentSubscription: subscriptions) { if (this.getNotifierName().equals(AlertService.SupportedNotifier.GUS.getName())) { if (currentSubscription.length() < 10) throw new IllegalArgumentException("GUS subjectId is incorrect."); } else if (this.getNotifierName().equals(AlertService.SupportedNotifier.EMAIL.getName())) { if (!currentSubscription.matches("[a-zA-Z0-9\\-\\_\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}")) throw new IllegalArgumentException("Email Address is incorrect."); } } if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } }
Source:
<code>private String etag(SourceFile srcmd, SourceFile navmd) { byte[] b = new byte[Constants.OBJECT_ID_LENGTH]; Hasher h = Hashing.sha1().newHasher(); h.putInt(ETAG_GEN); <START> h.putBytes(renderer.getTemplateHash(SOY_FILE).asBytes()); <END> if (navmd != null) { navmd.id.copyRawTo(b, 0); h.putBytes(b); } srcmd.id.copyRawTo(b, 0); h.putBytes(b); return h.hash().toString(); }</code><technical_language>Optional: renderer.getTemplateHash(SOY_FILE).writeBytesTo(b, 0, b.length); h.putBytes(b);</technical_language>

Target:
private String etag(SourceFile srcmd, SourceFile navmd) { byte[] b = new byte[Constants.OBJECT_ID_LENGTH]; Hasher h = Hashing.sha1().newHasher(); h.putInt(ETAG_GEN); renderer.getTemplateHash(SOY_FILE).writeBytesTo(b, 0, b.length); h.putBytes(b); if (navmd != null) { navmd.id.copyRawTo(b, 0); h.putBytes(b); } srcmd.id.copyRawTo(b, 0); h.putBytes(b); return h.hash().toString(); }
Source:
<code>public FrameIterator frameIterator() { <START> return new FrameIterator(startFrame); <END> }</code><technical_language>Is remove FrameIterator also? ClientMessage iterator itself. drawback is iterators I need anyway</technical_language>

Target:
public ForwardFrameIterator frameIterator() { return new ForwardFrameIterator(startFrame); }
Source:
<code>public void changeStatusToClosed(long issueID, int resolution, String bugNote, Date closeDate) { IIssue issue = getIssue(issueID); int oldStatus = issue.getStatusValue(); IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName("mantis_bug_table"); valueSet.addInsertValue("status", Integer.toString(ITSEnum.CLOSED_STATUS)); valueSet.addInsertValue("resolution", Integer.toString(resolution)); valueSet.addEqualCondition("id", Long.toString(issueID)); String query = valueSet.getUpdateQuery(); getControl().execute(query); <START> HistoryObject history = new HistoryObject( <END> issue.getIssueID(), issue.getIssueType(), HistoryObject.TYPE_STATUS, String.valueOf(oldStatus), String.valueOf(ITSEnum.CLOSED_STATUS), System.currentTimeMillis()); history.save(); if (bugNote != null && !bugNote.equals("")) { issue.addIssueNote(bugNote); updateBugNote(issue); } }</code><technical_language>statusHistory</technical_language>

Target:
public void changeStatusToClosed(long issueID, int resolution, String bugNote, Date closeDate) { IIssue issue = getIssue(issueID); int oldStatus = issue.getStatusValue(); IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName("mantis_bug_table"); valueSet.addInsertValue("status", Integer.toString(ITSEnum.CLOSED_STATUS)); valueSet.addInsertValue("resolution", Integer.toString(resolution)); valueSet.addEqualCondition("id", Long.toString(issueID)); String query = valueSet.getUpdateQuery(); getControl().execute(query); HistoryObject statusHistory = new HistoryObject( issue.getIssueID(), issue.getIssueType(), HistoryObject.TYPE_STATUS, String.valueOf(oldStatus), String.valueOf(ITSEnum.CLOSED_STATUS), System.currentTimeMillis()); statusHistory.save(); if (bugNote != null && !bugNote.equals("")) { issue.addIssueNote(bugNote); updateBugNote(issue); } }
Source:
<code>public void logFrame(StompFrame request, boolean in) { <START> if (ActiveMQStompProtocolLogger.LOGGER.isDebugEnabled()) { <END> StringBuilder message = new StringBuilder() .append("STOMP(") .append(getRemoteAddress()) .append(", ") .append(this.getID()) .append("):"); if (in) { message.append(" IN << "); } else { message.append("OUT >> "); } message.append(request); ActiveMQStompProtocolLogger.LOGGER.debug(message.toString()); } }</code><technical_language>for direct calls debug trace, I individualized Logger. Logger logger = Logger.getLogger(StompConnection.class) Logger for INFO messages ID... of debugging this, difficult do individual logs. wait ask debug loggers users difficult</technical_language>

Target:
public void logFrame(StompFrame request, boolean in) { if (logger.isDebugEnabled()) { StringBuilder message = new StringBuilder() .append("STOMP(") .append(getRemoteAddress()) .append(", ") .append(this.getID()) .append("):"); if (in) { message.append(" IN << "); } else { message.append("OUT >> "); } message.append(request); logger.debug(message.toString()); } }
Source:
<code>public Iterable<NetworkClient.InFlightRequest> clearAll(String node) { Deque<NetworkClient.InFlightRequest> reqs = requests.get(node); if (reqs == null) { return Collections.emptyList(); } else { final Deque<NetworkClient.InFlightRequest> clearedRequests = requests.remove(node); <START> inFlightRequestCount.addAndGet(-clearedRequests.size()); <END> return () -> clearedRequests.descendingIterator(); } }</code><technical_language>is reason for this change</technical_language>

Target:
public Iterable<NetworkClient.InFlightRequest> clearAll(String node) { Deque<NetworkClient.InFlightRequest> reqs = requests.get(node); if (reqs == null) { return Collections.emptyList(); } else { final Deque<NetworkClient.InFlightRequest> clearedRequests = requests.remove(node); inFlightRequestCount.getAndAdd(-clearedRequests.size()); return () -> clearedRequests.descendingIterator(); } }
Source:
<code>public void testWhereWithOrForLargeValueList() throws Exception { Cache cache = POLICY.cache(); QueryService queryService = cache.getQueryService(); Query query = queryService.newQuery("select state as state from /zips"); SelectResults results = (SelectResults) query.execute(); <START> Set<String> stateList = new LinkedHashSet<>(); <END> Iterator iterator = results.iterator(); while (iterator.hasNext()) { StructImpl struct = (StructImpl) iterator.next(); stateList.add((String) struct.get("state")); } List<String> statePredicateList = new ArrayList<>(); stateList.forEach(state -> statePredicateList.add("state = '" + state + "'")); String stateListPredicate = String.join(" OR ", statePredicateList); String stateListStr = "'" + String.join("', '", stateList) + "'"; String queryToBeExecuted = "SELECT state as state FROM view WHERE " + stateListPredicate; String expectedQuery = "SELECT state AS state FROM /zips WHERE state " + "IN SET(" + stateListStr + ")"; calciteAssert() .query(queryToBeExecuted) .returnsCount(149) .queryContains( GeodeAssertions.query(expectedQuery)); }</code><technical_language>[SelectResults](<LINK_0> implements Collection convert stream: java Set<String> states = results.stream() .map(s -> (String) s.get("state")) .collect(Collectors.toCollection(LinkedHashSet::new))</technical_language>

Target:
public void testWhereWithOrForLargeValueList() throws Exception { Cache cache = POLICY.cache(); QueryService queryService = cache.getQueryService(); Query query = queryService.newQuery("select state as state from /zips"); SelectResults results = (SelectResults) query.execute(); Set<String> stateList = (Set<String>) results.stream().map(s -> { StructImpl struct = (StructImpl) s; return struct.get("state"); }) .collect(Collectors.toCollection(LinkedHashSet::new)); String stateListPredicate = stateList.stream() .map(s -> String.format(Locale.ROOT, "state = '%s'", s)) .collect(Collectors.joining(" OR ")); String stateListStr = "'" + String.join("', '", stateList) + "'"; String queryToBeExecuted = "SELECT state as state FROM view WHERE " + stateListPredicate; String expectedQuery = "SELECT state AS state FROM /zips WHERE state " + "IN SET(" + stateListStr + ")"; calciteAssert() .query(queryToBeExecuted) .returnsCount(149) .queryContains( GeodeAssertions.query(expectedQuery)); }
Source:
<code>public ElideDynamicEntityCompiler buildElideDynamicEntityCompiler(ElideConfigProperties settings) { ElideDynamicEntityCompiler compiler = null; if (settings.getDynamicConfig().isEnabled()) { compiler = new ElideDynamicEntityCompiler(settings.getDynamicConfig().getPath()); try { compiler.compile(settings.getDynamicConfig().getPath()); } catch (Exception e) { <START> e.printStackTrace(); <END> } } return compiler; }</code><technical_language>print stack traces - log exception. - catch Exception. propagate</technical_language>

Target:
public ElideDynamicEntityCompiler buildElideDynamicEntityCompiler(ElideConfigProperties settings) throws Exception { ElideDynamicEntityCompiler compiler = null; if (settings.getDynamicConfig().isEnabled()) { compiler = new ElideDynamicEntityCompiler(settings.getDynamicConfig().getPath()); } return compiler; }
Source:
<code>public boolean shouldUseNativeIO(VM vm, DiskImage diskImage, VmDevice device) { StorageType storageType = diskImage.getStorageTypes().get(0); String diskType = getDiskType(vm, diskImage, device); boolean isNativeIO = !"file".equals(diskType) || (storageType == StorageType.GLUSTERFS && FeatureSupported.useNativeIOForGluster(vm.getCompatibilityVersion())); if ("file".equals(diskType) && device.getSnapshotId() != null) { isNativeIO = false; } <START> return isNativeIO; <END> }</code><technical_language>duplicating code a checking "file".equals(...) multiple times in consecutive lines, other cases. additional method (public boolean isSnapshot(...)), simply: boolean isSnapshot = device.getSnapshotId() != null; return isSnapshot ? false : !"file".equals(diskType) || (storageType == StorageType.GLUSTERFS && ...) Otherwise, keeping track of</technical_language>

Target:
public boolean shouldUseNativeIO(VM vm, DiskImage diskImage, VmDevice device) { StorageType storageType = diskImage.getStorageTypes().get(0); String diskType = getDiskType(vm, diskImage, device); boolean isNativeIO = !"file".equals(diskType) || (storageType == StorageType.GLUSTERFS && FeatureSupported.useNativeIOForGluster(vm.getCompatibilityVersion())); if (device.getSnapshotId() != null) { isNativeIO = false; } return isNativeIO; }
Source:
<code>public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { <START> LOGGER.debug("Skipping because the requestBody is null or empty", this); <END> return new ArrayList<>(0); } final String username = requestBody.getFirst(USERNAME); final String password = requestBody.getFirst(PASSWORD); if (username == null || password == null) { LOGGER.debug("Invalid payload. 'username' and 'password' form fields are required."); return new ArrayList<>(0); } final Credential c = new UsernamePasswordCredential(username, password); return CollectionUtils.wrap(c); }</code><technical_language>Consider getClass().getSimpleName() instead of this</technical_language>

Target:
public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { LOGGER.debug("Skipping because the requestBody is null or empty", getClass().getSimpleName()); return new ArrayList<>(0); } final String username = requestBody.getFirst(USERNAME); final String password = requestBody.getFirst(PASSWORD); if (username == null || password == null) { LOGGER.debug("Invalid payload. 'username' and 'password' form fields are required."); return new ArrayList<>(0); } final Credential c = new UsernamePasswordCredential(username, password); return CollectionUtils.wrap(c); }
Source:
<code><START> public @Nullable String getSelectedItemName() { <END> String value = null; RegistrationOption selected = (RegistrationOption)getSelectedItem(); if (selected != null) { value = selected.getName(); } return value; }</code><technical_language>This a pattern follow in project. @Nullable a line this one</technical_language>

Target:
public String getSelectedItemName() { String value = null; final RegistrationOption selected = (RegistrationOption) getSelectedItem(); if (selected != null) { value = selected.getName(); } return value; }
Source:
<code>public static void error (int code, Throwable throwable) { <START> error (code, throwable, " [Application is out of heap memory]"); <END> }</code><technical_language>change message here. apply calls error(int, Throwable). Instead, error() String arg</technical_language>

Target:
public static void error (int code, Throwable throwable) { error (code, throwable, null); }
Source:
<code>public boolean receive(CarbonMessage carbonMessage, CarbonCallback carbonCallback) { if (microservicesRegistry == null) { microservicesRegistry = <START> DataHolder.getInstance().getMicroservicesRegistries().get(carbonMessage.getProperty("ID")); <END> } Request request = new Request(carbonMessage); request.setSessionManager(microservicesRegistry.getSessionManager()); Response response = new Response(carbonCallback, request); try { dispatchMethod(request, response); } catch (HandlerException e) { handleHandlerException(e, carbonCallback); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof HandlerException) { handleHandlerException((HandlerException) targetException, carbonCallback); } else { handleThrowable(targetException, carbonCallback, request); } } catch (InterceptorException e) { log.warn("Interceptors threw an exception", e); carbonCallback.done(HttpUtil .createTextResponse(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), HttpUtil.EMPTY_BODY)); } catch (Throwable t) { handleThrowable(t, carbonCallback, request); } finally { carbonMessage.release(); } return true; }</code><technical_language>This "channel.id" "ID"</technical_language>

Target:
public boolean receive(CarbonMessage carbonMessage, CarbonCallback carbonCallback) { currentMicroservicesRegistry = DataHolder.getInstance().getMicroservicesRegistries() .get(carbonMessage.getProperty(MSF4JConstants.CHANNEL_ID)); Request request = new Request(carbonMessage); request.setSessionManager(currentMicroservicesRegistry.getSessionManager()); Response response = new Response(carbonCallback, request); try { dispatchMethod(request, response); } catch (HandlerException e) { handleHandlerException(e, carbonCallback); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof HandlerException) { handleHandlerException((HandlerException) targetException, carbonCallback); } else { handleThrowable(targetException, carbonCallback, request); } } catch (InterceptorException e) { log.warn("Interceptors threw an exception", e); carbonCallback.done(HttpUtil .createTextResponse(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), HttpUtil.EMPTY_BODY)); } catch (Throwable t) { handleThrowable(t, carbonCallback, request); } finally { carbonMessage.release(); } return true; }
Source:
<code>public Scheduler cleanupJobScheduler() throws SchedulerException { <START> return this.constructScheduler(AbstractSchedulingConfigBuilder.newBuilder() <END> .withJobClass(ResponseDataCleanupJob.class).withThreadCountKey(KEY_CLEANUP_JOB_THREAD_COUNT) .withCronExpressionKey(KEY_CLEANUP_JOB_CRON_EXPRESSION).withJobStoreDbUrl(this.getDatabaseUrl()) .withJobStoreDbUsername(this.databaseUsername).withJobStoreDbPassword(this.databasePassword) .withJobStoreDbDriver(this.databaseDriver).build()); }</code><technical_language>Extract building of Scheduler variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides scheduler</technical_language>

Target:
public Scheduler cleanupJobScheduler() throws SchedulerException { AbstractSchedulingConfigBuilder abstractSchedulingConfig = AbstractSchedulingConfigBuilder.newBuilder() .withJobClass(ResponseDataCleanupJob.class).withThreadCountKey(KEY_CLEANUP_JOB_THREAD_COUNT) .withCronExpressionKey(KEY_CLEANUP_JOB_CRON_EXPRESSION).withJobStoreDbUrl(this.getDatabaseUrl()) .withJobStoreDbUsername(this.databaseUsername).withJobStoreDbPassword(this.databasePassword) .withJobStoreDbDriver(this.databaseDriver).build(); return this.constructScheduler(abstractSchedulingConfig); }
Source:
<code>private void doInit(InstallerDao installerDao, Installer i) throws InstallerException { String installerKey = InstallerFqn.of(i).toKey(); try { Version.validate(i.getVersion()); <START> } catch (IllegalArgumentException e) { <END> throw new InstallerException(format("Illegal version format '%s' for installer '%s'", i.getVersion(), installerKey)); } try { installerDao.create(new InstallerImpl(i)); LOG.info(format("Installer '%s' added to the registry.", installerKey)); } catch (InstallerAlreadyExistsException e) { LOG.info(format("Installer '%s' already exists in the registry.", installerKey)); } }</code><technical_language>Mb throw InstallerException Version.validate? Also, create VersionValidator class avoid static calls</technical_language>

Target:
private void doInit(InstallerDao installerDao, Installer i) throws InstallerException { String installerKey = InstallerFqn.of(i).toKey(); installerValidator.validate(i); try { installerDao.create(new InstallerImpl(i)); LOG.info(format("Installer '%s' added to the registry.", installerKey)); } catch (InstallerAlreadyExistsException e) { LOG.info(format("Installer '%s' already exists in the registry.", installerKey)); } }
Source:
<code>public void stop() { <START> refreshThread.stop = true; <END> try { refreshThread.join(); } catch (InterruptedException e) { log.warn("error stopping refresh thread", e); } openIndex.close(); closedIndex.close(); }</code><technical_language>refreshThread.halt();</technical_language>

Target:
public void stop() { refreshThread.halt(); openIndex.close(); closedIndex.close(); }
Source:
<code>private BucketDataNode createBucketDataNode(long groupId, Block block, int position) { <START> long valueOnlyRawHash = TypeUtils.hashPosition(type, block, position); <END> long valueRawHash = getHashPosition(groupId, valueOnlyRawHash); int bucketId = (int) (valueRawHash & mask); int nodePointer; int probeCount = 1; int originalBucketId = bucketId; boolean isEmpty; while (true) { nodePointer = buckets.get(bucketId); if (nodePointer == EMPTY_BUCKET) { isEmpty = true; break; } int valuePosition = valuePositions.get(nodePointer); if (groupAndValueMatches(groupId, block, position, nodePointer, valuePosition)) { isEmpty = false; break; } int probe = nextProbe(probeCount); bucketId = nextBucketId(originalBucketId, mask, probe); probeCount++; } int nodePointerToUse = isEmpty ? nextNodePointer : nodePointer; return new BucketDataNode(bucketId, createValueNode(nodePointerToUse), valueRawHash, valueOnlyRawHash, nodePointerToUse, isEmpty); }</code><technical_language>call this valueHash valueAndGroupHash for below</technical_language>

Target:
private BucketDataNode createBucketDataNode(long groupId, Block block, int position) { long valueHash = murmurHash3(TypeUtils.hashPosition(type, block, position)); long groupIdHash = murmurHash3(groupId); long valueAndGroupHash = combineGroupAndValueHash(groupIdHash, valueHash); int bucketId = (int) (valueAndGroupHash & mask); int nodePointer; int probeCount = 1; int originalBucketId = bucketId; while (true) { nodePointer = buckets.get(bucketId); if (nodePointer == EMPTY_BUCKET) { return new BucketDataNode(bucketId, new ValueNode(nextNodePointer), valueHash, valueAndGroupHash, nextNodePointer, true); } else if (groupAndValueMatches(groupId, block, position, nodePointer, valuePositions.get(nodePointer))) { return new BucketDataNode(bucketId, new ValueNode(nodePointer), valueHash, valueAndGroupHash, nodePointer, false); } else { int probe = nextProbe(probeCount); bucketId = nextBucketId(originalBucketId, mask, probe); probeCount++; } } }
Source:
<code><START> public static long encryptedToRaw(final byte[] key, final byte[] encryptedMotionData) <END> throws NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException { final byte[] nonce = Arrays.copyOfRange(encryptedMotionData, 0, 8); final byte[] encryptedRawMotion = Arrays.copyOfRange(encryptedMotionData, 8, encryptedMotionData.length); final byte[] decryptedRawMotion = counterModeDecrypt(key, nonce, encryptedRawMotion); final LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream(new ByteArrayInputStream(decryptedRawMotion)); long motionAmplitude = littleEndianDataInputStream.readInt(); if(motionAmplitude < 0){ motionAmplitude += 0xFFFFFFFF; } littleEndianDataInputStream.close(); return motionAmplitude; }</code><technical_language>Suggestion: catch errors function throw a single invalidException. is nicer for code calling function. lets change encryption/decryption in a single place</technical_language>

Target:
public static long encryptedToRaw(final byte[] key, final byte[] encryptedMotionData) throws IllegalArgumentException { final byte[] nonce = Arrays.copyOfRange(encryptedMotionData, 0, 8); final byte[] encryptedRawMotion = Arrays.copyOfRange(encryptedMotionData, 8, encryptedMotionData.length); final byte[] decryptedRawMotion = counterModeDecrypt(key, nonce, encryptedRawMotion); final LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream(new ByteArrayInputStream(decryptedRawMotion)); Exception exception = null; long motionAmplitude = -1; try { motionAmplitude = UnsignedInts.toLong(littleEndianDataInputStream.readInt()); }catch (IOException ioe){ exception = ioe; }finally { try { littleEndianDataInputStream.close(); }catch (IOException ioe){ exception = ioe; } } if(exception != null){ throw new IllegalArgumentException(exception); } return motionAmplitude; }
Source:
<code>private boolean elementsContains(Object someObject) { if (elements == null) { return false; } if (elementsAndAdapters == null) { elementsAndAdapters = new ArrayList(elements.length); for (Object element : elements) { elementsAndAdapters.add(element); if (affectedObjectsClass != null && !affectedObjectsClass.isInstance(element)) { Object adapter = Adapters.adapt(element, affectedObjectsClass); if (adapter != null) { elementsAndAdapters.add(adapter); } } } } for (Object <START> elementsAndAdapter : <END> elementsAndAdapters) { if (elementsAndAdapter.equals(someObject)) { return true; } } return false; }</code><technical_language>rename elementOrAdapter</technical_language>

Target:
private boolean elementsContains(Object someObject) { if (elements == null) { return false; } if (elementsAndAdapters == null) { elementsAndAdapters = new ArrayList(elements.length); for (Object element : elements) { elementsAndAdapters.add(element); if (affectedObjectsClass != null && !affectedObjectsClass.isInstance(element)) { Object adapter = Adapters.adapt(element, affectedObjectsClass); if (adapter != null) { elementsAndAdapters.add(adapter); } } } } for (Object elementOrAdapter : elementsAndAdapters) { if (elementOrAdapter.equals(someObject)) { return true; } } return false; }
Source:
<code>private void disconnectStorageByType(StorageType storageType, List<StorageServerConnections> connections) { <START> List<String> heIds = <END> storageDomainDao.getHostedEngineStorageDomainIds().stream() .map(storageDomainDao::get) .map(StorageDomain::getStorageStaticData) .map(StorageDomainStatic::getStorage) .collect(Collectors.toList()); connections = connections.stream() .filter(c -> heIds.stream().noneMatch(heId -> c.getId().equals(heId))) .collect(Collectors.toList()); storageHelperDirector.getItem(storageType).prepareDisconnectHostFromStoragePoolServers(getParameters(), connections); VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.DisconnectStorageServer, new StorageServerConnectionManagementVDSParameters(getVds().getId(), getStoragePool().getId(), storageType, connections)); setSucceeded(vdsReturnValue.getSucceeded()); if (!vdsReturnValue.getSucceeded()) { storageHelperDirector.getItem(storageType) .isConnectSucceeded((HashMap<String, String>) vdsReturnValue.getReturnValue(), connections); } }</code><technical_language>a Set</technical_language>

Target:
private void disconnectStorageByType(StorageType storageType, List<StorageServerConnections> connections) { Set<String> heIds = storageDomainDao.getHostedEngineStorageDomainIds().stream() .map(storageDomainDao::get) .map(StorageDomain::getStorageStaticData) .map(StorageDomainStatic::getStorage) .collect(Collectors.toSet()); connections = connections.stream() .filter(c -> !heIds.contains(c.getId())) .collect(Collectors.toList()); storageHelperDirector.getItem(storageType).prepareDisconnectHostFromStoragePoolServers(getParameters(), connections); VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.DisconnectStorageServer, new StorageServerConnectionManagementVDSParameters(getVds().getId(), getStoragePool().getId(), storageType, connections)); setSucceeded(vdsReturnValue.getSucceeded()); if (!vdsReturnValue.getSucceeded()) { storageHelperDirector.getItem(storageType) .isConnectSucceeded((HashMap<String, String>) vdsReturnValue.getReturnValue(), connections); } }
Source:
<code>public void consistentFullBatchesGravitatesTowardsMinimumPause() { for (int i = 0; i < 20; i++) { delay.getNextPause(SUCCESS_TOO_SLOW); } <START> assertThat(delay.getNextPause(SUCCESS_TOO_FAST)).isGreaterThanOrEqualTo((long) (MIN_PAUSE_MILLIS * 1.05)); <END> }</code><technical_language>If understanding this correctly this read suggestion assertThat(delay.getNextPause(SUCCESS_TOO_SLOW)).isLessThanOrEqualTo((long) (MIN_PAUSE_MILLIS * 1.05));</technical_language>

Target:
public void consistentFullBatchesGravitatesTowardsMinimumPause() { sweepTwentyIterationsWithResult(SUCCESS_TOO_SLOW); assertThat(delay.getNextPause(SUCCESS_TOO_SLOW)).isGreaterThanOrEqualTo((long) (MIN_PAUSE_MILLIS * 1.05)); }
Source:
<code>public void deleteSecretCodeSnippets() throws InterruptedException { SecretClient secretClient = getSecretClient(); Poller<DeletedSecret, Void> poller = secretClient.beginDeleteSecret("secretName"); poller.getObserver() .map(pollResponse -> { System.out.println("Current status: " + pollResponse.getStatus()); if (pollResponse.getStatus() != PollResponse.OperationStatus.NOT_STARTED) { DeletedSecret deletedSecret = pollResponse.getValue(); System.out.println("Deleted date: " + deletedSecret.getDeletedOn().toString()); <START> System.out.printf("Deleted Secret's Recovery id: %s%n", deletedSecret.getRecoveryId()); <END> } return pollResponse.getStatus(); }) .blockLast(); System.out.println("Final status: " + poller.getStatus()); System.out.println("Final response: " + poller.getLastPollResponse()); END: com.azure.security.keyvault.secretclient.deleteSecret#string }</code><technical_language>Sync client, a sync poller coming in. This create conflicts. showcasing reactor style sync side, feel right</technical_language>

Target:
public void deleteSecretCodeSnippets() throws InterruptedException { SecretClient secretClient = getSecretClient(); Poller<DeletedSecret, Void> deletedSecretPoller = secretClient.beginDeleteSecret("secretName"); while (deletedSecretPoller.getStatus() != PollResponse.OperationStatus.IN_PROGRESS && !deletedSecretPoller.isComplete()) { System.out.println(deletedSecretPoller.getStatus().toString()); Thread.sleep(2000); } DeletedSecret deletedSecret = deletedSecretPoller.getLastPollResponse().getValue(); System.out.println("Deleted Date: " + deletedSecret.getDeletedOn().toString()); System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); while (!deletedSecretPoller.isComplete()) { System.out.println(deletedSecretPoller.getStatus().toString()); Thread.sleep(2000); } END: com.azure.security.keyvault.secretclient.deleteSecret#string }
Source:
<code>Builder() { this.startTime = 0; this.druidCluster = null; this.databaseRuleManager = null; this.segmentReplicantLookup = null; this.dataSources = Sets.newHashSet(); this.availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator())); this.loadManagementPeons = Maps.newHashMap(); this.replicationManager = null; this.emitter = null; this.stats = new MasterStats(); <START> this.dynamicConfigs = new DynamicConfigs(null,null,null,null); <END> this.balancerReferenceTimestamp = null; }</code><technical_language>a default constructor reasonable default values</technical_language>

Target:
Builder() { this.startTime = 0; this.druidCluster = null; this.databaseRuleManager = null; this.segmentReplicantLookup = null; this.dataSources = Sets.newHashSet(); this.availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator())); this.loadManagementPeons = Maps.newHashMap(); this.replicationManager = null; this.emitter = null; this.stats = new MasterStats(); this.masterSegmentSettings = new MasterSegmentSettings.Builder().build(); this.balancerReferenceTimestamp = null; }
Source:
<code>public String[] getCountries() { <START> return new String[]{"DZ"}; <END> }</code><technical_language>other countries added here</technical_language>

Target:
public String[] getCountries() { return new String[]{"", "AE", "BH", "EG", "IN", "IQ", "JQ", "JO", "KW", "LB", "LY", "MA", "OM", "QA", "SA", "SD", "SY", "TN", "YE"}; }
Source:
<code><START> public void testDataSyncToPassiveCustomGets() throws Exception { <END> System.setProperty(ClusterTierActiveEntity.SYNC_DATA_GETS_PROP, "2"); try { prepareAndRunActiveEntityForPassiveSync((activeEntity, concurrencyKey) -> { @SuppressWarnings("unchecked") PassiveSynchronizationChannel<EhcacheEntityMessage> syncChannel = mock(PassiveSynchronizationChannel.class); activeEntity.synchronizeKeyToPassive(syncChannel, concurrencyKey); verify(syncChannel, atLeast(1)).synchronizeToPassive(any(EhcacheDataSyncMessage.class)); }); } finally { System.clearProperty(ClusterTierActiveEntity.SYNC_DATA_GETS_PROP); } }</code><technical_language>More invoke context issues again</technical_language>

Target:
public void testDataSyncToPassiveCustomGets() throws Exception { System.setProperty(ClusterTierActiveEntity.SYNC_DATA_GETS_PROP, "2"); try { prepareAndRunActiveEntityForPassiveSync((activeEntity, concurrencyKey) -> { @SuppressWarnings("unchecked") PassiveSynchronizationChannel<EhcacheEntityMessage> syncChannel = mock(PassiveSynchronizationChannel.class); activeEntity.synchronizeKeyToPassive(syncChannel, concurrencyKey); verify(syncChannel, atLeast(2)).synchronizeToPassive(any(EhcacheDataSyncMessage.class)); }); } finally { System.clearProperty(ClusterTierActiveEntity.SYNC_DATA_GETS_PROP); } }
Source:
<code>private void volumeType_SelectedItemChanged() { if (getVolumeType().getSelectedItem() == null || getDataCenter().getSelectedItem() == null) { return; } VolumeType volumeType = (VolumeType) getVolumeType().getSelectedItem(); <START> StorageType storageType = ((StorageDomain) getStorageDomain().getSelectedItem()).getStorageType(); <END> updateVolumeFormat(volumeType, storageType); updateShareable(volumeType, storageType); }</code><technical_language>please check getStorageDomain().getSelectedItem() for nullity - iirc, null in case storage domain is in maintenance</technical_language>

Target:
private void volumeType_SelectedItemChanged() { if (getVolumeType().getSelectedItem() == null || getDataCenter().getSelectedItem() == null || getStorageDomain().getSelectedItem() == null) { return; } VolumeType volumeType = (VolumeType) getVolumeType().getSelectedItem(); StorageType storageType = ((StorageDomain) getStorageDomain().getSelectedItem()).getStorageType(); updateVolumeFormat(volumeType, storageType); updateShareable(volumeType, storageType); }
Source:
<code>private TestSplit(int id, OptionalInt bucketNumber) { super( "path", 0, 100, 100, ImmutableList.of(new InternalHiveBlock(0, 100, ImmutableList.of())), bucketNumber, bucketNumber, true, false, false, <START> new HiveSplitPartitionInfo(properties("id", String.valueOf(id)), ImmutableList.of(), "partition-name", ImmutableMap.of(), Optional.empty())); <END> }</code><technical_language>nit: store this a static final field TEST_PARTITION_INFO int this class</technical_language>

Target:
private TestSplit(int id, OptionalInt bucketNumber) { super( "path", 0, 100, 100, ImmutableList.of(new InternalHiveBlock(100, ImmutableList.of())), bucketNumber, bucketNumber, true, false, false, new HiveSplitPartitionInfo(properties("id", String.valueOf(id)), new Path("path").toUri(), ImmutableList.of(), "partition-name", ImmutableMap.of(), Optional.empty())); }
Source:
<code>public OutputStream createOutput(final String blobName) throws IOException { deleteBlob(blobName); final PipedInputStream in = new PipedInputStream(); final Thread transport = new Thread(new Runnable(){ public void run(){ blobStore.swift().getObject(buildKey(blobName)).uploadObject(in); } }); transport.start(); return new PipedOutputStream(in) { @Override public void close() throws IOException { try { super.close(); transport.join(); } catch(InterruptedException e) { <START> throw new IOException("Swift input/output shenanigans."); <END> } } }; }</code><technical_language>throw new IOException("Swift input/output shenanigans", e); e information cause. If IOException do log here</technical_language>

Target:
public OutputStream createOutput(final String blobName) throws IOException { deleteBlob(blobName); final PipedInputStream in = new PipedInputStream(); final Thread transport = new Thread(new Runnable(){ public void run(){ blobStore.swift().getObject(buildKey(blobName)).uploadObject(in); } }); transport.start(); return new PipedOutputStream(in) { @Override public void close() throws IOException { try { super.close(); transport.join(); } catch(InterruptedException e) { throw new IOException("Swift input/output shenanigans.", e); } } }; }