auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method == null) { return invocation.proceed(); } Method mostSpecificMethod = AopUtils <START> .getMostSpecificMethod(invocation.getMethod(), invocation.getThis().getClass()); <END> NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, NewSpan.class); ContinueSpan continueSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, ContinueSpan.class); if (newSpan == null && continueSpan == null) { return invocation.proceed(); } Class<?> returnType = method.getReturnType(); if(isReactiveReturnType(returnType)){ return proceedUnderSpanReactively(invocation, newSpan, continueSpan); } else { return proceedUnderSpanSynchronously(invocation, newSpan, continueSpan); } }</code><technical_language>revert I this effectively is earlier right</technical_language>

Target:
public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method == null) { return invocation.proceed(); } Method mostSpecificMethod = AopUtils .getMostSpecificMethod(method, invocation.getThis().getClass()); NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, NewSpan.class); ContinueSpan continueSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, ContinueSpan.class); if (newSpan == null && continueSpan == null) { return invocation.proceed(); } if(isReactorReturnType(method.getReturnType())){ return proceedUnderReactorSpan(invocation, newSpan, continueSpan); } else { return proceedUnderSynchronousSpan(invocation, newSpan, continueSpan); } }
Source:
<code>private boolean validateServerURL(String userUrl) { <START> if (userUrl == null || userUrl.trim().length() == 0) { <END> EditTextPreference preference = (EditTextPreference) findPreference(KEY_URL); preference.setText(getString(R.string.settings_url_default_value)); return false; } int port = Uri.parse(userUrl).getPort(); if (URLUtil.isValidUrl(userUrl) && (port >= -1 && port <= 65535) && (URLUtil.isHttpUrl(userUrl) || URLUtil.isHttpsUrl(userUrl))) { return true; } Toast.makeText(MainActivity.this, R.string.error_msg_invalid_url, Toast.LENGTH_LONG).show(); return false; }</code><technical_language>do reset default one</technical_language>

Target:
private boolean validateServerURL(String userUrl) { int port = Uri.parse(userUrl).getPort(); if (URLUtil.isValidUrl(userUrl) && (port == -1 || (port > 0 && port <= 65535)) && (URLUtil.isHttpUrl(userUrl) || URLUtil.isHttpsUrl(userUrl))) { return true; } Toast.makeText(MainActivity.this, R.string.error_msg_invalid_url, Toast.LENGTH_LONG).show(); return false; }
Source:
<code>public void run() { System.out.println("Running DownloadMediaUseCase"); final List<Media> currentMedias = mMediaRepository.getAll(); if (mConnectivityManager.isDeviceOnline()) { if(mFileDownloader.isFileDownloaderIProgress()) { System.out.println("File downloader is already downloading"); return; } mFileDownloader.download(currentMedias, PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getCode(), new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); mFileDownloader.changeFileDownloaderIProgress(false); } @Override public void onProgress() { <START> mCallback.onProgress(); <END> } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); removeNotDownloadedMedia(syncMedias, currentMedias); mCallback.onSuccess(numOfSyncedFiles); mFileDownloader.changeFileDownloaderIProgress(false); } }); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); mFileDownloader.changeFileDownloaderIProgress(false); } }</code><technical_language>callback invocations executed in main thread MainExecutor other cases</technical_language>

Target:
public void run() { System.out.println("Running DownloadMediaUseCase"); final List<Media> currentMedias = mMediaRepository.getAll(); if (mConnectivityManager.isDeviceOnline()) { if(mFileDownloader.isFileDownloaderIProgress()) { System.out.println("File downloader is already downloading"); return; } mCallback.onDownloadInProgressChanged(true); mFileDownloader.changeFileDownloaderIProgress(true); mFileDownloader.download(currentMedias, PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getCode(), new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); mFileDownloader.changeFileDownloaderIProgress(false); mCallback.onDownloadInProgressChanged(false); } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); removeNotDownloadedMedia(syncMedias, currentMedias); mCallback.onSuccess(numOfSyncedFiles); mFileDownloader.changeFileDownloaderIProgress(false); mCallback.onDownloadInProgressChanged(false); } }); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); mFileDownloader.changeFileDownloaderIProgress(false); } }
Source:
<code>private Request makeCreateRequest(String path, long sessionId) throws IOException { ByteArrayOutputStream boas = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas); CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag()); createRequest.serialize(boa, "request"); ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray()); <START> return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<>()); <END> }</code><technical_language>(new ArrayList<>)</technical_language>

Target:
private Request makeCreateRequest(String path, long sessionId) throws IOException { ByteArrayOutputStream boas = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas); CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag()); createRequest.serialize(boa, "request"); ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray()); return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>()); }
Source:
<code>public void close() throws IOException { innerScanner.close(); if (verify) { try { verificationResultRepository.logToIndexToolResultTable(verificationResult, verifyType, region.getRegionInfo().getRegionName()); } finally { this.pool.stop("IndexerRegionScanner is closing"); <START> hTableFactory.shutdown(); <END> indexHTable.close(); verificationResultRepository.close(); } } }</code><technical_language>This method check max lookback window update max lookback counters</technical_language>

