auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static <R extends Named> ImmutableList<NamedLookup<R>> parseProviders( IniFile config, Class<R> enumType) { <START> if (!config.contains("providers")) { <END> return ImmutableList.of(); } PropertySet section = config.getSection("providers"); ImmutableList.Builder<NamedLookup<R>> builder = ImmutableList.builder(); for (String key : section.keys()) { Class<?> cls; try { cls = RenameHandler.INSTANCE.lookupType(key); } catch (Exception ex) { throw new IllegalArgumentException("Unable to find enum provider class: " + key, ex); } String value = section.getValue(key); if (value.equals("constants")) { builder.add(parseConstants(enumType, cls)); } else if (value.equals("lookup")) { if (!NamedLookup.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("Enum provider class must implement NamedLookup " + cls.getName()); } try { Constructor<?> cons = cls.getDeclaredConstructor(); if (Modifier.isPublic(cls.getModifiers()) == false) { cons.setAccessible(true); } builder.add((NamedLookup<R>) cons.newInstance()); } catch (Exception ex) { throw new IllegalArgumentException("Invalid enum provider constructor: new " + cls.getName() + "()", ex); } } else { throw new IllegalArgumentException("Provider value must be either 'constants' or 'lookup'"); } } return builder.build(); }</code><technical_language>a constant instead of magic strings</technical_language>

Target:
private static <R extends Named> ImmutableList<NamedLookup<R>> parseProviders( IniFile config, Class<R> enumType) { if (!config.contains(PROVIDERS_SECTION)) { return ImmutableList.of(); } PropertySet section = config.getSection(PROVIDERS_SECTION); ImmutableList.Builder<NamedLookup<R>> builder = ImmutableList.builder(); for (String key : section.keys()) { Class<?> cls; try { cls = RenameHandler.INSTANCE.lookupType(key); } catch (Exception ex) { throw new IllegalArgumentException("Unable to find enum provider class: " + key, ex); } String value = section.getValue(key); if (value.equals("constants")) { builder.add(parseConstants(enumType, cls)); } else if (value.equals("lookup")) { if (!NamedLookup.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("Enum provider class must implement NamedLookup " + cls.getName()); } try { Constructor<?> cons = cls.getDeclaredConstructor(); if (Modifier.isPublic(cls.getModifiers()) == false) { cons.setAccessible(true); } builder.add((NamedLookup<R>) cons.newInstance()); } catch (Exception ex) { throw new IllegalArgumentException("Invalid enum provider constructor: new " + cls.getName() + "()", ex); } } else { throw new IllegalArgumentException("Provider value must be either 'constants' or 'lookup'"); } } return builder.build(); }
Source:
<code>private void runParallelLoad(final RDFFormat rdfFormat, final String baseURI, final String defaultGraph, BigdataSailConnection conn, List<File> files) throws InterruptedException, SailException { BlockingQueue<File> fileQueue = new LinkedBlockingDeque<>(files); BlockingQueue<TmpStore> tmpStoreQueue = new LinkedBlockingDeque<>(); Collection<Callable<Integer>> allTasks = new ArrayList<>(); AbstractTripleStore db = conn.getTripleStore(); ExecutorService executorService = db.getExecutorService(); <START> Semaphore tmpQueueSemaphore = new Semaphore(tmpQueueLimit); <END> for (int i = 0; i < fileReadersCount; i++) { allTasks.add(new FileReaderTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, baseURI, rdfFormat, defaultGraph, maxTmpStatementsSize)); } for (int i = 0; i < mergersCount; i++) { allTasks.add(new MergerTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, maxTmpStatementsSize)); } long startTime = System.currentTimeMillis(); List<Future<Integer>> results = executorService.invokeAll(allTasks); int merges = results.stream().collect(Collectors.summingInt(f -> { try { return f.get(); } catch (InterruptedException | ExecutionException e) { log.error("Error collecting stats", e); return 0; } })); log.info("allTasks completed in with merges, dbsize {}", System.currentTimeMillis() - startTime, merges, db.getStatementCount(true)); conn.commit(); log.info("CONN commit."); }</code><technical_language>unclear protect this semaphore. acquire release calls others confident run a dead lock imo</technical_language>

Target:
private void runParallelLoad(final RDFFormat rdfFormat, final String baseURI, final String defaultGraph, BigdataSailConnection conn, List<File> files) throws InterruptedException, SailException { BlockingQueue<File> fileQueue = new LinkedBlockingDeque<>(files); BlockingQueue<TmpStore> tmpStoreQueue = new LinkedBlockingDeque<>(); Collection<Callable<Integer>> allTasks = new ArrayList<>(); AbstractTripleStore db = conn.getTripleStore(); ExecutorService executorService = db.getExecutorService(); Semaphore tmpQueueSemaphore = new Semaphore(tmpQueueLimit); for (int i = 0; i < fileReadersCount; i++) { allTasks.add(new FileReaderTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, baseURI, rdfFormat, defaultGraph, maxTmpStatementsSize)); } for (int i = 0; i < mergersCount; i++) { allTasks.add(new MergerTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, maxTmpStatementsSize)); } long startTime = System.currentTimeMillis(); List<Future<Integer>> results = executorService.invokeAll(allTasks); int merges = results.stream().collect(Collectors.summingInt(f -> { try { return f.get(); } catch (InterruptedException | ExecutionException e) { log.error("Error collecting stats", e); return 0; } })); log.info("allTasks completed in with merges, dbsize {}", System.currentTimeMillis() - startTime, merges, db.getStatementCount(true)); }
Source:
<code>public void testVerseTwo() { <START> String expectedVerseTwo = "On the second day of Christmas my true love gave to me, " + "two Turtle Doves, " + <END> "and a Partridge in a Pear Tree.\n"; assertEquals(expectedVerseTwo, twelveDays.verse(2)); }</code><technical_language>changes needed. matter split string. do if fit line. sense</technical_language>

