auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testContinuousQuery() throws Exception { try(IgniteEx g1 = startGrid(1)) { IgniteCache<Integer, Integer> cache = ignite.createCache("cache-1"); try(QueryCursor qry = cache.query(new ContinuousQuery<>() .setInitialQuery(new ScanQuery<>()) .setPageSize(100) .setTimeInterval(1000) .setLocalListener(evts -> { }) .setRemoteFilterFactory(() -> evt -> true) )) { for (int i=0; i<100; i++) cache.put(i, i); List<List<?>> qrys = execute(ignite, "SELECT " + " CACHE_NAME, " + " BUFFER_SIZE, " + " INTERVAL, " + " NODE_ID, " + " LOCAL_LISTENER, " + " REMOTE_FILTER, " + " LOCAL_TRANSFORMED_LISTENER, " + " REMOTE_TRANSFORMER " + "FROM SYS.QUERY_CONTINUOUS"); assertEquals(1, qrys.size()); for (List<?> cq : qrys) checkContinuousQuery(cq, true); qrys = execute(g1, "SELECT " + " CACHE_NAME, " + " BUFFER_SIZE, " + " INTERVAL, " + " NODE_ID, " + " LOCAL_LISTENER, " + " REMOTE_FILTER, " + " LOCAL_TRANSFORMED_LISTENER, " + " REMOTE_TRANSFORMER " + "FROM SYS.QUERY_CONTINUOUS"); <START> assertEquals(1, qrys.size()); for (List<?> cq : qrys) checkContinuousQuery(cq, false); <END> } } }</code><technical_language>code duplication</technical_language>

Target:
public void testContinuousQuery() throws Exception { try(IgniteEx remoteNode = startGrid(1)) { IgniteCache<Integer, Integer> cache = ignite.createCache("cache-1"); assertTrue(execute(ignite, "SELECT * FROM SYS.QUERY_CONTINUOUS").isEmpty()); assertTrue(execute(remoteNode, "SELECT * FROM SYS.QUERY_CONTINUOUS").isEmpty()); try(QueryCursor qry = cache.query(new ContinuousQuery<>() .setInitialQuery(new ScanQuery<>()) .setPageSize(100) .setTimeInterval(1000) .setLocalListener(evts -> { }) .setRemoteFilterFactory(() -> evt -> true) )) { for (int i=0; i<100; i++) cache.put(i, i); checkContinuouQueryView(ignite, true); checkContinuouQueryView(remoteNode, false); } assertTrue(execute(ignite, "SELECT * FROM SYS.QUERY_CONTINUOUS").isEmpty()); assertTrue(execute(remoteNode, "SELECT * FROM SYS.QUERY_CONTINUOUS").isEmpty()); } }
Source:
<code>public List<String> getDependencies() { <START> return MoreObjects.firstNonNull(dependencies, new ArrayList<>()); <END> }</code><technical_language>produces needed objects. wasting CPU time</technical_language>

Target:
public List<String> getDependencies() { return dependencies != null ? dependencies : new ArrayList<>(); }
Source:
<code><START> boolean scheduleHeronWorkers(PackingPlan topologyPacking) { <END> this.packing = topologyPacking; for (Entry<String, ContainerPlan> entry : topologyPacking.containers.entrySet()) { Resource reqResource = entry.getValue().resource; int mem = getMemInMBForExecutor(reqResource); int cores = getCpuForExecutor(reqResource); AllocatedEvaluator container = launchContainerForExecutor(entry.getKey(), cores, mem); if (container == null) { return false; } } return true; }</code><technical_language>a terminology perspective HeronWorker mean</technical_language>

Target:
void scheduleHeronWorkers(PackingPlan topologyPacking) throws ContainerAllocationException { this.packing = topologyPacking; for (Entry<String, ContainerPlan> entry : topologyPacking.getContainers().entrySet()) { Resource reqResource = entry.getValue().getResource(); int mem = getMemInMBForExecutor(reqResource); int cores = getCpuForExecutor(reqResource); launchContainerForExecutor(entry.getKey(), cores, mem); } }
Source:
<code>private void expandPreviousExpandedAndPaths(Object[] previous, TreeViewer viewer, Set<IPath> additionalPaths) { StagingViewContentProvider stagedContentProvider = getContentProvider( viewer); int count = stagedContentProvider.getCount(); updateAutoExpand(viewer, count); if (viewer.getAutoExpandLevel() == AbstractTreeViewer.ALL_LEVELS) { return; } if (getPresentation() == Presentation.LIST) return; Set<IPath> paths = new HashSet<>(additionalPaths); for (Object element : previous) if (element instanceof StagingFolderEntry) addPathAndParentPaths(((StagingFolderEntry) element).getPath(), paths); for (Object element : getVisibleExpandedElements(viewer)) if (element instanceof StagingFolderEntry) addPathAndParentPaths(((StagingFolderEntry) element).getPath(), <START> paths); <END> List<StagingFolderEntry> expand = new ArrayList<>(); calculateNodesToExpand(paths, stagedContentProvider.getElements(null), expand); viewer.setExpandedElements(expand.toArray()); }</code><technical_language>Please add missing braces (also in legacy for-loop above)</technical_language>