Target:
public void close() throws IOException { innerScanner.close(); try { verificationResultRepository.logToIndexToolResultTable(verificationResult, IndexTool.IndexVerifyType.ONLY, region.getRegionInfo().getRegionName()); } finally { this.pool.stop("IndexerRegionScanner is closing"); hTableFactory.shutdown(); indexHTable.close(); verificationResultRepository.close(); } }
Source:
<code>public void exportMesh( final AtlasSourceState< ?, ? > state, final long id, final int scaleIndex, String path ) { final Cache< Long, Interval[] >[] blockListCache = state.blocklistCacheProperty().get(); final Cache< ShapeKey, Pair< float[], float[] > >[] meshCache = state.meshesCacheProperty().get(); Interval[] blocks = null; try { blocks = blockListCache[ scaleIndex ].get( id ); } catch ( ExecutionException e ) { LOG.warn( "Could not get mesh block list for id {}: {}", id, e.getMessage() ); } final List< ShapeKey > keys = new ArrayList<>(); for ( final Interval block : blocks ) keys.add( new ShapeKey( id, scaleIndex, 0, Intervals.minAsLongArray( block ), Intervals.maxAsLongArray( block ) ) ); float[] allVertices = null; float[] allNormals = null; for ( final ShapeKey key : keys ) { Pair< float[], float[] > verticesAndNormals; try { verticesAndNormals = meshCache[ scaleIndex ].get( key ); allVertices = ArrayUtils.addAll( allVertices, verticesAndNormals.getA() ); allNormals = ArrayUtils.addAll( allNormals, verticesAndNormals.getB() ); } catch ( final ExecutionException e ) { LOG.warn( "Was not able to retrieve mesh for {}: {}", key, e.getMessage() ); } catch ( final RuntimeException e ) { LOG.warn( "{} : {}", e.getClass(), e.getMessage() ); e.printStackTrace(); throw e; } } assert allVertices.length == allNormals.length: "Vertices and normals must have the same size."; <START> save( path, id, allVertices, allNormals ); <END> }</code><technical_language>Meshes get big highest resolution. Instead of loading vertices for blocks memory, append vertex/normal array of block file located path, i.e. save happen for loop (maybe pass option append save)</technical_language>

Target:
public void exportMesh( final AtlasSourceState< ?, ? > state, final long id, final int scaleIndex, String path ) { final Cache< Long, Interval[] >[] blockListCache = state.blocklistCacheProperty().get(); final Cache< ShapeKey, Pair< float[], float[] > >[] meshCache = state.meshesCacheProperty().get(); Interval[] blocks = null; try { blocks = blockListCache[ scaleIndex ].get( id ); } catch ( ExecutionException e ) { LOG.warn( "Could not get mesh block list for id {}: {}", id, e.getMessage() ); } final List< ShapeKey > keys = new ArrayList<>(); for ( final Interval block : blocks ) keys.add( new ShapeKey( id, scaleIndex, 0, Intervals.minAsLongArray( block ), Intervals.maxAsLongArray( block ) ) ); for ( final ShapeKey key : keys ) { Pair< float[], float[] > verticesAndNormals; try { verticesAndNormals = meshCache[ scaleIndex ].get( key ); assert verticesAndNormals.getA().length == verticesAndNormals.getB().length: "Vertices and normals must have the same size."; save( path, id, verticesAndNormals.getA(), verticesAndNormals.getB(), BooleanUtils.toBoolean( numberOfFaces ) ); numberOfFaces += verticesAndNormals.getA().length / 3; } catch ( final ExecutionException e ) { LOG.warn( "Was not able to retrieve mesh for {}: {}", key, e.getMessage() ); } catch ( final RuntimeException e ) { LOG.warn( "{} : {}", e.getClass(), e.getMessage() ); e.printStackTrace(); throw e; } } }
Source:
<code>public String show(Request request, Response response) throws IOException { long id = getIdFromRequest(request.params("id")); User user = userService.findUserByName(currentUsernameString()); <START> Optional<NotificationFilter> optionalFilter = user.getNotificationFilters().stream() .filter(filter -> filter.getId() == id) <END> .findFirst(); if (optionalFilter.isEmpty()) { throw new RecordNotFoundException(EntityType.NotificationFilter, id); } return writerForTopLevelObject(request, response, writer -> NotificationFilterRepresenter.toJSON(writer, optionalFilter.get())); }</code><technical_language>logic is similar doFetchEntityFromConfig. Maybe, replace that</technical_language>

Target:
public String show(Request request, Response response) throws IOException { NotificationFilter notificationFilter = doFetchEntityFromConfig(request.params("id")); if (notificationFilter == null) { throw new RecordNotFoundException(EntityType.NotificationFilter, parseIdToLong(request.params("id"))); } return writerForTopLevelObject(request, response, writer -> NotificationFilterRepresenter.toJSON(writer, notificationFilter)); }
Source:
<code>public void handleUpdateData(UpdateData data) { if (data.getDao() == null || !data.getDao().getClass().isAnnotationPresent(MaterializedView.class)) { return; } <START> String entityName = null; <END> for (Class<?> clz : data.getDao().getClass().getInterfaces()) { if (DAO.class.isAssignableFrom(clz)) { for (Type t : clz.getGenericInterfaces()) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; if (pt.getActualTypeArguments().length > 0) { Type actualParameter = pt.getActualTypeArguments()[0]; if (actualParameter instanceof Class) { Class<?> entityClass = (Class<?>) actualParameter; entityName = entityClass.getSimpleName(); } } } } } } if (entityName == null) { log.error("MaterializedViewListener could not discover activated entity for DAO " + data.getDao() + " . Data inconsistency might occur."); } else { log.info("Refreshing materialized view for entity " + entityName); } }</code><technical_language>I encapsulate getEntityName for loop</technical_language>

