auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { // Dont' change the password START throw BennuCoreDomainException.passwordIsEmpty(); END } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } //avoid same password if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); } Won't this change prevent the use of the User Management interface without inputting the password? (For when information other than the password is being edited).

Target:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { // Don't change the password. return; } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } //avoid same password if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }
Source:
public void onClick(View v) { if(v.getId() == R.id.twitter_login){ TwitterAuthorizationTask task = new TwitterAuthorizationTask(); getInjector().injectMembers(task); START task.execute(); END } } あ、ごめんなさい。`SafeAsyncTask`はInjectをする必要がありません。`(new TwitterAuthorizationTask()).execute()`で問題ないです。 もう一つの`SafeAsyncTask`についても同じですね……

Target:
public void onClick(View v) { if(v.getId() == R.id.twitter_login){ TwitterAuthorizationTask task = new TwitterAuthorizationTask(); task.execute(); } }
Source:
public void parserShouldReturnGlobPattern() throws Exception { START Assert.assertEquals("**/*.csv", locustParser.getDefaultGlobPattern()); END } use import static method for remove `Assert.`

Target:
public void parserShouldReturnGlobPattern() throws Exception { assertEquals("**/*.csv", locustParser.getDefaultGlobPattern()); }
Source:
private Boolean checkCanSyncSolr(String studyStr, String sessionId) throws CatalogException { String userId = catalogManager.getUserManager().getUserId(sessionId); START if ("admin".equals(userId)) { END return true; } return authorizationManager.checkCanSyncSolr(studyStr, userId); } This if condition should actually be in authorizationManager.checkCanSyncSolr(studyStr, userId).

Target:
private Boolean checkCanSyncSolr(String studyStr, String sessionId) throws CatalogException { String userId = catalogManager.getUserManager().getUserId(sessionId); return authorizationManager.checkCanSyncSolr(studyStr, userId); }
Source:
START private long getClinicalId(boolean silent, String clinicalStrAux) throws CatalogDBException { END long clinicalId = Long.parseLong(clinicalStrAux); try { clinicalDBAdaptor.checkId(clinicalId); } catch (CatalogException e) { if (silent) { return -1L; } else { throw e; } } return clinicalId; } This method should throw a CatalogException

Target:
private long getClinicalId(boolean silent, String clinicalStrAux) throws CatalogException { long clinicalId = Long.parseLong(clinicalStrAux); try { clinicalDBAdaptor.checkId(clinicalId); } catch (CatalogException e) { if (silent) { return -1L; } else { throw e; } } return clinicalId; }
Source:
protected PairSupplier<Q, E> getPairSupplier(){ if (endpointProvider == null){ throw new NullPointerException("Init endpoint provider!"); } if (queryProvider == null) { START logger.info("Query provider is null."); END } if (pairSupplier == null){ pairSupplier = pairSupplierFactory.create(queryProvider, endpointProvider); } return pairSupplier; } please, don't. it will log for every starting load thread. we have already tried :)

Target:
protected PairSupplier<Q, E> getPairSupplier(){ return pairSupplier; }
Source:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return (metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_TG) || metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_MONITORING)); START } END in general: it is necessary to review what Origins are still in code. IMHO SESSION_SCOPE_MONITORING should not appear in the code after this commit

Target:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return metricNameDto.getOrigin() == MetricNameDto.Origin.SESSION_SCOPE_TG; }
Source:
public ResponseEntity<?> deleteProject(@PathVariable Long projectId) { START ProjectEntity project = new ProjectEntity(); END project.setId(projectId); projectService.delete(project); return ResponseEntity.noContent().build(); } I'd extract this to service method deleteProjectById(id)