Target:
private void expandPreviousExpandedAndPaths(Object[] previous, TreeViewer viewer, Set<IPath> additionalPaths) { StagingViewContentProvider stagedContentProvider = getContentProvider( viewer); int count = stagedContentProvider.getCount(); updateAutoExpand(viewer, count); if (viewer.getAutoExpandLevel() == AbstractTreeViewer.ALL_LEVELS) { return; } if (getPresentation() == Presentation.LIST) return; Set<IPath> paths = new HashSet<>(additionalPaths); for (Object element : previous) { if (element instanceof StagingFolderEntry) addPathAndParentPaths(((StagingFolderEntry) element).getPath(), paths); } for (Object element : getVisibleExpandedElements(viewer)) { if (element instanceof StagingFolderEntry) addPathAndParentPaths(((StagingFolderEntry) element).getPath(), paths); } List<StagingFolderEntry> expand = new ArrayList<>(); calculateNodesToExpand(paths, stagedContentProvider.getElements(null), expand); viewer.setExpandedElements(expand.toArray()); }
Source:
<code>public final void onTimer(MessageCollector collector, TaskCoordinator coordinator) { long startNs = System.nanoTime(); Collection<RM> results = handleTimer(collector, coordinator); long endNs = System.nanoTime(); <START> this.handleTimerTimer.update(endNs - startNs); <END> results.forEach(rm -> this.registeredOperators.forEach(op -> op.onMessage(rm, collector, coordinator))); this.registeredOperators.forEach(op -> op.onTimer(collector, coordinator)); }</code><technical_language>nit: handleTimerTimer feels slightly redundant? :) Maybe, like: handleTimerNs. variable name metric names slightly consistent</technical_language>

Target:
public final void onTimer(MessageCollector collector, TaskCoordinator coordinator) { long startNs = this.highResClock.nanoTime(); Collection<RM> results = handleTimer(collector, coordinator); long endNs = this.highResClock.nanoTime(); this.handleTimerNs.update(endNs - startNs); results.forEach(rm -> this.registeredOperators.forEach(op -> op.onMessage(rm, collector, coordinator))); this.registeredOperators.forEach(op -> op.onTimer(collector, coordinator)); }
Source:
<code>public List<String> getPossibleValues(String var) { List<String> vals = new ArrayList<>(); switch (var.toLowerCase()) { <START> case m_debugEnvVar: <END> vals.add("true"); vals.add("false"); return vals; default: return null; } }</code><technical_language>I a abstraction for list of values for a variable. consider this improvement for next iteration</technical_language>

Target:
List<String> getPossibleValues(String var) { List<String> vals = new ArrayList<>(); switch (var.toLowerCase()) { case debugEnvVar: vals.add("true"); vals.add("false"); return vals; default: return null; } }
Source:
<code>public boolean updateState(OutOfBandManagement.PowerState oldStatus, OutOfBandManagement.PowerState.Event event, OutOfBandManagement.PowerState newStatus, OutOfBandManagement vo, Object data) { OutOfBandManagementVO oobmHost = lockRow(vo.getId(), true); if (oobmHost == null) { if (LOG.isTraceEnabled()) { LOG.trace("Failed to lock row to update state for out-of-band management host id: " + vo.getHostId()); } return false; } Long newManagementServerId = event.getServerId(); if (oldStatus == newStatus && (oobmHost.getManagementServerId() != null && oobmHost.getManagementServerId().equals(newManagementServerId))) { return false; } if (event == OutOfBandManagement.PowerState.Event.Disabled) { newManagementServerId = null; } SearchCriteria<OutOfBandManagementVO> sc = StateUpdateSearch.create(); sc.setParameters("status", oldStatus); sc.setParameters("id", oobmHost.getId()); sc.setParameters("update", oobmHost.getUpdateCount()); oobmHost.incrUpdateCount(); UpdateBuilder ub = getUpdateBuilder(oobmHost); ub.set(oobmHost, PowerStateAttr, newStatus); ub.set(oobmHost, UpdateTimeAttr, DateUtil.currentGMTTime()); ub.set(oobmHost, MsIdAttr, newManagementServerId); int result = update(ub, sc, null); if (LOG.isDebugEnabled() && result <= 0) { <START> LOG.debug(String.format("Failed to update out-of-band management power state from:%s to:%s due to event:%s for the host id:%d", oldStatus, newStatus, event, oobmHost.getHostId())); <END> } return result > 0; }</code><technical_language>this message a WARN</technical_language>

Target:
public boolean updateState(OutOfBandManagement.PowerState oldStatus, OutOfBandManagement.PowerState.Event event, OutOfBandManagement.PowerState newStatus, OutOfBandManagement vo, Object data) { OutOfBandManagementVO oobmHost = (OutOfBandManagementVO) vo; if (oobmHost == null) { if (LOG.isTraceEnabled()) { LOG.trace("Invalid out-of-band management host view object provided"); } return false; } Long newManagementServerId = event.getServerId(); if (oldStatus == newStatus && (oobmHost.getManagementServerId() != null && oobmHost.getManagementServerId().equals(newManagementServerId))) { return false; } if (event == OutOfBandManagement.PowerState.Event.Disabled) { newManagementServerId = null; } SearchCriteria<OutOfBandManagementVO> sc = StateUpdateSearch.create(); sc.setParameters("status", oldStatus); sc.setParameters("id", oobmHost.getId()); sc.setParameters("update", oobmHost.getUpdateCount()); oobmHost.incrUpdateCount(); UpdateBuilder ub = getUpdateBuilder(oobmHost); ub.set(oobmHost, PowerStateAttr, newStatus); ub.set(oobmHost, UpdateTimeAttr, DateUtil.currentGMTTime()); ub.set(oobmHost, MsIdAttr, newManagementServerId); int result = update(ub, sc, null); if (LOG.isDebugEnabled() && result <= 0) { LOG.debug(String.format("Failed to update out-of-band management power state from:%s to:%s due to event:%s for the host id:%d", oldStatus, newStatus, event, oobmHost.getHostId())); } return result > 0; }
Source:
<code>public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; <START> ExternalDataInstanceFactory.registerExternalDataInstanceBuilder(CaseInstanceTreeElement.MODEL_NAME, new CaseDataInstance()); <END> if (currentApp.initializeApplication()) { resourceState = STATE_READY; this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform()); } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); }</code><technical_language>talk strategies for putting this in app</technical_language>

