auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void deleteContainer(ContainerDTO container, Consumer<ContainerDTO> onSuccess, Consumer<Exception> onError) { try { <START> this.fileUtilities.remove(container.getPath()); <END> } catch (IOException e) { LOGGER.error("Cannot delete container (" + container.getPath() + ")! Exception: " + e.toString()); onError.accept(e); } final String engineId = container.getEngine().toLowerCase(); final List<ShortcutCategoryDTO> categories = this.libraryManager.fetchShortcuts(); categories.stream().flatMap(shortcutCategory -> shortcutCategory.getShortcuts().stream()) .forEach(shortcut -> { final InteractiveScriptSession interactiveScriptSession = this.scriptInterpreter .createInteractiveSession(); interactiveScriptSession.eval("include(\"engines." + engineId + ".shortcuts.reader\");", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final org.graalvm.polyglot.Value shortcutReader = (org.graalvm.polyglot.Value) output; shortcutReader.invokeMember("of", shortcut); final String containerName = shortcutReader.invokeMember("container").as(String.class); if (containerName.equals(container.getName())) { this.shortcutManager.deleteShortcut(shortcut); } }, onError), onError); }); onSuccess.accept(container); }</code><technical_language>I agree</technical_language>

Target:
public void deleteContainer(ContainerDTO container, Consumer<ContainerDTO> onSuccess, Consumer<Exception> onError) { try { final File containerFile = new File(container.getPath()); FileUtils.deleteDirectory(containerFile); } catch (IOException e) { LOGGER.error("Cannot delete container (" + container.getPath() + ")! Exception: " + e.toString()); onError.accept(e); } final String engineId = container.getEngine().toLowerCase(); final List<ShortcutCategoryDTO> categories = this.libraryManager.fetchShortcuts(); categories.stream().flatMap(shortcutCategory -> shortcutCategory.getShortcuts().stream()) .forEach(shortcut -> { final InteractiveScriptSession interactiveScriptSession = this.scriptInterpreter .createInteractiveSession(); interactiveScriptSession.eval("include(\"engines." + engineId + ".shortcuts.reader\");", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final org.graalvm.polyglot.Value shortcutReader = (org.graalvm.polyglot.Value) output; shortcutReader.invokeMember("of", shortcut); final String containerName = shortcutReader.invokeMember("container").as(String.class); if (containerName.equals(container.getName())) { this.shortcutManager.deleteShortcut(shortcut); } }, onError), onError); }); onSuccess.accept(container); }
Source:
<code>private FileDownloader createCustomFileDownloader() { if (customClass == null) { <START> throw new CustomFilePersistenceException("CustomFilePersistence class cannot be accessed, is it public?"); <END> } try { ClassLoader systemClassLoader = getClass().getClassLoader(); Class<?> customFilePersistenceClass = systemClassLoader.loadClass(customClass.getCanonicalName()); return (FileDownloader) customFilePersistenceClass.newInstance(); } catch (IllegalAccessException e) { throw new CustomFilePersistenceException(customClass, "Class cannot be accessed, is it public?", e); } catch (ClassNotFoundException e) { throw new CustomFilePersistenceException(customClass, "Class does not exist", e); } catch (InstantiationException e) { throw new CustomFilePersistenceException(customClass, "Class cannot be instantiated", e); } }</code><technical_language>CustomFileDownloader</technical_language>

Target:
private FileDownloader createCustomFileDownloader() { if (customClass == null) { throw new CustomFileDownloaderException("CustomFileDownloader class cannot be accessed, is it public?"); } try { ClassLoader systemClassLoader = getClass().getClassLoader(); Class<?> customFileDownloaderClass = systemClassLoader.loadClass(customClass.getCanonicalName()); return (FileDownloader) customFileDownloaderClass.newInstance(); } catch (IllegalAccessException e) { throw new CustomFileDownloaderException(customClass, "Class cannot be accessed, is it public?", e); } catch (ClassNotFoundException e) { throw new CustomFileDownloaderException(customClass, "Class does not exist", e); } catch (InstantiationException e) { throw new CustomFileDownloaderException(customClass, "Class cannot be instantiated", e); } }
Source:
<code><START> public void testGetDependentFields() throws Exception <END> { List<String> dependentFields = fac.getDependentFields(); assertEquals(1, dependentFields.size()); assertEquals("field", dependentFields.get(0)); }</code><technical_language>I teamcity is complaining Exception is thrown</technical_language>

Target:
public void testGetDependentFields() { List<String> dependentFields = fac.getDependentFields(); assertEquals(1, dependentFields.size()); assertEquals("field", dependentFields.get(0)); }
Source:
<code>public void addPrivateDnsRoutes() { if (DBG) { Log.d(TAG, "addPrivateDnsRoutes for " + this + "(" + mInterfaceName + ") - mPrivateDnsRouteSet = "+mPrivateDnsRouteSet); } if (mInterfaceName != null && !mPrivateDnsRouteSet) { for (String addrString : getNameServers()) { if (addrString != null) { try { InetAddress inetAddress = InetAddress.getByName(addrString); if (DBG) Log.d(TAG, " adding " + addrString); NetworkUtils.addHostRoute(mInterfaceName, inetAddress); } catch (UnknownHostException e) { if (DBG) Log.d(TAG, " DNS address " + addrString + " : Exception " + e); } } } <START> mPrivateDnsRouteSet = true; <END> } }</code><technical_language>Instead of setting mPrivateDnsRouteSet if operation failed, do: try { InetAddress inetAddress = InetAddress.getByName(addrString); if (DBG) Log.d(TAG, " adding " + addrString); if (NetworkUtils.addHostRoute(mInterfaceName, inetAddress) == 0) { mPrivateDnsRouteSet = true; } }</technical_language>