Target:
public void handleUpdateData(UpdateData data) { if (data.getDao() == null || !data.getDao().getClass().isAnnotationPresent(MaterializedView.class)) { return; } MaterializedView mView = data.getDao().getClass().getAnnotation(MaterializedView.class); String[] effectedViews = mView.effectedViews(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("matviews", effectedViews); DbFacade.getInstance().getCallsHandler().executeModification("RefreshManyMaterializedViews", params); log.info("Refreshing materialized view for entities " + Arrays.toString(effectedViews)); }
Source:
<code>private void showRemoveTemplateWithDependentVMConfirmationWindow(HashMap<String, List<String>> problematicVmNames) { ArrayList<String> missingTemplatesFromVms = new ArrayList<>(); for (Map.Entry<String, List<String>> templateName : problematicVmNames.entrySet()) { List<String> vms = problematicVmNames.get(templateName.getKey()); <START> String vmsListString = StringUtils.join(vms, ","); END> missingTemplatesFromVms.add(ConstantsManager.getInstance() .getMessages() .templatesWithDependentVMs(templateName.getKey(), vmsListString)); } ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance() .getConstants() .removeBackedUpTemplatesWithDependentsVMTitle()); confirmModel.setHelpTag(HelpTag.remove_backed_up_template); confirmModel.setHashName("remove_backed_up_template"); confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .theFollowingTemplatesHaveDependentVmsBackupOnExportDomainMsg()); confirmModel.setItems(missingTemplatesFromVms); UICommand removeTemplateUiCommand = UICommand.createDefaultOkUiCommand("RemoveVmTemplates", this); confirmModel.getCommands().add(removeTemplateUiCommand); UICommand cancelConfirmationUiCommand = UICommand.createCancelUiCommand("CancelConfirmation", this); confirmModel.getCommands().add(cancelConfirmationUiCommand); }</code><technical_language>s/","/", " (just proper spaces...)</technical_language>

Target:
private void showRemoveTemplateWithDependentVMConfirmationWindow(HashMap<String, List<String>> problematicVmNames) { ArrayList<String> missingTemplatesFromVms = new ArrayList<>(); for (Map.Entry<String, List<String>> templateName : problematicVmNames.entrySet()) { List<String> vms = problematicVmNames.get(templateName.getKey()); String vmsListString = StringUtils.join(vms, ", "); missingTemplatesFromVms.add(ConstantsManager.getInstance() .getMessages() .templatesWithDependentVMs(templateName.getKey(), vmsListString)); } setConfirmWindow(null); ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance() .getConstants() .removeBackedUpTemplatesWithDependentsVMTitle()); confirmModel.setHelpTag(HelpTag.remove_backed_up_template); confirmModel.setHashName("remove_backed_up_template"); confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .theFollowingTemplatesHaveDependentVmsBackupOnExportDomainMsg()); confirmModel.setItems(missingTemplatesFromVms); UICommand removeTemplateUiCommand = UICommand.createDefaultOkUiCommand("RemoveVmTemplates", this); confirmModel.getCommands().add(removeTemplateUiCommand); UICommand cancelConfirmationUiCommand = UICommand.createCancelUiCommand("CancelConfirmation", this); confirmModel.getCommands().add(cancelConfirmationUiCommand); }
Source:
<code>public void draw(Context context, GL10 gl) { gl.glPushMatrix(); OpenGlTransform.apply(gl, getTransform()); scale(gl); <START> innerDraw(context, gl); <END> gl.glPopMatrix(); }</code><technical_language>call this method "drawShape()" instead</technical_language>

Target:
public void draw(Context context, GL10 gl) { gl.glPushMatrix(); OpenGlTransform.apply(gl, getTransform()); scale(gl); drawShape(context, gl); gl.glPopMatrix(); }
Source:
<code>private static String validate(String path) { if (path == null) { log.error("Path is null"); return null; } if (path.length() - 4 < 0) { log.error("File name too short (should at least end with .jyn) (got {})", path); return null; } if (path.endsWith(File.separator)) { path = path.substring(0, path.length()-File.separator.length()); } File f = new File(path); if (!f.isDirectory()) { log.debug("Not a directory, trying parent"); return null; } <START> if (! path.toLowerCase().startsWith(".jyn", path.length() - 4)) { <END> log.debug("Not an instrument (folder name not ending with .jyn) (got {})", path); return null; } String[] children = f.list(); String className = null; if (children == null) { log.error("Didn't find any files in {}", f); return className; } String assumedClassName = f.getName().substring(0, f.getName().length() - 4); for (String c : children) { if ((c).compareToIgnoreCase(assumedClassName + ".py") == 0) { return assumedClassName; } } log.warn("Coulnd't find best candidate ({}), reverting to first one", assumedClassName + ".py"); for (String c : children) { if (c.substring(c.length() - 3).compareToIgnoreCase(".py") == 0) { className = c.substring(0, c.length() - 3); } } log.warn("Using {}", className); return className; }</code><technical_language>Shouln't this be: if (! path.toLowerCase().endsWith(".jyn")) { instead</technical_language>