Target:
public void testVerseTwo() { String expectedVerseTwo = "On the second day of Christmas my true love gave to me, two Turtle Doves, " + "and a Partridge in a Pear Tree.\n"; assertEquals(expectedVerseTwo, twelveDays.verse(2)); }
Source:
<code>protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final String name = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); final String jndiName = ManagedExecutorServiceResourceDefinition.JNDI_NAME_AD.resolveModelAttribute(context, model).asString(); final int priority = ManagedThreadFactoryResourceDefinition.PRIORITY_AD.resolveModelAttribute(context, model).asInt(); final ServiceName serviceName = ManagedThreadFactoryResourceDefinition.CAPABILITY.getCapabilityServiceName(name); final ManagedThreadFactoryService service = new ManagedThreadFactoryService(name, jndiName, priority); <START> final ServiceBuilder<ManagedThreadFactoryImpl> serviceBuilder = context.getServiceTarget().addService(serviceName, service); <END> String contextService = null; if(model.hasDefined(ManagedThreadFactoryResourceDefinition.CONTEXT_SERVICE)) { contextService = ManagedThreadFactoryResourceDefinition.CONTEXT_SERVICE_AD.resolveModelAttribute(context, model).asString(); } if (contextService != null) { serviceBuilder.addDependency(context.getCapabilityServiceName(ContextServiceResourceDefinition.CAPABILITY.getName(), contextService, ContextServiceImpl.class), ContextServiceImpl.class, service.getContextServiceInjector()); } serviceBuilder.install(); }</code><technical_language>context.getCapabilityServiceTarget().addCapability(...) if possible</technical_language>

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final String name = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); final String jndiName = ManagedExecutorServiceResourceDefinition.JNDI_NAME_AD.resolveModelAttribute(context, model).asString(); final int priority = ManagedThreadFactoryResourceDefinition.PRIORITY_AD.resolveModelAttribute(context, model).asInt(); final ManagedThreadFactoryService service = new ManagedThreadFactoryService(name, jndiName, priority); final CapabilityServiceBuilder serviceBuilder = context.getCapabilityServiceTarget().addCapability(ManagedThreadFactoryResourceDefinition.CAPABILITY, service); String contextService = null; if(model.hasDefined(ManagedThreadFactoryResourceDefinition.CONTEXT_SERVICE)) { contextService = ManagedThreadFactoryResourceDefinition.CONTEXT_SERVICE_AD.resolveModelAttribute(context, model).asString(); } if (contextService != null) { serviceBuilder.addCapabilityRequirement(ContextServiceResourceDefinition.CAPABILITY.getName(), ContextServiceImpl.class, service.getContextServiceInjector(), contextService); } serviceBuilder.install(); }
Source:
<code>protected Set<Identity> identities(Map<String, Object> jsonData) { Set<Identity> identities = new HashSet<>(); if (jsonData == null) { return identities; } List<String> idList = (List<String>) jsonData.get(ID_LIST); for (String id : idList) { Identity identityObj = Identity.fromId(id); if (identityObj != null) { identities.add(identityObj); } else { <START> logger.trace("Identity is null for id: " + id); <END> } } return identities; }</code><technical_language>slf4j format log.trace("Identity is null for id: {}", id);</technical_language>

Target:
protected Set<Identity> identities(Map<String, Object> jsonData) { Set<Identity> identities = new HashSet<>(); if (jsonData == null) { return identities; } List<String> idList = (List<String>) jsonData.get(ID_LIST); for (String id : idList) { Identity identityObj = Identity.fromId(id); if (identityObj != null) { identities.add(identityObj); } else { log.trace("Identity is null for id: {}", id); } } return identities; }
Source:
<code>public void load(final GameChooserEntry entry) { fileName = null; if (entry == null) { ClientSetting.defaultGameName.resetValue(); ClientSetting.defaultGameUri.resetValue(); ClientSetting.flush(); } else { setGameData(entry.getGameData()); ClientSetting.defaultGameName.setValue(entry.getGameData().getGameName()); ClientSetting.defaultGameUri.setValue(entry.getUri().toString()); ClientSetting.flush(); <START> } <END> }</code><technical_language>place ClientSetting.flush() of individual if cases</technical_language>

Target:
public void load(final GameChooserEntry entry) { fileName = null; if (entry == null) { ClientSetting.defaultGameName.resetValue(); ClientSetting.defaultGameUri.resetValue(); } else { setGameData(entry.getGameData()); ClientSetting.defaultGameName.setValue(entry.getGameData().getGameName()); ClientSetting.defaultGameUri.setValue(entry.getUri().toString()); } ClientSetting.flush(); }
Source:
<code>void findProperty_Success() { String[] dnsServers = { "server1", "server2" }; String[] dnsSearch = { "dnsjava.org", "example.com", "dnsjava.org" }; Name[] searchPath = Arrays.stream(dnsSearch) <START> .map(s -> Name.fromConstantString(s, Name.root)) <END> .toArray(Name[]::new); System.setProperty(ResolverConfig.DNS_SERVER_PROP, String.join(",", dnsServers)); System.setProperty(ResolverConfig.DNS_SEARCH_PROP, String.join(",", dnsSearch)); try { ResolverConfig.refresh(); ResolverConfig rc = ResolverConfig.getCurrentConfig(); assertTrue(rc.findProperty()); assertEquals("server1", rc.server()); assertEquals(2, rc.servers().length); assertEquals(2, rc.searchPath().length); assertEquals(searchPath[0], rc.searchPath()[0]); assertEquals(searchPath[1], rc.searchPath()[1]); } finally { System.clearProperty(ResolverConfig.DNS_SERVER_PROP); System.clearProperty(ResolverConfig.DNS_SEARCH_PROP); } }</code><technical_language>If this call is reason added Name.fromConstantString(String, Name), simply put trailing dot for root string array</technical_language>