Target:
public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; if (currentApp.initializeApplication()) { resourceState = STATE_READY; this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform()); } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); }
Source:
<code>public void migrationConstructorUpdatesSignedOnValue() throws Exception { String json = "{\"name\":\"test name\",\"birthdate\":\"1970-01-01\"}"; ConsentSignature sig = BridgeObjectMapper.get().readValue(json, ConsentSignature.class); ConsentSignature updated = new ConsentSignature.Builder().withConsentSignature(sig) .withSignedOn(SIGNED_ON_TIMESTAMP.getMillis()).build(); assertEquals("test name", updated.getName()); assertEquals("1970-01-01", updated.getBirthdate()); assertEquals(SIGNED_ON_TIMESTAMP.getMillis(), updated.getSignedOn()); <START> String timestamp = new DateTime(SIGNED_ON_TIMESTAMP, DateTimeZone.UTC).toString(); <END> json = "{\"name\":\"test name\",\"birthdate\":\"1970-01-01\",\"signedOn\":\""+timestamp+"\"}"; sig = BridgeObjectMapper.get().readValue(json, ConsentSignature.class); assertEquals(SIGNED_ON_TIMESTAMP.getMillis(), sig.getSignedOn()); }</code><technical_language>call SIGNED_ON_TIMESTAMP.toString()</technical_language>

Target:
public void migrationConstructorUpdatesSignedOnValue() throws Exception { String json = "{\"name\":\"test name\",\"birthdate\":\"1970-01-01\"}"; ConsentSignature sig = BridgeObjectMapper.get().readValue(json, ConsentSignature.class); ConsentSignature updated = new ConsentSignature.Builder().withConsentSignature(sig) .withSignedOn(SIGNED_ON_TIMESTAMP.getMillis()).build(); assertEquals("test name", updated.getName()); assertEquals("1970-01-01", updated.getBirthdate()); assertEquals(SIGNED_ON_TIMESTAMP.getMillis(), updated.getSignedOn()); json = "{\"name\":\"test name\",\"birthdate\":\"1970-01-01\",\"signedOn\":\"" + SIGNED_ON_TIMESTAMP.toString() + "\"}"; sig = BridgeObjectMapper.get().readValue(json, ConsentSignature.class); assertEquals(SIGNED_ON_TIMESTAMP.getMillis(), sig.getSignedOn()); }
Source:
<code>public DateTime extractDateTime(AbstractInstance instance) { Attributes attributes = instance.getAttributes(); try { Date currentTimeMillis = dateFormat.parse((String) attributes.get("created_at")); return new DateTime(currentTimeMillis); } catch (ParseException e) { logger.error("Error parsing date", e); } <START> return new DateTime(); <END> }</code><technical_language>this is desired behavior if date time parsed</technical_language>

Target:
public DateTime extractDateTime(AbstractInstance instance) { Attributes attributes = instance.getAttributes(); try { Date currentTimeMillis = dateFormat.parse((String) attributes.get(dateAttribute)); return new DateTime(currentTimeMillis, DateTimeZone.UTC); } catch (ParseException e) { logger.error("Error parsing date", e); } return new DateTime(); }
Source:
<code>public static String lpad(String base, Integer len, String pad) { if (len < 0) { return null; } else if (len == 0) { return ""; } char[] data = new char[len]; <START> char[] baseChars = base.toCharArray(); <END> char[] padChars = pad.toCharArray(); int pos = Math.max(len - base.length(), 0); int i = 0; while (i < pos) { int j = 0; while (j < pad.length() && j < pos - i) { data[i + j] = padChars[j]; j += 1; } i += pad.length(); } i = 0; while (pos + i < len && i < base.length()) { data[pos + i] = baseChars[i]; i += 1; } return new String(data); }</code><technical_language>Is a reason copy base pad char arrays instead of calling charAt(index) original strings</technical_language>

Target:
public static String lpad(String base, Integer len, String pad) { if (len < 0) { return null; } else if (len == 0) { return ""; } char[] data = new char[len]; int pos = Math.max(len - base.length(), 0); for (int i = 0; i < pos; i += pad.length()) { for (int j = 0; j < pad.length() && j < pos - i; j++) { data[i + j] = pad.charAt(j); } } for (int i = 0; pos + i < len && i < base.length(); i++) { data[pos + i] = base.charAt(i); } return new String(data); }
Source:
<code>private Snapshot.LocationType getLocationType() { if (Snapshot.LocationType.values() == null || Snapshot.LocationType.values().length == 0) { return null; } Snapshot.LocationType locationTypeToReturn = Snapshot.LocationType.values()[0]; if (locationType != null && locationType >= 1 && locationType <= Snapshot.LocationType.values().length) { <START> locationTypeToReturn = Snapshot.LocationType.values()[locationType-1]; <END> } return locationTypeToReturn; }</code><technical_language>I suggest keeping enum values upper case, locationType string in cmd LocationType.valueOf(cmd.locationType.toUpperCase()) <LINK_0></technical_language>