Target:
private static String validate(String path) { if (path == null) { log.error("Path is null"); return null; } if (path.length() - 4 < 0) { log.error("File name too short (should at least end with .jyn) (got {})", path); return null; } if (path.endsWith(File.separator)) { path = path.substring(0, path.length()-File.separator.length()); } File f = new File(path); if (!f.isDirectory()) { log.debug("Not a directory, trying parent"); return null; } if (! path.toLowerCase().endsWith(".jyn")) { log.debug("Not an instrument (folder name not ending with .jyn) (got {})", path); return null; } String[] children = f.list(); String className = null; if (children == null) { log.error("Didn't find any files in {}", f); return className; } String assumedClassName = f.getName().substring(0, f.getName().length() - 4); for (String c : children) { if ((c).compareToIgnoreCase(assumedClassName + ".py") == 0) { return assumedClassName; } } log.warn("Coulnd't find best candidate ({}), reverting to first one", assumedClassName + ".py"); for (String c : children) { if (c.substring(c.length() - 3).compareToIgnoreCase(".py") == 0) { className = c.substring(0, c.length() - 3); } } log.warn("Using {}", className); return className; }
Source:
<code>private boolean checkForManagementPortException() { <START> if (this.getStatusCode() == FailedRequestUsingMgmtPortException.MGMT_PORT_STATUS_CODE) { <END> if (getFirstHeaderValue(getResponse().getHeaders(), FailedRequestUsingMgmtPortException.MGMT_PORT_HEADER) != null) { return true; } } return false; }</code><technical_language>This consolidated a single boolean expression. result of boolean expression returned. is need return true false explicitly</technical_language>

Target:
private boolean checkForManagementPortException() { return ((this.getStatusCode() == FailedRequestUsingMgmtPortException.MGMT_PORT_STATUS_CODE) && (getFirstHeaderValue(getResponse().getHeaders(), FailedRequestUsingMgmtPortException.MGMT_PORT_HEADER) != null)); }
Source:
<code>public void onAcquiredLockNotification() { <START> synchronized (ZKDistributedNonblockingLock.this) { <END> _isLocked = true; ZKDistributedNonblockingLock.this.notify(); } }</code><technical_language>put synchronized (this)</technical_language>

Target:
public void onAcquiredLockNotification() { _lockStatus = LockConstants.LockStatus.LOCKED; _countDownLatch.countDown(); }
Source:
<code>public GameProfile call() throws Exception { if (this.id != null) { return this.fromId(this.id); } else if (this.name != null) { return this.fromNames(Lists.newArrayList(this.name)).get(0); } <START> throw new IllegalStateException("Impossibru"); <END> }</code><technical_language>a more professional error message</technical_language>

Target:
public GameProfile call() throws Exception { if (this.id != null) { return this.fromId(this.id); } else if (this.name != null) { return this.fromNames(Lists.newArrayList(this.name)).get(0); } throw new IllegalStateException("Impossible! The query if not for a name or a uuid."); }
Source:
<code>public Favicon(File fav) { if ( fav == null ) { return; } try { if ( !fav.exists() ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it does not exist!" ); <START> return; <END> } if ( !fav.getName().endsWith( ".png" ) ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it is not a PNG file!" ); return; } if ( !fav.isFile() ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it is not a file!" ); return; } BufferedImage image = ImageIO.read( fav ); if ( image != null ) { if ( image.getHeight() == 64 && image.getWidth() == 64 ) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write( image, "png", bytes ); favicon = "data:image/png;base64," + BaseEncoding.base64().encode( bytes.toByteArray() ); if ( favicon.length() > Short.MAX_VALUE ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Favicon file too large for server to process" ); favicon = null; } } else { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Server icon must be exactly 64x64 pixels" ); } } else { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon for unknown reason. Please double check its format." ); } } catch ( IOException e ) { e.printStackTrace(); } }</code><technical_language>Throw exceptions, log. FaviconException</technical_language>

Target:
public Favicon(File fav) throws FaviconException { if ( fav == null ) { return; } try { if ( !fav.exists() ) { throw new FaviconException( "Could not load server icon because it does not exist!" ); } if ( !fav.isFile() ) { throw new FaviconException( "Could not load server icon because it is not a file!" ); } if ( !fav.getName().toLowerCase().endsWith( ".png" ) ) { throw new FaviconException( "Could not load server icon because it is not a PNG file!" ); } BufferedImage image = ImageIO.read( fav ); if ( image != null ) { if ( image.getHeight() == 64 && image.getWidth() == 64 ) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write( image, "png", bytes ); favicon = "data:image/png;base64," + BaseEncoding.base64().encode( bytes.toByteArray() ); if ( favicon.length() > Short.MAX_VALUE ) { throw new FaviconException( "Favicon file too large for server to process" ); } } else { throw new FaviconException( "Server icon must be exactly 64x64 pixels" ); } } else { throw new FaviconException( "Could not load server icon for unknown reason. Please double check its format." ); } } catch ( IOException e ) { throw new FaviconException( e.getMessage() ); } }
Source:
<code>public static <T> String toSerializedPersistent(T object) { <START> return toSerializedPersistent(object); <END> }</code><technical_language>this infinite loop</technical_language>

Target:
public static <T> String toSerializedPersistent(T object) { return toSerialized(object, PERSISTENT); }
Source:
<code>public boolean dispatch(InternetAddress recipient, String subject, <START> String templatePlain, <END> String templateHtml, Map<String, Object> properties) { Message message = new MimeMessage(mailSession); String processedContentPlain; String processedContentHtml; try { processedContentPlain = templateService.getProcessedTemplate("invitation_plain.ftl", Locale.US, properties); processedContentHtml = templateService.getProcessedTemplate("invitation_html.ftl", Locale.US, properties); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, recipient); message.setSubject(subject); MimeBodyPart text = new MimeBodyPart(); text.setContent(processedContentPlain, "text/plain"); MimeBodyPart rich = new MimeBodyPart(); rich.setContent(processedContentHtml, "text/html"); Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(rich); multipart.addBodyPart(text); message.setContent(multipart); } catch (MessagingException | TemplateException | IOException e) { logger.exceptionPreparingMessage(recipient.getAddress(), e); return false; } try { Transport.send(message); } catch (MessagingException e) { logger.exceptionSendingMessage(recipient.getAddress(), e); return false; } return true; }</code><technical_language>Is this used? hardcoded template names below</technical_language>