Target:
void findProperty_Success() { String[] dnsServers = { "server1", "server2" }; String[] dnsSearch = { "dnsjava.org", "example.com", "dnsjava.org" }; Name[] searchPath = Arrays.stream(dnsSearch) .map(s -> Name.fromConstantString(s + ".")) .toArray(Name[]::new); System.setProperty(ResolverConfig.DNS_SERVER_PROP, String.join(",", dnsServers)); System.setProperty(ResolverConfig.DNS_SEARCH_PROP, String.join(",", dnsSearch)); try { ResolverConfig.refresh(); ResolverConfig rc = ResolverConfig.getCurrentConfig(); assertTrue(rc.findProperty()); assertEquals("server1", rc.server()); assertEquals(2, rc.servers().length); assertEquals(2, rc.searchPath().length); assertEquals(searchPath[0], rc.searchPath()[0]); assertEquals(searchPath[1], rc.searchPath()[1]); } finally { System.clearProperty(ResolverConfig.DNS_SERVER_PROP); System.clearProperty(ResolverConfig.DNS_SEARCH_PROP); } }
Source:
<code>public <T> Query where(String name, QueryOperation<T> queryOperation, T... values) { checkNotEmpty(name, "Name cannot be empty/null, please specify a name to apply operations on."); checkNotNull(queryOperation, "QueryOperation cannot be null."); checkNotNull(values, "Values to be compared with need to be set to something."); if (values.length == 0 && !queryOperation.hasDefaultValue()) { throw new IllegalArgumentException("Please specify at least one value to be searched for."); } for (int i = 0; i < values.length; ++i) { final T value = values[i]; checkNotNull(value, "Value at position %d must not be null.", i); if (value instanceof CharSequence) { checkNotEmpty(value.toString(), "Value at position %d must not be empty.", i); } } if ((!name.startsWith("sys.") && !name.startsWith("fields.")) && !CDAContentType.class.isAssignableFrom(type)) { throw new IllegalArgumentException("Please specify either a \"sys.\" or a \"fields.\" " + "attribute to be searched for. (Remember to specify a ContentType for \"fields.\" " + <START> "searches on Entries only.)"); <END> } if (name.startsWith("fields.") && !hasContentTypeSet()) { throw new IllegalStateException("Cannot request fields of an entry without having a " + "content type set first."); } if (values.length == 0) { params.put(name + queryOperation.operator, queryOperation.defaultValue.toString()); } else { params.put(name + queryOperation.operator, join(values)); } return (Query) this; }</code><technical_language>I this wording is unclear. I read "when querying types Entry's"</technical_language>

Target:
public <T> Query where(String name, QueryOperation<T> queryOperation, T... values) { checkNotEmpty(name, "Name cannot be empty/null, please specify a name to apply operations on."); checkNotNull(queryOperation, "QueryOperation cannot be null."); checkNotNull(values, "Values to be compared with need to be set to something."); if (values.length == 0 && !queryOperation.hasDefaultValue()) { throw new IllegalArgumentException("Please specify at least one value to be searched for."); } for (int i = 0; i < values.length; ++i) { final T value = values[i]; checkNotNull(value, "Value at position %d must not be null.", i); if (value instanceof CharSequence) { checkNotEmpty(value.toString(), "Value at position %d must not be empty.", i); } } if ((!name.startsWith("sys.") && !name.startsWith("fields.")) && !CDAContentType.class.isAssignableFrom(type)) { throw new IllegalArgumentException("Please specify either a \"sys.\" or a \"fields.\" " + "attribute to be searched for. (Remember to specify a ContentType for \"fields.\" " + "searches when querying entries.)"); } if (name.startsWith("fields.") && !hasContentTypeSet()) { throw new IllegalStateException("Cannot request fields of an entry without having a " + "content type set first."); } if (values.length == 0) { params.put(name + queryOperation.operator, queryOperation.defaultValue.toString()); } else { params.put(name + queryOperation.operator, join(values)); } return (Query) this; }
Source:
<code>private void initializeSpaceUpdaterHelper() { String name = spaceSystemDriver.getName(); if (name.equals(GPFSSpaceSystem.class.getName())) { spaceUpdater = new NullSpaceUpdaterHelper(); <START> return; <END> } spaceUpdater = new SimpleSpaceUpdaterHelper(); }</code><technical_language>else</technical_language>

Target:
private void initializeSpaceUpdaterHelper() { spaceUpdater = SpaceUpdaterHelperFactory.getSpaceUpdaterHelper(this); }
Source:
<code>public AttributeTypeBuilder() { <START> this( CommonFactoryFinder.getFeatureTypeFactory(null) ); <END> }</code><technical_language>Btw, removing this init means userData map initialized a empty map, calling addUserData right constructor generate a NPE (unless missing something, another quick look)</technical_language>

Target:
public AttributeTypeBuilder() { this( CommonFactoryFinder.getFeatureTypeFactory(null) ); init(); }
Source:
<code>private void onBoardDelete(String boardName) { logger.info("Menu: Boards > Delete > " + boardName); Alert dlg = new Alert(AlertType.CONFIRMATION, ""); dlg.initModality(Modality.APPLICATION_MODAL); dlg.setTitle("Confirmation"); dlg.getDialogPane().setHeaderText("Delete board '" + boardName + "'?"); dlg.getDialogPane().setContentText("Are you sure you want to delete this board?"); Optional<ButtonType> response = dlg.showAndWait(); if (response.isPresent() && response.get().getButtonData() == ButtonData.OK_DONE) { prefs.removeBoard(boardName); if (prefs.getLastOpenBoard().equals(boardName)) { <START> prefs.setLastOpenBoard(""); <END> } ui.triggerEvent(new BoardSavedEvent()); logger.info(boardName + " was deleted"); } else { logger.info(boardName + " was not deleted"); } }</code><technical_language>This is clear method useful. handle possibility of last-opened board present</technical_language>