Target:
public void addPrivateDnsRoutes() { if (DBG) { Log.d(TAG, "addPrivateDnsRoutes for " + this + "(" + mInterfaceName + ") - mPrivateDnsRouteSet = "+mPrivateDnsRouteSet); } if (mInterfaceName != null && !mPrivateDnsRouteSet) { for (String addrString : getNameServers()) { if (addrString != null) { try { InetAddress inetAddress = InetAddress.getByName(addrString); if (DBG) Log.d(TAG, " adding " + addrString); if (NetworkUtils.addHostRoute(mInterfaceName, inetAddress, null)) { mPrivateDnsRouteSet = true; } } catch (UnknownHostException e) { if (DBG) Log.d(TAG, " DNS address " + addrString + " : Exception " + e); } } } } }
Source:
<code>public void loadParameterValues(String fileName) throws NoScriptDefinitionSelectedException, ScriptDefinitionNotMatched, UnsupportedOperationException { ScriptDefinitionWrapper scriptDefinition = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException("No Configuration Selected")); <START> List<Map<ActionParameter, String>> list = scriptGenFileHandler.getParameterValues(preferenceSupplier.scriptGeneratorDataFileFolder() + fileName + ".json", <END> preferenceSupplier.scriptGeneratorScriptDefinitionFolders() + scriptDefinition.getName() + ".py"); scriptGeneratorTable.addMultipleActions(list); currentlyLoadedDataFileContent = scriptGenFileHandler.getCurrentlyLoadedDataFileContent(); }</code><technical_language>json place pull out a constant</technical_language>

Target:
public void loadParameterValues(String fileName) throws NoScriptDefinitionSelectedException, ScriptDefinitionNotMatched, UnsupportedOperationException { ScriptDefinitionWrapper scriptDefinition = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException("No Configuration Selected")); List<Map<ActionParameter, String>> list = scriptGenFileHandler.getParameterValues(fileName, preferenceSupplier.scriptGeneratorScriptDefinitionFolders() + scriptDefinition.getName() + PYTHON_EXT); scriptGeneratorTable.addMultipleActions(list); }
Source:
<code>public void processWatermark(Watermark mark) throws Exception { super.processWatermark(mark); <START> this.currentWatermark = mark.getTimestamp(); <END> ((FlinkKafkaShuffleProducer) userFunction).invoke(mark); }</code><technical_language>this is done super. Afaik need change in StreamSink</technical_language>

Target:
public void processWatermark(Watermark mark) throws Exception { super.processWatermark(mark); ((FlinkKafkaShuffleProducer) userFunction).invoke(mark); }
Source:
<code>public Object getSource(Cell cell, Predicate<Object> predicate) { for (Cell c = cell; c != null; c = c.getParent()) { Collection<Mapper<?, ?>> mappers = myIndex.getMappers(c); if (!mappers.isEmpty()) { Mapper<?, ?> mapper = mappers.iterator().next(); Object source = doGetSource(mapper, cell); <START> Object res = source == null ? mapper.getSource() : source; <END> if (predicate.apply(res)) return res; } } return null; }</code><technical_language>If 'res' 'result', put this name directly</technical_language>

Target:
public Object getSource(Cell cell, Predicate<Object> predicate) { for (Cell c = cell; c != null; c = c.getParent()) { Collection<Mapper<?, ?>> mappers = myIndex.getMappers(c); if (!mappers.isEmpty()) { Mapper<?, ?> mapper = mappers.iterator().next(); Object source = doGetSource(mapper, cell); Object result = source == null ? mapper.getSource() : source; if (predicate.apply(result)) return result; } } return null; }
Source:
<code>private void addStatusFilter(DiscoverQuery query) { try { if (!authorizeService.isAdmin(context) && (authorizeService.isCommunityAdmin(context) || authorizeService.isCollectionAdmin(context))) { query.addFilterQueries(searcher.createLocationQueryForAdministrableItems(context)); } } catch (SQLException ex) { <START> log.error(ex); <END> } }</code><technical_language>While I realize this code new in this PR, this opportunity improve log statement here? I this like: log.error("Error authorization rights of current user", ex);</technical_language>

Target:
private void addStatusFilter(DiscoverQuery query) { try { if (!authorizeService.isAdmin(context) && (authorizeService.isCommunityAdmin(context) || authorizeService.isCollectionAdmin(context))) { query.addFilterQueries(searcher.createLocationQueryForAdministrableItems(context)); } } catch (SQLException ex) { log.error("Error looking up authorization rights of current user", ex); } }
Source:
<code>public TransactionTemplate( GraphDatabaseService gds, Monitor monitor, int retries, long backoff, Predicate<Throwable> retryPredicate ) <START> { <END> this.gds = gds; this.monitor = monitor; this.retries = retries; this.backoff = backoff; this.retryPredicate = retryPredicate; }</code><technical_language>This check invariants</technical_language>