Target:
private Snapshot.LocationType getLocationType() { if (Snapshot.LocationType.values() == null || Snapshot.LocationType.values().length == 0 || locationType == null) { return null; } try { String lType = locationType.trim().toUpperCase(); return Snapshot.LocationType.valueOf(lType); } catch (IllegalArgumentException e) { String errMesg = "Invalid locationType " + locationType + "Specified for volume " + getVolumeId() + " Valid values are: primary,secondary "; s_logger.warn(errMesg); throw new CloudRuntimeException(errMesg); } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MENU_REMEMBER_PW_AND_LOGOUT) { launchRememberPasswordConfirmDialog(); } <START> return true; <END> }</code><technical_language>consider calling return super.onOptionsItemSelected(item);</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MENU_REMEMBER_PW_AND_LOGOUT) { launchRememberPasswordConfirmDialog(); } return super.onOptionsItemSelected(item); }
Source:
<code>public Response removeCartridge( @PathParam("cartridgeType") String cartridgeType) throws RestAPIException { try { StratosApiV41Utils.removeCartridge(cartridgeType); return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS, String.format("Cartridge deleted successfully: [cartridge-type] %s", cartridgeType))).build(); <START> } catch (RemoteException e) { <END> return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean( ResponseMessageBean.ERROR, e.getMessage())).build(); } catch (CloudControllerServiceInvalidCartridgeTypeExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean( ResponseMessageBean.ERROR, e.getFaultMessage().getInvalidCartridgeTypeException().getMessage())) .build(); } catch (CloudControllerServiceCartridgeNotFoundExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean( ResponseMessageBean.ERROR, e.getFaultMessage().getCartridgeNotFoundException().getMessage())).build(); } }</code><technical_language>send BAD_REQUEST for Remote exception. throw a RestAPIException for that, internal server error</technical_language>

Target:
public Response removeCartridge( @PathParam("cartridgeType") String cartridgeType) throws RestAPIException { try { StratosApiV41Utils.removeCartridge(cartridgeType); return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS, String.format("Cartridge deleted successfully: [cartridge-type] %s", cartridgeType))).build(); } catch (RemoteException e) { throw new RestAPIException(e.getMessage()); } catch (CloudControllerServiceInvalidCartridgeTypeExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean( ResponseMessageBean.ERROR, e.getFaultMessage().getInvalidCartridgeTypeException().getMessage())) .build(); } catch (CloudControllerServiceCartridgeNotFoundExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean( ResponseMessageBean.ERROR, e.getFaultMessage().getCartridgeNotFoundException().getMessage())).build(); } }
Source:
<code>public boolean addDependency(Taint<T> other) { if(other == null) { return false; } else if(BIT_SET_CAPACITY > 0) { BitSet prev = this.labelBitSet; <START> this.labelBitSet = BitSet.union(this.labelBitSet, other.labelBitSet); <END> return (prev == null && this.labelBitSet != null) || (prev != null && !prev.equals(this.labelBitSet)); } else { PowerSetTree.SetNode union = this.labelSet.union(other.labelSet); boolean changed = (this.labelSet != union); this.labelSet = union; return changed; } }</code><technical_language>BitSets pooled, instead a method mutate this.labelBitSet</technical_language>

Target:
public boolean addDependency(Taint<T> other) { if(other == null) { return false; } else if(BIT_SET_CAPACITY > 0) { if(this.labelBitSet == null && other.labelBitSet != null) { this.labelBitSet = other.labelBitSet.copy(); return true; } else if(this.labelBitSet != null && !this.labelBitSet.isSuperset(other.labelBitSet)) { this.labelBitSet.union(other.labelBitSet); return true; } else { return false; } } else { PowerSetTree.SetNode union = this.labelSet.union(other.labelSet); boolean changed = (this.labelSet != union); this.labelSet = union; return changed; } }
Source:
<code>public void transientFilesWorkAreCleaned() throws Exception { <START> LogFactory.getLog(WorkManagerTest.class).fatal("\"default\" is processing=" + service.isProcessingEnabled("default")); <END> final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }</code><technical_language>Do want this log.fatal</technical_language>

Target:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }
Source:
<code>public void start() { Profiler profiler = Profiler.create(LOG).startInfo("Register rules"); try (DbSession session = dbClient.openSession(false)) { Map<RuleKey, RuleDefinitionDto> allRules = loadRules(session); List<RuleKey> keysToIndex = new ArrayList<>(); RulesDefinition.Context context = defLoader.load(); for (RulesDefinition.ExtendedRepository repoDef : getRepositories(context)) { if (languages.get(repoDef.language()) != null) { for (RulesDefinition.Rule ruleDef : repoDef.rules()) { boolean relevantForIndex = registerRule(ruleDef, allRules, session); if (relevantForIndex) { keysToIndex.add(RuleKey.of(ruleDef.repository().key(), ruleDef.key())); } } session.commit(); } } List<RuleDefinitionDto> removedRules = processRemainingDbRules(allRules.values(), session); List<ActiveRuleChange> changes = removeActiveRulesOnStillExistingRepositories(session, removedRules, context); session.commit(); persistRepositories(session, context.repositories()); <START> ruleIndexer.delete(removedRules.stream().map(r -> r.getKey()).collect(java.util.stream.Collectors.toList())); <END> ruleIndexer.index(getDefaultOrganization(), keysToIndex); activeRuleIndexer.index(changes); profiler.stopDebug(); } }</code><technical_language>sonar-core Collectors</technical_language>