Target:
private void onBoardDelete(String boardName) { logger.info("Menu: Boards > Delete > " + boardName); Alert dlg = new Alert(AlertType.CONFIRMATION, ""); dlg.initModality(Modality.APPLICATION_MODAL); dlg.setTitle("Confirmation"); dlg.getDialogPane().setHeaderText("Delete board '" + boardName + "'?"); dlg.getDialogPane().setContentText("Are you sure you want to delete this board?"); Optional<ButtonType> response = dlg.showAndWait(); if (response.isPresent() && response.get().getButtonData() == ButtonData.OK_DONE) { prefs.removeBoard(boardName); if (prefs.getLastOpenBoard().isPresent()) { if (prefs.getLastOpenBoard().get().equals(boardName)) { prefs.clearLastOpenBoard(); } } ui.triggerEvent(new BoardSavedEvent()); logger.info(boardName + " was deleted"); } else { logger.info(boardName + " was not deleted"); } }
Source:
<code>protected void doOpen() throws Throwable { final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this); bootstrap = new Bootstrap(); bootstrap.group(nioEventLoopGroup) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .channel(NioSocketChannel.class); if (getConnectTimeout() < 3000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); } else { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); } bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { int heartbeatInterval = UrlUtils.getIdleTimeout(getUrl()); NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ch.pipeline() .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); String socksProxyHost = System.getProperty(SOCKS_PROXY_HOST); if(socksProxyHost != null) { <START> Integer socksProxyPort = Integer.getInteger(SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT); <END> Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); } } }); }</code><technical_language>System.getProperty(SOCKS_PROXY_PORT) ??</technical_language>

Target:
protected void doOpen() throws Throwable { final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this); bootstrap = new Bootstrap(); bootstrap.group(nioEventLoopGroup) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .channel(NioSocketChannel.class); if (getConnectTimeout() < 3000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); } else { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); } bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { int heartbeatInterval = UrlUtils.getHeartbeat(getUrl()); NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ch.pipeline() .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); String socksProxyHost = ConfigUtils.getProperty(SOCKS_PROXY_HOST); if(socksProxyHost != null) { int socksProxyPort = Integer.parseInt(ConfigUtils.getProperty(SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); } } }); }
Source:
<code>public <ContextType> ContextType getContextValue(String key) { <START> return context == null ? null : (ContextType) context.get(key); <END> }</code><technical_language>if gaining generics in this case</technical_language>

Target:
public Object getContextValue(String key) { return context == null ? null : context.get(key); }
Source:
<code>private synchronized void stopWithRequirement( AvailabilityRequirement requirement ) throws Throwable { log.info( "Stopping, reason: " + requirement.description() ); databaseHealth = null; localCommit = null; dataSourceManager.stop(); <START> raiseAvailabilityGuard( requirement ); <END> }</code><technical_language>raise this first</technical_language>

Target:
private synchronized void stopWithRequirement( AvailabilityRequirement requirement ) throws Throwable { log.info( "Stopping, reason: " + requirement.description() ); raiseAvailabilityGuard( requirement ); databaseHealth = null; localCommit = null; dataSourceManager.stop(); }
Source:
<code>public Set<Permission> permissionsFor(DataverseRequest req, DvObject dvo) { Set<Permission> permissions = permissionsForSingleRoleAssignee(req.getUser(), dvo); for (Group g : groupService.groupsFor(req, dvo)) { <START> permissionsForSingleRoleAssignee(g, dvo, permissions); <END> } if (!req.getUser().isAuthenticated()) { permissions.removeAll(PERMISSIONS_FOR_AUTHENTICATED_USERS_ONLY); } return permissions; }</code><technical_language>I find kind of confusing in some versions of "permissionsForSingleRoleAssignee" assign return permissions while in other cases is assigned passed in object. for uniform? change naming</technical_language>

Target:
public Set<Permission> permissionsFor(DataverseRequest req, DvObject dvo) { if (req.getUser().isSuperuser()) { return EnumSet.allOf(Permission.class); } Set<Permission> permissions = getInferredPermissions(dvo); Set<RoleAssignee> ras = new HashSet<>(groupService.groupsFor(req, dvo)); ras.add(req.getUser()); addGroupPermissionsFor(ras, dvo, permissions); if (!req.getUser().isAuthenticated()) { permissions.removeAll(PERMISSIONS_FOR_AUTHENTICATED_USERS_ONLY); } return permissions; }
Source:
<code>public void start(IProgressMonitor progressMonitor) { List<IResource> resourcesToMonitor = getResourcesToMonitor(); SubMonitor subMonitor = SubMonitor.convert(progressMonitor, resourcesToMonitor.size() + 1); boolean refreshNeeded = false; for (Iterator<IResource> i = resourcesToMonitor.iterator(); i.hasNext();) refreshNeeded |= !monitor(i.next(), subMonitor.split(1)); workspace.getPathVariableManager().addChangeListener(this); workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); ((Workspace) workspace).addLifecycleListener(this); if (Policy.DEBUG_AUTO_REFRESH) Policy.debug(RefreshManager.DEBUG_PREFIX + " starting monitor manager."); if (refreshNeeded) { new PollingMonitor(refreshManager).runOnce(); <START> subMonitor.worked(1); <END> } else { subMonitor.setWorkRemaining(0); } }</code><technical_language>step(1)</technical_language>

