auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validate(String beforeReformat, String afterReformat) { String normalizedBefore = getNormalized(beforeReformat); String normalizedAfter = getNormalized(afterReformat); if (!normalizedBefore.equalsIgnoreCase(normalizedAfter)) { int minLen = Math.min(normalizedAfter.length(), normalizedBefore .length()); StringBuilder diffPos = new StringBuilder(); for (int i = 0; i < minLen; ++i) { if (Character.toUpperCase(normalizedBefore.charAt(i)) != Character .toUpperCase(normalizedAfter.charAt(i))) { break; } diffPos.append('-'); } diffPos.append('^'); <START> StringBuilder msg = new StringBuilder(I18N.getString("orbisgis.core.ui.plugins.views.sqlConsole.codereformat.reformatFailed")); <END> msg.append(_lineSep); msg.append(normalizedBefore); msg.append(_lineSep); msg.append(normalizedAfter); msg.append(_lineSep); msg.append(diffPos.toString()); msg.append(_lineSep); if (s_log.isInfoEnabled()) { s_log.info(msg.toString()); } throw new IllegalStateException(msg.toString()); } }</code><technical_language>good I18N</technical_language>

Target:
private void validate(String beforeReformat, String afterReformat) { String normalizedBefore = getNormalized(beforeReformat); String normalizedAfter = getNormalized(afterReformat); if (!normalizedBefore.equalsIgnoreCase(normalizedAfter)) { int minLen = Math.min(normalizedAfter.length(), normalizedBefore .length()); StringBuilder diffPos = new StringBuilder(); for (int i = 0; i < minLen; ++i) { if (Character.toUpperCase(normalizedBefore.charAt(i)) != Character .toUpperCase(normalizedAfter.charAt(i))) { break; } diffPos.append('-'); } diffPos.append('^'); StringBuilder msg = new StringBuilder(I18N.tr("Reformat failed, normalised strings differ")); msg.append(_lineSep); msg.append(normalizedBefore); msg.append(_lineSep); msg.append(normalizedAfter); msg.append(_lineSep); msg.append(diffPos.toString()); msg.append(_lineSep); if (s_log.isInfoEnabled()) { s_log.info(msg.toString()); } throw new IllegalStateException(msg.toString()); } }
Source:
<code>public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); <START> MPLog.d(LOGTAG, "MP FCM notification received: " + mixpanelPushNotification.getData().getMessage()); <END> if (null != notification) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final int id = new Random().nextInt(Integer.MAX_VALUE); if (mixpanelPushNotification.getData().getTag() != null) { notificationManager.notify(mixpanelPushNotification.getData().getTag(), 0, notification); } else { notificationManager.notify(id, notification); } } }</code><technical_language>mData null this point, check for npe</technical_language>

Target:
public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); MixpanelNotificationData data = mixpanelPushNotification.getData(); String message = data == null ? "null" : data.getMessage(); MPLog.d(LOGTAG, "MP FCM notification received: " + message); if (null != notification) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final int id = new Random().nextInt(Integer.MAX_VALUE); if (mixpanelPushNotification.getData().getTag() != null) { notificationManager.notify(mixpanelPushNotification.getData().getTag(), 0, notification); } else { notificationManager.notify(id, notification); } } }
Source:
<code>public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) { <START> try { <END> List entities; if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.ASCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"asc\" }", first, pageSize, filters); } else if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.DESCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"desc\" }", first, pageSize, filters); } else { entities = searchService.findAll(null, first, pageSize, filters); } logger.info(entities.size() + " entities loaded!"); return entities; } catch (DataException e) { logger.error(e.getMessage()); return new LinkedList(); } }</code><technical_language>removed is more needed for displaying amount of results</technical_language>

Target:
public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) { try { setRowCount(toIntExact(searchService.count(searchService.createCountQuery(filters)))); List entities; if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.ASCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"asc\" }", first, pageSize, filters); } else if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.DESCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"desc\" }", first, pageSize, filters); } else { entities = searchService.findAll(null, first, pageSize, filters); } logger.info(entities.size() + " entities loaded!"); return entities; } catch (DataException e) { logger.error(e.getMessage()); return new LinkedList(); } }
Source:
<code>public Date getStartDate() { <START> return startDate; <END> }</code><technical_language>Dates mutable, a copy of startDate returned avoid downstream side-effects</technical_language>

Target:
public Date getStartDate() { return startDate == null ? null : new Date(startDate.getTime()); }
Source:
<code>public static List<Map<String,String>> getAvailableMetadataFormats() { List<Map<String,String>> configs = new ArrayList<>(); String metaString = "oai.harvester.metadataformats."; Enumeration pe = Collections.enumeration( DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys("oai") ); <START> while (pe.hasMoreElements()) { <END> String key = (String) pe.nextElement(); if (key.startsWith(metaString)) { String metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); String id = key.substring(metaString.length()); String label; String namespace = ""; if (metadataString.indexOf(',') != -1) { label = metadataString.substring(metadataString.indexOf(',') + 2); namespace = metadataString.substring(0, metadataString.indexOf(',')); } else { label = id + "(" + metadataString + ")"; } Map<String,String> config = new HashMap<>(); config.put("id", id); config.put("label", label); config.put("namespace", namespace); configs.add(config); } } return configs; }</code><technical_language>need enumerate keys in a Collection...you able getPropertyKeys("oai.harvester.metadataformats"); get a List of matching keys, instead of looping starting "oai" for "oai.harvester.metadataformats" that</technical_language>