Target:
public void start() { Profiler profiler = Profiler.create(LOG).startInfo("Register rules"); try (DbSession session = dbClient.openSession(false)) { Map<RuleKey, RuleDefinitionDto> allRules = loadRules(session); List<RuleKey> keysToIndex = new ArrayList<>(); RulesDefinition.Context context = defLoader.load(); for (RulesDefinition.ExtendedRepository repoDef : getRepositories(context)) { if (languages.get(repoDef.language()) != null) { for (RulesDefinition.Rule ruleDef : repoDef.rules()) { boolean relevantForIndex = registerRule(ruleDef, allRules, session); if (relevantForIndex) { keysToIndex.add(RuleKey.of(ruleDef.repository().key(), ruleDef.key())); } } session.commit(); } } List<RuleDefinitionDto> removedRules = processRemainingDbRules(allRules.values(), session); List<ActiveRuleChange> changes = removeActiveRulesOnStillExistingRepositories(session, removedRules, context); session.commit(); persistRepositories(session, context.repositories()); ruleIndexer.delete(removedRules.stream().map(RuleDefinitionDto::getKey).collect(Collectors.toList(removedRules.size()))); ruleIndexer.index(getDefaultOrganization(), keysToIndex); activeRuleIndexer.index(changes); profiler.stopDebug(); } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } <START> if (!(o instanceof Analysis)) { <END> return false; } Analysis analysis = (Analysis) o; return Objects.equal(projectUuid, analysis.projectUuid) && Objects.equal(ceTaskUuid, analysis.ceTaskUuid) && Objects.equal(analysisUuid, analysis.analysisUuid); }</code><technical_language>this equals support subclasses. This is necessarily intent</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Analysis analysis = (Analysis) o; return Objects.equals(projectUuid, analysis.projectUuid) && Objects.equals(ceTaskUuid, analysis.ceTaskUuid) && Objects.equals(analysisUuid, analysis.analysisUuid); }
Source:
<code>public void run(String... args) throws Exception { <START> List<ModuleLaunchRequest> modulesToRun = toModuleLaunchRequests(moduleLauncherProperties); <END> if (log.isInfoEnabled()) { StringBuilder sb = new StringBuilder("Launching\n"); for (ModuleLaunchRequest moduleLaunchRequest : modulesToRun) { sb.append('\t').append(moduleLaunchRequest).append('\n'); } log.info(sb.toString()); } this.moduleLauncher.launch(modulesToRun); }</code><technical_language>change "modulesToRun" "launchRequests" introducing another term (run) while "launch" for else</technical_language>

Target:
public void run(String... args) throws Exception { List<ModuleLaunchRequest> launchRequests = toModuleLaunchRequests(moduleLauncherProperties); if (log.isInfoEnabled()) { StringBuilder sb = new StringBuilder("Launching\n"); for (ModuleLaunchRequest moduleLaunchRequest : launchRequests) { sb.append('\t').append(moduleLaunchRequest).append('\n'); } log.info(sb.toString()); } this.moduleLauncher.launch(launchRequests); }
Source:
<code><START> public Account removeGroup(Group group) { <END> GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getHref().equalsIgnoreCase(group.getHref())) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } return this; }</code><technical_language>@since 1.0.RC5 Assert.notNull(group, "group null");</technical_language>

Target:
public Account removeGroup(Group group) { Assert.notNull(group, "group cannot be null"); GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getHref().equals(group.getHref())) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; }
Source:
<code>public AutoGenerationOption save(AutoGenerationOption autoGenerationOption) { <START> return Context.getService(IdentifierSourceService.class).saveAutoGenerationOption(autoGenerationOption); <END> }</code><technical_language>Declare Context.getService(IdentifierSourceService.class) top of class</technical_language>

Target:
public AutoGenerationOption save(AutoGenerationOption autoGenerationOption) { return identifierSourceService.saveAutoGenerationOption(autoGenerationOption); }
Source:
<code><START> private Optional<LockWatchVersion> extractVersionFromUpdate(LockWatchStateUpdate update) { <END> return update.accept(new LockWatchStateUpdate.Visitor<Optional<LockWatchVersion>>() { @Override public Optional<LockWatchVersion> visit(Success success) { return currentVersion .filter(current -> current.id().equals(success.logId())) .map(_unused -> LockWatchVersion.of(success.logId(), success.lastKnownVersion())); } @Override public Optional<LockWatchVersion> visit(Snapshot snapshot) { return Optional.of(LockWatchVersion.of(snapshot.logId(), snapshot.lastKnownVersion())); } }); }</code><technical_language>Unclear if this a convention Lock Watches, decomp - in particular, rejecting a success post-leader election a snapshot _here_ - a bit unexpected. prefer this return version, updateVersion care of filtering. do in updateVersion</technical_language>

Target:
private Optional<LockWatchVersion> extractVersionFromUpdate(LockWatchStateUpdate update) { return update.accept(new LockWatchStateUpdate.Visitor<Optional<LockWatchVersion>>() { @Override public Optional<LockWatchVersion> visit(LockWatchStateUpdate.Success success) { return currentVersion .filter(current -> current.id().equals(success.logId())) .map(_unused -> LockWatchVersion.of(success.logId(), success.lastKnownVersion())); } @Override public Optional<LockWatchVersion> visit(LockWatchStateUpdate.Snapshot snapshot) { return Optional.of(LockWatchVersion.of(snapshot.logId(), snapshot.lastKnownVersion())); } }); }
Source:
<code>public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { match: { if (!OR_ELSE_GET_METHOD.matches(tree, state)) { break match; } ExpressionTree orElseGetArg = tree.getArguments().get(0); if (orElseGetArg.getKind() != Tree.Kind.LAMBDA_EXPRESSION) { break match; } LambdaExpressionTree lambdaExpressionTree = (LambdaExpressionTree) orElseGetArg; LambdaExpressionTree.BodyKind bodyKind = lambdaExpressionTree.getBodyKind(); if (bodyKind != LambdaExpressionTree.BodyKind.EXPRESSION) { break match; } ExpressionTree expressionBody = (ExpressionTree) lambdaExpressionTree.getBody(); <START> if (COMPILE_TIME_CONSTANT.matches(expressionBody, state) <END> || isTrivialExpression(expressionBody) || isTrivialSelect(expressionBody)) { return buildDescription(tree) .setMessage("Prefer Optional#orElse instead of Optional#orElseGet for compile time constants") .addFix(SuggestedFix.builder() .merge(SuggestedFixes.renameMethodInvocation(tree, "orElse", state)) .replace(orElseGetArg, state.getSourceForNode(expressionBody)) .build()) .build(); } } return Description.NO_MATCH; }</code><technical_language>Is compile time constant check necessary? catch checks cannot</technical_language>