Target:
public void start(IProgressMonitor progressMonitor) { List<IResource> resourcesToMonitor = getResourcesToMonitor(); SubMonitor subMonitor = SubMonitor.convert(progressMonitor, resourcesToMonitor.size() + 1); boolean refreshNeeded = false; for (Iterator<IResource> i = resourcesToMonitor.iterator(); i.hasNext();) refreshNeeded |= !monitor(i.next(), subMonitor.split(1)); workspace.getPathVariableManager().addChangeListener(this); workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); ((Workspace) workspace).addLifecycleListener(this); if (Policy.DEBUG_AUTO_REFRESH) Policy.debug(RefreshManager.DEBUG_PREFIX + " starting monitor manager."); if (refreshNeeded) { new PollingMonitor(refreshManager).runOnce(); } subMonitor.step(1); }
Source:
<code>public PopupMenuExportResponse() { super(Constant.messages.getString("history.export.response.popup")); this.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.size() == 0) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.select.warning")); return; } <START> HttpMessage msg = null; <END> try { msg = hrefs.get(0).getHttpMessage(); } catch (Exception e1) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.read.warning")); return; } if (msg.getResponseHeader().isEmpty() || msg.getResponseBody().length() == 0) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.body.warning")); return; } File file = getOutputFile(msg); if (file == null) { return; } boolean isAppend = true; if (file.exists()) { int rc = extension.getView().showYesNoCancelDialog(Constant.messages.getString("file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { isAppend = false; } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(file, isAppend)); for (HistoryReference href : hrefs) { exportHistory(href.getHttpMessage(), bos); } } catch (Exception e1) { extension.getView().showWarningDialog(Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); log.warn(e1.getMessage(), e1); } finally { try { bos.close(); } catch (Exception e2) { log.warn(e2.getMessage(), e2); } } } }); }</code><technical_language>message validations removed well? (We validate none?)</technical_language>

Target:
public PopupMenuExportResponse() { super(Constant.messages.getString("history.export.response.popup")); this.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.size() == 0) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.select.warning")); return; } File file = getOutputFile(); if (file == null) { return; } boolean isAppend = true; if (file.exists()) { int rc = extension.getView().showYesNoCancelDialog(Constant.messages.getString("file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { isAppend = false; } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(file, isAppend)); for (HistoryReference href : hrefs) { HttpMessage msg = null; msg = href.getHttpMessage(); exportHistory(msg, bos); } } catch (Exception e1) { extension.getView().showWarningDialog(Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); log.warn(e1.getMessage(), e1); } finally { try { bos.close(); } catch (Exception e2) { log.warn(e2.getMessage(), e2); } } } }); }
Source:
<code>public WorkerCoordinatorMetrics(Metrics metrics, String metricGrpPrefix) { this.metricGrpName = metricGrpPrefix + "-coordinator-metrics"; Measurable numConnectors = new Measurable() { @Override public double measure(MetricConfig config, long now) { return assignmentSnapshot.connectors().size(); } }; Measurable numTasks = new Measurable() { @Override public double measure(MetricConfig config, long now) { return assignmentSnapshot.tasks().size(); } }; <START> if (assignmentSnapshot != null) { <END> metrics.addMetric(metrics.metricName("assigned-connectors", this.metricGrpName, "The number of connector instances currently assigned to this consumer"), numConnectors); metrics.addMetric(metrics.metricName("assigned-tasks", this.metricGrpName, "The number of tasks currently assigned to this consumer"), numTasks); } }</code><technical_language>this change, if assignmentSnapshot is null enter this constructor, metrics get registered, if initialized shortly after. register metrics, return Double.NaN in measure() method if assignmentSnapshot is null</technical_language>

Target:
public WorkerCoordinatorMetrics(Metrics metrics, String metricGrpPrefix) { this.metricGrpName = metricGrpPrefix + "-coordinator-metrics"; Measurable numConnectors = new Measurable() { @Override public double measure(MetricConfig config, long now) { if (assignmentSnapshot == null) { return 0.0; } return assignmentSnapshot.connectors().size(); } }; Measurable numTasks = new Measurable() { @Override public double measure(MetricConfig config, long now) { if (assignmentSnapshot == null) { return 0.0; } return assignmentSnapshot.tasks().size(); } }; metrics.addMetric(metrics.metricName("assigned-connectors", this.metricGrpName, "The number of connector instances currently assigned to this consumer"), numConnectors); metrics.addMetric(metrics.metricName("assigned-tasks", this.metricGrpName, "The number of tasks currently assigned to this consumer"), numTasks); }
Source:
<code>public BlobId(byte flag, byte datacenterId, short accountId, short containerId, PartitionId partitionId) { if (partitionId == null) { throw new IllegalArgumentException("partitionId cannot be null"); } version = getCurrentVersion(); <START> switch (version) { <END> case BLOB_ID_V1: this.flag = DEFAULT_FLAG; this.datacenterId = LEGACY_DATACENTER_ID; this.accountId = LEGACY_ACCOUNT_ID; this.containerId = LEGACY_CONTAINER_ID; break; case BLOB_ID_V2: this.flag = flag; this.datacenterId = datacenterId; this.accountId = accountId; this.containerId = containerId; break; default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } this.partitionId = partitionId; uuid = UUID.randomUUID().toString(); }</code><technical_language>this switch case is required - is passed in</technical_language>