Target:
public static List<Map<String,String>> getAvailableMetadataFormats() { List<Map<String,String>> configs = new ArrayList<>(); String metaString = "oai.harvester.metadataformats."; Enumeration pe = Collections.enumeration( DSpaceServicesFactory.getInstance().getConfigurationService() .getPropertyKeys("oai.harvester.metadataformats") ); while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); String metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); String id = key.substring(metaString.length()); String label; String namespace = ""; if (metadataString.indexOf(',') != -1) { label = metadataString.substring(metadataString.indexOf(',') + 2); namespace = metadataString.substring(0, metadataString.indexOf(',')); } else { label = id + "(" + metadataString + ")"; } Map<String,String> config = new HashMap<>(); config.put("id", id); config.put("label", label); config.put("namespace", namespace); configs.add(config); } return configs; }
Source:
<code>protected boolean isTargetDirectoryForbidden() { File nuxeoHome = ConfigurationGenerator.retrieveNuxeoHome(); <START> return Paths.get(directory).startsWith(nuxeoHome.toPath()); <END> }</code><technical_language>Paths.get(directory).toAbsolutePath().normalize().startsWith(nuxeoHome.toPath().toAbsolutePath().normalize()) avoid dangerous .. path components allow escaping nuxeoHome directory</technical_language>

Target:
protected boolean isTargetDirectoryForbidden() { File nuxeoHome = ConfigurationGenerator.retrieveNuxeoHome(); return Paths.get(directory) .toAbsolutePath() .normalize() .startsWith(nuxeoHome.toPath().toAbsolutePath().normalize()); }
Source:
<code>public InvocationStage toInvocationStage(Supplier<TimeoutException> timeoutSupplier) { if (notifier.isDone()) { return checkState(notifier.getNow(lockState), InvocationStage::completedNullStage, ExceptionSyncInvocationStage::new, timeoutSupplier); } return new SimpleAsyncInvocationStage(CompletionStages.continueOnExecutor(notifier.thenApplyAsync(state -> { Object rv = checkState(state, () -> null, throwable -> throwable, timeoutSupplier); if (rv != null) { throw (RuntimeException) rv; } return null; <START> }, blockingExecutor), nonBlockingExecutor, this)); <END> }</code><technical_language>This in a separate commit for ISPN-11295. Also, I expect blocking in vast majority of cases, need optimized path for case and/or a PerfAck test if extra thread switching affects performance</technical_language>

Target:
public InvocationStage toInvocationStage(Supplier<TimeoutException> timeoutSupplier) { if (notifier.isDone()) { return checkState(notifier.getNow(lockState), InvocationStage::completedNullStage, ExceptionSyncInvocationStage::new, timeoutSupplier); } return new SimpleAsyncInvocationStage(notifier.thenApplyAsync(state -> { Object rv = checkState(state, () -> null, throwable -> throwable, timeoutSupplier); if (rv != null) { throw (RuntimeException) rv; } return null; }, nonBlockingExecutor)); }
Source:
<code>public void push() { if (Session.getCredentials().isLogged()) { Log.d(TAG, "execute push"); <START> executePush(); <END> } else { Log.d(TAG, "execute push fails, not logged"); } }</code><technical_language>remove mocked push. talk this</technical_language>

Target:
public void push() { if (Session.getCredentials().isDemoCredentials()) { Log.d(TAG, "execute push"); executeMockedPush(); } else { Log.d(TAG, "execute push fails, not logged"); } }
Source:
<code><START> public void setVariable(final String identifier, final String content) { <END> setVariable(identifier, content, null); }</code><technical_language>is this anywhere? If not, please remove</technical_language>