Target:
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!OR_ELSE_GET_METHOD.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree orElseGetArg = tree.getArguments().get(0); if (orElseGetArg.getKind() != Tree.Kind.LAMBDA_EXPRESSION) { return Description.NO_MATCH; } LambdaExpressionTree lambdaExpressionTree = (LambdaExpressionTree) orElseGetArg; LambdaExpressionTree.BodyKind bodyKind = lambdaExpressionTree.getBodyKind(); if (bodyKind != LambdaExpressionTree.BodyKind.EXPRESSION) { return Description.NO_MATCH; } ExpressionTree expressionBody = (ExpressionTree) lambdaExpressionTree.getBody(); if (!COMPILE_TIME_CONSTANT.matches(expressionBody, state) && !isTrivialExpression(expressionBody) && !isTrivialSelect(expressionBody)) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage("Prefer Optional#orElse instead of Optional#orElseGet for compile time constants") .addFix(SuggestedFix.builder() .merge(SuggestedFixes.renameMethodInvocation(tree, "orElse", state)) .replace(orElseGetArg, state.getSourceForNode(expressionBody)) .build()) .build(); }
Source:
<code>static void createAndPopulateTable(Connection connection, RowShapeParams rowShapeParams) throws IOException { try (Admin admin = connection.getAdmin()) { if (admin.tableExists(rowShapeParams.tableName)) { LOG.info("Using existing table"); return; } LOG.info("Did not found the the table with tableName as: " + rowShapeParams.tableName); admin.createTable( new HTableDescriptor(rowShapeParams.tableName) .addFamily(new HColumnDescriptor(COL_FAMILY).setMaxVersions(1))); } try (BufferedMutator bufferedMutator = connection.getBufferedMutator(rowShapeParams.tableName)) { long timestamp = getTimeInMicroSecond(); byte[] cellValue = getRandomBytes(rowShapeParams.cellSize); for (int rowInd = 0; rowInd < rowShapeParams.totalRows; rowInd++) { Put put = new Put(Bytes.toBytes(ROW_PREFIX + String.format("%010d", rowInd))); for (int cellInd = 0; cellInd < rowShapeParams.cellsPerRow; cellInd++) { put.addColumn( COL_FAMILY, Bytes.toBytes("qualifier-" + String.format("%06d", cellInd)), timestamp, cellValue); } bufferedMutator.mutate(put); if (rowInd % 1000 == 0) { <START> bufferedMutator.flush(); <END> } } } LOG.info(String.format("Mutate table with %d rows", rowShapeParams.totalRows)); }</code><technical_language>I dont this is necessary...let buffered mutator do flushing</technical_language>

Target:
static void createAndPopulateTable(Connection connection, RowShapeParams rowShapeParams) throws IOException { try (Admin admin = connection.getAdmin()) { if (admin.tableExists(rowShapeParams.tableName)) { LOG.info("Using existing table"); return; } LOG.info("Did not found the the table with tableName as: " + rowShapeParams.tableName); admin.createTable( new HTableDescriptor(rowShapeParams.tableName) .addFamily(new HColumnDescriptor(COL_FAMILY).setMaxVersions(1))); } try (BufferedMutator bufferedMutator = connection.getBufferedMutator(rowShapeParams.tableName)) { for (int rowInd = 0; rowInd < rowShapeParams.totalRows; rowInd++) { Put put = new Put(Bytes.toBytes(READ_ROW_PREFIX + String.format("%010d", rowInd))); for (int cellInd = 0; cellInd < rowShapeParams.cellsPerRow; cellInd++) { put.addColumn( COL_FAMILY, Bytes.toBytes("qualifier-" + String.format("%06d", cellInd)), SAMPLE_TIMESTAMP, getRandomBytes(rowShapeParams.cellSize)); } bufferedMutator.mutate(put); } } LOG.info(String.format("Mutate table with %d rows", rowShapeParams.totalRows)); }
Source:
<code>public HttpResponse doNotifyCommit(@QueryParameter(required=true) String url) throws ServletException, IOException { final List<AbstractProject<?,?>> projects = Lists.newArrayList(); boolean scmFound = false, triggerFound = false, urlFound = false; <START> Authentication old = SecurityContextHolder.getContext().getAuthentication(); <END> SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { for (AbstractProject<?,?> project : Hudson.getInstance().getAllItems(AbstractProject.class)) { SCM scm = project.getScm(); if (scm instanceof MercurialSCM) scmFound = true; else continue; MercurialSCM hg = (MercurialSCM) scm; String repository = hg.getSource(); if (url.equals(repository)) urlFound = true; else continue; SCMTrigger trigger = project.getTrigger(SCMTrigger.class); if (trigger!=null) triggerFound = true; else continue; LOGGER.info("Triggering the polling of "+project.getFullDisplayName()); trigger.run(); projects.add(project); } } finally { SecurityContextHolder.getContext().setAuthentication(old); } final String msg; if (!scmFound) msg = "No mercurial jobs found"; else if (!urlFound) msg = "No mercurial jobs using repository: " + url; else if (!triggerFound) msg = "Jobs found but they aren't configured for polling"; else msg = null; return new HttpResponse() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setStatus(SC_OK); rsp.setContentType("text/plain"); for (AbstractProject<?, ?> p : projects) { rsp.addHeader("Triggered", p.getAbsoluteUrl()); } PrintWriter w = rsp.getWriter(); for (AbstractProject<?, ?> p : projects) { w.println("Scheduled polling of "+p.getFullDisplayName()); } if (msg!=null) w.println(msg); } }; }</code><technical_language>BTW I prefer for body of function left previous indentation (perhaps moved a private helper method) is clear diff adding lines, changing inside. GitHub ignore whitespace changes showing a pull request</technical_language>