Target:
public ResponseEntity<?> deleteProject(@PathVariable Long projectId) { projectService.delete(projectId); return ResponseEntity.noContent().build(); }
Source:
private void getData(String sessionId) { if (sessionId.equals(this.sessionId)) { // data already fetched return; } // fetch data this.sessionId = sessionId; SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup( START databaseService.getWebClientProperties().isShowOnlyMatchedTests(), END EnumSet.of(SessionMatchingSetup.MatchBy.ALL)); RootNode controlTree = databaseService.getControlTreeForSessions( new HashSet<String>(Arrays.asList(sessionId)), sessionMatchingSetup); fetchSessionScopeData(controlTree); fetchPerTestData(controlTree); } no properties already. please replace with true

Target:
private void getData(String sessionId) { if (sessionId.equals(this.sessionId)) { // data already fetched return; } // fetch data this.sessionId = sessionId; SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup( true, EnumSet.of(SessionMatchingSetup.MatchBy.ALL)); RootNode controlTree = databaseService.getControlTreeForSessions( new HashSet<String>(Arrays.asList(sessionId)), sessionMatchingSetup); fetchSessionScopeData(controlTree); fetchPerTestData(controlTree); }
Source:
public WebClientStartProperties getWebClientStartProperties() { WebClientProperties webClientProperties = databaseService.getWebClientProperties(); Map<String, Set<String>> defaultMonitoringParameters = databaseService.getDefaultMonitoringParameters(); WebClientStartProperties startProperties = new WebClientStartProperties(); START startProperties.setWebClientProperties(webClientProperties); END startProperties.setDefaultMonitoringParameters(defaultMonitoringParameters); return startProperties; } Why it is so complicated?

Target:
public WebClientStartProperties getWebClientStartProperties() { WebClientStartProperties startProperties = new WebClientStartProperties(); startProperties.setWebClientProperties(databaseService.getWebClientProperties()); startProperties.setDefaultMonitoringParameters(databaseService.getDefaultMonitoringParameters()); return startProperties; }
Source:
public void addChild(Widget widget) { switch (layout) { case ONE_COLUMN: addChildOneColumn(widget); break; case TWO_COLUMNS: addChildTwoColumns(widget); break; default: START Info.display("DynamicLayoutPanel", "addChild with layout " + layout + " not yet implemented"); END } } is it intended to be so?

Target:
public void addChild(Widget widget) { switch (layout) { case TWO_COLUMNS: addChildTwoColumns(widget); break; default: addChildOneColumn(widget); } }
Source:
START private static Namespace of(List<String> values) { END return new Namespace(values); } you don't need this function, you can use constructor directly

Target:
public static Namespace of(List<String> values) { return new Namespace(values); }
Source:
START public static Namespace of(String... values) { END List<String> list = Lists.newArrayList(values); return new Namespace(list); } Why we need to change this class at all ? I can not find a reason.

Target:
public static Namespace of(String... values) { return of(Lists.newArrayList(values)); }
Source:
public void setTreeViewGroupMetricsToNodeRuleProvider(TreeViewGroupMetricsToNodeRuleProvider treeViewGroupMetricsToNodeRuleProvider) { this.treeViewGroupMetricsToNodeRuleProvider = treeViewGroupMetricsToNodeRuleProvider; START setDefaultMonitoringParams(this.treeViewGroupMetricsToNodeRuleProvider.getMonitoringPlotGroups()); END } Please avoid to use another setter in your setter

Target:
public void setTreeViewGroupMetricsToNodeRuleProvider(TreeViewGroupMetricsToNodeRuleProvider treeViewGroupMetricsToNodeRuleProvider) { this.treeViewGroupMetricsToNodeRuleProvider = treeViewGroupMetricsToNodeRuleProvider; }
Source:
START public synchronized List<TagDto> getAllTags() { END List<TagEntity> tags = (List<TagEntity>) (entityManager.createQuery("select te from TagEntity as te")).getResultList(); List<TagDto> allTags = new ArrayList<TagDto>(); if (!tags.isEmpty()) { for (TagEntity tagEntity : tags) { allTags.add(new TagDto(tagEntity.getName(), tagEntity.getDescription())); } } return allTags; } why synchronized?

Target:
public List<TagDto> getAllTags() { List<TagEntity> tags = (List<TagEntity>) (entityManager.createQuery("select te from TagEntity as te")).getResultList(); List<TagDto> allTags = new ArrayList<TagDto>(); if (!tags.isEmpty()) { for (TagEntity tagEntity : tags) { allTags.add(new TagDto(tagEntity.getName(), tagEntity.getDescription())); } } return allTags; }
Source:
private S getService(String url) { S service = services.get(url); if (service == null) { service = initService(url); services.putIfAbsent(url, service); } START return service; END } I would write return services.get(url) here

Target:
private S getService(String url) { S service = services.get(url); if (service == null) { service = initService(url); services.putIfAbsent(url, service); service = services.get(url); } return service; }
Source:
private boolean shouldProcess(final Triple triple) { return triple != null && triple.getSubject().isURI() && triple.getSubject().toString() .startsWith(prefix == null ? "" : prefix) && TO_RESOLVE.contains(triple.getPredicate().toString()) START & !(triple.getObject().isLiteral()); END } Bitwise `&` here?

Target:
private boolean shouldProcess(final Triple triple) { return triple != null && triple.getSubject().isURI() && triple.getSubject().toString() .startsWith(prefix == null ? "" : prefix) && TO_RESOLVE.contains(triple.getPredicate().toString()) && !(triple.getObject().isLiteral()); }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { blockFactory = new BlockItemFactory(entityManager); START inventoryManager = new InventoryAuthoritySystem(); END EntityRef flagTaker = event.getInstigator(); // If the flag being taken is a red flag and the player is on the black team, let them take the flag if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); attachParticleEmitterToPlayer(flagTaker); } } I doubt if inventoryManager needs initialisation since it's being injected

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef flagTaker = event.getInstigator(); // If the flag being taken is a red flag and the player is on the black team, let them take the flag if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); } }
Source:
public void initialise() { for (EntityRef entity : entityManager.getEntitiesWith(ScoreComponent.class)) { START scoreEntity = entity; END score = scoreEntity.getComponent(ScoreComponent.class); } if (!scoreEntity.equals(EntityRef.NULL)) { scoreArea = find("scoreArea", UIText.class); scoreArea.bindText(new ReadOnlyBinding<String>() { @Override public String get() { return String.valueOf(score.blackScore); } }); } // String scoreText = "Red Team: " + redScore + " " + // "Black Team: " + blackScore; // scoreArea.setText(String.format(scoreText)); } Are you expecting one or more entities with `ScoreComponent.class`? If it is more than one, why store one of them (the last one) as `private EntityRef scoreEntity;` Currently, the variable is only accessed in the local scope of `initialise`.

Target:
public void initialise() { }
Source:
public void initialize() { BlockManager blockManager = CoreRegistry.get(BlockManager.class); theme = BlockTheme.builder(blockManager) .register(DefaultBlockType.ROOF_FLAT, "LightAndShadowResources:MagicPlank") .register(DefaultBlockType.FENCE, "LightAndShadowResources:MagicGlass") .register(DefaultBlockType.BUILDING_WALL, "LightAndShadowResources:MagicStone") .build(); START redDice = CoreRegistry.get(BlockManager.class).getBlock("LightAndShadowResources:redDice"); END blackDice = CoreRegistry.get(BlockManager.class).getBlock("LightAndShadowResources:blackDice"); } Convert "L&SResources:redDice" to a constant as well. Try to avoid hard coded strings as much as possible, everywhere.

Target:
public void initialize() { BlockManager blockManager = CoreRegistry.get(BlockManager.class); theme = BlockTheme.builder(blockManager) .register(DefaultBlockType.ROOF_FLAT, "LightAndShadowResources:MagicPlank") .register(DefaultBlockType.FENCE, "LightAndShadowResources:MagicGlass") .register(DefaultBlockType.BUILDING_WALL, "LightAndShadowResources:MagicStone") .build(); }
Source:
public void process(GeneratingRegion region) { START Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 8, 4); END BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); } Why do we need the extension? I removed and tested it with abnormally large bases and it seems to work.

Target:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }
Source:
public void process(GeneratingRegion region) { START Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 0, 0); END BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); } This is unnecessary. Remove the extension altogether. `Border3D border = region.getBorderForFacet(BaseFacet.class);`

Target:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }
Source:
public void init() { START startTime = new Date(); END try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } } Looks like, once initialized, `startTime`'s value will never change. If so, you can remove setting its value in `init()`, and make it `final`: ``` private final Date startTime = new Date(); ```