Target:
public void setVariable(final String identifier, final String content) { Variable variable = getVariable(identifier); if (variable != null) { variable.setContent(content); fDirty = true; return; } this.addVariable(identifier, content, null); }
Source:
<code>public Integer addGroup(String nameOfGroup) { ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { PreparedStatement statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_GROUPS + "(" + Constants.GROUPS_GROUP_NAME + ")" + " VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS ); statement.setString(1, nameOfGroup); statement.executeUpdate(); results = statement.getGeneratedKeys(); int groupId = -1; if (results.next()) { groupId = results.getInt(1); } else { throw new Exception("Could not add group"); } return groupId; } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) results.close(); } catch (Exception e) { } } <START> return null; <END> }</code><technical_language>queryStatement null is used, removing this logic variable</technical_language>

Target:
public Integer addGroup(String nameOfGroup) { PreparedStatement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_GROUPS + "(" + Constants.GROUPS_GROUP_NAME + ")" + " VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS ); queryStatement.setString(1, nameOfGroup); queryStatement.executeUpdate(); results = queryStatement.getGeneratedKeys(); int groupId = -1; if (results.next()) { groupId = results.getInt(1); } else { throw new Exception("Could not add group"); } return groupId; } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return null; }
Source:
<code>private CompletionStage<RestResponse> convertToJson(RestRequest restRequest) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = restRequest.contents(); ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(contents.rawContent(), UTF_8)); ConfigurationBuilder builder = builderHolder.getNamedConfigurationBuilders().values().iterator().next(); Configuration configuration = builder.build(); return CompletableFuture.completedFuture(responseBuilder .contentType(APPLICATION_JSON) .entity(JSON_WRITER.toJSON(configuration)) <START> .build()); <END> }</code><technical_language>alignment is a bit wonky, split java responseBuilder.contentType(APPLICATION_JSON) .entity(JSON_WRITER.toJSON(configuration)); return CompletableFuture.completedFuture(responseBuilder.build());</technical_language>

Target:
private CompletionStage<RestResponse> convertToJson(RestRequest restRequest) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = restRequest.contents(); ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(contents.rawContent(), UTF_8)); ConfigurationBuilder builder = builderHolder.getNamedConfigurationBuilders().values().iterator().next(); Configuration configuration = builder.build(); responseBuilder.contentType(APPLICATION_JSON) .entity(JSON_WRITER.toJSON(configuration)); return CompletableFuture.completedFuture(responseBuilder.build()); }
Source:
<code>private void injectBootstrapper() throws InfrastructureException { String machineName = kubernetesMachine.getName(); LOG.debug( "Bootstrapping {}:{}. Creating folder for bootstrapper", runtimeIdentity, machineName); kubernetesMachine.exec("mkdir", "-p", BOOTSTRAPPER_DIR, bootstrapperLogsFolder); LOG.debug("Bootstrapping {}:{}. Downloading bootstrapper binary", runtimeIdentity, machineName); kubernetesMachine.exec( "curl", "-o", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE, bootstrapperBinaryUrl); kubernetesMachine.exec("chmod", "+x", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE); LOG.debug("Bootstrapping {}:{}. Creating config file", runtimeIdentity, machineName); List<String> filesToContatenate = new ArrayList<String>(); filesToContatenate.add("["); boolean firstOne = true; for (Installer installer : installers) { if (firstOne) { firstOne = false; } else { filesToContatenate.add(","); } filesToContatenate.add(GSON.toJson(installer)); } filesToContatenate.add("]"); int counter = 1; for (String fileToConcatenate : filesToContatenate) { kubernetesMachine.exec( "sh", "-c", <START> "cat > " <END> + BOOTSTRAPPER_DIR + CONFIG_FILE + "____" + counter + " << 'EOF'\n" + fileToConcatenate + "\nEOF"); counter++; } String generalConcatCommand = "cat "; for (int i = 1; i < counter; i++) { generalConcatCommand += BOOTSTRAPPER_DIR + CONFIG_FILE + "____" + i + " "; } generalConcatCommand += "> " + BOOTSTRAPPER_DIR + CONFIG_FILE; LOG.debug("Executing {}", "sh -c '" + generalConcatCommand + "'"); kubernetesMachine.exec("sh", "-c", generalConcatCommand); kubernetesMachine.exec("sh", "-c", "rm " + BOOTSTRAPPER_DIR + CONFIG_FILE + "____*"); }</code><technical_language>do need created n files? >> instead of > cat content file part part</technical_language>

Target:
private void injectBootstrapper() throws InfrastructureException { String machineName = kubernetesMachine.getName(); LOG.debug( "Bootstrapping {}:{}. Creating folder for bootstrapper", runtimeIdentity, machineName); kubernetesMachine.exec("mkdir", "-p", BOOTSTRAPPER_DIR, bootstrapperLogsFolder); LOG.debug("Bootstrapping {}:{}. Downloading bootstrapper binary", runtimeIdentity, machineName); kubernetesMachine.exec( "curl", "-o", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE, bootstrapperBinaryUrl); kubernetesMachine.exec("chmod", "+x", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE); LOG.debug("Bootstrapping {}:{}. Creating config file", runtimeIdentity, machineName); kubernetesMachine.exec("sh", "-c", "rm " + BOOTSTRAPPER_DIR + CONFIG_FILE); List<String> contentsToContatenate = new ArrayList<String>(); contentsToContatenate.add("["); boolean firstOne = true; for (Installer installer : installers) { if (firstOne) { firstOne = false; } else { contentsToContatenate.add(","); } contentsToContatenate.add(GSON.toJson(installer)); } contentsToContatenate.add("]"); for (String content : contentsToContatenate) { kubernetesMachine.exec( "sh", "-c", "cat >> " + BOOTSTRAPPER_DIR + CONFIG_FILE + " << 'EOF'\n" + content + "\nEOF"); } }
Source:
<code>public H2YearWeekFunction() { <START> super("(select CONCAT(extract(year from DATE_TRUNC('week', x.y)), '-', iso_week(x.y)) from (values (?1)) x(y))"); <END> }</code><technical_language>Unfortunately, H2 support syntax. In DB2 this works lateral (values (?1)) I doubt this work here. of other SQL able produce result while rendering template argument once? If not, bail if encountering a parameter</technical_language>

