auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Table findTableOrThrow(String table) throws SchemaSyncError { Table t = findTable(table); if ( t == null ) <START> throw new SchemaSyncError("Couldn't find table '" + table + "'" + " in database '" + this.name); <END> return t; }</code><technical_language>This out of place... part of SchemaChange? (it'd need accept a database param)</technical_language>

Target:
public Table findTableOrThrow(String table) throws InvalidSchemaError { Table t = findTable(table); if ( t == null ) throw new InvalidSchemaError("Couldn't find table '" + table + "'" + " in database '" + this.name); return t; }
Source:
<code>protected boolean canDoAction() { if (getParameters() != null) { if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN.toString()); <START> addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM.toString()); <END> return false; } } return true; }</code><technical_language>run vm</technical_language>

Target:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }
Source:
<code>private boolean peekIdOrKeyword() { <START> return peekIdOrKeyword(0); <END> }</code><technical_language>remove int index version need it</technical_language>

Target:
private boolean peekIdOrKeyword() { TokenType type = peekType(); return TokenType.IDENTIFIER == type || Keywords.isKeyword(type); }
Source:
<code>private boolean validateListMethodsResponse(Object[] availableMethods) { if (availableMethods == null) { AppLog.e(T.NUX, "The response of system.listMethods was empty!"); return false; } String[] requiredMethods = { "wp.getUsersBlogs", "wp.getPage", "wp.getCommentStatusList", "wp.newComment", "wp.editComment", "wp.deleteComment", "wp.getComments", "wp.getComment", "wp.getOptions", "wp.uploadFile", "wp.newCategory", "wp.getTags", "wp.getCategories", "wp.editPage", "wp.deletePage", "wp.newPage", "wp.getPages" }; for (String currentRequiredMethod: requiredMethods) { boolean match = false; for (Object currentAvailableMethod: availableMethods) { if ((currentAvailableMethod).equals(currentRequiredMethod)) { match = true; <START> continue; <END> } } if (!match) { AppLog.e(T.NUX, "The following XML-RPC method: " + currentRequiredMethod + " is missing on the server."); return false; } } return true; }</code><technical_language>a compiler warning here: "continue" is unnecessary statement in a loop</technical_language>

Target:
private boolean validateListMethodsResponse(Object[] availableMethods) { if (availableMethods == null) { AppLog.e(T.NUX, "The response of system.listMethods was empty!"); return false; } String[] requiredMethods = { "wp.getUsersBlogs", "wp.getPage", "wp.getCommentStatusList", "wp.newComment", "wp.editComment", "wp.deleteComment", "wp.getComments", "wp.getComment", "wp.getOptions", "wp.uploadFile", "wp.newCategory", "wp.getTags", "wp.getCategories", "wp.editPage", "wp.deletePage", "wp.newPage", "wp.getPages" }; for (String currentRequiredMethod: requiredMethods) { boolean match = false; for (Object currentAvailableMethod: availableMethods) { if ((currentAvailableMethod).equals(currentRequiredMethod)) { match = true; break; } } if (!match) { AppLog.e(T.NUX, "The following XML-RPC method: " + currentRequiredMethod + " is missing on the server."); return false; } } return true; }
Source:
<code>public void setClientInfo(Properties properties) throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException(); } if (properties != null) { <START> if (properties.isEmpty()) { <END> this.properties.clear(); } else { this.properties = properties; } } }</code><technical_language>if (paroperties == null || properties.isEmpty()) {</technical_language>

Target:
public void setClientInfo(Properties properties) throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException(); } if (properties == null || properties.isEmpty()) { this.properties.clear(); } else { this.properties = properties; } }
Source:
<code>private void loadAndPut(String environment) { try (InputStream resource = getClass().getResourceAsStream("/" + environment + ".properties")) { properties.load(resource); LOG.debug("File {}.properties loaded", environment); } catch (NullPointerException | IOException whenNotFound) { <START> LOG.debug("Could not find the file " + environment + ".properties to load.", whenNotFound); <END> } }</code><technical_language>hey, @ferrelucas do keeping warning, move exception stack debug level? this: LOG.warn("Could find file " + environment + ".properties load."); LOG.debug("exception " + whenNotFound);</technical_language>

Target:
private void loadAndPut(String environment) { try (InputStream resource = getClass().getResourceAsStream("/" + environment + ".properties")) { properties.load(resource); LOG.debug("File {}.properties loaded", environment); } catch (NullPointerException | IOException whenNotFound) { LOG.warn("Could not find the file " + environment + ".properties to load."); LOG.debug("Exception was " + whenNotFound); } }
Source:
<code>public void afterCompletion(boolean committed) throws EJBException, RemoteException { <START> log.infof("afterCompletion: transaction was%s committed", committed ? "" : " not"); <END> checker.setSynchronizedAfter(committed); }</code><technical_language>log.tracef</technical_language>