Target:
public void init() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } }
Source:
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if (entity instanceof Comment) { Comment comment = (Comment) entity; START KafkaJsonOutput output = new KafkaJsonOutput(comment.getCommentUri(), KafkaEventType.DELETE); END sendMessage("ambra-comment", output); } super.onDelete(entity, id, state, propertyNames, types); } What do you think of moving the creation of `KafkaJsonOutput` inside `sendMessage`?

Target:
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if (entity instanceof Comment) { Comment comment = (Comment) entity; sendMessage("ambra-comment", comment.getCommentUri(), KafkaEventType.DELETE); } super.onDelete(entity, id, state, propertyNames, types); }
Source:
public JsonElement serialize(JsonSerializationContext context) { JsonObject serialized = context.serialize(flag).getAsJsonObject(); // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity. // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body. serialized.add("body", serialized.remove("comment")); if (flag.getUserProfileId() != null) { START serialized.remove("userProfileID"); END serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId()))); } serialized.add("flaggedComment", context.serialize(flaggedComment)); return serialized; } I think this line serialized.remove("userProfileID") should be before if() block.

Target:
public JsonElement serialize(JsonSerializationContext context) { JsonObject serialized = context.serialize(flag).getAsJsonObject(); // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity. // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body. serialized.add("body", serialized.remove("comment")); serialized.remove("userProfileID"); if (flag.getUserProfileId() != null) { serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId()))); } serialized.add("flaggedComment", context.serialize(flaggedComment)); return serialized; }
Source:
public String getCrepoKey() { START return entry; END } shouldn't this be `key`?

Target:
public String getCrepoKey() { return key; }
Source:
public RelationshipView(String type, Doi doi, String title) { this.type = Objects.requireNonNull(type); START this.doi = Objects.requireNonNull(doi).getName(); END this.title = title; } This can just be `doi.getName()`, which serves the same purpose as `Objects.requireNonNull`: throwing an NPE if `doi` is null.

Target:
public RelationshipView(String type, Doi doi, String title) { this.type = Objects.requireNonNull(type); this.doi = doi.getName(); this.title = Objects.requireNonNull(title); }
Source:
START public ResponseEntity<?> syndicate(HttpServletRequest request, END @RequestParam(value = "revision", required = false) Integer revisionNumber) throws IOException { ArticleVersionIdentifier versionId = getArticleVersionIdentifier(request, revisionNumber); SyndicationInputView input = readJsonFromRequest(request, SyndicationInputView.class); Syndication created = syndicationCrudService.syndicate(versionId, input.getTarget()); return reportOk(created.toString()); } you can use `ResponseEntity<Object>` instead of `?`.

Target:
public ResponseEntity<Object> syndicate(HttpServletRequest request, @RequestParam(value = "revision", required = false) Integer revisionNumber) throws IOException { ArticleVersionIdentifier versionId = getArticleVersionIdentifier(request, revisionNumber); SyndicationInputView input = readJsonFromRequest(request, SyndicationInputView.class); Syndication created = syndicationCrudService.syndicate(versionId, input.getTarget()); return reportOk(created.toString()); }
Source:
private void assertArticleExistence(ArticleIdentity id, boolean expectedToExist) { boolean received404 = false; try { articleCrudService.readXml(id); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException me) { received404 = true; } catch(NotFoundException nfe) { START received404 = true; END } catch (RestClientException e) { throw e; } assertEquals(received404, !expectedToExist, (expectedToExist ? "Article expected to exist but doesn't" : "Article expected not to exist but does")); } You can use the "or version" of the catch block to make this more succinct: ``` } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException | NotFoundException ex) { received404 = true; } ```

Target:
private void assertArticleExistence(ArticleIdentity id, boolean expectedToExist) { boolean received404 = false; try { articleCrudService.readXml(id); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException|NotFoundException nfe) { received404 = true; } catch (RestClientException e) { throw e; } assertEquals(received404, !expectedToExist, (expectedToExist ? "Article expected to exist but doesn't" : "Article expected not to exist but does")); }
Source:
private void checkFileExistence(AssetFileIdentity fileIdentity, boolean expectedToExist) throws IOException { try (InputStream stream = contentRepoService.getLatestRepoObject(fileIdentity.toString())) { assertNotNull(stream); assertTrue(expectedToExist); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException me) { assertFalse(expectedToExist); } catch (NotFoundException nfe) { START assertFalse(expectedToExist); END } catch (ContentRepoException e) { throw e; } } Use a single catch block.

Target:
private void checkFileExistence(AssetFileIdentity fileIdentity, boolean expectedToExist) throws IOException { try (InputStream stream = contentRepoService.getLatestRepoObject(fileIdentity.toString())) { assertNotNull(stream); assertTrue(expectedToExist); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException|NotFoundException nfe) { assertFalse(expectedToExist); } catch (ContentRepoException e) { throw e; } }
Source:
public List<String> getRawTerms(Document articleXml) throws IOException { ArrayList<String> rawTerms = new ArrayList<>(); rawTerms.add("dummy raw term"); START return rawTerms; END } Guava's `ImmutableList.of(...)` can save you a little typing in cases like this.

Target:
public List<String> getRawTerms(Document articleXml) throws IOException { return ImmutableList.of("dummy raw term"); }
Source:
String summaryString(Response response) { try { if (response.getExample() != null) return response.getFormulaAnswer(); if (response.getLines().size() > 0) return response.getLines().get(0); } catch (Exception e) { START return null; END } return null; } Should return e.toString() or something? Silent failures are sometimes no fun to track down...

Target:
String summaryString(Response response) { if (response.getExample() != null) return response.getFormulaAnswer(); if (response.getLines().size() > 0) return response.getLines().get(0); return null; }
Source:
START private void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { END for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && c != null) { c.connect(false); } jenkins.addNode(slave); } } ```suggestion private static void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { ```