Target:
public boolean dispatch(InternetAddress recipient, String subject, String templatePlain, String templateHtml, Map<String, Object> properties) { Message message = new MimeMessage(mailSession); String processedContentPlain; String processedContentHtml; try { processedContentPlain = templateService.getProcessedTemplate(templatePlain, Locale.US, properties); processedContentHtml = templateService.getProcessedTemplate(templateHtml, Locale.US, properties); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, recipient); message.setSubject(subject); MimeBodyPart text = new MimeBodyPart(); text.setContent(processedContentPlain, "text/plain"); MimeBodyPart rich = new MimeBodyPart(); rich.setContent(processedContentHtml, "text/html"); Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(rich); multipart.addBodyPart(text); message.setContent(multipart); } catch (MessagingException | TemplateException | IOException e) { logger.exceptionPreparingMessage(recipient.getAddress(), e); return false; } try { Transport.send(message); } catch (MessagingException e) { logger.exceptionSendingMessage(recipient.getAddress(), e); return false; } return true; }
Source:
<code>public TransactionImportResult importRemoteTransaction(Xid xid, int timeout) throws XAException { if (xid == null) { <START> throw new IllegalArgumentException(jtaLogger.i18NLogger.get_error_imported_transaction_uid_is_null()); <END> } return addImportedTransaction(null, convertXid(xid), xid, timeout); }</code><technical_language>this get_error_xid_is_null</technical_language>

Target:
public TransactionImportResult importRemoteTransaction(Xid xid, int timeout) throws XAException { if (xid == null) { throw new IllegalArgumentException(jtaLogger.i18NLogger.get_error_xid_is_null()); } return addImportedTransaction(null, convertXid(xid), xid, timeout); }
Source:
<code>public StorageDiskListModel() { setTitle(ConstantsManager.getInstance().getConstants().disksTitle()); setHelpTag(HelpTag.disks); setHashName("disks"); <START> diskOperationsHelper = new DiskOperationsHelper(); <END> setMoveCommand(new UICommand("Move", this)); setCopyCommand(new UICommand("Copy", this)); setRemoveCommand(new UICommand("Remove", this)); setUploadCommand(new UICommand("Upload", this)); setCancelUploadCommand(new UICommand("CancelUpload", this)); setPauseUploadCommand(new UICommand("PauseUpload", this)); setResumeUploadCommand(new UICommand("ResumeUpload", this)); setDownloadCommand(new UICommand("Download", this)); updateActionAvailability(); }</code><technical_language>do need create instance here? operations in this class static</technical_language>

Target:
public StorageDiskListModel() { setTitle(ConstantsManager.getInstance().getConstants().disksTitle()); setHelpTag(HelpTag.disks); setHashName("disks"); setMoveCommand(new UICommand("Move", this)); setCopyCommand(new UICommand("Copy", this)); setRemoveCommand(new UICommand("Remove", this)); setUploadCommand(new UICommand("Upload", this)); setCancelUploadCommand(new UICommand("CancelUpload", this)); setPauseUploadCommand(new UICommand("PauseUpload", this)); setResumeUploadCommand(new UICommand("ResumeUpload", this)); setDownloadCommand(new UICommand("Download", this)); updateActionAvailability(); }
Source:
<code>private static void maybeWarnAboutCodeInRocksDBConfigSetter(final Logger log, final StreamsConfig config) { if (config.getClass(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG) != null) { <START> log.warn("Kafka Streams cannot guarantee backwards compatibility of code in the RocksDB config setter " + "because RocksDB may remove methods without deprecating them."); <END> } }</code><technical_language>I more concrete: RocksDB version bumped version 6+ KAFKA-8897 in a future release. If org.rocksdbOptions#WhatEverMethodWasRemoved, need rewrite code KAFKA-8897 is resolved methods removed org.rocksdbOptions class a deprecation period. this</technical_language>

Target:
private static void maybeWarnAboutCodeInRocksDBConfigSetter(final Logger log, final StreamsConfig config) { if (config.getClass(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG) != null) { RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter.logWarning(log); } }
Source:
<code>public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException { <START> final List<ObjectType> objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "initObjects")); <END> final Iterator<ObjectType> iterator = objects.iterator(); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public LineIterator next() { if (!hasNext()) { throw new NoSuchElementException(); } final ObjectType object = iterator.next(); try { return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(openStream(object), Charsets.UTF_8) ) ); } catch (Exception e) { LOG.error( e, "Exception reading object[%s]", object ); throw Throwables.propagate(e); } } }, firehoseParser ); }</code><technical_language>objects cached? IndexTask connects firehose multiple times, caching useful for performance for consistent run-to-run</technical_language>

Target:
public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException { if (objects == null) { objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "initObjects")); } final Iterator<ObjectType> iterator = objects.iterator(); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public LineIterator next() { if (!hasNext()) { throw new NoSuchElementException(); } final ObjectType object = iterator.next(); try { return IOUtils.lineIterator(wrapObjectStream(object, openObjectStream(object)), Charsets.UTF_8); } catch (Exception e) { LOG.error( e, "Exception reading object[%s]", object ); throw Throwables.propagate(e); } } }, firehoseParser ); }
Source:
<code>protected Appender<ILoggingEvent> wrapAppenderAsAsyncIfNecessary(Appender<ILoggingEvent> delegate) { if (this.async) { AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(delegate); asyncAppender.setQueueSize(this.asyncQueueLength); <START> asyncAppender.setDiscardingThreshold(this.discarding ? 5 : 0); <END> asyncAppender.setIncludeCallerData(this.calleeData); return asyncAppender; } else { return delegate; } }</code><technical_language>5? 0? numbers magic</technical_language>