Target:
public BlobId(byte flag, byte datacenterId, short accountId, short containerId, PartitionId partitionId) { if (partitionId == null) { throw new IllegalArgumentException("partitionId cannot be null"); } version = getCurrentVersion(); switch (version) { case BLOB_ID_V1: this.flag = DEFAULT_FLAG; this.datacenterId = UNKNOWN_DATACENTER_ID; this.accountId = UNKNOWN_ACCOUNT_ID; this.containerId = UNKNOWN_CONTAINER_ID; break; case BLOB_ID_V2: this.flag = flag; this.datacenterId = datacenterId; this.accountId = accountId; this.containerId = containerId; break; default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } this.partitionId = partitionId; uuid = UUID.randomUUID().toString(); }
Source:
<code>public String getQuestionWithExistingResponseSubmissionFormHtml(boolean sessionIsOpen, int qnIdx, int responseIdx, String courseId, int totalNumRecipients, FeedbackResponseDetails existingResponseDetails) { return Templates.populateTemplate( FormTemplates.TEXT_SUBMISSION_FORM, <START> Slots.IS_SESSION_OPEN, sessionIsOpen ? "true" : "false", <END> Slots.FEEDBACK_RESPONSE_TEXT, Const.ParamsNames.FEEDBACK_RESPONSE_TEXT, Slots.QUESTION_INDEX, Integer.toString(qnIdx), Slots.RESPONSE_INDEX, Integer.toString(responseIdx), "${recommendedLengthDisplay}", recommendedLength == 0 ? "style=\"display:none\"" : "", "${recommendedLength}", Integer.toString(recommendedLength), Slots.TEXT_EXISTING_RESPONSE, SanitizationHelper.sanitizeForRichText(existingResponseDetails.getAnswerString())); }</code><technical_language>readonly needs set false if session is open vice versa, I if agree if passed data IS_SESSION_CLOSED instead. new line read like: Java Slots.IS_SESSION_CLOSED, !sessionIsOpen ? "true" : "false" Note: rename Slots constant content accordingly</technical_language>

Target:
public String getQuestionWithExistingResponseSubmissionFormHtml(boolean sessionIsOpen, int qnIdx, int responseIdx, String courseId, int totalNumRecipients, FeedbackResponseDetails existingResponseDetails) { return Templates.populateTemplate( FormTemplates.TEXT_SUBMISSION_FORM, Slots.IS_SESSION_OPEN, Boolean.toString(sessionIsOpen), Slots.FEEDBACK_RESPONSE_TEXT, Const.ParamsNames.FEEDBACK_RESPONSE_TEXT, Slots.QUESTION_INDEX, Integer.toString(qnIdx), Slots.RESPONSE_INDEX, Integer.toString(responseIdx), "${recommendedLengthDisplay}", recommendedLength == 0 ? "style=\"display:none\"" : "", "${recommendedLength}", Integer.toString(recommendedLength), Slots.TEXT_EXISTING_RESPONSE, SanitizationHelper.sanitizeForRichText(existingResponseDetails.getAnswerString())); }
Source:
<code>protected boolean isMemoryStateRemovable(String memoryVolume) { if (memoryVolume.isEmpty()) { return false; } return enclosingCommand.getParameters().getParentCommand() == VdcActionType.RemoveVm ? <START> getSnapshotDao().getNumOfSnapshotsByMemory(memoryVolume) == 0 <END> : getSnapshotDao().getNumOfSnapshotsByMemory(memoryVolume) == 1; }</code><technical_language>IMO MemoryImageRemoverOnDataDomain shouldbn't aware of executed commands, if want run internal flow? this passed in parameters imo. btw, if please export db load a line before</technical_language>

Target:
protected boolean isMemoryStateRemovable(String memoryVolume) { if (memoryVolume.isEmpty()) { return false; } int numOfSnapshotsUsingThisMemory = getSnapshotDao().getNumOfSnapshotsByMemory(memoryVolume); return enclosingCommand.getParameters().getParentCommand() == VdcActionType.RemoveVm ? numOfSnapshotsUsingThisMemory == 0 : numOfSnapshotsUsingThisMemory == 1; }
Source:
<code>public PartitionWideEntryBackupOperation(String name, EntryBackupProcessor backupProcessor) { super(name, backupProcessor); <START> Thread.dumpStack(); <END> }</code><technical_language>Leftover debug statement (most test failures & large PR builder time)</technical_language>

Target:
public PartitionWideEntryBackupOperation(String name, EntryBackupProcessor backupProcessor) { super(name, backupProcessor); }
Source:
<code>protected void build(UnitVmModel frontend, VM backend) { backend.setCpuPinning((String) frontend.getCpuPinning().getEntity()); VDS defaultHost = (VDS) frontend.getDefaultHost().getSelectedItem(); if ((Boolean) frontend.getIsAutoAssign().getEntity()) { backend.setDedicatedVmForVds(null); } else { backend.setDedicatedVmForVds(defaultHost.getId()); } <START> backend.setMigrationSupport((MigrationSupport) frontend.getMigrationMode().getSelectedItem()); <END> backend.setUseHostCpuFlags((Boolean) frontend.getHostCpu().getEntity()); }</code><technical_language>this is part separated HA..builder</technical_language>

Target:
protected void build(UnitVmModel frontend, VM backend) { backend.setCpuPinning((String) frontend.getCpuPinning().getEntity()); backend.setUseHostCpuFlags((Boolean) frontend.getHostCpu().getEntity()); }
Source:
<code><START> public NetworkAccess(CoreNode coreNode, <END> SocialNetwork social, ContentAddressedStorage dhtClient, MutablePointers mutable, MutableTree tree, WriteSynchronizer synchronizer, InstanceAdmin instanceAdmin, SpaceUsage spaceUsage, List<String> usernames, boolean isJavascript) { this.coreNode = coreNode; this.social = social; this.dhtClient = new HashVerifyingStorage(dhtClient, isJavascript ? new ScryptJS() : new ScryptJava()); this.mutable = mutable; this.tree = tree; this.synchronizer = synchronizer; this.instanceAdmin = instanceAdmin; this.spaceUsage = spaceUsage; this.usernames = usernames; this.creationTime = LocalDateTime.now(); this.isJavascript = isJavascript; }</code><technical_language>This Scala background talking, NetworkAccess takes 7 args. wrap in a new class (maybe NetworkAccessConfig) subsequent changes argument in invocation of NetworkAccess</technical_language>