Target:
public void afterCompletion(boolean committed) throws EJBException, RemoteException { log.tracef("afterCompletion: transaction was%s committed", committed ? "" : " not"); checker.setSynchronizedAfter(committed); }
Source:
<code>public boolean validateLoginDataFast() { if ( loginData == null ) { return true; } try { final HttpClient httpClient = getHttpClient(); final URI uri = new URI( StringUtils.stripEnd( loginData.getUrl(), "/ " ) + TREE_API_URL_PART ); final Credentials credentials = new UsernamePasswordCredentials( loginData.getUsername(), loginData.getPassword() ); final HttpState state = new HttpState(); state.setCredentials( new AuthScope( uri.getHost(), uri.getPort(), AuthScope.ANY_REALM ), credentials ); httpClient.setState( state ); final HttpMethod get = new GetMethod( uri.toString() ); final String authenticationString = loginData.getUsername() + ":" + loginData.getPassword(); final String base64Credentials = new Base64Encoder().encode( authenticationString.getBytes( Charset.forName( "UTF-8" ) ) ); <START> get.setRequestHeader( AUTHORIZATION, "Basic " + base64Credentials ); <END> final int code = httpClient.executeMethod( get ); if ( code == HttpStatus.SC_OK ) { return true; } logger.info( "Can't log in with the provided credentials. Status code: " + code ); } catch ( final IOException | URISyntaxException | IllegalArgumentException e ) { logger.info( "Can't connect to the server", e ); } return false; }</code><technical_language>dont need manual base64Credentials stuff. HTTP-Client's Credentials care of authentication for you</technical_language>

Target:
public boolean validateLoginDataFast() { if ( loginData == null ) { return true; } try { final HttpClient httpClient = getHttpClient(); final URI uri = new URI( StringUtils.stripEnd( loginData.getUrl(), "/ " ) + TREE_API_URL_PART ); final Credentials credentials = new UsernamePasswordCredentials( loginData.getUsername(), loginData.getPassword() ); final HttpState state = new HttpState(); state.setCredentials( new AuthScope( uri.getHost(), uri.getPort(), AuthScope.ANY_REALM ), credentials ); httpClient.setState( state ); final HttpMethod get = new GetMethod( uri.toString() ); final int code = httpClient.executeMethod( get ); if ( code == HttpStatus.SC_OK ) { return true; } logger.info( "Can't log in with the provided credentials. Status code: " + code ); } catch ( final IOException | URISyntaxException | IllegalArgumentException e ) { logger.info( "Can't connect to the server", e ); } return false; }
Source:
<code>private void writeAndClose(ByteBuffer data, OutputStream to) throws IOException { try { WritableByteChannel channel = Channels.newChannel(to); <START> channel.write(data); <END> } finally { to.close(); } }</code><technical_language>is this change related bugfix</technical_language>

Target:
private void writeAndClose(ByteBuffer data, OutputStream to) throws IOException { byte[] input = data.array(); int offset = data.arrayOffset() + data.position(); int length = data.remaining(); try { to.write(input, offset, length); } finally { to.close(); } }
Source:
<code>protected void handleRepositoryModified( final MavenRepository mavenRepository ) { try { wlManager.forceUpdateWhitelist( mavenRepository ); } catch ( IllegalStateException e ) { <START> getLogger().info( e.getMessage() ); <END> } }</code><technical_language>info log, getMessage() ? This end logging null if ISE thrown w/o a message</technical_language>