Target:
public TransactionTemplate( GraphDatabaseService gds, Monitor monitor, int retries, long backoff, Predicate<Throwable> retryPredicate ) { Objects.requireNonNull( gds ); Objects.requireNonNull( monitor ); if ( retries < 0 ) { throw new IllegalArgumentException( "Number of retries must be greater than or equal to 0" ); } if ( backoff < 0 ) { throw new IllegalArgumentException( "Backoff time must be a positive number" ); } Objects.requireNonNull( retryPredicate ); this.gds = gds; this.monitor = monitor; this.retries = retries; this.backoff = backoff; this.retryPredicate = retryPredicate; }
Source:
<code>private DatanodeInfo chooseDatanode(final Router router, final String path, final HttpOpParam.Op op, final long openOffset, final String excludeDatanodes) throws IOException { DatanodeInfo[] dns = null; HashSet<Node> excludes = new HashSet<Node>(); if (op == GetOpParam.Op.OPEN || op == PostOpParam.Op.APPEND || op == GetOpParam.Op.GETFILECHECKSUM) { final ClientProtocol cp = getRpcClientProtocol(); final HdfsFileStatus status = cp.getFileInfo(path); if (status == null) { throw new FileNotFoundException("File " + path + " not found."); } final long len = status.getLen(); if (op == GetOpParam.Op.OPEN) { if (openOffset < 0L || (openOffset >= len && len > 0)) { throw new IOException("Offset=" + openOffset + " out of the range [0, " + len + "); " + op + ", path=" + path); } } if (len > 0) { final long offset = op == GetOpParam.Op.OPEN ? openOffset : len - 1; final LocatedBlocks locations = cp.getBlockLocations(path, offset, 1); final int count = locations.locatedBlockCount(); if (count > 0) { if (excludeDatanodes != null) { Collection<String> collection = getTrimmedStringCollection(excludeDatanodes); dns = getDatanodeReport(router); for (DatanodeInfo dn : dns) { if (collection.contains(dn.getName())) { excludes.add(dn); } } } LocatedBlock location0 = locations.get(0); return bestNode(location0.getLocations(), excludes); } } } <START> if (dns == null) { <END> dns = getDatanodeReport(router); } return getRandomDatanode(dns, excludes); }</code><technical_language>nit: this is true</technical_language>

Target:
private DatanodeInfo chooseDatanode(final Router router, final String path, final HttpOpParam.Op op, final long openOffset, final String excludeDatanodes) throws IOException { final RouterRpcServer rpcServer = getRPCServer(router); DatanodeInfo[] dns = null; try { dns = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); } catch (IOException e) { LOG.error("Cannot get the datanodes from the RPC server", e); } HashSet<Node> excludes = new HashSet<Node>(); if (excludeDatanodes != null) { Collection<String> collection = getTrimmedStringCollection(excludeDatanodes); for (DatanodeInfo dn : dns) { if (collection.contains(dn.getName())) { excludes.add(dn); } } } if (op == GetOpParam.Op.OPEN || op == PostOpParam.Op.APPEND || op == GetOpParam.Op.GETFILECHECKSUM) { final ClientProtocol cp = getRpcClientProtocol(); final HdfsFileStatus status = cp.getFileInfo(path); if (status == null) { throw new FileNotFoundException("File " + path + " not found."); } final long len = status.getLen(); if (op == GetOpParam.Op.OPEN) { if (openOffset < 0L || (openOffset >= len && len > 0)) { throw new IOException("Offset=" + openOffset + " out of the range [0, " + len + "); " + op + ", path=" + path); } } if (len > 0) { final long offset = op == GetOpParam.Op.OPEN ? openOffset : len - 1; final LocatedBlocks locations = cp.getBlockLocations(path, offset, 1); final int count = locations.locatedBlockCount(); if (count > 0) { LocatedBlock location0 = locations.get(0); return bestNode(location0.getLocations(), excludes); } } } return getRandomDatanode(dns, excludes); }
Source:
<code><START> void check(CommandEnvelope envelope) { <END> if (didHandleSinceLastSnapshot(envelope)) { final Command command = envelope.getOuterObject(); throw DuplicateCommandException.forAggregate(command); } }</code><technical_language>delegate check RecentHistory class instead? I history answer question: "Did events originated this command?" If yes, guard fire exception</technical_language>

Target:
void check(CommandEnvelope envelope) { if (didHandleSinceLastSnapshot(envelope)) { final Command command = envelope.getOuterObject(); throw DuplicateCommandException.of(command); } }
Source:
<code>public void shouldMigrate() throws Exception { List<LogEntry> entries = new ArrayList<>(); for (int i = 0; i < 1000; i++) { entries.add(LogEntryGen.doCreateEntry("mydoc", "evt" + i, "cat" + i % 2)); } jpaBackend.addLogEntries(entries); txFeature.nextTransaction(); List<Long> res = (List<Long>) jpaBackend.nativeQuery("select count(*) from LogEntry", 1, 20); final long nbEntriesToMigrate = res.get(0).longValue(); Assert.assertEquals(1000, nbEntriesToMigrate); <START> AuditBackend backend = (AuditBackend) Framework.getService(AuditLogger.class); <END> Assert.assertNotNull(backend); Assert.assertTrue(backend instanceof ESAuditBackend); ESAuditBackend esBackend = (ESAuditBackend) backend; esBackend.migrate(100); Framework.getLocalService(WorkManager.class).awaitCompletion(1, TimeUnit.MINUTES); LogEntryGen.flushAndSync(); String singleQuery = " {\"query\": {\n" + " \"bool\" : {\n" + " \"must\" : {\n" + " \"match\" : {\n" + " \"docUUID\" : {\n" + " \"query\" : \"mydoc\",\n" + " \"type\" : \"boolean\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }} \n" + ""; List<LogEntry> migratedEntries = (List<LogEntry>) backend.nativeQuery(singleQuery, 0, 1001); Assert.assertEquals(1000, migratedEntries.size()); }</code><technical_language>Is normal ask for AuditLogger cast AuditBackend</technical_language>