Target:
protected Appender<ILoggingEvent> wrapAppenderAsAsyncIfNecessary(Appender<ILoggingEvent> delegate) { if (this.async) { AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(delegate); asyncAppender.setQueueSize(this.asyncQueueLength); asyncAppender.setDiscardingThreshold(this.discarding ? DISCARD_20_PCT_HEADROOM : DONT_DISCARD); asyncAppender.setIncludeCallerData(this.calleeData); return asyncAppender; } else { return delegate; } }
Source:
<code><START> private void deletePaaSDB(ClaudiaData claudiaData, EnvironmentInstance envInstance, TierInstance tierInstance, boolean error) <END> throws InvalidEntityException, InfrastructureException { log.info("Deleting the environment instance " + envInstance.getBlueprintName() + " in the database "); envInstance = environmentInstanceDao.update(envInstance); try { infrastructureManager.deleteNetworksInTierInstance(claudiaData, tierInstance); } catch (Exception e) { log.error(e.getMessage()); error = true; } finally { log.info("Deleting security group from in tier " + tierInstance.getName() + " in TierInstance"); if (tierInstance.getSecurityGroup() != null && !tierInstance.getVdc().isEmpty()) { SecurityGroup securityGroup=null; try { securityGroup = securityGroupDao.loadWithRules(tierInstance.getSecurityGroup().getName()); } catch (EntityNotFoundException e1) { String msg = "SecurityGroup is not present in database " + securityGroup.getName(); log.error(msg); e1.printStackTrace(); throw new InvalidEntityException(msg); } log.info("Deleting security group " + securityGroup.getName() + " in tier " + tierInstance.getName()); tierInstance.setSecurityGroup(null); tierInstanceDao.update(tierInstance); securityGroupManager.destroy(tierInstance.getTier().getRegion(), claudiaData.getUser().getToken(), tierInstance.getVdc(), securityGroup); } tierInstanceManager.remove(tierInstance); } }</code><technical_language>more 120 chars</technical_language>

Target:
private void deletePaaSDB(ClaudiaData claudiaData, EnvironmentInstance envInstance, TierInstance tierInstance, boolean error) throws InvalidEntityException, InfrastructureException { log.info("Deleting the environment instance " + envInstance.getBlueprintName() + " in the database "); envInstance = environmentInstanceDao.update(envInstance); try { infrastructureManager.deleteNetworksInTierInstance(claudiaData, tierInstance); } catch (Exception e) { log.error(e.getMessage()); error = true; } finally { log.info("Deleting security group from tierInstance " + tierInstance.getName() + " in TierInstance"); SecurityGroup secGroup = tierInstance.getSecurityGroup(); if (secGroup != null) { SecurityGroup securityGroup=null; try { securityGroup = securityGroupDao.loadWithRules(secGroup.getName()); } catch (EntityNotFoundException e1) { String msg = "SecurityGroup is not present in database " + securityGroup.getName(); log.error(msg); e1.printStackTrace(); throw new InvalidEntityException(msg); } log.info("Deleting security group " + securityGroup.getName() + " associated to tierInstance " + tierInstance.getName()); tierInstance.setSecurityGroup(null); tierInstanceDao.update(tierInstance); securityGroupManager.destroy(tierInstance.getTier().getRegion(), claudiaData.getUser().getToken(), tierInstance.getVdc(), securityGroup); } tierInstanceManager.remove(tierInstance); } }
Source:
<code>public void createPartControl(final Composite parent) { super.createPartControl(parent); if (getTreeModel() == null) { final Label errorLabel = new Label(parent, SWT.CENTER); errorLabel.setText(Messages.DTreeEditor_treeModelUnsaved); return; } treeViewerManager = new DTreeViewerManager(parent, getTreeModel(), getEditingDomain(), accessor, emfCommandFactory, this); getSite().setSelectionProvider(treeViewerManager.getTreeViewer()); if (session != null) { InterpreterRegistry.prepareImportsFromSession(session.getInterpreter(), session); } ((DTreeActionBarContributor) getEditorSite().getActionBarContributor()).addCreateTreeItemMenu(((DTreeViewerManager) this.getTableViewer()).getCreateTreeItemMenu()); refreshAtOpeningActivator = new RefreshAtOpeningActivator(this); getSite().getPage().addPartListener(refreshAtOpeningActivator); IContextService contextService <START> = <END> getSite().getService(IContextService.class); contextService.activateContext(CONTEXT_ID); }</code><technical_language>remove cast getService generic mars</technical_language>