Target:
public H2YearWeekFunction() { super("CONCAT(extract(year from DATE_TRUNC('week', ?1)), '-', iso_week(?1))"); }
Source:
<code>private static void NonOperationalPoolTreatment(storage_pool pool) { boolean changeStatus = false; <START> if (DbFacade.getInstance().getVdsDAO().getActiveVdsByPoolId(pool.getId()).size() > 0) { <END> changeStatus = true; } if (changeStatus) { log.info("Moving data center " + pool.getname() + " with Id " + pool.getId() + " to status Problematic from status NotOperational on a one time basis to try to recover"); Backend.getInstance().runInternalAction( VdcActionType.SetStoragePoolStatus, new SetStoragePoolStatusParameters(pool.getId(), StoragePoolStatus.Problematic, AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_FROM_NON_OPERATIONAL)); synchronized (_nonOperationalPools) { _nonOperationalPools.remove(pool.getId()); } } }</code><technical_language>getVdsDAO() instead of DbFacade.getInstance.getVdsDAO</technical_language>

Target:
private static void NonOperationalPoolTreatment(storage_pool pool) { boolean changeStatus = false; if (DbFacade.getInstance().getVdsDAO().getAllByPoolIdAndStatus(pool.getId(), VDSStatus.Up).size() > 0) { changeStatus = true; } if (changeStatus) { log.info("Moving data center " + pool.getname() + " with Id " + pool.getId() + " to status Problematic from status NotOperational on a one time basis to try to recover"); Backend.getInstance().runInternalAction( VdcActionType.SetStoragePoolStatus, new SetStoragePoolStatusParameters(pool.getId(), StoragePoolStatus.Problematic, AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_FROM_NON_OPERATIONAL)); synchronized (_nonOperationalPools) { _nonOperationalPools.remove(pool.getId()); } } }
Source:
<code>public void testProgress() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = 100; Mockito.when(logger.isLoggable(any())).thenReturn(true); try (final Progress progress = new Progress(logger, "foo", totalCount)) { assertNotNull(progress.getLoggerThread()); while (progress.getLoggerThread().getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { progress.increment(); while (progress.getLoggerThread().getState() != Thread.State.WAITING) { TimeUnit.MILLISECONDS.sleep(10); } } } <START> <END> Mockito.verify(logger, times(totalCount)).log(any(), anyString(), any(Object[].class)); }</code><technical_language>worth confirm logged thread terminated</technical_language>

Target:
public void testProgress() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = 100; Thread loggerThread = null; Mockito.when(logger.isLoggable(any())).thenReturn(true); try (final Progress progress = new Progress(logger, "foo", totalCount)) { assertNotNull(progress.getLoggerThread()); loggerThread = progress.getLoggerThread(); while (loggerThread.getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { progress.increment(); while (loggerThread.getState() != Thread.State.WAITING) { TimeUnit.MILLISECONDS.sleep(10); } } } System.out.println("Waiting for the logger thread to terminate"); int i = 0; while (i < 3 && loggerThread.getState() != Thread.State.TERMINATED) { TimeUnit.MILLISECONDS.sleep(10); i++; } Assert.assertSame(loggerThread.getState(), Thread.State.TERMINATED); Mockito.verify(logger, times(totalCount)).log(any(), anyString(), any(Object[].class)); }
Source:
<code>default boolean hasParticipant(User user) { for (ChangeLogSet<? extends ChangeLogSet.Entry> c : getChangeSets()) { for (ChangeLogSet.Entry e : c) try { <START> if (e.getAuthor() == user) <END> return true; } catch (RuntimeException re) { Logger LOGGER = Logger.getLogger(RunWithSCM.class.getName()); LOGGER.log(Level.INFO, "Failed to determine author of changelog " + e.getCommitId() + "for " + ((RunT)this).getParent().getDisplayName() + ", " + ((RunT)this).getDisplayName(), re); } } return false; }</code><technical_language>braces</technical_language>

Target:
default boolean hasParticipant(User user) { for (ChangeLogSet<? extends ChangeLogSet.Entry> c : getChangeSets()) { for (ChangeLogSet.Entry e : c) { try { if (e.getAuthor() == user) { return true; } } catch (RuntimeException re) { Logger LOGGER = Logger.getLogger(RunWithSCM.class.getName()); LOGGER.log(Level.INFO, "Failed to determine author of changelog " + e.getCommitId() + "for " + ((RunT) this).getParent().getDisplayName() + ", " + ((RunT) this).getDisplayName(), re); } } } return false; }
Source:
<code>protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { setClampHeight(1.0f); collectTote(); setClampHeight(0.0f); QuasarHelios.clamp.openControl.set(true); drive(nudge.get()); QuasarHelios.clamp.openControl.set(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); setClampHeight(0.0f); QuasarHelios.clamp.openControl.set(true); drive(nudge.get()); <START> QuasarHelios.clamp.openControl.set(false); <END> setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); turn(90); drive(autoZoneDistance.get()); DriveCode.octocanumShifting.set(true); DriveCode.octocanumShifting.set(false); }</code><technical_language>QuasarHelios.clamp.openControl.set a good helper addition base class</technical_language>

Target:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { setClampHeight(1.0f); collectTote(); setClampHeight(0.0f); setClampOpen(true); drive(nudge.get()); setClampOpen(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); setClampHeight(0.0f); setClampOpen(true); drive(nudge.get()); setClampOpen(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); turn(90); drive(autoZoneDistance.get()); DriveCode.octocanumShifting.set(true); DriveCode.octocanumShifting.set(false); }
Source:
<code>public void addOrUpdateAlert(final Alert alert) { <START> LOGGER.info() <END> .setMessage("This is a read only repository.") .log(); }</code><technical_language>want this throw some sort of exception UI display some notification write happen</technical_language>