Target:
protected NetworkAccess(CoreNode coreNode, SocialNetwork social, ContentAddressedStorage dhtClient, MutablePointers mutable, MutableTree tree, WriteSynchronizer synchronizer, InstanceAdmin instanceAdmin, SpaceUsage spaceUsage, List<String> usernames, boolean isJavascript) { this.coreNode = coreNode; this.social = social; this.dhtClient = new HashVerifyingStorage(dhtClient, isJavascript ? new ScryptJS() : new ScryptJava()); this.mutable = mutable; this.tree = tree; this.synchronizer = synchronizer; this.instanceAdmin = instanceAdmin; this.spaceUsage = spaceUsage; this.usernames = usernames; this.creationTime = LocalDateTime.now(); this.isJavascript = isJavascript; }
Source:
<code><START> public Response export() throws IOException { <END> String exportFile = dataTransferServices.doExport(DataTransferExportModel.exportAll()); org.uberfire.java.nio.file.Path path = Paths.get(exportFile); return Response.ok(ioService.readAllBytes(path)).build(); }</code><technical_language>propagate IOException? In case of exception, worth catching returning a more friendly message a response error 500</technical_language>

Target:
public Response export() { try { String exportFile = dataTransferServices.doExport(DataTransferExportModel.exportAll()); org.uberfire.java.nio.file.Path path = Paths.get(exportFile); return Response.ok(ioService.readAllBytes(path)).build(); } catch (Exception e) { String errorMessage = "Error creating export: " + e.getMessage(); logger.error(errorMessage); logger.debug("Not able to create export.", e); return Response.serverError() .entity(errorMessage) .build(); } }
Source:
<code>private String getKeyForRecord(final SAMRecord record) { <START> boolean t = record.getReadPairedFlag() && record.getSecondOfPairFlag(); <END> return record.getReadName() + "-" + (t ? "first" : "second"); }</code><technical_language>final. nice get a more informative variable name. isSecondOfPair</technical_language>

Target:
private String getKeyForRecord(final SAMRecord record) { final boolean isSecondOfPair = record.getReadPairedFlag() && record.getSecondOfPairFlag(); return record.getReadName() + "-" + (isSecondOfPair ? "second" : "first"); }
Source:
<code>public void process(Document document) { Element body = document.body(); CssParser cssParser = new CssParser(); for (Element element : Selector.select("[style]", body)) { String style = element.attr("style"); String newStyle = ""; List<CssRule> rules = null; CssRule newRule = null; if (style != null && style.length() > 0) { rules = cssParser.parseBlockContent(style); Iterator<CssRule> ruleIt = rules.iterator(); while (ruleIt.hasNext()) { CssRule rule = ruleIt.next(); if ("color".equals(rule.name)) { String color = rule.value; Matcher invalidHexColorMatcher = Pattern.compile( <START> "^([0-9a-fA-F]{6}|[0-9a-fA-F]{3})(\\s+(!)\\s*important)?\\s*$") END> .matcher(color); if (invalidHexColorMatcher.find()) { String newColor = "#" + invalidHexColorMatcher.group(1); boolean importantExists = invalidHexColorMatcher.group(2) != null; if (importantExists) { newColor += " !important"; } ruleIt.remove(); newRule = new CssRule("color", newColor.trim(), 0, 0, 0, 0); } } } } if (rules != null && newRule != null) { newStyle = addRuleToStyle(newStyle, newRule); for (CssRule rule : rules) { newStyle = addRuleToStyle(newStyle, rule); } element.attr("style", newStyle); } } }</code><technical_language>consider changing regex follows: ^\\s*([0-9a-fA-F]{6}|[0-9a-fA-F]{3})(?:\\s+(.*))?\\s*$ capturing group catch !important other</technical_language>

Target:
public void process(Document document) { Element body = document.body(); CssParser cssParser = new CssParser(); for (Element element : Selector.select("[style]", body)) { String style = element.attr("style"); String newStyle = ""; List<CssRule> rules = null; CssRule newRule = null; if (style != null && style.length() > 0) { rules = cssParser.parseBlockContent(style); Iterator<CssRule> ruleIt = rules.iterator(); while (ruleIt.hasNext()) { CssRule rule = ruleIt.next(); if ("color".equals(rule.name)) { String color = rule.value; Matcher invalidHexColorMatcher = Pattern.compile( "^\\s*([0-9a-fA-F]{6}|[0-9a-fA-F]{3})(?:\\s+(.*))?\\s*$") .matcher(color); if (invalidHexColorMatcher.matches()) { String newColor = "#" + invalidHexColorMatcher.group(1); String additionalDeclarations = invalidHexColorMatcher.group(2); if (additionalDeclarations != null) { newColor += " " + additionalDeclarations; } ruleIt.remove(); newRule = new CssRule("color", newColor.trim(), 0, 0, 0, 0); } } } } if (rules != null && newRule != null) { newStyle = addRuleToStyle(newStyle, newRule); for (CssRule rule : rules) { newStyle = addRuleToStyle(newStyle, rule); } element.attr("style", newStyle); } } }
Source:
<code>public RuleViolations evaluate(final Occurrences rule, final CardinalityContext context) { final String ruleRole = rule.getRole(); final int minOccurrences = rule.getMinOccurrences(); final int maxOccurrences = rule.getMaxOccurrences(); final Set<String> candidateRoles = context.getRoles(); final int candidatesCount = context.getCandidateCount(); final CardinalityContext.Operation operation = context.getOperation(); final DefaultRuleViolations results = new DefaultRuleViolations(); if (candidateRoles.contains(ruleRole)) { final int count = operation.equals(CardinalityContext.Operation.NONE) ? candidatesCount : (operation.equals(CardinalityContext.Operation.ADD) ? candidatesCount + 1 : candidatesCount - 1); if (count < minOccurrences) { results.addViolation(new CardinalityMinRuleViolation(candidateRoles.toString(), ruleRole, <START> (int) minOccurrences, <END> candidatesCount)); } else if (maxOccurrences > -1 && count > maxOccurrences) { results.addViolation(new CardinalityMaxRuleViolation(candidateRoles.toString(), ruleRole, (int) maxOccurrences, candidatesCount)); } } return results; }</code><technical_language>need for cast</technical_language>