Target:
public void createPartControl(final Composite parent) { super.createPartControl(parent); if (getTreeModel() == null) { final Label errorLabel = new Label(parent, SWT.CENTER); errorLabel.setText(Messages.DTreeEditor_treeModelUnsaved); return; } treeViewerManager = new DTreeViewerManager(parent, getTreeModel(), getEditingDomain(), accessor, emfCommandFactory, this); getSite().setSelectionProvider(treeViewerManager.getTreeViewer()); if (session != null) { InterpreterRegistry.prepareImportsFromSession(session.getInterpreter(), session); } ((DTreeActionBarContributor) getEditorSite().getActionBarContributor()).addCreateTreeItemMenu(((DTreeViewerManager) this.getTableViewer()).getCreateTreeItemMenu()); refreshAtOpeningActivator = new RefreshAtOpeningActivator(this); getSite().getPage().addPartListener(refreshAtOpeningActivator); IContextService contextService = (IContextService) getSite().getService(IContextService.class); contextService.activateContext(CONTEXT_ID); }
Source:
<code>private void organiseResponses(String courseId) { questionToResponses = new HashMap<>(); <START> for (int i = 1; i <= 3; i++) { <END> FeedbackQuestionAttributes question = testData.feedbackQuestions.get("qn" + i); List<FeedbackResponseAttributes> responses = getResponsesByQuestion(courseId, i); questionToResponses.put(question, responses); } questionToGiverToResponses = new HashMap<>(); questionToRecipientToResponses = new HashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponses.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); Map<String, List<FeedbackResponseAttributes>> recipientToResponse = new HashMap<>(); Map<String, List<FeedbackResponseAttributes>> giverToResponse = new HashMap<>(); for (FeedbackResponseAttributes response : responses) { String recipient = response.getRecipient(); String giver = response.getGiver(); if (!recipientToResponse.containsKey(recipient)) { recipientToResponse.put(recipient, new ArrayList<>()); } if (!giverToResponse.containsKey(giver)) { giverToResponse.put(giver, new ArrayList<>()); } recipientToResponse.get(recipient).add(response); giverToResponse.get(giver).add(response); } questionToRecipientToResponses.put(question, recipientToResponse); questionToGiverToResponses.put(question, giverToResponse); } }</code><technical_language>1 3 magic numbers</technical_language>

Target:
private void organiseResponses(String courseId) { List<FeedbackQuestionAttributes> questions = getQuestionsByCourse(courseId); questionToResponses = new HashMap<>(); for (FeedbackQuestionAttributes question : questions) { List<FeedbackResponseAttributes> responses = getResponsesByQuestion(courseId, question.getQuestionNumber()); questionToResponses.put(question, responses); } questionToGiverToResponses = new HashMap<>(); questionToRecipientToResponses = new HashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponses.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); Map<String, List<FeedbackResponseAttributes>> recipientToResponse = new HashMap<>(); Map<String, List<FeedbackResponseAttributes>> giverToResponse = new HashMap<>(); for (FeedbackResponseAttributes response : responses) { String recipient = response.getRecipient(); String giver = response.getGiver(); if (!recipientToResponse.containsKey(recipient)) { recipientToResponse.put(recipient, new ArrayList<>()); } if (!giverToResponse.containsKey(giver)) { giverToResponse.put(giver, new ArrayList<>()); } recipientToResponse.get(recipient).add(response); giverToResponse.get(giver).add(response); } questionToRecipientToResponses.put(question, recipientToResponse); questionToGiverToResponses.put(question, giverToResponse); } }
Source:
<code>public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!ctx.channel().isOpen()) { logger.debug("Channel closed when write. Channel: {}", ctx.channel()); promise.setFailure(new ChannelException("Channel has been closed when write.")); } if (!(msg instanceof Send)) { ctx.write(msg, promise); return; } Send send = (Send) msg; Http2Headers http2Headers; if (forServer) { logger.trace("Write content to channel as server {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); } else { logger.trace("Write content to channel as client {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).scheme("https").path("/"); } DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(http2Headers, false); ctx.write(headersFrame); ByteBuf dataContent = send.content(); if (dataContent == null) { ByteBufChannel byteBufChannel = new ByteBufChannel(); try { send.writeTo(byteBufChannel); dataContent = byteBufChannel.getBuf(); <START> send.release(); <END> } catch (IOException e) { promise.setFailure(e); return; } } DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(dataContent, true); ctx.write(dataFrame, promise); }</code><technical_language>finally here</technical_language>

Target:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!ctx.channel().isOpen()) { logger.debug("Channel closed when write. Channel: {}", ctx.channel()); promise.setFailure(new ChannelException("Channel has been closed when write.")); } if (!(msg instanceof Send)) { ctx.write(msg, promise); return; } Send send = (Send) msg; Http2Headers http2Headers; if (forServer) { logger.trace("Write content to channel as server {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); } else { logger.trace("Write content to channel as client {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).scheme("https").path("/"); } DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(http2Headers, false); ctx.write(headersFrame); ByteBuf dataContent = send.content(); if (dataContent == null) { ByteBufChannel byteBufChannel = new ByteBufChannel(); try { send.writeTo(byteBufChannel); dataContent = byteBufChannel.getBuf(); } catch (IOException e) { promise.setFailure(e); return; } finally { send.release(); } } DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(dataContent, true); ctx.write(dataFrame, promise); }
Source:
<code>private void configureTask(SonarQubeTask sonarQubeTask, Project project, Map<String, ActionBroadcast<SonarQubeProperties>> actionBroadcastMap) { ConventionMapping conventionMapping = sonarQubeTask.getConventionMapping(); conventionMapping.map("properties", () -> new SonarPropertyComputer(actionBroadcastMap, project) .computeSonarProperties()); Callable<Iterable<? extends Task>> testTasks = () -> project.getAllprojects().stream() .filter(p -> p.getPlugins().hasPlugin(JavaPlugin.class) && !p.getExtensions().getByType(SonarQubeExtension.class).isSkipProject()) .map(p -> p.getTasks().getByName(JavaPlugin.TEST_TASK_NAME)) .collect(Collectors.toList()); sonarQubeTask.mustRunAfter(testTasks); Callable<Iterable<? extends Task>> compileTasks = () -> project.getAllprojects().stream() .filter(p -> isAndroidProject(p) && !p.getExtensions().getByType(SonarQubeExtension.class).isSkipProject()) .map(p -> { BaseVariant variant = AndroidUtils.findVariant(p, p.getExtensions().getByType(SonarQubeExtension.class).getAndroidVariant()); List<Task> allCompileTasks = new ArrayList<>(); if (variant != null) { boolean unitTestTaskDepAdded = addTaskByName(p, "compile" + capitalize(variant.getName()) + "UnitTestJavaWithJavac", allCompileTasks); boolean androidTestTaskDepAdded = addTaskByName(p, "compile" + capitalize(variant.getName()) + "AndroidTestJavaWithJavac", allCompileTasks); if (!unitTestTaskDepAdded && !androidTestTaskDepAdded) { addTaskByName(p, "compile" + capitalize(variant.getName()) + "JavaWithJavac", allCompileTasks); } } return allCompileTasks; }) .flatMap(List::stream) .collect(Collectors.toList()); <START> sonarQubeTask.mustRunAfter(compileTasks); <END> }</code><technical_language>this change deserve a separate ticket, impact accuracy of Java analysis. Bytecode missing if people run gradle sonarqube. want do it</technical_language>