Target:
protected void handleRepositoryModified( final MavenRepository mavenRepository ) { try { wlManager.forceUpdateWhitelist( mavenRepository ); } catch ( IllegalStateException e ) { getLogger().debug( "Repository is in bad state for white-list update: {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ), e.getMessage() ); } }
Source:
<code>private void initModule(InputStream modulesXML, boolean isCustom) throws ScriptException { try { Context cx = RhinoEngine.enterGlobalContext(); JAXBContext jaxbContext = JAXBContext.newInstance(Module.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); <START> <END> Module moduleObject = (Module) jaxbUnmarshaller.unmarshal(modulesXML); String moduleName = moduleObject.getName(); if (modules.get(moduleName) != null) { log.info("A module with the name : " + moduleName + " already exists and it will be overwritten."); } String namespace = moduleObject.getNamespace(); boolean expose = ("true".equals(moduleObject.getExpose())); JavaScriptModule module = new JavaScriptModule(moduleName); module.setNamespace(namespace); module.setExpose(expose); initHostObjects(moduleObject, module); initMethods(moduleObject, module); initScripts(moduleObject, cx, module, isCustom); modules.put(moduleName, module); }catch (JAXBException e) { String msg = "Error while reading the module.xml"; log.error(msg, e); throw new ScriptException(msg, e); }finally { RhinoEngine.exitContext(); } }</code><technical_language>Remove this blank line</technical_language>

Target:
private void initModule(InputStream modulesXML, boolean isCustom) throws ScriptException { try { Context cx = RhinoEngine.enterGlobalContext(); JAXBContext jaxbContext = JAXBContext.newInstance(Module.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Module moduleObject = (Module) jaxbUnmarshaller.unmarshal(modulesXML); String moduleName = moduleObject.getName(); if (modules.get(moduleName) != null) { log.info("A module with the name : " + moduleName + " already exists and it will be overwritten."); } String namespace = moduleObject.getNamespace(); boolean expose = (Boolean.parseBoolean(moduleObject.getExpose()) == true); JavaScriptModule module = new JavaScriptModule(moduleName); module.setNamespace(namespace); module.setExpose(expose); initHostObjects(moduleObject, module); initMethods(moduleObject, module); initScripts(moduleObject, cx, module, isCustom); modules.put(moduleName, module); } catch (JAXBException e) { String msg = "Error while reading the module.xml"; log.error(msg, e); throw new ScriptException(msg, e); } finally { RhinoEngine.exitContext(); } }
Source:
<code>private UserConfig(Config rc) { authorName = getNameInternal(rc, Constants.GIT_AUTHOR_NAME_KEY); if (authorName == null) { authorName = getDefaultUserName(); isAuthorNameImplicit = true; } authorEmail = getEmailInternal(rc, Constants.GIT_AUTHOR_EMAIL_KEY); if (authorEmail == null) { authorEmail = getDefaultEmail(); isAuthorEmailImplicit = true; } committerName = getNameInternal(rc, Constants.GIT_COMMITTER_NAME_KEY); if (committerName == null) { committerName = getDefaultUserName(); isCommitterNameImplicit = true; } committerEmail = getEmailInternal(rc, Constants.GIT_COMMITTER_EMAIL_KEY); if (committerEmail == null) { committerEmail = getDefaultEmail(); isCommitterEmailImplicit = true; } <START> commitTemplatePath = getCommitTemplatePathInternal(rc, <END> Constants.GIT_COMMIT_TEMPLATE_KEY); }</code><technical_language>This class captures options in config section "user" this is wrong class for handling option "commit.template"</technical_language>

Target:
private UserConfig(Config rc) { authorName = getNameInternal(rc, Constants.GIT_AUTHOR_NAME_KEY); if (authorName == null) { authorName = getDefaultUserName(); isAuthorNameImplicit = true; } authorEmail = getEmailInternal(rc, Constants.GIT_AUTHOR_EMAIL_KEY); if (authorEmail == null) { authorEmail = getDefaultEmail(); isAuthorEmailImplicit = true; } committerName = getNameInternal(rc, Constants.GIT_COMMITTER_NAME_KEY); if (committerName == null) { committerName = getDefaultUserName(); isCommitterNameImplicit = true; } committerEmail = getEmailInternal(rc, Constants.GIT_COMMITTER_EMAIL_KEY); if (committerEmail == null) { committerEmail = getDefaultEmail(); isCommitterEmailImplicit = true; } }
Source:
<code>public void verifyTestContent(XdEnvironment hosts, URL url, String fileName, String data) throws IOException { if (hosts.isOnEc2()) { StreamUtils.transferResultsToLocal(hosts, url, fileName); } <START> BufferedReader reader = new BufferedReader(new FileReader(fileName)); <END> char cbuf[] = new char[15]; String result = ""; while (reader.ready()) { int size = reader.read(cbuf); result += String.valueOf(cbuf,0, size); } if (!result.equals(data+"\n")) { reader.close(); throw new ResourceAccessException( "Data in the result file is not what was sent. Read " + result + "\n but expected " + data); } reader.close(); }</code><technical_language>Reader fileReader = new InputStreamReader(new FileInputStream(file), charset); String dataInFile = FileCopyUtils.copyToString(fileReader);</technical_language>

Target:
public void verifyTestContent(XdEnvironment hosts, URL url, String fileName, String data) throws IOException { if (hosts.isOnEc2()) { StreamUtils.transferResultsToLocal(hosts, url, fileName); } Reader fileReader = new InputStreamReader(new FileInputStream(fileName)); String result = FileCopyUtils.copyToString(fileReader); if (!result.equals(data + "\n")) { fileReader.close(); throw new ResourceAccessException( "Data in the result file is not what was sent. Read " + result + "\n but expected " + data); } fileReader.close(); }
Source:
<code>public void testImportInvalidAsset() throws Exception { final int nextNodeId = m_nodeDao.getNextNodeId(); assertEquals(0, m_nodeDao.countAll()); final Resource invalidAssetFieldResource = getResource("classpath:/import_invalidAssetFieldName.xml"); m_eventManager.getEventAnticipator().anticipateEvent(getStarted(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getSuccessful(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeAdded(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedInterface(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedService(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanCompleted(nextNodeId)); m_provisioner.doImport(invalidAssetFieldResource.getURL().toString(), Boolean.TRUE.toString()); waitForEverything(); <START> m_eventManager.getEventAnticipator().verifyAnticipated(); <END> assertEquals(1, m_nodeDao.countAll()); OnmsNode node = m_nodeDao.get(m_nodeDao.getNodeIds().iterator().next()); assertEquals("yellow human", node.getAssetRecord().getDescription()); assertNull(node.getAssetRecord().getPollerCategory()); }</code><technical_language>Unnecessary change</technical_language>

Target:
public void testImportInvalidAsset() throws Exception { final int nextNodeId = m_nodeDao.getNextNodeId(); assertEquals(0, m_nodeDao.countAll()); final Resource invalidAssetFieldResource = getResource("classpath:/import_invalidAssetFieldName.xml"); m_eventManager.getEventAnticipator().anticipateEvent(getStarted(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getSuccessful(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeAdded(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanStarted(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedInterface(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedService(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanCompleted(nextNodeId)); m_provisioner.doImport(invalidAssetFieldResource.getURL().toString(), Boolean.TRUE.toString()); waitForEverything(); m_eventManager.getEventAnticipator().verifyAnticipated(); assertEquals(1, m_nodeDao.countAll()); OnmsNode node = m_nodeDao.get(m_nodeDao.getNodeIds().iterator().next()); assertEquals("yellow human", node.getAssetRecord().getDescription()); assertNull(node.getAssetRecord().getPollerCategory()); }
Source:
<code>protected boolean doSend(Message<?> message, long timeout) { blockGenerator.addDataWithCallback(message.getPayload(), message.getHeaders()); <START> headersList.add(message.getHeaders()); <END> return true; }</code><technical_language>This a race condition - get callback add headers. if swap statements, consider concurrency; thread puts header in first, while initiates push. synchronize this entire method</technical_language>

Target:
protected synchronized boolean doSend(Message<?> message, long timeout) { try { headersList.put(message.getHeaders()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } blockGenerator.addDataWithCallback(message.getPayload(), message.getHeaders()); return true; }
Source:
<code>public String onnxName() { <START> return "Erf"; <END> }</code><technical_language>for onnx equivalents: <LINK_0> If exist throw exception</technical_language>

Target:
public String onnxName() { throw new NoOpNameFoundException("No onnx op opName found for " + opName()); }
Source:
<code>public void run() { if (!processing.isEmpty()) { String files = processing .stream() .map(AsyncFileEntry::getName) <START> .collect(Collectors.toList()) <END> .toString(); LOGGER.debug("{} files being processed: {}", processing.size(), files); } }</code><technical_language>Please create a temp collection get a string representation of it. collectors for streams do directly</technical_language>

Target:
public void run() { if (LOGGER.isDebugEnabled() && !processing.isEmpty()) { String files = processing.stream().map(AsyncFileEntry::getName).collect(Collectors.joining(", ")); LOGGER.debug("{} files being processed: {}", processing.size(), files); } }
Source:
<code>private void stopBuild(final Run build, final String jobName) throws IOException, ServletException { final String buildName = build.getDisplayName(); Executor executor = build.getExecutor(); if (executor != null) { isAnyBuildStopped = true; executor.doStop(); stdout.println(String.format("Build %s stopped for job '%s';", buildName, jobName)); } else { <START> stdout.println(String.format("Build %s in job %s not stopped", buildName, jobName)); <END> } }</code><technical_language>do some lines of output semicolons end others don't</technical_language>

Target:
private void stopBuild(final Run build, final String jobName) { final String buildName = build.getDisplayName(); Executor executor = build.getExecutor(); if (executor != null) { try { executor.doStop(); isAnyBuildStopped = true; stdout.println(String.format("Build '%s' stopped for job '%s'", buildName, jobName)); } catch (final Exception e) { stdout.print(String.format("Exception occurred while trying to stop build '%s' for job '%s'. ", buildName, jobName)); stdout.println(String.format("Exception class: %s, message: %s", e.getClass().getSimpleName(), e.getMessage())); } } else { stdout.println(String.format("Build '%s' in job '%s' not stopped", buildName, jobName)); } }
Source:
<code><START> public ListenableFuture<ControllerResult> sendCustomCommand(@NonNull SessionCommand2 command, @Nullable Bundle args) { <END> synchronized (mLock) { if (!mConnected) { Log.w(TAG, "Session isn't active", new IllegalStateException()); return createFutureWithResult(RESULT_CODE_DISCONNECTED); } final ResolvableFuture<ControllerResult> result = ResolvableFuture.create(); ResultReceiver cb = new ResultReceiver(mHandler) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { result.set(new ControllerResult(resultCode, resultData)); } }; mControllerCompat.sendCommand(command.getCustomCommand(), args, cb); return result; } }</code><technical_language>If controller2 allowed commands PlaybackStateCompat.CustomAction, I guess controller2 users call MediaController2.sendCustomCommand() commands, eventually call MediaControllerCompat.sendCustomCommand() (As in L589). However, PlaybackStateCompat.CustomAction is expected MediaControllerCompat.TransportControls.sendCustomAction(), sendCustomCommand. session prepared for custom actions in onCustomCommand(). I need distinguish two: 1) 'Real' custom commands -> MediaControllerCompat.sendCommand() 2) Custom commands PlaybackState.CustomAction -> MediaControllerCompat.TransportControls.sendCustomAction()</technical_language>

Target:
public ListenableFuture<ControllerResult> sendCustomCommand(@NonNull SessionCommand2 command, @Nullable Bundle args) { synchronized (mLock) { if (!mConnected) { Log.w(TAG, "Session isn't active", new IllegalStateException()); return createFutureWithResult(RESULT_CODE_DISCONNECTED); } if (mAllowedCommands.hasCommand(command)) { mControllerCompat.getTransportControls().sendCustomAction( command.getCustomCommand(), args); return createFutureWithResult(RESULT_CODE_SUCCESS); } final ResolvableFuture<ControllerResult> result = ResolvableFuture.create(); ResultReceiver cb = new ResultReceiver(mHandler) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { result.set(new ControllerResult(resultCode, resultData)); } }; mControllerCompat.sendCommand(command.getCustomCommand(), args, cb); return result; } }
Source:
<code>void addLocationIdValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap, final Map<Integer, StudyInstance> selectedDatasetInstancesMap) { for(final Integer instanceId: observationUnitRowMap.keySet()) { final ObservationUnitData locationIdData = new ObservationUnitData(); locationIdData.setValue(selectedDatasetInstancesMap.get(instanceId).getLocationId().toString()); observationUnitRowMap.get(instanceId).forEach(row -> { row.getVariables().put(LOCATION_ID_VARIABLE_NAME, locationIdData); }); <START> } <END> }</code><technical_language>@gelli-leafnode - I delete StudyDataManager#getInstanceIdLocationIdMap method in Middleware rendered unused anymore</technical_language>

Target:
void addLocationIdValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap, final Map<Integer, StudyInstance> selectedDatasetInstancesMap) { for(final Integer instanceId: observationUnitRowMap.keySet()) { final ObservationUnitData locationIdData = new ObservationUnitData(); locationIdData.setValue(selectedDatasetInstancesMap.get(instanceId).getLocationId().toString()); observationUnitRowMap.get(instanceId).forEach(row -> row.getVariables().put(LOCATION_ID_VARIABLE_NAME, locationIdData)); } }
Source:
<code>public void write(DataOutput out) throws IOException { if (conf == null) { throw new IOException("Hadoop Configuration not set via setConf"); } WritableUtils.writeVInt(out, splits.size()); for (InputSplit split : splits) { Class<? extends InputSplit> clazz = split.getClass(); Text.writeString(out, clazz.getName()); SerializationFactory factory = new SerializationFactory(conf); Serializer serializer = factory.getSerializer(clazz); serializer.open((DataOutputStream)out); <START> serializer.serialize(split); <END> } }</code><technical_language>factor out this code block? is code in DeprecatedInputFormatWrapper</technical_language>

Target:
public void write(DataOutput out) throws IOException { if (conf == null) { throw new IOException("Hadoop Configuration not set via setConf"); } WritableUtils.writeVInt(out, splits.size()); for (InputSplit split : splits) { SplitUtil.serializeInputSplit(conf, (DataOutputStream) out, split); } }
Source:
<code>private void createPageTitle(Record.Page page) { HashMap<String, Object> attributes = new HashMap<>(); attributes.put("label", page.getDescription()); attributes.put("name", page.getDescription()); attributes.put("showLabel", true); <START> attributes.put("type", TEXT.getValue()); <END> attributes.put("dataType", STRING.getValue()); attributes.put("readOnly", true); StringField titlePage = new StringField(attributes, LiferayLocale.getDefaultLocale(), LiferayLocale.getDefaultLocale()); addFieldView(titlePage, 0); }</code><technical_language>ok, :) I understand</technical_language>

Target:
private void createPageTitle(Record.Page page) { HashMap<String, Object> attributes = new HashMap<>(); attributes.put("label", page.getDescription()); attributes.put("name", page.getDescription()); attributes.put("showLabel", true); attributes.put("type", Field.EditorType.TEXT.getValue()); attributes.put("dataType", Field.DataType.STRING.getValue()); attributes.put("readOnly", true); StringField titlePage = new StringField(attributes, LiferayLocale.getDefaultLocale(), LiferayLocale.getDefaultLocale()); addFieldView(titlePage, 0); }
Source:
<code>public void cannotPerformTimestampManagementWithoutQuorum() { assertThatThrownBy(() -> getTimestampManagementService(CLIENT).fastForwardTimestamp(1000L)) <START> .satisfies(IsolatedPaxosTimeLockServerIntegrationTest::isRetryableExceptionWhereLeaderCannotBeFound); <END> }</code><technical_language>this instance method this::</technical_language>

Target:
public void cannotPerformTimestampManagementWithoutQuorum() { assertThatThrownBy(() -> getTimestampManagementService(CLIENT).fastForwardTimestamp(1000L)) .satisfies(this::isRetryableExceptionWhereLeaderCannotBeFound); }
Source:
<code>private boolean confirmClose(BasePanel panel) { String filename = panel.getBibDatabaseContext() .getDatabasePath() .map(Path::toAbsolutePath) .map(Path::toString) .orElse(GUIGlobals.UNTITLED_TITLE); ButtonType saveChanges = new ButtonType(Localization.lang("Save changes"), ButtonBar.ButtonData.YES); ButtonType discardChanges = new ButtonType(Localization.lang("Discard changes"), ButtonBar.ButtonData.NO); ButtonType cancel = new ButtonType(Localization.lang("Return to JabRef"), ButtonBar.ButtonData.CANCEL_CLOSE); Optional<ButtonType> response = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.CONFIRMATION, Localization.lang("Save before closing"), Localization.lang("Library '%0' has changed.", filename), saveChanges, discardChanges, cancel); if (response.isPresent() && response.get().equals(saveChanges)) { try { SaveDatabaseAction saveAction = new SaveDatabaseAction(panel, Globals.prefs); if (saveAction.save()) { return true; } output(Localization.lang("Unable to save library")); } catch (Throwable ex) { LOGGER.error("A problem occurred when saving the file", ex); } } <START> return !response.isPresent() || !response.get().equals(cancel); <END> }</code><technical_language>is sufficient return simply false, do check first. user click save cancel</technical_language>

Target:
private boolean confirmClose(BasePanel panel) { String filename = panel.getBibDatabaseContext() .getDatabasePath() .map(Path::toAbsolutePath) .map(Path::toString) .orElse(GUIGlobals.UNTITLED_TITLE); ButtonType saveChanges = new ButtonType(Localization.lang("Save changes"), ButtonBar.ButtonData.YES); ButtonType discardChanges = new ButtonType(Localization.lang("Discard changes"), ButtonBar.ButtonData.NO); ButtonType cancel = new ButtonType(Localization.lang("Return to JabRef"), ButtonBar.ButtonData.CANCEL_CLOSE); Optional<ButtonType> response = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.CONFIRMATION, Localization.lang("Save before closing"), Localization.lang("Library '%0' has changed.", filename), saveChanges, discardChanges, cancel); if (response.isPresent() && response.get().equals(saveChanges)) { try { SaveDatabaseAction saveAction = new SaveDatabaseAction(panel, Globals.prefs); if (saveAction.save()) { return true; } output(Localization.lang("Unable to save library")); } catch (Throwable ex) { LOGGER.error("A problem occurred when trying to save the file", ex); dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); } return false; } return !response.isPresent() || !response.get().equals(cancel); }
Source:
<code>private void disposeTextures() { for (Scene scene : project.getSceneList()) { List<Sprite> sprites = scene.getSpriteList(); for (Sprite sprite : sprites) { List<LookData> lookDatas = sprite.getLookDataList(); int lookDatasSize = lookDatas.size(); <START> for (int j = 0; j < lookDatasSize; j++) { <END> LookData lookData = lookDatas.get(j); lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }</code><technical_language>Improve lookDatas loop for-each. Inline variables. is need declare List<?></technical_language>

Target:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { for (LookData lookData : sprite.getLookDataList()) { lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }
Source:
<code>public Intent createCaptureIntent(final Context context) { deleteTemporaryFile(); try { outputFile = File.createTempFile( "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + "_", ".jpg", context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) ); } catch (IOException e) { throw new RuntimeException(e); } <START> if (Build.VERSION.SDK_INT >= 24) { <END> outputFileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", outputFile); } else { outputFileUri = Uri.fromFile(outputFile); } final Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1); intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); return intent; }</code><technical_language>Build.VERSION_CODES.N instead of 24</technical_language>

Target:
public Intent createCaptureIntent(final Context context) { deleteTemporaryFile(); try { outputFile = File.createTempFile( "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + "_", ".jpg", context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) ); } catch (IOException e) { throw new RuntimeException(e); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { outputFileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", outputFile); } else { outputFileUri = Uri.fromFile(outputFile); } final Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1); intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); return intent; }
Source:
<code><START> private SAMSequenceDictionary getActiveDictionary(final HaplotypeMap haplotypes){ <END> final SAMSequenceDictionary origSequenceDictionary = haplotypes.getHeader().getSequenceDictionary(); final OptionalInt maxSequenceIndex = haplotypes.getAllSnps().stream() .map(Snp::getChrom) .mapToInt(origSequenceDictionary::getSequenceIndex) .max(); if (!maxSequenceIndex.isPresent()) { return origSequenceDictionary; } return new SAMSequenceDictionary(origSequenceDictionary.getSequences().subList(0, maxSequenceIndex.getAsInt() + 1)); }</code><technical_language>whitespace, this static? suggestion private SAMSequenceDictionary getActiveDictionary(final HaplotypeMap haplotypes) {</technical_language>

Target:
private static SAMSequenceDictionary getActiveDictionary(final HaplotypeMap haplotypes) { final SAMSequenceDictionary origSequenceDictionary = haplotypes.getHeader().getSequenceDictionary(); final OptionalInt maxSequenceIndex = haplotypes.getAllSnps().stream() .map(Snp::getChrom) .mapToInt(origSequenceDictionary::getSequenceIndex) .max(); if (!maxSequenceIndex.isPresent()) { return origSequenceDictionary; } return new SAMSequenceDictionary(origSequenceDictionary.getSequences().subList(0, maxSequenceIndex.getAsInt() + 1)); }
Source:
<code>protected void proceedProxyReturnValue() { try { super.proceedProxyReturnValue(); } catch (VDSNetworkException ignored) { <START> } <END> }</code><technical_language>I log this exception in debug</technical_language>

Target:
protected void proceedProxyReturnValue() { try { super.proceedProxyReturnValue(); } catch (VDSNetworkException ignored) { log.debug("VDSNetworkException was caught and ignored", ignored); } }
Source:
<code>public ModelAndView resolve(final JEEContext ctx, final ProfileManager manager, final String url) { val prompt = OidcAuthorizationRequestSupport.getOidcPromptFromAuthorizationRequest(url); if (prompt.contains(OidcConstants.PROMPT_NONE)) { val result = manager.get(true); if (result.isPresent()) { LOGGER.trace("Redirecting to URL without prompting for login", url); return new ModelAndView(url); } val originalRedirectUrl = ctx.getRequestParameter(OAuth20Constants.REDIRECT_URI); if (originalRedirectUrl.isEmpty()) { val model = new HashMap<String, String>(); model.put(OAuth20Constants.ERROR, OidcConstants.LOGIN_REQUIRED); return new ModelAndView(new MappingJackson2JsonView(), model); <START> } else { <END> LOGGER.warn("Unable to detect an authenticated user profile for prompt-less login attempts. Redirecting to URL[{}]", originalRedirectUrl.get()); return new ModelAndView(new RedirectView(OidcAuthorizationRequestSupport.getRedirectUrlWithError(originalRedirectUrl.get(), OidcConstants.LOGIN_REQUIRED))); } } if (prompt.contains(OidcConstants.PROMPT_LOGIN)) { LOGGER.trace("Removing login prompt from URL [{}]", url); val newUrl = OidcAuthorizationRequestSupport.removeOidcPromptFromAuthorizationRequest(url, OidcConstants.PROMPT_LOGIN); LOGGER.trace("Redirecting to URL [{}]", newUrl); return new ModelAndView(new RedirectView(newUrl)); } LOGGER.trace("Redirecting to URL [{}]", url); return new ModelAndView(new RedirectView(url)); }</code><technical_language>Minor styling change: please re-adjust <LINK_0></technical_language>

Target:
public ModelAndView resolve(final JEEContext ctx, final ProfileManager manager, final String url) { val prompt = OidcAuthorizationRequestSupport.getOidcPromptFromAuthorizationRequest(url); if (prompt.contains(OidcConstants.PROMPT_NONE)) { val result = manager.get(true); if (result.isPresent()) { LOGGER.trace("Redirecting to URL without prompting for login", url); return new ModelAndView(url); } val originalRedirectUrl = ctx.getRequestParameter(OAuth20Constants.REDIRECT_URI); if (originalRedirectUrl.isEmpty()) { val model = new HashMap<String, String>(); model.put(OAuth20Constants.ERROR, OidcConstants.LOGIN_REQUIRED); return new ModelAndView(new MappingJackson2JsonView(), model); } val redirectUrlWithErrorCode = OidcAuthorizationRequestSupport.getRedirectUrlWithError(originalRedirectUrl.get(), OidcConstants.LOGIN_REQUIRED); LOGGER.warn("Unable to detect an authenticated user profile for prompt-less login attempts. Redirecting to URL [{}]", redirectUrlWithErrorCode); return new ModelAndView(new RedirectView(redirectUrlWithErrorCode)); } if (prompt.contains(OidcConstants.PROMPT_LOGIN)) { LOGGER.trace("Removing login prompt from URL [{}]", url); val newUrl = OidcAuthorizationRequestSupport.removeOidcPromptFromAuthorizationRequest(url, OidcConstants.PROMPT_LOGIN); LOGGER.trace("Redirecting to URL [{}]", newUrl); return new ModelAndView(new RedirectView(newUrl)); } LOGGER.trace("Redirecting to URL [{}]", url); return new ModelAndView(new RedirectView(url)); }
Source:
<code>private void commitDelete(AsyncFileEntry entry, boolean success) { LOGGER.trace("commitDelete({},{}): Starting...", entry.getName(), success); if (success) { entry.getParent().ifPresent(e -> e.removeChild(entry)); entry.destroy(); LOGGER.debug( "{} was removed from {}", entry.getName(), entry.getParent().map(AsyncFileEntry::getName).orElse("parent")); } else { LOGGER.debug("Delete task failed for {}", entry.getName()); } <START> onFinish(entry); <END> }</code><technical_language>onFinish() called in a finally clause ensure properly cleanup</technical_language>

Target:
private void commitDelete(AsyncFileEntry entry, boolean success) { LOGGER.trace("commitDelete({},{}): Starting...", entry.getName(), success); try { if (success) { entry.getParent().ifPresent(e -> e.removeChild(entry)); entry.destroy(); LOGGER.debug( "{} was removed from {}", entry.getName(), entry.getParent().map(AsyncFileEntry::getName).orElse("parent")); } else { LOGGER.debug("Delete task failed for {}", entry.getName()); } } finally { onFinish(entry); } }
Source:
<code>public void addItem(final ShoppingCartItem item) { <START> ShoppingCartItem existingItemOfSameType = Iterables.find(items, new Predicate<ShoppingCartItem>() { <END> @Override public boolean apply(ShoppingCartItem shoppingCartItem) { return shoppingCartItem.equals(item); } }, null); if (existingItemOfSameType != null) { existingItemOfSameType.addMore(item.getQuantity()); ShoppingCartQuantityChangeEvent.fire(this, existingItemOfSameType, existingItemOfSameType.getQuantity()); } else { items.add(item); ShoppingCartChangedEvent.fire(item, this); } }</code><technical_language>change Iterables.tryFind(items, predicate).orNull(), more verbose</technical_language>

Target:
public void addItem(final ShoppingCartItem item) { ShoppingCartItem existingItemOfSameType = Iterables.tryFind(items, new Predicate<ShoppingCartItem>() { @Override public boolean apply(ShoppingCartItem shoppingCartItem) { return shoppingCartItem.equals(item); } }).orNull(); if (existingItemOfSameType != null) { existingItemOfSameType.addMore(item.getQuantity()); ShoppingCartQuantityChangeEvent.fire(this, existingItemOfSameType, existingItemOfSameType.getQuantity()); } else { items.add(item); ShoppingCartChangedEvent.fire(item, this); } }
Source:
<code>public static <T> T createModel(Class<T> model, List<OpenEngSBModelEntry> entries) { checkIfClassIsModel(model); try { T instance = model.newInstance(); for (OpenEngSBModelEntry entry : entries) { <START> if (!tryToSetValueThroughField(entry, instance) && !tryToSetValueThroughSetter(entry, instance)) { <END> ((OpenEngSBModel) instance).addOpenEngSBModelEntry(entry); } } return instance; } catch (InstantiationException e) { LOGGER.error("InstantiationException while creating a new model instance.", e); } catch (IllegalAccessException e) { LOGGER.error("IllegalAccessException while creating a new model instance.", e); } catch (SecurityException e) { LOGGER.error("SecurityException while creating a new model instance.", e); } return null; }</code><technical_language>This line is confusing imho</technical_language>

Target:
public static <T> T createModel(Class<T> model, List<OpenEngSBModelEntry> entries) { checkIfClassIsModel(model); try { T instance = model.newInstance(); for (OpenEngSBModelEntry entry : entries) { if (tryToSetValueThroughField(entry, instance)) { continue; } if (tryToSetValueThroughSetter(entry, instance)) { continue; } ((OpenEngSBModel) instance).addOpenEngSBModelEntry(entry); } return instance; } catch (InstantiationException e) { LOGGER.error("InstantiationException while creating a new model instance.", e); } catch (IllegalAccessException e) { LOGGER.error("IllegalAccessException while creating a new model instance.", e); } catch (SecurityException e) { LOGGER.error("SecurityException while creating a new model instance.", e); } return null; }
Source:
<code>public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("favouriteColour","blue"); <START> List<Integer> primes = new ArrayList<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17)); <END> ctx.setVariable("primes",primes); Expression expr = parser.parseRaw("#favouriteColour"); Object value = expr.getValue(ctx); assertThat(value).isEqualTo("blue"); expr = parser.parseRaw("#primes.get(1)"); value = expr.getValue(ctx); assertThat(value).isEqualTo(3); expr = parser.parseRaw("#primes.?[#this>10]"); value = expr.getValue(ctx); assertThat(value.toString()).isEqualTo("[11, 13, 17]"); }</code><technical_language>need create lists in this context. suggestion List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17);</technical_language>

Target:
public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("favouriteColour","blue"); List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17); ctx.setVariable("primes",primes); Expression expr = parser.parseRaw("#favouriteColour"); Object value = expr.getValue(ctx); assertThat(value).isEqualTo("blue"); expr = parser.parseRaw("#primes.get(1)"); value = expr.getValue(ctx); assertThat(value).isEqualTo(3); expr = parser.parseRaw("#primes.?[#this>10]"); value = expr.getValue(ctx); assertThat(value.toString()).isEqualTo("[11, 13, 17]"); }
Source:
<code>public long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType) { List<PhysicalNetworkVO> pNtwks = new ArrayList<PhysicalNetworkVO>(); if (trafficType != null) { pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); } else { pNtwks = _physicalNetworkDao.listByZone(zoneId); } if (pNtwks.isEmpty()) { throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); } if (pNtwks.size() > 1) { Long pNtwkId = null; for (PhysicalNetwork pNtwk : pNtwks) { <START> if (pNtwk.getTags().isEmpty() && tag == null) { s_logger.debug("Found physical network id=" + pNtwk.getId() + " with null tag"); if (pNtwkId != null) { throw new CloudRuntimeException("There is more than 1 physical network with empty tag in the zone id=" + zoneId); } pNtwkId = pNtwk.getId(); } <END> if (pNtwk.getTags().contains(tag)) { s_logger.debug("Found physical network id=" + pNtwk.getId() + " based on requested tags " + tag); pNtwkId = pNtwk.getId(); break; } } if (pNtwkId == null) { throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag); } return pNtwkId; } else { return pNtwks.get(0).getId(); } }</code><technical_language>method call</technical_language>