Target:
private static void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && c != null) { c.connect(false); } jenkins.addNode(slave); } }
Source:
public SpotConfiguration(boolean useBidPrice) { this.useBidPrice = useBidPrice; this.spotMaxBidPrice = ""; START this.fallbackToOndemand = false; this.spotBlockReservationDuration = 0; END } These are default for bool and int so no need to clarify. ```suggestion ```

Target:
public SpotConfiguration(boolean useBidPrice) { this.useBidPrice = useBidPrice; this.spotMaxBidPrice = ""; }
Source:
private void fetchLiveInstanceData(boolean force) throws AmazonClientException { START return fetchLiveInstanceData(force, 25); END } ```suggestion fetchLiveInstanceData(force, 25); ```

Target:
private void fetchLiveInstanceData(boolean force) throws AmazonClientException { fetchLiveInstanceData(force, 25); }
Source:
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { START return Objects.requireNonNull(nodeProperties); END } Nit: it might make more sense to throw an `IllegalStateException` here instead of `NullPointerException`.

Target:
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { if (nodeProperties == null) throw new IllegalStateException(); return nodeProperties; }
Source:
public static AmazonEC2Client createAmazonEC2Mock(@Nullable Answer defaultAnswer) { AmazonEC2Client mock; if (defaultAnswer != null) { mock = Mockito.mock(AmazonEC2Client.class, defaultAnswer); } else { START mock = Mockito.mock(AmazonEC2Client.class); END mockDescribeRegions(mock); mockDescribeInstances(mock); mockDescribeImages(mock); mockDescribeKeyPairs(mock); mockDescribeSecurityGroups(mock); mockDescribeSubnets(mock); mockRunInstances(mock); mockTerminateInstances(mock); } return mock; } Nit: You can use static imports for `Mockito` methods.