Target:
private void configureTask(SonarQubeTask sonarQubeTask, Project project, Map<String, ActionBroadcast<SonarQubeProperties>> actionBroadcastMap) { ConventionMapping conventionMapping = sonarQubeTask.getConventionMapping(); conventionMapping.map("properties", () -> new SonarPropertyComputer(actionBroadcastMap, project) .computeSonarProperties()); sonarQubeTask.mustRunAfter(getJavaTestTasks(project)); sonarQubeTask.dependsOn(getJavaCompileTasks(project)); sonarQubeTask.mustRunAfter(getJacocoTasks(project)); sonarQubeTask.dependsOn(getAndroidCompileTasks(project)); }
Source:
<code>public Dimension getDefaultDimension() { final Dimension result = DEFAULT_NODE_DIMENSION.getCopy(); if (node.getStyle() instanceof WorkspaceImage) { final WorkspaceImage workspaceImage = (WorkspaceImage) node.getStyle(); final String path = workspaceImage.getWorkspacePath(); <START> Dimension imageDimension = WorkspaceImageFigure.getImageBounds(path); <END> if (imageDimension != null) { if (node.getWidth() == null || Integer.valueOf(node.getWidth()) == -1) { result.width = imageDimension.width; result.height = imageDimension.height; } else { final double ratio = (double) imageDimension.width / imageDimension.height; double newHeight = node.getWidth().intValue() / ratio; result.width = node.getWidth().intValue() * LayoutUtils.SCALE; result.height = (int) (newHeight * LayoutUtils.SCALE); } } } else { if (node.getWidth() != null) { result.width = node.getWidth().intValue(); } if (node.getHeight() != null) { result.height = node.getHeight().intValue(); } result.width = result.width * LayoutUtils.SCALE; result.height = result.height * LayoutUtils.SCALE; } return result; }</code><technical_language>if(path!=null)</technical_language>

Target:
public Dimension getDefaultDimension() { final Dimension result = DEFAULT_NODE_DIMENSION.getCopy(); if (node.getStyle() instanceof WorkspaceImage) { final WorkspaceImage workspaceImage = (WorkspaceImage) node.getStyle(); final String path = workspaceImage.getWorkspacePath(); Dimension imageDimension = path != null ? WorkspaceImageFigure.getImageBounds(path) : null; if (imageDimension != null) { if (node.getWidth() == null || Integer.valueOf(node.getWidth()) == -1) { result.width = imageDimension.width; result.height = imageDimension.height; } else { final double ratio = (double) imageDimension.width / imageDimension.height; double newHeight = node.getWidth().intValue() / ratio; result.width = node.getWidth().intValue() * LayoutUtils.SCALE; result.height = (int) (newHeight * LayoutUtils.SCALE); } } } else { if (node.getWidth() != null) { result.width = node.getWidth().intValue(); } if (node.getHeight() != null) { result.height = node.getHeight().intValue(); } result.width = result.width * LayoutUtils.SCALE; result.height = result.height * LayoutUtils.SCALE; } return result; }
Source:
<code>public void dateType() { <START> long testDatesValid[] = {-1001, -1000, -1, 0, 1, 1000, 1001}; <END> realm.beginTransaction(); for (long value : testDatesValid) { AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnDate(new Date(value)); } realm.commitTransaction(); int i = 0; for (AllTypes allTypes : realm.allObjects(AllTypes.class)) { assertEquals("Item " + i, new Date(testDatesValid[i]), allTypes.getColumnDate()); i++; } }</code><technical_language>remove boundary checks? Long.MIN/MAX ? great multiple negative tests</technical_language>

Target:
public void dateType() { long testDatesValid[] = {Long.MIN_VALUE, -1001, -1000, -1, 0, 1, 1000, 1001, Long.MAX_VALUE}; realm.beginTransaction(); for (long value : testDatesValid) { AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnDate(new Date(value)); } realm.commitTransaction(); int i = 0; for (AllTypes allTypes : realm.allObjects(AllTypes.class)) { assertEquals("Item " + i, new Date(testDatesValid[i]), allTypes.getColumnDate()); i++; } }