Target:
public long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType) { return _networkModel.findPhysicalNetworkId(zoneId, tag, trafficType); }
Source:
<code>protected String getExpectedUsage() { return "logicalpull <setup> [--debug (-d)] [--git-dir gitFolderPath] [--help (-h)] [--show-stack-trace]" + EOL + EOL +" <setup> : Path to the setup file. The setup file is a Oomph" + EOL +" model." + EOL <START> +" --debug (-d) : Launched the provisionned eclipse in debug mode."+ EOL <END> +" --git-dir gitFolderPath : Path to the .git folder of your repository." + EOL +" --help (-h) : Dispays help for this command." + EOL +" --show-stack-trace : Use this option to display java stack trace in" + EOL +" console on error." + EOL +EOL; }</code><technical_language>Launched -> Launches ? ( is mistake in previous command)</technical_language>

Target:
protected String getExpectedUsage() { return "logicalpull <setup> [--debug (-d)] [--git-dir gitFolderPath] [--help (-h)] [--show-stack-trace]" + EOL + EOL +" <setup> : Path to the setup file. The setup file is a Oomph" + EOL +" model." + EOL +" --debug (-d) : Launches the provisionned eclipse in debug mode."+ EOL +" --git-dir gitFolderPath : Path to the .git folder of your repository." + EOL +" --help (-h) : Dispays help for this command." + EOL +" --show-stack-trace : Use this option to display java stack trace in" + EOL +" console on error." + EOL +EOL; }
Source:
<code>public LimitedSet<Integer> createLimitSet(Integer limit, SearchHit[]... pages){ final LimitedSet<Integer> limitedSet = new LimitedSet<>(new HashSet<>(), limit != null); Stream<SearchHit> stream = Arrays.stream(pages) .map(Arrays::stream) .reduce(Stream.empty(), Stream::concat); if (limit!=null){ stream = stream.limit(limit); } stream.map(Object::hashCode) <START> .forEach(limitedSet.getSet()::add); <END> return limitedSet; }</code><technical_language>Containers generally designed immutable. I consider a safe assumption set returned this getter is necessarily (it now) is mutable. build HashSet first, constructing a LimitedSet out of that</technical_language>