Target:
public void shouldMigrate() throws Exception { List<LogEntry> entries = new ArrayList<>(); for (int i = 0; i < 1000; i++) { entries.add(LogEntryGen.doCreateEntry("mydoc", "evt" + i, "cat" + i % 2)); } jpaBackend.addLogEntries(entries); txFeature.nextTransaction(); List<Long> res = (List<Long>) jpaBackend.nativeQuery("select count(*) from LogEntry", 1, 20); final long nbEntriesToMigrate = res.get(0).longValue(); Assert.assertEquals(1000, nbEntriesToMigrate); AuditBackend backend = Framework.getService(AuditBackend.class); Assert.assertNotNull(backend); Assert.assertTrue(backend instanceof ESAuditBackend); ESAuditBackend esBackend = (ESAuditBackend) backend; esBackend.migrate(100); Framework.getLocalService(WorkManager.class).awaitCompletion(1, TimeUnit.MINUTES); LogEntryGen.flushAndSync(); String singleQuery = " {\"query\": {\n" + " \"bool\" : {\n" + " \"must\" : {\n" + " \"match\" : {\n" + " \"docUUID\" : {\n" + " \"query\" : \"mydoc\",\n" + " \"type\" : \"boolean\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }} \n" + ""; List<LogEntry> migratedEntries = (List<LogEntry>) backend.nativeQuery(singleQuery, 0, 1001); Assert.assertEquals(1000, migratedEntries.size()); }
Source:
<code><START> public final InetSocketAddress getSource() { <END> return endpoint.getAddress(); }</code><technical_language>do need this method final rest</technical_language>

Target:
public InetSocketAddress getSource() { return endpoint.getAddress(); }
Source:
<code>private double calculateDistance(double lat1, double lng1, double lat2, double lng2, Metric metric) { if ((lat1 == lat2) && (lng1 == lng2)) { return 0; } else { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lng2 - lng1); <START> lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); <END> double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); double dist = R * c; if (Metrics.MILES.equals(metric)) { dist = dist * KM_TO_MILES; } else if (Metrics.NEUTRAL.equals(metric)) { dist = dist * KM_TO_NEUTRAL; } return dist; } }</code><technical_language>write method params create separate variables instead</technical_language>

Target:
private double calculateDistance(double lat1, double lng1, double lat2, double lng2, Metric metric) { if ((lat1 == lat2) && (lng1 == lng2)) { return 0; } else { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lng2 - lng1); double lat1Radians = Math.toRadians(lat1); double lat2Radians = Math.toRadians(lat2); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1Radians) * Math.cos(lat2Radians); double c = 2 * Math.asin(Math.sqrt(a)); double dist = R * c; if (Metrics.MILES.equals(metric)) { dist = dist * KM_TO_MILES; } else if (Metrics.NEUTRAL.equals(metric)) { dist = dist * KM_TO_NEUTRAL; } return dist; } }
Source:
<code>public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { String clientRegistrationId = this.resolveClientRegistrationId(parameter); if (StringUtils.isEmpty(clientRegistrationId)) { throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. " + "It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or " + "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."); } Authentication principal = SecurityContextHolder.getContext().getAuthentication(); HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient( clientRegistrationId, principal, servletRequest); if (authorizedClient != null) { return authorizedClient; } ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId); if (clientRegistration == null) { return null; } OAuth2AuthorizationContext.Builder contextBuilder = OAuth2AuthorizationContext.forAuthorization(clientRegistration); if (principal != null) { contextBuilder.principal(principal); } else { contextBuilder.principal("anonymousUser"); } OAuth2AuthorizationContext authorizationContext = contextBuilder.build(); <START> authorizedClient = this.authorizedClientProvider.authorize(authorizationContext); <END> HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class); this.authorizedClientRepository.saveAuthorizedClient( authorizedClient, authorizationContext.getPrincipal(), servletRequest, servletResponse); return authorizedClient; }</code><technical_language>How/when is refresh handled</technical_language>

Target:
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { String clientRegistrationId = this.resolveClientRegistrationId(parameter); if (StringUtils.isEmpty(clientRegistrationId)) { throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. " + "It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or " + "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."); } Authentication principal = SecurityContextHolder.getContext().getAuthentication(); if (principal == null) { principal = ANONYMOUS_AUTHENTICATION; } HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class); OAuth2AuthorizeRequest authorizeRequest = new OAuth2AuthorizeRequest( clientRegistrationId, principal, servletRequest, servletResponse); return this.authorizedClientManager.authorize(authorizeRequest); }
Source:
<code>private int getDateTimeStyle() { EEF_DATE_DISPLAY display = this.description.getDisplay(); switch (display.getValue()) { case EEF_DATE_DISPLAY.CALENDAR_VALUE: return SWT.CALENDAR; case EEF_DATE_DISPLAY.DATE_VALUE: return SWT.DATE; case EEF_DATE_DISPLAY.TIME_VALUE: return SWT.TIME; default: <START> return SWT.CALENDAR; <END> } }</code><technical_language>Max 2 returns in a method</technical_language>

Target:
private int getDateTimeStyle() { EEF_DATE_DISPLAY display = this.description.getDisplay(); int style; switch (display.getValue()) { case EEF_DATE_DISPLAY.CALENDAR_VALUE: style = SWT.CALENDAR; break; case EEF_DATE_DISPLAY.DATE_VALUE: style = SWT.DATE; break; case EEF_DATE_DISPLAY.TIME_VALUE: style = SWT.TIME; break; default: style = SWT.CALENDAR; break; } return style; }
Source:
<code>private void displayDetails(String period, String unit, String dataType) throws Exception { <START> System.out.println("***********************************************"); <END> System.out.println("executing for:"); System.out.println(unit + "(" + period + ")"); System.out.println("dataType=" + dataType); System.out.println("***********************************************"); }</code><technical_language>logger</technical_language>

Target:
private void displayDetails(String period, String unit, String dataType) throws Exception { logger.info("***********************************************"); logger.info("executing for:"); logger.info(unit + "(" + period + ")"); logger.info("dataType=" + dataType); logger.info("***********************************************"); }
Source:
<code>public void setFeatureAttributeName(String featureAttributeName) { <START> if (null == featureAttributeName) <END> log.debug("WPS request process error: Feature Attribute Name was null. Can not process without the output column name."); this.featureAttributeName = featureAttributeName; }</code><technical_language>I Sonar flag this for block. This tricky read logic coming a date</technical_language>

Target:
public void setFeatureAttributeName(String featureAttributeName) { if (null == featureAttributeName) { log.debug("WPS request process error: Feature Attribute Name was null. Can not process without the output column name."); } this.featureAttributeName = featureAttributeName; }
Source:
<code>void shouldReturnAllKeys() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); issues.add(builder.setCategory("keyA").build()); issues.add(builder.setCategory("keyB").build()); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); Set<String> str = new HashSet(); str.add("keyA"); str.add("keyB"); Set<String> actualProperty = statistics.getKeys(); <START> assertThat(actualProperty).isEqualTo(str); <END> }</code><technical_language>s.o</technical_language>

Target:
void shouldReturnAllKeys() { Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); issues.add(builder.setCategory("keyA").build()); issues.add(builder.setCategory("keyB").build()); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); Set<String> str = new HashSet(); str.add("keyA"); str.add("keyB"); Set<String> actualProperty = statistics.getKeys(); assertThat(actualProperty).isEqualTo(str); }
Source:
<code>public boolean equals(Object o) { <START> if (o instanceof MappedFieldType == false) { <END> return false; } MappedFieldType fieldType = (MappedFieldType) o; return boost == fieldType.boost && docValues == fieldType.docValues && Objects.equals(name, fieldType.name) && Objects.equals(indexAnalyzer, fieldType.indexAnalyzer) && Objects.equals(searchAnalyzer, fieldType.searchAnalyzer) && Objects.equals(searchQuoteAnalyzer(), fieldType.searchQuoteAnalyzer()) && Objects.equals(eagerGlobalOrdinals, fieldType.eagerGlobalOrdinals) && Objects.equals(similarity, fieldType.similarity) && Objects.equals(meta, fieldType.meta); }</code><technical_language>a fan of if (o == null || getClass() != o.getClass()) for this. equals implementation is ugly, bails early if subtypes line up</technical_language>