Target:
public void addOrUpdateAlert(final Alert alert) { throw new UnsupportedOperationException("This is a read only repository."); }
Source:
<code><START> protected BasicNameValuePair addPair(QueryParam queryParam) { <END> return new BasicNameValuePair(queryParam.name(), queryParam.value()); }</code><technical_language>Protected sense a final class</technical_language>

Target:
private BasicNameValuePair addPair(QueryParam queryParam) { return new BasicNameValuePair(queryParam.name(), queryParam.value()); }
Source:
<code>public void end() { <START> int c; <END> synchronized (this) { c = count; } if (total == UNKNOWN && c > 0) { wakeUp(); } }</code><technical_language>int c = getCount(); inline in next line too</technical_language>

Target:
public void end() { if (total == UNKNOWN && getCount() > 0) { wakeUp(); } }
Source:
<code>protected TextPresentation createPresentation(IRegion damage, IDocument document) { TextPresentation presentation = super.createPresentation(damage, document); IDocument doc = textViewer.getDocument(); URI uri = Server2ClientProtocolExtension.getUri(doc); if (uri == null) { return presentation; } Position[] returnedPositions = null; List<StyleRange> styleRanges = new ArrayList<>(); HighlightedPosition[] highlightedPositions; try { returnedPositions = doc.getPositions(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); } catch (BadPositionCategoryException e) { Activator.log(e); } <START> if(returnedPositions == null) { <END> return presentation; } highlightedPositions = Arrays.copyOf(returnedPositions, returnedPositions.length, HighlightedPosition[].class); int damageStartOffset = damage.getOffset(); int damageEndOffset = damageStartOffset + damage.getLength(); for(HighlightedPosition eachPosition : highlightedPositions) { if ((eachPosition.getOffset() + eachPosition.getLength()) >= damageStartOffset && eachPosition.getOffset() < damageEndOffset) { StyleRange range = eachPosition.createStyleRange(); styleRanges.add(range); } } StyleRange[] styleRangesArray = new StyleRange[styleRanges.size()]; styleRangesArray = styleRanges.toArray(styleRangesArray); presentation.replaceStyleRanges(styleRangesArray); return presentation; }</code><technical_language>space '(' Applies in a other places in this file too</technical_language>

Target:
protected TextPresentation createPresentation(IRegion damage, IDocument document) { TextPresentation presentation = super.createPresentation(damage, document); IDocument doc = textViewer.getDocument(); URI uri = Server2ClientProtocolExtension.getUri(doc); if (uri == null) { return presentation; } Position[] returnedPositions = null; List<StyleRange> styleRanges = new ArrayList<>(); HighlightedPosition[] highlightedPositions; doc.addPositionCategory(PresentationReconcilerCPP.SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); try { returnedPositions = doc.getPositions(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); } catch (BadPositionCategoryException e) { Activator.log(e); } if (returnedPositions == null) { return presentation; } highlightedPositions = Arrays.copyOf(returnedPositions, returnedPositions.length, HighlightedPosition[].class); int damageStartOffset = damage.getOffset(); int damageEndOffset = damageStartOffset + damage.getLength(); for (HighlightedPosition eachPosition : highlightedPositions) { if ((eachPosition.getOffset() + eachPosition.getLength()) >= damageStartOffset && eachPosition.getOffset() < damageEndOffset) { StyleRange range = eachPosition.createStyleRange(); styleRanges.add(range); } } StyleRange[] styleRangesArray = new StyleRange[styleRanges.size()]; styleRangesArray = styleRanges.toArray(styleRangesArray); presentation.replaceStyleRanges(styleRangesArray); return presentation; }
Source:
<code><START> private Selection<ResourceBasedNode< ? >> getExplorerSelection() { <END> final Selection<ResourceBasedNode< ? >> selection = (Selection<ResourceBasedNode< ? >>)projectExplorer.getSelection(); if (selection == null || selection.isEmpty() || selection.getHeadElement() instanceof HasStorablePath) { return selection; } else { return null; } }</code><technical_language>SelectionAgen in this case</technical_language>

Target:
private Selection<?> getExplorerSelection() { final Selection<?> selection = selectionAgent.getSelection(); if (selection == null || selection.isEmpty() || selection.getHeadElement() instanceof HasStorablePath) { return selection; } else { return null; } }
Source:
<code>private void parseValue(String fieldName) { int chr = sr.read(); if (chr == QUOTATION_MARK) { int beginToken = sr.getPosition(); <START> while (true) { <END> chr = sr.read(); if (chr == BACKSLASH) { sr.read(); } else if (chr == QUOTATION_MARK) { break; } else if (chr == -1) { throw new IllegalArgumentException("EOF reached while reading JSON field name"); } } addParameter(fieldName, beginToken, sr.getPosition()-1, false, true); } else if (Character.isDigit(chr) || chr == '-') { sr.unreadLastCharacter(); int beginToken = sr.getPosition(); do { chr = sr.read(); if (chr == -1) { throw new IllegalArgumentException("Reached EOF while reading number"); } } while (Character.isDigit(chr) || (chr == '.') || (chr == 'e') || (chr == 'E') || (chr == '+') || (chr == '-')); sr.unreadLastCharacter(); addParameter(fieldName, beginToken, sr.getPosition()-1, true, false); } else if (chr == BEGIN_OBJECT) { sr.unreadLastCharacter(); parseObject(); } else if (chr == BEGIN_ARRAY) { parseArray(fieldName); } else if (chr == END_ARRAY) { sr.unreadLastCharacter(); } else if (chr == 't' || chr == 'T') { sr.unreadLastCharacter(); parseToken("true"); } else if (chr == 'f' || chr == 'F') { sr.unreadLastCharacter(); parseToken("false"); } else if (chr == 'n' || chr == 'N') { sr.unreadLastCharacter(); parseToken("null"); } else if (chr == -1) { throw new IllegalArgumentException("EOF reached prematurely"); } else { throw new IllegalArgumentException("Unknown value type at position " + sr.getPosition()); } }</code><technical_language>Worth extracting a method change read of property name (to fixing well)</technical_language>