Target:
public static AmazonEC2Client createAmazonEC2Mock(@Nullable Answer defaultAnswer) { AmazonEC2Client mock; if (defaultAnswer != null) { mock = mock(AmazonEC2Client.class, defaultAnswer); } else { mock = mock(AmazonEC2Client.class); mockDescribeRegions(mock); mockDescribeInstances(mock); mockDescribeImages(mock); mockDescribeKeyPairs(mock); mockDescribeSecurityGroups(mock); mockDescribeSubnets(mock); mockRunInstances(mock); mockTerminateInstances(mock); } return mock; }
Source:
public BurstableUnlimitedMode getBurstableUnlimitedMode() { if (burstableUnlimitedMode == null) { // For backward-compatibility. return t2Unlimited ? BurstableUnlimitedMode.ENABLED : BurstableUnlimitedMode.DEFAULT; } START return burstableUnlimitedMode; END } Yous should resolve this bit in `readResolve`

Target:
public BurstableUnlimitedMode getBurstableUnlimitedMode() { return burstableUnlimitedMode; }
Source:
public void testEmptyConfig() throws Exception { final AmazonEC2Cloud ec2Cloud = (AmazonEC2Cloud) Jenkins.get().getCloud("ec2-"); assertNotNull(ec2Cloud); START assertEquals(ec2Cloud.getTemplates().size(), 0); END } ```suggestion assertEquals(0, ec2Cloud.getTemplates().size()); ``` These assertions are usually ordered `assertEquals(expected, actual)`.

Target:
public void testEmptyConfig() throws Exception { final AmazonEC2Cloud ec2Cloud = (AmazonEC2Cloud) Jenkins.get().getCloud("ec2-"); assertNotNull(ec2Cloud); assertEquals(0, ec2Cloud.getTemplates().size()); }
Source:
public WinConnection(String host, String username, String password) { this.host = host; this.username = username; this.password = password; this.smbclient = new SMBClient(); START this.authentication = new AuthenticationContext(username, password.toCharArray(), null);; END } ```suggestion this.authentication = new AuthenticationContext(username, password.toCharArray(), null); ```

Target:
public WinConnection(String host, String username, String password) { this.host = host; this.username = username; this.password = password; this.smbclient = new SMBClient(); this.authentication = new AuthenticationContext(username, password.toCharArray(), null); }
Source:
private static void setLogStreamLevel(int level) { START LogStream.level = 6; END } hardcoded value instead of argument? :)

Target:
private static void setLogStreamLevel(int level) { LogStream.level = level; }
Source:
public int getLaunchTimeout() { if( StringUtils.isEmpty(launchTimeout) || Integer.parseInt(launchTimeout) <= 0 ) START launchTimeout = "" + Integer.MAX_VALUE; END return Integer.parseInt(launchTimeout); } using a toString() is probably better than building a string

Target:
public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; }
Source:
public static Integer get(final String key) { START if (key == null) { END return R.drawable.acc_none; } return map.containsKey(key.toUpperCase(Locale.getDefault())) ? map.get(key.toUpperCase()) : R.drawable.acc_none; } Can this key ever get null?

Target:
public static Integer get(final String key) { return map.containsKey(key.toUpperCase(Locale.getDefault())) ? map.get(key.toUpperCase()) : R.drawable.acc_none; }
Source:
public void onBackPressed() { START if (!shouldShowDualPane) { END if (isDrawerOpen()) { toggleNavigationDrawer(false); } } if (navigationDrawer.fetchDefaultPosition() != navigationDrawer.getCheckedItemPosition()) { navigationDrawer.checkDefaultItemPosition(); return; } super.onBackPressed(); } You can make single check out of this `if (!shouldShowDualPane && isDrawerOpen())` since you interested only in single outcome

Target:
public void onBackPressed() { if (!shouldShowDualPane && isDrawerOpen()) { toggleNavigationDrawer(false); } if (navigationDrawer.fetchDefaultPosition() != navigationDrawer.getCheckedItemPosition()) { navigationDrawer.checkDefaultItemPosition(); return; } super.onBackPressed(); }
Source:
public void onRefreshEvent(RefreshEvent event) { START Log.d("YOLO", getClass().getSimpleName() + " is refrehshing!"); END startLoadingData(); } Rubbish

Target:
public void onRefreshEvent(RefreshEvent event) { startLoadingData(); }
Source:
START public Object getItem(int position) { END return itemsList.get(position); } This should return T.

Target:
public T getItem(int position){ return itemsList.get(position); }
Source:
public ERDatabaseAttachment _process(EOEditingContext editingContext, File uploadedFile, String recommendedFileName, String mimeType, String configurationName, String ownerID, boolean pendingDelete) throws IOException { NSData data = new NSData(uploadedFile.toURI().toURL()); ERDatabaseAttachment attachment = _process(editingContext, data, recommendedFileName, mimeType, configurationName); if (pendingDelete) { START uploadedFile.delete(); END } return attachment; } If line 33 throws an error this line won't be reached. Prior this PR that delete would always be executed in a finally block.

Target:
public ERDatabaseAttachment _process(EOEditingContext editingContext, File uploadedFile, String recommendedFileName, String mimeType, String configurationName, String ownerID, boolean pendingDelete) throws IOException { try { NSData data = new NSData(uploadedFile.toURI().toURL()); ERDatabaseAttachment attachment = _process(editingContext, data, recommendedFileName, mimeType, configurationName); return attachment; } finally { if (pendingDelete) { uploadedFile.delete(); } } }
Source:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); START if (hasBinding(Keys.SortKey)) { END String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } if(result != null) { return result; } } return NSArray.EmptyArray; } Should be moved down into the `if(result != null) {` block as sorting a non-existing result does not make sense and even will throw an exception in ERXArrayUtilities.

Target:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); if(result != null) { if (hasBinding(Keys.SortKey)) { String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } return result; } } return NSArray.EmptyArray; }
Source:
public Node apply(@Nonnull Node node) { for (Rule rule : rules) { if (!rule.matches(node)) { return rule.apply(node); } } for (Rule rule : rules) { node = rule.apply(node); if (isErrorResult(node)) START return createNodeUsingFactory(node); END } return createNodeUsingFactory(node); } Why do you return a new node instead of the failing one?