Target:
public HttpResponse doNotifyCommit(@QueryParameter(required=true) String url) throws ServletException, IOException { SecurityContext securityContext = ACL.impersonate(ACL.SYSTEM); try { return handleNotifyCommit(url); } finally { SecurityContextHolder.setContext(securityContext); } }
Source:
<code>public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = ""; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } else if (!StringUtils.isEmpty(errorMsg)) { <START> localizedErrorMsg = StringUtils.join(errorMsg.toLowerCase().split("[_]", -1), " "); <END> } return localizedErrorMsg; }</code><technical_language>fallback default locale initialized in constructor if translation for client locale? If forced this nasty split/join code ..</technical_language>

Target:
public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = errorMsg; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } return localizedErrorMsg; }
Source:
<code>public ClientCompactQueryTuningConfig( @JsonProperty("maxRowsPerSegment") @Nullable Integer maxRowsPerSegment, @JsonProperty("maxRowsInMemory") @Nullable Integer maxRowsInMemory, @JsonProperty("maxTotalRows") @Nullable Integer maxTotalRows, @JsonProperty("indexSpec") @Nullable IndexSpec indexSpec, @JsonProperty("maxPendingPersists") @Nullable Integer maxPendingPersists, @JsonProperty("pushTimeout") @Nullable Long pushTimeout ) { this.maxRowsPerSegment = maxRowsPerSegment; this.maxRowsInMemory = maxRowsInMemory == null ? DEFAULT_MAX_ROWS_IN_MEMORY : maxRowsInMemory; this.maxTotalRows = maxTotalRows == null ? DEFAULT_MAX_TOTAL_ROWS : maxTotalRows; this.indexSpec = indexSpec == null ? DEFAULT_INDEX_SPEC : indexSpec; this.maxPendingPersists = maxPendingPersists == null ? DEFAULT_MAX_PENDING_PERSISTS : maxPendingPersists; <START> this.pushTimeout = pushTimeout == null ? DEFAULT_PUBLISH_TIMEOUT : pushTimeout; <END> }</code><technical_language>change DEFAULT_PUBLISH_TIMEOUT DEFAULT_PUSH_TIMEOUT</technical_language>

Target:
public ClientCompactQueryTuningConfig( @JsonProperty("maxRowsPerSegment") @Nullable Integer maxRowsPerSegment, @JsonProperty("maxRowsInMemory") @Nullable Integer maxRowsInMemory, @JsonProperty("maxTotalRows") @Nullable Integer maxTotalRows, @JsonProperty("indexSpec") @Nullable IndexSpec indexSpec, @JsonProperty("maxPendingPersists") @Nullable Integer maxPendingPersists, @JsonProperty("pushTimeout") @Nullable Long pushTimeout ) { this.maxRowsPerSegment = maxRowsPerSegment; this.maxRowsInMemory = maxRowsInMemory == null ? DEFAULT_MAX_ROWS_IN_MEMORY : maxRowsInMemory; this.maxTotalRows = maxTotalRows == null ? DEFAULT_MAX_TOTAL_ROWS : maxTotalRows; this.indexSpec = indexSpec == null ? DEFAULT_INDEX_SPEC : indexSpec; this.maxPendingPersists = maxPendingPersists == null ? DEFAULT_MAX_PENDING_PERSISTS : maxPendingPersists; this.pushTimeout = pushTimeout == null ? DEFAULT_PUSH_TIMEOUT : pushTimeout; }
Source:
<code>public void start() { <START> if (!running) { <END> synchronized (lifecycleMonitor) { if (!running) { BindingUtils.bindAll(this.applicationContext); this.running = true; } } } }</code><technical_language>I running needs volatile for this safe</technical_language>