Target:
private void parseValue(String fieldName) { int chr = sr.read(); if (chr == QUOTATION_MARK) { int beginToken = sr.getPosition(); readEscapedString(); addParameter(fieldName, beginToken, sr.getPosition()-1, false, true); } else if (Character.isDigit(chr) || chr == '-') { sr.unreadLastCharacter(); int beginToken = sr.getPosition(); do { chr = sr.read(); if (chr == -1) { throw new IllegalArgumentException("Reached EOF while reading number"); } } while (Character.isDigit(chr) || (chr == '.') || (chr == 'e') || (chr == 'E') || (chr == '+') || (chr == '-')); sr.unreadLastCharacter(); addParameter(fieldName, beginToken, sr.getPosition()-1, true, false); } else if (chr == BEGIN_OBJECT) { sr.unreadLastCharacter(); parseObject(); } else if (chr == BEGIN_ARRAY) { parseArray(fieldName); } else if (chr == END_ARRAY) { sr.unreadLastCharacter(); } else if (chr == 't' || chr == 'T') { sr.unreadLastCharacter(); parseToken("true"); } else if (chr == 'f' || chr == 'F') { sr.unreadLastCharacter(); parseToken("false"); } else if (chr == 'n' || chr == 'N') { sr.unreadLastCharacter(); parseToken("null"); } else if (chr == -1) { throw new IllegalArgumentException("EOF reached prematurely"); } else { throw new IllegalArgumentException("Unknown value type at position " + sr.getPosition()); } }
Source:
<code>public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(connectionString) .buildClient(); QueueProperties queueProperties = administrationClient.getQueue("<<queue-name>>"); System.out.printf("Before update queue properties status :[%s], Max Delivery count :[%d]. %n" , queueProperties.getStatus(), queueProperties.getMaxDeliveryCount()); <START> queueProperties.setStatus(EntityStatus.DISABLED); <END> queueProperties.setMaxDeliveryCount(9); QueueProperties updatedQueueProperties = administrationClient.updateQueue(queueProperties); System.out.printf("After update queue properties status :[%s], Max Delivery count :[%d]. %n" , updatedQueueProperties.getStatus(), updatedQueueProperties.getMaxDeliveryCount()); }</code><technical_language>This is a fluent model, chain properties</technical_language>

Target:
public static void main(String[] args) { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusAdministrationClient client = new ServiceBusAdministrationClientBuilder() .connectionString(connectionString) .buildClient(); QueueProperties properties = client.getQueue("<<queue-name>>"); System.out.printf("Before queue properties LockDuration: [%d seconds], Max Delivery count: [%d].%n", properties.getLockDuration().getSeconds(), properties.getMaxDeliveryCount()); properties.setMaxDeliveryCount(10).setLockDuration(Duration.ofSeconds(60)); QueueProperties updatedProperties = client.updateQueue(properties); System.out.printf("After queue properties LockDuration: [%d seconds], Max Delivery count: [%d].%n", updatedProperties.getLockDuration().getSeconds(), updatedProperties.getMaxDeliveryCount()); }
Source:
<code>public void setValues(LinkedFile linkedFile) { description.set(linkedFile.getDescription()); <START> link.setValue(linkedFile.getLink()); END> selectedExternalFileType.setValue(null); Optional<ExternalFileType> fileType = externalFileTypes.fromLinkedFile(linkedFile, false); if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } }</code><technical_language>relativize command is missing, right? if (linkedFile.isOnline()) link.setValue(...) else link.setValue(relativize(Paths.get(...)))</technical_language>

Target:
public void setValues(LinkedFile linkedFile) { description.set(linkedFile.getDescription()); if (linkedFile.isOnlineLink()) { link.setValue(linkedFile.getLink()); } else { link.setValue(relativize(Paths.get(linkedFile.getLink()))); } selectedExternalFileType.setValue(null); Optional<ExternalFileType> fileType = externalFileTypes.fromLinkedFile(linkedFile, false); if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } }
Source:
<code>public void run() throws IOException, InterruptedException { String jobName = System.getenv(AbstractProcessJob.JOB_NAME_ENV); _logger.info("Running job " + jobName); String tokenFile = System.getenv(HADOOP_TOKEN_FILE_LOCATION); UserGroupInformation proxyUser = HadoopSecureWrapperUtils.setupProxyUser(_jobProps, tokenFile, _logger); <START> proxyUser.doAs(new PrivilegedExceptionAction<Void>() { <END> @Override public Void run() throws Exception { runCopyTdToHdfs(); return null; } }); }</code><technical_language>this code handle scenario proxying is required? Note Spark if/else statement depending shouldProxy() <LINK_0></technical_language>