Target:
public Node apply(@Nonnull Node node) { for (Rule rule : rules) { if (!rule.matches(node)) { return rule.apply(node); } } for (Rule rule : rules) { node = rule.apply(node); if (isErrorResult(node)) return node; } return createNodeUsingFactory(node); }
Source:
public ObjectRule untitledRaml() { return super.untitledRaml() .with(annotationTypesField()) .with(annotationField()) .with(typesField()) .with(usesField()) START .with(exclusiveKeys(BaseRamlGrammar.TYPES_KEY_NAME, BaseRamlGrammar.SCHEMAS_KEY_NAME)); END } use static imports

Target:
public ObjectRule untitledRaml() { return super.untitledRaml() .with(annotationTypesField()) .with(annotationField()) .with(typesField()) .with(usesField()) .with(exclusiveKeys(TYPES_KEY_NAME, SCHEMAS_KEY_NAME)); }
Source:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { START incidentDtos[i] = fromIncident(incidents[0]); END } return incidentDtos; } We should update the index to point to the current iteration of the loop. This way we always convert the first incident only. ```suggestion incidentDtos[i] = fromIncident(incidents[i]); ```

Target:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { incidentDtos[i] = fromIncident(incidents[i]); } return incidentDtos; }
Source:
public SetLicenseKeyCmd(final String licenseKey) { START this.LicenseKey = licenseKey; END } ```suggestion this.licenseKey = licenseKey; ```

Target:
public SetLicenseKeyCmd(final String licenseKey) { this.licenseKey = licenseKey; }
Source:
START public static Restaurant createFakeRestaurant(ParseUser u) throws ParseException { END ParseUser restUser = new ParseUser(); restUser.setUsername("testRestUser"); restUser.setPassword("12345"); restUser.setObjectId("_marksrest"); return new Restaurant(restUser); } shouldn't you set the object Id?

Target:
public static Restaurant createFakeRestaurant(ParseUser u) throws ParseException { return createFakeRestaurant(); }
Source:
START private void disableMenuItem(Menu menu, int rID) { END MenuItem item = menu.findItem(rID); item.setEnabled(false); item.setVisible(false); } We need to add a null check for safety. Because our layouts are going to be dynamic we need to be able handle the case where we try to disable a MenuItem that doesn't exist. I know in the previous example there wasn't a null check. Thats because that piece of code was in an optionsmenyoncreate call where we can assert the existence of certain items. In summary for disabling a menu item first check if its null. That means it already is gone.

Target:
private void disableMenuItem(Menu menu, int rID) { MenuItem item = menu.findItem(rID); if(item != null) { item.setEnabled(false); item.setVisible(false); } }
Source:
private void enableMenuItem(Menu menu, int rID) { START MenuItem item = menu.findItem(rID); END item.setEnabled(true); item.setVisible(true); } Add a null check, if it is null add a menu item or invalidate the menu. Find some way of adding the menu item back in the view

Target:
private void enableMenuItem(Menu menu, int rID) { MenuItem item = menu.findItem(rID); if(item == null) { menu.add(rID); } item.setEnabled(true); item.setVisible(true); }
Source:
START public static long[] copyFromIntArray(int[] source) { END long[] dest = new long[source.length]; for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } return dest; } @fchauveau there is no null handling of source, is this intended ?

Target:
public static long[] copyFromIntArray(int[] source) { if(source == null){ return new long[0]; } long[] dest = new long[source.length]; for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } return dest; }
Source:
public QueryRegistrationHandler(final TSDB tsdb, final HttpHandler next) { this.tsdb = tsdb; this.next = next; closeTask = new Runnable() { @Override public void run() { START LOG.info("Closing the query!"); END } }; } debug and log the hash of the query for tracking

Target:
public QueryRegistrationHandler(final TSDB tsdb, final HttpHandler next) { this.tsdb = tsdb; this.next = next; }
Source:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) START .putString(Strings.nullToEmpty(pattern.pattern()), Const.UTF8_CHARSET) END .hash(); return hc; } This (And other filters) need their type as well. The reason being we could have a `TagValueRegexp` with a filter like `.*` and a `FieldRegexp` filter with the same filter and want them to hash to something different. For this and other regex filters, you can omit the pattern from equals and hash as those are just compiled versions of the `filter` field. It's ok not to use the parsed version even if someone puts a space in front or back.

Target:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) .putString(Strings.nullToEmpty(getType()), Const.UTF8_CHARSET) .hash(); return hc; }
Source:
public void prefixKeyWithSalt(final byte[] row_key, final int bucket) { if (salt_width == 1) { row_key[0] = (byte) bucket; return; } int shift = 0; for (int i = 0; i <= salt_width; i++) { START row_key[salt_width - i] = 0; END row_key[salt_width - i] = (byte) (bucket >>> shift); shift += 8; } } This will replace the first byte of the metric name when i = 0. Also, total iterations are salt_width + 1. Starting from i = 1 may fix it.