Target:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } MappedFieldType fieldType = (MappedFieldType) o; return boost == fieldType.boost && docValues == fieldType.docValues && Objects.equals(name, fieldType.name) && Objects.equals(indexAnalyzer, fieldType.indexAnalyzer) && Objects.equals(searchAnalyzer, fieldType.searchAnalyzer) && Objects.equals(searchQuoteAnalyzer(), fieldType.searchQuoteAnalyzer()) && Objects.equals(eagerGlobalOrdinals, fieldType.eagerGlobalOrdinals) && Objects.equals(similarity, fieldType.similarity) && Objects.equals(meta, fieldType.meta); }
Source:
<code>public void loadModulesIntoClasspath() { Path pluginFolder = FileSystems.getDefault().getPath(ConfigMain.getParameter("pluginFolder")); URLClassLoader sysLoader = null; try { DirectoryStream<Path> stream = Files.newDirectoryStream(pluginFolder, "*.jar"); for (Path f : stream) { File loc = new File(f.toString()); sysLoader = (URLClassLoader) this.getClass().getClassLoader(); ArrayList<URL> urls = new ArrayList<>(Arrays.asList(sysLoader.getURLs())); URL udir = loc.toURI().toURL(); if (!urls.contains(udir)) { Class<URLClassLoader> sysClass = URLClassLoader.class; Method method = sysClass.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, udir); } } } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Do printStackTrace() - logger mechanism</technical_language>