Target:
public void run() throws IOException, InterruptedException { String jobName = System.getenv(AbstractProcessJob.JOB_NAME_ENV); _logger.info("Running job " + jobName); if (HadoopSecureWrapperUtils.shouldProxy(_jobProps)) { String tokenFile = System.getenv(HADOOP_TOKEN_FILE_LOCATION); UserGroupInformation proxyUser = HadoopSecureWrapperUtils.setupProxyUser(_jobProps, tokenFile, _logger); proxyUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runCopyTdToHdfs(); return null; } }); } else { runCopyTdToHdfs(); } }
Source:
<code>private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && <START> (!formatString.contains("{}") && formatString.contains("%")); <END> }</code><technical_language>useless parenthesis</technical_language>

Target:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && !formatString.contains("{}") && formatString.contains("%"); }
Source:
<code>public void testAlreadyCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false, NEVER_SKIP)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3 | WebSocketExtension.RSV1, Unpooled.wrappedBuffer(payload)); encoderChannel.writeOutbound(frame); BinaryWebSocketFrame newFrame = encoderChannel.readOutbound(); <START> assertNotNull(newFrame); <END> assertNotNull(newFrame.content()); assertEquals(WebSocketExtension.RSV3 | WebSocketExtension.RSV1, newFrame.rsv()); assertEquals(300, newFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; newFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); newFrame.release(); }</code><technical_language>this removed</technical_language>

Target:
public void testAlreadyCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3 | WebSocketExtension.RSV1, Unpooled.wrappedBuffer(payload)); assertTrue(encoderChannel.writeOutbound(frame)); BinaryWebSocketFrame newFrame = encoderChannel.readOutbound(); assertNotNull(newFrame); assertNotNull(newFrame.content()); assertEquals(WebSocketExtension.RSV3 | WebSocketExtension.RSV1, newFrame.rsv()); assertEquals(300, newFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; newFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); newFrame.release(); }
Source:
<code>private void forwardMessage(FirebaseMessage o) { Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody(o); try { getProcessor().process(exchange); } catch (Exception e) { <START> throw new FirebaseException("Message forwarding failed", e); <END> } finally { if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException()); } } }</code><technical_language>Dont throw this exception, set exchange instead, exchange.setException, handled in finally block configured exception handler consumer</technical_language>

Target:
private void forwardMessage(FirebaseMessage o) { Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody(o); try { getProcessor().process(exchange); } catch (Exception e) { exchange.setException(new RuntimeCamelException("Message forwarding failed", e)); } finally { if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException()); } } }
Source:
<code>public static RegistrationRequest getNewInstance(String json) { RegistrationRequest request = new RegistrationRequest(); try { JsonObject o = new JsonParser().parse(json).getAsJsonObject(); if (o.has("name")) request.setName(o.get("name").getAsString()); if (o.has("description")) request.setDescription(o.get("description").getAsString()); JsonObject config = o.get("configuration").getAsJsonObject(); GridNodeConfiguration configuration = new JsonToBeanConverter().convert(GridNodeConfiguration.class, config); request.setConfiguration(configuration); if (o.has("id")) request.configuration.id = o.get("id").getAsString(); JsonArray capabilities = o.get("capabilities").getAsJsonArray(); for (int i = 0; i < capabilities.size(); i++) { DesiredCapabilities cap = new JsonToBeanConverter() .convert(DesiredCapabilities.class, capabilities.get(i)); request.capabilities.add(cap); } return request; } catch (JsonSyntaxException e) { <START> return null; <END> } }</code><technical_language>parseGrid1Request throw return RegirstaionRequest. this throw? return empty request object</technical_language>

Target:
public static RegistrationRequest getNewInstance(String json) throws JsonSyntaxException { RegistrationRequest request = new RegistrationRequest(); JsonObject o = new JsonParser().parse(json).getAsJsonObject(); if (o.has("name")) { request.setName(o.get("name").getAsString()); } if (o.has("description")) { request.setDescription(o.get("description").getAsString()); } JsonObject config = o.get("configuration").getAsJsonObject(); GridNodeConfiguration configuration = new JsonToBeanConverter().convert(GridNodeConfiguration.class, config); request.setConfiguration(configuration); if (o.has("id")) { request.configuration.id = o.get("id").getAsString(); } JsonArray capabilities = o.get("capabilities").getAsJsonArray(); for (int i = 0; i < capabilities.size(); i++) { DesiredCapabilities cap = new JsonToBeanConverter() .convert(DesiredCapabilities.class, capabilities.get(i)); request.capabilities.add(cap); } return request; }
Source:
<code>private void insertWrongReference() throws NamingException, SQLException, AssertionFailedError { DataSource ds = DataSourceHelper.getDataSource("jdbc/canrollback"); try (Connection db = ds.getConnection()) { try (Statement st = db.createStatement()) { st.execute("INSERT INTO footest (a) VALUES (0)"); st.execute("INSERT INTO footest (a) VALUES (1)"); st.execute("INSERT INTO footest (a) VALUES (1)"); } } catch (SQLException cause) { <START> cause.printStackTrace(); <END> TransactionHelper.setTransactionRollbackOnly(); throw cause; } finally { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); try (Connection db = ds.getConnection()) { try (Statement st = db.createStatement()) { try (ResultSet rs = st.executeQuery("SELECT a FROM footest WHERE a = 0")) { if (rs.next()) { throw new AssertionFailedError("connection was not rollbacked"); } } } } } }</code><technical_language>Remove this</technical_language>