Target:
public RuleViolations evaluate(final Occurrences rule, final CardinalityContext context) { final String ruleRole = rule.getRole(); final int minOccurrences = rule.getMinOccurrences(); final int maxOccurrences = rule.getMaxOccurrences(); final Set<String> candidateRoles = context.getRoles(); final int candidatesCount = context.getCandidateCount(); final CardinalityContext.Operation operation = context.getOperation(); final DefaultRuleViolations results = new DefaultRuleViolations(); if (candidateRoles.contains(ruleRole)) { final int count = operation.equals(CardinalityContext.Operation.NONE) ? candidatesCount : (operation.equals(CardinalityContext.Operation.ADD) ? candidatesCount + 1 : candidatesCount - 1); if (count < minOccurrences) { results.addViolation(new CardinalityMinRuleViolation(candidateRoles.toString(), ruleRole, minOccurrences, candidatesCount)); } else if (maxOccurrences > -1 && count > maxOccurrences) { results.addViolation(new CardinalityMaxRuleViolation(candidateRoles.toString(), ruleRole, maxOccurrences, candidatesCount)); } } return results; }
Source:
<code>public void TextSize(int fontSize) { <START> if(fontSize>1000) <END> textSize = 999; else textSize = fontSize; setAdapterData(); }</code><technical_language>earlier notes code style if statements</technical_language>

Target:
public void TextSize(int fontSize) { if (fontSize > 1000 || fontSize < 1) textSize = 999; else textSize = fontSize; setAdapterData(); }
Source:
<code>public void clickedOnNavDrawerSection(@NonNull String sectionName) { trackEvent(clickedOnNavDrawerSectionEventName, sectionNameMapKey, sectionName); <START> <END> }</code><technical_language>new line</technical_language>

Target:
public void clickedOnNavDrawerSection(@NonNull String sectionName) { trackEventWithProperties(CLICKED_ON_NAV_DRAWER_SECTION_EVENT_NAME, SECTION_NAME_MAP_KEY, sectionName); }
Source:
<code>protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { RatingWidgetAnswerBinding binding = RatingWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); View answerView = binding.getRoot(); RangeQuestion rangeQuestion = (RangeQuestion) prompt.getQuestion(); int numberOfStars = rangeQuestion.getRangeEnd().intValue(); int columns = calculateColumns(48); int rows = (int) Math.ceil((double) numberOfStars / columns); if (rows == 1) { <START> binding.ratingBar.setVisibility(VISIBLE); <END> this.ratingBar = binding.ratingBar; } else { binding.ratingBar.setVisibility(GONE); columns = calculateColumns(36); rows = (int) Math.ceil((double) numberOfStars / columns); if (rows == 1) { binding.ratingBar2.setVisibility(VISIBLE); this.ratingBar = binding.ratingBar2; } else { binding.ratingBar3.setVisibility(VISIBLE); this.ratingBar = binding.ratingBar3; } } ratingBar.setNumStars(rangeQuestion.getRangeEnd().intValue()); ratingBar.setOnRatingBarChangeListener((ratingBar, rating, fromUser) -> widgetValueChanged()); ratingBar.setEnabled(!prompt.isReadOnly()); if (prompt.getAnswerText() != null) { ratingBar.setRating(Integer.parseInt(prompt.getAnswerText())); } return answerView; }</code><technical_language>blank lines please remove one</technical_language>

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = RatingWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); View answerView = binding.getRoot(); int numberOfStars = getTotalStars((RangeQuestion) prompt.getQuestion()); int maxNumberOfStars = calculateMaximumStarsInOneLine(); if (maxNumberOfStars < numberOfStars) { binding.ratingBar1.setNumStars(maxNumberOfStars); binding.ratingBar1.setMax(maxNumberOfStars); binding.ratingBar2.setNumStars(Math.min(numberOfStars - maxNumberOfStars, maxNumberOfStars)); binding.ratingBar2.setMax(Math.min(numberOfStars - maxNumberOfStars, maxNumberOfStars)); binding.ratingBar2.setVisibility(View.VISIBLE); } else { binding.ratingBar1.setNumStars(numberOfStars); binding.ratingBar1.setMax(numberOfStars); } if (prompt.isReadOnly()) { binding.ratingBar1.setEnabled(false); binding.ratingBar2.setEnabled(false); } else { setUpRatingBar(maxNumberOfStars); } if (prompt.getAnswerText() != null) { int rating = Integer.parseInt(prompt.getAnswerText()); if (rating > maxNumberOfStars) { binding.ratingBar2.setRating(rating - maxNumberOfStars); } else { binding.ratingBar1.setRating(rating); } } return answerView; }