Target:
private void loadModulesIntoClasspath() { Path pluginFolder = FileSystems.getDefault().getPath(ConfigMain.getParameter("pluginFolder")); URLClassLoader sysLoader = null; try { DirectoryStream<Path> stream = Files.newDirectoryStream(pluginFolder, "*.jar"); for (Path f : stream) { File loc = new File(f.toString()); sysLoader = (URLClassLoader) this.getClass().getClassLoader(); ArrayList<URL> urls = new ArrayList<>(Arrays.asList(sysLoader.getURLs())); URL udir = loc.toURI().toURL(); if (!urls.contains(udir)) { Class<URLClassLoader> sysClass = URLClassLoader.class; Method method = sysClass.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, udir); } } } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { logger.error("Classpath could not be accessed", e.getMessage()); } }
Source:
<code>private OpenFoodAPIService getApiServiceForProductType(int productType){ final int OPEN_FOOD_FACT = 5; final int OPEN_BEAUTY_FACTS = 6; final int OPEN_PET_FOOD_FACTS = 7; final int OPEN_PRODUCTS_FACTS = 8; switch (productType){ case OPEN_FOOD_FACT: <START> return new OpenFoodAPIClient(getActivity(), "<LINK_4>").getAPIService(); <END> case OPEN_BEAUTY_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_0>").getAPIService(); case OPEN_PET_FOOD_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_2>").getAPIService(); case OPEN_PRODUCTS_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_1>").getAPIService(); default: return CommonApiManager.getInstance().getOpenFoodApiService(); } }</code><technical_language><LINK_3> work</technical_language>

Target:
private OpenFoodAPIService getApiServiceForProductType(int productType){ final int OPEN_FOOD_FACTS = 5; final int OPEN_BEAUTY_FACTS = 6; final int OPEN_PET_FOOD_FACTS = 7; final int OPEN_PRODUCTS_FACTS = 8; switch (productType){ case OPEN_FOOD_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_3>").getAPIService(); case OPEN_BEAUTY_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_0>").getAPIService(); case OPEN_PET_FOOD_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_2>").getAPIService(); case OPEN_PRODUCTS_FACTS: return new OpenFoodAPIClient(getActivity(), "<LINK_1>").getAPIService(); default: return CommonApiManager.getInstance().getOpenFoodApiService(); } }
Source:
<code>public void verifyHttpsCiphers() throws Exception { brooklynProperties.put(BrooklynWebConfig.HTTPS_REQUIRED, true); brooklynProperties.put(BrooklynWebConfig.TRANSPORT_PROTOCOLS, "XXX"); brooklynProperties.put(BrooklynWebConfig.TRANSPORT_CIPHERS, "XXX"); try { verifyHttpsFromConfig(brooklynProperties); <START> fail("Expected to fail due to to unsupported ciphers during connection negotiation"); <END> } catch (Exception e) { assertTrue(Exceptions.getFirstThrowableOfType(e, SocketException.class) != null, "Expected to fail due to inability to negotiate"); } }</code><technical_language>@neykov tests pass for too. Is stack trace client server side</technical_language>

Target:
public void verifyHttpsCiphers() throws Exception { brooklynProperties.put(BrooklynWebConfig.HTTPS_REQUIRED, true); brooklynProperties.put(BrooklynWebConfig.TRANSPORT_PROTOCOLS, "XXX"); brooklynProperties.put(BrooklynWebConfig.TRANSPORT_CIPHERS, "XXX"); try { verifyHttpsFromConfig(brooklynProperties); fail("Expected to fail due to unsupported ciphers during connection negotiation"); } catch (Exception e) { assertTrue((Exceptions.getFirstThrowableOfType(e, SocketException.class) != null) || (Exceptions.getFirstThrowableOfType(e, SSLHandshakeException.class) != null), "Expected to fail due to inability to negotiate"); } }
Source:
<code>public void init() throws IOException { monitor.init(); boolean storeExists = hasStore(); boolean isDirty; try { needsRebuild = !storeExists; if ( !storeExists ) { monitor.noIndex(); } isDirty = instantiateTree(); } catch ( MetadataMismatchException e ) { isDirty = true; } if ( isDirty ) { monitor.notValidIndex(); dropStrict(); instantiateTree(); } if ( isDirty || !storeExists ) <START> { <END> needsRebuild = true; } }</code><technical_language>|| !storeExists part is covered needsRebuild = !storeExists; up, is not</technical_language>

Target:
public void init() throws IOException { monitor.init(); boolean storeExists = hasStore(); boolean isDirty; try { needsRebuild = !storeExists; if ( !storeExists ) { monitor.noIndex(); } isDirty = instantiateTree(); } catch ( MetadataMismatchException e ) { isDirty = true; } if ( isDirty ) { monitor.notValidIndex(); dropStrict(); instantiateTree(); needsRebuild = true; } }
Source:
<code>private boolean processMail(TaskMailbox mailbox, boolean singleStep) throws Exception { boolean processed = false; if (!mailbox.createBatch()) { <START> return processed; <END> } Optional<Mail> maybeMail; while (isMailboxLoopRunning() && (maybeMail = mailbox.tryTakeFromBatch()).isPresent()) { maybeMail.get().run(); processed = true; if (singleStep) { break; } } if (singleStep) { return processed; } while (isDefaultActionUnavailable() && isMailboxLoopRunning()) { maybeMail = mailbox.tryTake(MIN_PRIORITY); if (!maybeMail.isPresent()) { long start = System.currentTimeMillis(); maybeMail = Optional.of(mailbox.take(MIN_PRIORITY)); idleTime.markEvent(System.currentTimeMillis() - start); } maybeMail.get().run(); processed = true; } return processed; }</code><technical_language>return false here</technical_language>

Target:
private boolean processMail(TaskMailbox mailbox, boolean singleStep) throws Exception { if (!mailbox.createBatch()) { return false; } boolean processed = false; Optional<Mail> maybeMail; while (isMailboxLoopRunning() && (maybeMail = mailbox.tryTakeFromBatch()).isPresent()) { maybeMail.get().run(); processed = true; if (singleStep) { break; } } if (singleStep) { return processed; } while (isDefaultActionUnavailable() && isMailboxLoopRunning()) { maybeMail = mailbox.tryTake(MIN_PRIORITY); if (!maybeMail.isPresent()) { long start = System.currentTimeMillis(); maybeMail = Optional.of(mailbox.take(MIN_PRIORITY)); idleTime.markEvent(System.currentTimeMillis() - start); } maybeMail.get().run(); processed = true; } return processed; }
Source:
<code>Mono<Response<DocumentResultCollection<DetectLanguageResult>>> detectBatchLanguagesWithResponse( List<DetectLanguageInput> textInputs, TextAnalyticsRequestOptions options, Context context) { final LanguageBatchInput languageBatchInput = new LanguageBatchInput().setDocuments(textInputs); return service.languagesWithRestResponseAsync( languageBatchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) <START> .doOnSubscribe(ignoredValue -> logger.info("A batch of language input - {}", languageBatchInput)) <END> .doOnSuccess(response -> logger.info("A batch of detected language output - {}", languageBatchInput)) .doOnError(error -> logger.warning("Failed to detected languages - {}", languageBatchInput)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }</code><technical_language>LanguageBatchInput.toString() like</technical_language>

Target:
Mono<Response<DocumentResultCollection<DetectLanguageResult>>> detectBatchLanguagesWithResponse( List<DetectLanguageInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final LanguageBatchInput languageBatchInput = new LanguageBatchInput() .setDocuments(textInputs.stream().map(detectLanguageInput -> new LanguageInput() .setId(detectLanguageInput.getId()).setText(detectLanguageInput.getText()) .setCountryHint(detectLanguageInput.getCountryHint())).collect(Collectors.toList())); return service.languagesWithRestResponseAsync( languageBatchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of language input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of detected language output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to detected languages - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }
Source:
<code>public CustomColumnNamesWidget(List<String> columnNames) { _innerPanel = new DCPanel(); _innerPanel.setLayout(new VerticalLayout(2)); final JButton addButton = WidgetFactory.createSmallButton(IconUtils.ACTION_ADD_DARK); addButton.addActionListener(e -> addColumnName("", true)); final JButton removeButton = WidgetFactory.createSmallButton(IconUtils.ACTION_REMOVE_DARK); removeButton.addActionListener(e -> { int componentCount = _innerPanel.getComponentCount(); <START> if (componentCount > 0) { <END> removeColumnName(); _innerPanel.updateUI(); } }); final DCPanel buttonPanel = new DCPanel(); buttonPanel.setBorder(new EmptyBorder(0, 4, 0, 0)); buttonPanel.setLayout(new VerticalLayout(2)); buttonPanel.add(addButton); buttonPanel.add(removeButton); _buttons = Arrays.asList(addButton, removeButton); if (columnNames != null) { columnNames.forEach(columnName -> addColumnName(columnName, false)); } _outerPanel = new DCPanel(); _outerPanel.setLayout(new BorderLayout()); _outerPanel.add(_innerPanel, BorderLayout.CENTER); _outerPanel.add(buttonPanel, BorderLayout.EAST); }</code><technical_language>Final (or consider dumping variable completely)</technical_language>

Target:
public CustomColumnNamesWidget(List<String> columnNames) { _innerPanel = new DCPanel(); _innerPanel.setLayout(new VerticalLayout(2)); final JButton addButton = WidgetFactory.createSmallButton(IconUtils.ACTION_ADD_DARK); addButton.addActionListener(e -> addColumnName("", true)); final JButton removeButton = WidgetFactory.createSmallButton(IconUtils.ACTION_REMOVE_DARK); removeButton.addActionListener(e -> { if (_innerPanel.getComponentCount() > 0) { removeColumnName(); _innerPanel.updateUI(); } }); final DCPanel buttonPanel = new DCPanel(); buttonPanel.setBorder(new EmptyBorder(0, 4, 0, 0)); buttonPanel.setLayout(new VerticalLayout(2)); buttonPanel.add(addButton); buttonPanel.add(removeButton); _buttons = Arrays.asList(addButton, removeButton); if (columnNames != null) { columnNames.forEach(columnName -> addColumnName(columnName, false)); } _outerPanel = new DCPanel(); _outerPanel.setLayout(new BorderLayout()); _outerPanel.add(_innerPanel, BorderLayout.CENTER); _outerPanel.add(buttonPanel, BorderLayout.EAST); }
Source:
<code>public void readBadlyDistributedFileTest() throws Exception { HPCCFile file = new HPCCFile(datasets[1], connString , hpccUser, hpccPass); file.setProjectList(""); <START> file.setFileAccessExpirySecs(10); <END> List<HPCCRecord> records = readFile(file, connTO); assertEquals("Not all records loaded",expectedCounts[1], records.size()); }</code><technical_language>values tough predict, configurable? Also, is 10 secs meant ensure time out? If so, close do expiring finishing</technical_language>

Target:
public void readBadlyDistributedFileTest() throws Exception { HPCCFile file = new HPCCFile(datasets[1], connString , hpccUser, hpccPass); file.setProjectList(""); List<HPCCRecord> records = readFile(file, connTO); assertEquals("Not all records loaded",expectedCounts[1], records.size()); }
Source:
<code>private byte[] configurePskCredentials(String identity, byte[] psk, byte[] otherSecret) throws HandshakeException { String virtualHost = null; if (indicatedServerNames == null) { LOGGER.debug("client uses PSK identity [{}]", getPeerAddress(), identity); } else { ServerName serverName = indicatedServerNames.getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname", getPeerAddress()); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("client uses PSK identity for server [{}]", getPeerAddress(), identity, virtualHost); } } if (psk == null) { throw new HandshakeException( String.format("cannot authenticate client, identity [%s] is unknown for server [%s]", identity, virtualHost), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); if(otherSecret==null) { return generatePremasterSecretFromPSK(psk, null); }else { <START> return generatePremasterSecretFromPSK(psk, otherSecret); <END> } } }</code><technical_language>is difference if otherSecret is null</technical_language>

Target:
private byte[] configurePskCredentials(String identity, byte[] psk, byte[] otherSecret) throws HandshakeException { String virtualHost = null; if (indicatedServerNames == null) { LOGGER.debug("client uses PSK identity [{}]", getPeerAddress(), identity); } else { ServerName serverName = indicatedServerNames.getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname", getPeerAddress()); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("client uses PSK identity for server [{}]", getPeerAddress(), identity, virtualHost); } } if (psk == null) { throw new HandshakeException( String.format("cannot authenticate client, identity [%s] is unknown for server [%s]", identity, virtualHost), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); return generatePremasterSecretFromPSK(psk, otherSecret); } }
Source:
<code>public static FormulaShifter createForRowShift(int externSheetIndex, String sheetName, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove, SpreadsheetVersion version) { FormulaShifter instance = new FormulaShifter(externSheetIndex, sheetName, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove, ShiftMode.RowMove, version); <START> return instance; <END> }</code><technical_language>return new FormulaShifter(... is fine. need store returned in instance</technical_language>

Target:
public static FormulaShifter createForRowShift(int externSheetIndex, String sheetName, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove, SpreadsheetVersion version) { return new FormulaShifter(externSheetIndex, sheetName, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove, ShiftMode.RowMove, version); }
Source:
<code><START> public Void call(ApiCaller ac, Deserializer params) throws PerunException { <END> ac.stateChangingCheck(); Member sponsoredMember = ac.getMemberById(params.readInt("sponsored")); User sponsorToRemove = ac.getUserById(params.readInt("sponsor")); ac.getMembersManager().removeSponsor(ac.getSession(), sponsoredMember, sponsorToRemove); return null; }</code><technical_language>RPC/Core API is consistent method sponsorMember(). sponsorMember(userId,userId) removeSponsor(memberId,userId) @licehammer do want ? params named (sponsored/sponsor)</technical_language>

Target:
public RichMember call(ApiCaller ac, Deserializer params) throws PerunException { ac.stateChangingCheck(); String guestName = params.readString("guestName"); String password = params.readString("password"); Vo vo = ac.getVoById(params.readInt("vo")); String namespace = params.readString("namespace"); User sponsor = null; if(params.contains("sponsor")) { sponsor = ac.getUserById(params.readInt("sponsor")); } return ac.getMembersManager().createSponsoredMember(ac.getSession(), vo, namespace, guestName, password, sponsor); }
Source:
<code>void assertMaxTaskConcurrency(LocalAwareExecutorService executor, int concurrency) throws InterruptedException { executor.setMaximumPoolSize(concurrency); CountDownLatch concurrencyGoal = new CountDownLatch(concurrency); for (int i = 0; i < concurrency; i++) { executor.execute(new LatchWaiter(concurrencyGoal, 5000L, TimeUnit.MILLISECONDS)); } <START> Assert.assertEquals(true, concurrencyGoal.await(3000L, TimeUnit.MILLISECONDS)); <END> }</code><technical_language>is a reason changed units? values if is a reason</technical_language>

Target:
void assertMaxTaskConcurrency(LocalAwareExecutorService executor, int concurrency) throws InterruptedException { executor.setMaximumPoolSize(concurrency); CountDownLatch concurrencyGoal = new CountDownLatch(concurrency); for (int i = 0; i < concurrency; i++) { executor.execute(new LatchWaiter(concurrencyGoal, 5L, TimeUnit.SECONDS)); } Assert.assertEquals("Test tasks did not hit max concurrency goal", true, concurrencyGoal.await(3L, TimeUnit.SECONDS)); }
Source:
<code>private static String getHBaseDownloadUrl() { <START> return "<LINK_0>"; <END> }</code><technical_language>suggestion return "<LINK_1>";</technical_language>

Target:
private static String getHBaseDownloadUrl() { return "<LINK_1>"; }
Source:
<code>public void initialize(Map<String, Param> params) throws TikaConfigException { try { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(new HttpGet(healthUri)); available = response.getStatusLine().getStatusCode() == 200; LOG.info("Available = {}, API Status = {}", available, response.getStatusLine()); apiUri = URI.create(String.format( <START> "http://localhost:8764/inception/v3/captions?beam_size=%1$d&max_caption_length=%2$d", <END> captions, maxCaptionLength)); LOG.info("Captions = {}, MaxCaptionLength = {}", captions, maxCaptionLength); } catch (Exception e) { available = false; throw new TikaConfigException(e.getMessage(), e); } }</code><technical_language>@ThejanW if users want point API hosted http://localhost:8764</technical_language>

Target:
public void initialize(Map<String, Param> params) throws TikaConfigException { try { healthUri = URI.create(apiBaseUri + "/ping"); apiUri = URI.create(apiBaseUri + String.format("/captions?beam_size=%1$d&max_caption_length=%2$d", captions, maxCaptionLength)); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(new HttpGet(healthUri)); available = response.getStatusLine().getStatusCode() == 200; LOG.info("Available = {}, API Status = {}", available, response.getStatusLine()); LOG.info("Captions = {}, MaxCaptionLength = {}", captions, maxCaptionLength); } catch (Exception e) { available = false; throw new TikaConfigException(e.getMessage(), e); } }
Source:
<code><START> private boolean isValidComponentInfo(ComponentInfo componentInfo) { <END> return componentInfo != null && componentInfo.applicationInfo != null && componentInfo.applicationInfo.packageName != null && componentInfo.name != null; }</code><technical_language>static</technical_language>

Target:
private static boolean isValidComponentInfo(ComponentInfo componentInfo) { return componentInfo != null && componentInfo.applicationInfo != null && componentInfo.applicationInfo.packageName != null && componentInfo.name != null; }
Source:
<code>public List<ResourceEntry> removeAndGet(ScalarResourceEntry scalarResourceEntry, ReservationType reservationType) throws ResourceNotAvailabeException { ScalarResourceEntry availableResource = availableResourcesByReservationType.get(reservationType); List<ResourceEntry> reservedResources = new ArrayList<>(); <START> if (scalarResourceEntry.getValue() < availableResource.getValue()) { <END> availableResourcesByReservationType.put(reservationType, availableResource.remove(scalarResourceEntry)); totalAvailableResource -= scalarResourceEntry.getValue(); reservedResources.add(new ScalarResourceEntry(scalarResourceEntry.getReservationType(), scalarResourceEntry.getValue())); return reservedResources; } String message = String.format("ResourceType '%s' of reservationType '%s' is not available. Requested value: %s Available: %s", resourceType, reservationType.toString(), scalarResourceEntry.getValue(), availableResourcesByReservationType.get(reservationType)); throw new ResourceNotAvailabeException(message); }</code><technical_language>< -> <=</technical_language>

Target:
public List<ResourceEntry> removeAndGet(ScalarResourceEntry scalarResourceEntry, ReservationType reservationType) throws ResourceNotAvailableException { ScalarResourceEntry availableResource = availableResourcesByReservationType.get(reservationType); List<ResourceEntry> reservedResources = new ArrayList<>(); if (scalarResourceEntry.getValue() <= availableResource.getValue()) { availableResourcesByReservationType.put(reservationType, availableResource.remove(scalarResourceEntry)); totalAvailableResource -= scalarResourceEntry.getValue(); reservedResources.add(new ScalarResourceEntry(scalarResourceEntry.getReservationType(), scalarResourceEntry.getValue())); return reservedResources; } String message = String.format("ResourceType '%s' of reservationType '%s' is not available. Requested value: %s Available: %s", resourceType, reservationType.toString(), scalarResourceEntry.getValue(), availableResourcesByReservationType.get(reservationType)); throw new ResourceNotAvailableException(message); }