Target:
private void insertWrongReference() throws NamingException, SQLException, AssertionFailedError { DataSource ds = DataSourceHelper.getDataSource("jdbc/canrollback"); try (Connection db = ds.getConnection()) { try (Statement st = db.createStatement()) { st.execute("INSERT INTO footest (a) VALUES (0)"); st.execute("INSERT INTO footest (a) VALUES (1)"); st.execute("INSERT INTO footest (a) VALUES (1)"); } } catch (SQLException cause) { TransactionHelper.setTransactionRollbackOnly(); throw cause; } finally { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); try (Connection db = ds.getConnection()) { try (Statement st = db.createStatement()) { try (ResultSet rs = st.executeQuery("SELECT a FROM footest WHERE a = 0")) { if (rs.next()) { throw new AssertionFailedError("connection was not rollbacked"); } } } } } }
Source:
<code>protected Object getTargetObject(boolean key) { Object targetObject; if (key) { <START> if (keyData.isPortable() || keyData.getType() == JAVASCRIPT_JSON_SERIALIZATION_TYPE) { <END> targetObject = keyData; } else { targetObject = getKey(); } } else { if (valueObject == null) { if (valueData.isPortable() || valueData.getType() == JAVASCRIPT_JSON_SERIALIZATION_TYPE) { targetObject = valueData; } else { targetObject = getValue(); } } else { if (valueObject instanceof Portable) { targetObject = getValueData(); } else { targetObject = getValue(); } } } return targetObject; }</code><technical_language>in other checks below</technical_language>

Target:
protected Object getTargetObject(boolean key) { Object targetObject; if (key) { if (keyData.isPortable() || keyData.isJson()) { targetObject = keyData; } else { targetObject = getKey(); } } else { if (valueObject == null) { if (valueData.isPortable() || valueData.isJson()) { targetObject = valueData; } else { targetObject = getValue(); } } else { if (valueObject instanceof Portable) { targetObject = getValueData(); } else { targetObject = getValue(); } } } return targetObject; }
Source:
<code>public void testAddJumpStitchPoint() { <START> EmbroideryStream stream = new DSTStream(); <END> stream.addJump(); stream.addStitchPoint(0, 0); assertEquals(1, stream.getPointList().size()); assertTrue(stream.getPointList().get(0).isJumpPoint()); }</code><technical_language>Please move a @before function</technical_language>

Target:
public void testAddJumpStitchPoint() { stream.addJump(); stream.addStitchPoint(0, 0); assertEquals(1, stream.getPointList().size()); assertTrue(stream.getPointList().get(0).isJumpPoint()); }
Source:
<code>private void printIfEnabled(MetricAttribute type, String status) { <START> if(isMetricAttributeDisabled(type)) { <END> return; } output.println(status); }</code><technical_language>I condition statement. I need isMetricAttributeDisabled method well. if (!getDisabledMetricAttributes().contains(type)) { output.println(status); }</technical_language>

Target:
private void printIfEnabled(MetricAttribute type, String status) { if(getDisabledMetricAttributes().contains(type)) { return; } output.println(status); }
Source:
<code>protected SIRIUS getParentOf(SIRIUS description) { SIRIUS nextParent = null; EStructuralFeature extensionFeature = description.eClass().getEStructuralFeature(EXTENDS_FEATURE_NAME); if (extensionFeature instanceof EReference) { EReference extendsEReference = (EReference) extensionFeature; if (extendsEReference.getEType().equals(description.eClass()) && !extendsEReference.isMany()) { Object currentExtends = description.eGet(extendsEReference); if <START> (currentExtends != null && <END> description.getClass().isAssignableFrom(currentExtends.getClass())) { nextParent = this.descriptionClass.cast(currentExtends); } } } return nextParent; }</code><technical_language>java8-isation [optional]</technical_language>

Target:
protected Optional<SIRIUS> getParentOf(SIRIUS description) { Optional<SIRIUS> nextParent = Optional.empty(); EStructuralFeature extensionFeature = description.eClass().getEStructuralFeature(EXTENDS_FEATURE_NAME); if (extensionFeature instanceof EReference) { EReference extendsEReference = (EReference) extensionFeature; if (extendsEReference.getEType().equals(description.eClass()) && !extendsEReference.isMany()) { Optional<Object> currentExtends = Optional.ofNullable(description.eGet(extendsEReference)); nextParent = currentExtends.filter(ref -> description.getClass().isAssignableFrom(ref.getClass())).map(ref -> this.descriptionClass.cast(ref)); } } return nextParent; }
Source:
<code>private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); <START> Jenkins.get().addNode(slave); <END> return slave; }</code><technical_language>changing Jenkins.getInstance() Jenkins.getActiveInstance() Jenkins.get() is ok, long get() is right method in situation - code getters for good reasons. claiming this code good reasons, a possibility consider justification is. However, changes done a separate PR</technical_language>

Target:
private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); Jenkins.getInstance().addNode(slave); return slave; }