Target:
public void start() { if (!running) { synchronized (lifecycleMonitor) { if (!running) { try { ChannelBindingService channelBindingService = this.applicationContext.getBean(ChannelBindingService.class); Map<String, Bindable> bindables = this.applicationContext.getBeansOfType(Bindable.class); for (Bindable bindable : bindables.values()) { bindable.bindOutputs(channelBindingService); } for (Bindable bindable : bindables.values()) { bindable.bindInputs(channelBindingService); } } catch (BeansException e) { throw new IllegalStateException("Cannot perform binding, no proper implementation found",e); } this.running = true; } } } }
Source:
<code>public Response update(final ClientRepresentation rep) { auth.requireManage(); try { RepresentationToModel.updateClient(rep, client); <START> adminEvent.realm(realm).operation(OperationType.UPDATE).resourcePath(client).representation(rep).success(); <END> return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Client " + rep.getClientId() + " already exists"); } }</code><technical_language>Set realm in RealmAdminResource, do</technical_language>

Target:
public Response update(final ClientRepresentation rep) { auth.requireManage(); try { RepresentationToModel.updateClient(rep, client); adminEvent.operation(OperationType.UPDATE).resourcePath(client).representation(rep).success(); return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Client " + rep.getClientId() + " already exists"); } }
Source:
<code>public void setSearchFactory(ExtendedSearchIntegrator boundSearchIntegrator) { this.searchIntegrator = boundSearchIntegrator; this.clientReference = searchIntegrator.getServiceManager().requestReference( JestClient.class ); if ( postInitialize != null ) { try { postInitialize.call(); } catch (Exception e) { <START> throw new SearchException( "Index manager initialization failed", e ); <END> } } }</code><technical_language>logger throw exceptions</technical_language>

Target:
public void setSearchFactory(ExtendedSearchIntegrator boundSearchIntegrator) { this.searchIntegrator = boundSearchIntegrator; this.clientReference = searchIntegrator.getServiceManager().requestReference( JestClient.class ); initializeIndex(); }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression percentileExp = (LiteralExpression)exps.get(2); float p = ((Number)percentileExp.getValue()).floatValue(); NavigableMap<ImmutableBytesPtr, Integer> sortedMap = new TreeMap<ImmutableBytesPtr, Integer>(valueVsCount); if (!isAscending) { sortedMap = sortedMap.descendingMap(); } float i = (p * this.totalCount) + 0.5F; long k = (long)i; float f = i - k; ImmutableBytesPtr pi1 = null; ImmutableBytesPtr pi2 = null; long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : sortedMap.entrySet()) { if (pi1 != null) { pi2 = entry.getKey(); break; } distinctCountsSum += entry.getValue(); if (distinctCountsSum == k) { pi1 = entry.getKey(); } else if (distinctCountsSum > k) { pi1 = pi2 = entry.getKey(); break; } } float result = 0F; Number n1 = (Number)columnExp.getDataType().toObject(pi1); if (pi2 == null || pi1 == pi2) { result = n1.floatValue(); } else { Number n2 = (Number)columnExp.getDataType().toObject(pi2); <START> result = (n1.floatValue() * (1.0F - f)) + (n2.floatValue() * f); <END> } this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }</code><technical_language>ok precision here</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression percentileExp = (LiteralExpression)exps.get(2); float p = ((Number)percentileExp.getValue()).floatValue(); Entry<ImmutableBytesPtr, Integer>[] entries = getSortedValueVsCount(isAscending); float i = (p * this.totalCount) + 0.5F; long k = (long)i; float f = i - k; ImmutableBytesPtr pi1 = null; ImmutableBytesPtr pi2 = null; long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : entries) { if (pi1 != null) { pi2 = entry.getKey(); break; } distinctCountsSum += entry.getValue(); if (distinctCountsSum == k) { pi1 = entry.getKey(); } else if (distinctCountsSum > k) { pi1 = pi2 = entry.getKey(); break; } } double result = 0.0; Number n1 = (Number)columnExp.getDataType().toObject(pi1); if (pi2 == null || pi1 == pi2) { result = n1.doubleValue(); } else { Number n2 = (Number)columnExp.getDataType().toObject(pi2); result = (n1.doubleValue() * (1.0F - f)) + (n2.doubleValue() * f); } this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }
Source:
<code>public static Optional<Long> findLedgerByName(BookKeeper bk, String name) throws Exception { <START> <END> Map<Long, LedgerMetadata> ledgers = new HashMap<Long, LedgerMetadata>(); final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK); final CountDownLatch processDone = new CountDownLatch(1); bk.getLedgerManager() .asyncProcessLedgers((ledgerId, cb) -> collectLedgers(bk, ledgerId, cb, ledgers), (rc, s, obj) -> { returnCode.set(rc); processDone.countDown(); }, null, BKException.Code.OK, BKException.Code.ReadException); processDone.await(5, TimeUnit.MINUTES); log.info("Ledgers collected: total found=" + ledgers.size()); byte[] nameBytes = name.getBytes(); Optional<Entry<Long, LedgerMetadata>> entry = ledgers.entrySet() .stream() .filter((e) -> { Map<String, byte[]> meta = e.getValue().getCustomMetadata(); if (meta != null) { log.info("ledger: " + e.getKey() + ", customMeta=" + meta); byte[] data = meta.get("name"); if (data != null && Arrays.equals(data, nameBytes)) { return true; } else { return false; } } else { log.info("ledger: " + e.getKey() + ", no meta"); return false; } }) .findFirst(); if (entry.isPresent()) { return Optional.of(entry.get().getKey()); } else { return Optional.empty(); } }</code><technical_language>remove blank lines start of methods</technical_language>

Target:
public static Optional<Long> findLedgerByName(BookKeeper bk, String name) throws Exception { Map<Long, LedgerMetadata> ledgers = new HashMap<Long, LedgerMetadata>(); final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK); final CountDownLatch processDone = new CountDownLatch(1); bk.getLedgerManager() .asyncProcessLedgers( (ledgerId, cb) -> collectLedgers(bk, ledgerId, cb, ledgers), (rc, s, obj) -> { returnCode.set(rc); processDone.countDown(); }, null, BKException.Code.OK, BKException.Code.ReadException); processDone.await(5, TimeUnit.MINUTES); LOG.info("Ledgers collected: total found=" + ledgers.size()); byte[] nameBytes = name.getBytes(); Optional<Entry<Long, LedgerMetadata>> entry = ledgers.entrySet() .stream() .filter((e) -> { Map<String, byte[]> meta = e.getValue() .getCustomMetadata(); if (meta != null) { LOG.info("ledger: " + e.getKey() + ", customMeta=" + meta); byte[] data = meta.get("name"); if (data != null && Arrays.equals(data, nameBytes)) { return true; } else { return false; } } else { LOG.info("ledger: " + e.getKey() + ", no meta"); return false; } }) .findFirst(); if (entry.isPresent()) { return Optional.of(entry.get() .getKey()); } else { return Optional.empty(); } }