Target:
public LimitedSet<SearchHit> createLimitSet(Integer limit, SearchHit[]... pages){ Set<SearchHit> set = new HashSet<>(); Stream<SearchHit> stream = Arrays.stream(pages) .map(Arrays::stream) .reduce(Stream.empty(), Stream::concat); if (limit!=null){ stream = stream.limit(limit); } stream.map(Function.identity()) .forEach(set::add); return new LimitedSet<>(set, limit != null); }
Source:
<code><START> private boolean isValueOfInvocation(AbstractTypedTree abstractTypedTree) { <END> if (!abstractTypedTree.is(Kind.METHOD_INVOCATION)) { return false; } MethodInvocationTreeImpl methodInvocationTreeImpl = (MethodInvocationTreeImpl) abstractTypedTree; AbstractTypedTree firstArgument = (AbstractTypedTree) methodInvocationTreeImpl.arguments().get(0); return "valueOf".equals((methodInvocationTreeImpl).getSymbol().getName()) && firstArgument.getSymbolType().isPrimitive(); }</code><technical_language>reuse MethodInvocationMatcher class, matches method</technical_language>

Target:
private boolean isValueOfInvocation(AbstractTypedTree abstractTypedTree) { if (!abstractTypedTree.is(Kind.METHOD_INVOCATION)) { return false; } Type type = abstractTypedTree.getSymbolType(); MethodInvocationMatcher valueOfMatcher = MethodInvocationMatcher.create() .typeDefinition(type.getSymbol().getFullyQualifiedName()) .name("valueOf") .addParameter(type.primitiveType().getSymbol().getFullyQualifiedName()); return valueOfMatcher.matches((MethodInvocationTree) abstractTypedTree, getSemanticModel()); }
Source:
<code>public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); ObjectHelper.requireNonNull(onComplete, "onComplete is null"); <START> return subscribe(onComplete, onError, Functions.emptyConsumer()); <END> }</code><technical_language>need for null checks delegate a common method</technical_language>

Target:
public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { return subscribe(onComplete, onError, Functions.emptyConsumer()); }
Source:
<code>private UnitedServerListenerManager() { list = new ArrayList<UnitedServerListener>(); <START> new Thread() { <END> public void run() { initializeManager(); } }.start(); }</code><technical_language>this</technical_language>

Target:
private UnitedServerListenerManager() { list = new CopyOnWriteArrayList<UnitedServerListener>(); new Thread() { public void run() { initializeManager(); } }.start(); }