Target:
public void prefixKeyWithSalt(final byte[] row_key, final int bucket) { if (salt_width == 1) { row_key[0] = (byte) bucket; return; } int shift = 0; for (int i = 0; i < salt_width; i++) { row_key[salt_width - i - 1] = 0; row_key[salt_width - i - 1] = (byte) (bucket >>> shift); shift += 8; } }
Source:
public final boolean getBoolean(final String property) { final String val = this.properties.getProperty(property).toUpperCase(); START if (val == null) END throw new NullPointerException(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; } I believe this isn't necessary. If the property wasn't set, an NPE would have been thrown already when the code attempts to call `.toUpperCase()`. This line and the next may be removed.

Target:
public final boolean getBoolean(final String property) { final String val = this.properties.get(property).toUpperCase(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }
Source:
private PrintLayer createMyPlacesPrintLayer(int categoryId, LayerProperties requestedLayer) { int opacity = requestedLayer.getOpacity() != null ? requestedLayer.getOpacity() : 100; if (opacity <= 0) { // Ignore fully transparent layers return null; } PrintLayer layer = new PrintLayer(); layer.setId(categoryId); layer.setType("myplaces"); layer.setVersion("1.3.0"); layer.setName("oskari:my_places_categories"); START layer.setSrsName("EPSG:3067"); END layer.setOpacity(opacity); return layer; } You should take srs name from properties. There's something like oskari.native.srs that's used elsewhere in the codebase.

Target:
private PrintLayer createMyPlacesPrintLayer(int categoryId, LayerProperties requestedLayer) { int opacity = requestedLayer.getOpacity() != null ? requestedLayer.getOpacity() : 100; if (opacity <= 0) { // Ignore fully transparent layers return null; } PrintLayer layer = new PrintLayer(); layer.setId(categoryId); layer.setType("myplaces"); layer.setVersion("1.3.0"); layer.setName("oskari:my_places_categories"); layer.setOpacity(opacity); return layer; }
Source:
public boolean deleteIndicatorData(long indicator, long regionset, int year) { try (final SqlSession session = factory.openSession()) { int updated = getMapper(session).deleteData(indicator, regionset, year); if(updated != 1) { START throw new ServiceRuntimeException("Delete wasn't successful"); END } } return true; } I wouldn't expect `public boolean delete()` to throw a RuntimeException in case there was nothing to delete. Instead I'd expect false to be returned, and an Exception to be thrown only in the case there was an actual Exception (like the DB connection unexpectedly error'd or something)

Target:
public boolean deleteIndicatorData(long indicator, long regionset, int year) { try (final SqlSession session = factory.openSession()) { int updated = getMapper(session).deleteData(indicator, regionset, year); return updated != 0; } }
Source:
public void init() { super.init(); START if(userLayerDbService == null) { END userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); } } No way to set the userLayerDbService so this will always be true

Target:
public void init() { userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); }
Source:
public void init() { START super.init(); END if(userLayerDbService == null) { setUserLayerDbService(OskariComponentManager.getComponentOfType(UserLayerDbService.class)); } } Calling `super.init();` is unnecessary, since `ActionHandlers` implementation is empty.

Target:
public void init() { userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); }
Source:
private String getFileExt(String name) { int i = name.lastIndexOf('.'); START if (i < 0 || i > name.length() - 1) { END return null; } return name.substring(i + 1); } True, I guess that would return an empty string instead of the null we now get on such a filename? Maybe i +1 == name.length() or name.endsWith(".") would be clearer? With "foo." isn't the i=3 and name.length() - 1 = 3 so the check wouldn't work properly now? Should check this in the morning, it's way too late for thinking this through :D

Target:
private String getFileExt(String name) { int i = name.lastIndexOf('.'); if (i < 0 || i + 1 == name.length()) { return null; } return name.substring(i + 1); }
Source:
public void handleAction(ActionParameters params) throws ActionException { START END log.debug("Getting layer groups"); JSONArray json = getGroupJSON(-1,params, 0); log.debug("Got layer groups"); ResponseHelper.writeResponse(params, json); } This file would read better if you have handleAction before getGroupJSON() since handleAction is the access point that uses getGroupJSON().

Target:
public void handleAction(ActionParameters params) throws ActionException { log.debug("Getting layer groups"); JSONArray json = getGroupJSON(-1, params); log.debug("Got layer groups"); ResponseHelper.writeResponse(params, json); }
Source:
public ReferencedEnvelope getEnlargedEnvelope() { if(this.enlargedEnvelope == null) { START log.warn("Enlarged envelope not created"); END if(this.envelope == null) { this.getEnvelope(); } return this.envelope; } return this.enlargedEnvelope; } I think this could be logged as just debug.

Target:
public ReferencedEnvelope getEnlargedEnvelope() { if(this.enlargedEnvelope == null) { log.debug("Enlarged envelope not created"); if(this.envelope == null) { this.getEnvelope(); } return this.envelope; } return this.enlargedEnvelope; }
Source:
public boolean servesCoverage(String coverageId) { START if (coverageId == null || coverageId.length() == 0) { END return false; } return contents.getCoverageSummary().stream() .anyMatch(c -> coverageId.equals(c.getCoverageId())); } String.isEmpty() is used in other places of Oskari. No biggie - just a heads up.

Target:
public boolean servesCoverage(String coverageId) { if (coverageId == null || coverageId.isEmpty()) { return false; } return contents.getCoverageSummary().stream() .anyMatch(c -> coverageId.equals(c.getCoverageId())); }
Source:
public boolean supportsFormat(String format) { START if (format == null || format.length() == 0) { END return false; } return serviceMetadata.getSupportedFormats().stream() .anyMatch(f -> format.equals(f)); } Same here with length() == 0 -> isEmpty(). I'll stop mentioning for the rest of these :)

Target:
public boolean supportsFormat(String format) { if (format == null || format.isEmpty()) { return false; } return serviceMetadata.getSupportedFormats().stream() .anyMatch(f -> format.equals(f)); }
Source:
private List<Row> updateRows(List<Row> rows) { for (ListIterator<Row> it = rows.listIterator(); it.hasNext();) { final Row original = (Row) it.next(); START validateUpdateType(original); END final Row updated = update(original); it.set(updated); } return rows; } Why add this here?

Target:
private List<Row> updateRows(List<Row> rows) { for (ListIterator<Row> it = rows.listIterator(); it.hasNext();) { final Row original = (Row) it.next(); final Row updated = update(original); it.set(updated); } return rows; }
Source:
public static int getMajorVersion(String stringToParse){ String fullVersion = getVersion(stringToParse); if(fullVersion != null) { int firstDot = fullVersion.indexOf('.'); if(firstDot >= 0) { return Integer.valueOf(fullVersion.substring(0, firstDot)); } } START return 0; END } `0` is a bad exception value I think, because versions might easily be 0-based. Better to go with `-1`.

Target:
public static int getMajorVersion(String stringToParse){ String fullVersion = getVersion(stringToParse); if(fullVersion != null) { int firstDot = fullVersion.indexOf('.'); if(firstDot >= 0) { return Integer.valueOf(fullVersion.substring(0, firstDot)); } } return -1; }
Source:
private Set<String> getSchemaSQLServerNames(DatabaseMetaData metaData) throws SQLException { // Distinct schema names. metaData.getTables() is a denormalized // resultset Set<String> schemas = new HashSet<>(); ResultSet rs = metaData.getTables(_catalogName, null, null, JdbcUtils.getTableTypesAsStrings(_tableTypes)); while (rs.next()) { schemas.add(rs.getString("TABLE_SCHEM")); } START FileHelper.safeClose(rs); END return schemas; } This should be in a finally block that you create once you have the ResultSet: ``` ResultSet rs = ... try { ... } finally { FileHelper.safeClose(rs); } ```

Target:
private Set<String> getSchemaSQLServerNames(DatabaseMetaData metaData) throws SQLException { // Distinct schema names. metaData.getTables() is a denormalized // resultset Set<String> schemas = new HashSet<>(); ResultSet rs = null; try { rs = metaData.getTables(_catalogName, null, null, JdbcUtils.getTableTypesAsStrings(_tableTypes)); while (rs.next()) { schemas.add(rs.getString("TABLE_SCHEM")); } }finally { FileHelper.safeClose(rs); } return schemas; }
Source:
START public RowInsertionBuilder value(final int columnIndex, final Object value) { END values.set(columnIndex, value); return this; } Wait ... So how would a user be able to pass in a column that's not already defined? I see that `HBaseTable` returns `HBaseColumn`s which represent that paths down into the column families as defined by the `SimpleTableDef`s. So it's kind of dynamic based on that `SimpleTableDef`. But is there some way that the columns will change after creating the simple table def? Or rather - in the middle of a update script? I don't see how that would be possible, but maybe it is, and then I think that deserves some clarification (since it's unusual for MetaModel).

Target:
public RowInsertionBuilder value(final int columnIndex, final Object value) { return value(columnIndex, value, null); }
Source:
START private void appendRemarks(MutableColumn column, String remarks) { END final String existingRemarks = column.getRemarks(); if (existingRemarks == null) { column.setRemarks(remarks); } else { column.setRemarks(existingRemarks + ", " + remarks); } } Could be static, if I'm not blind

Target:
private static void appendRemarks(MutableColumn column, String remarks) { final String existingRemarks = column.getRemarks(); if (existingRemarks == null) { column.setRemarks(remarks); } else { column.setRemarks(existingRemarks + ", " + remarks); } }
Source:
public WildcardPattern(String pattern, char wildcard) { _pattern = pattern; _wildcard = wildcard; START _startsWithDelim = (_pattern.charAt(0) == _wildcard); END _endsWithDelim = (_pattern.charAt(pattern.length() - 1) == _wildcard); } This will throw IndexOutOfBoundsException if an empty string is passed as the pattern.

Target:
public WildcardPattern(String pattern, char wildcard) { _pattern = pattern; _wildcard = wildcard; if(_pattern.isEmpty()){ _startsWithDelim = _endsWithDelim = false; } else { _startsWithDelim = _pattern.charAt(0) == _wildcard; _endsWithDelim = _pattern.charAt(pattern.length() - 1) == _wildcard; } }
Source:
public CustomColumnNamingStrategy(String... columnNames) { START this.columnNames = Arrays.asList(columnNames); END } No biggie, but I guess best practice would be to do `this(Arrays.asList(columnNames));`

Target:
public CustomColumnNamingStrategy(String... columnNames) { this(Arrays.asList(columnNames)); }
Source:
private static void indexTweeterDocument(String indexType, int id, Date date) { try { client.prepareIndex(indexName, indexType).setSource(buildTweeterJson(id, date)) .setId("tweet_" + indexType + "_" + id).execute().actionGet(); } catch (Exception ex) { START System.out.println("Exception indexing documents!!!!!"); END } } Wouldn't a rethrow be better?

Target:
private static void indexTweeterDocument(String indexType, int id, Date date) { client.prepareIndex(indexName, indexType).setSource(buildTweeterJson(id, date)) .setId("tweet_" + indexType + "_" + id).execute().actionGet(); }