auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void prepareDataForEpoch() { listOfTrainingDataKeys.clear(); final List<K> keys = new ArrayList<>(memoryStore.getAll().keySet()); <START> final int sizeOfTrainingDataKeys = keys.size() / numMiniBatchesPerEpoch; <END> final int extraDataSize = keys.size() % numMiniBatchesPerEpoch; int consumedDataCount = 0; for (int i = 0; i < numMiniBatchesPerEpoch; i++) { final int miniBatchSize = i < extraDataSize ? sizeOfTrainingDataKeys + 1 : sizeOfTrainingDataKeys; final List<K> trainingData = keys.subList(consumedDataCount, consumedDataCount + miniBatchSize); listOfTrainingDataKeys.add(trainingData); consumedDataCount += miniBatchSize; } trainingDataKeysIterator = listOfTrainingDataKeys.iterator(); }</code><technical_language>fix this #841 merged</technical_language>

Target:
void prepareDataForEpoch() { final List<K> keys = new ArrayList<>(memoryStore.getAll().keySet()); final int numMiniBatches = (int) Math.ceil((double) keys.size() / miniBatchSize); final List<List<K>> keysList = new ArrayList<>(numMiniBatches); final int remainderForLastMiniBatch = keys.size() % miniBatchSize; final int numInstancesForLastMiniBatch = remainderForLastMiniBatch == 0 ? miniBatchSize : remainderForLastMiniBatch; int numKeysCounted = 0; int numKeysToCount = miniBatchSize; for (int miniBatchIdx = 0; miniBatchIdx < numMiniBatches; miniBatchIdx++) { if (miniBatchIdx == numMiniBatches - 1) { numKeysToCount = numInstancesForLastMiniBatch; } final List<K> trainingData = keys.subList(numKeysCounted, numKeysCounted + numKeysToCount); numKeysCounted += numKeysToCount; keysList.add(trainingData); } trainingDataKeysIterator = keysList.iterator(); }
Source:
<code>public void visitNode(Tree tree) { if (tree.is(Tree.Kind.METHOD_INVOCATION)) { <START> MethodInvocationTree mit = (MethodInvocationTree) tree; <END> if(EQUALS_MATCHER.matches(mit)) { if(mit.methodSelect().is(Tree.Kind.MEMBER_SELECT)) { ExpressionTree leftOp = ((MemberSelectExpressionTree) mit.methodSelect()).expression(); ExpressionTree rightOp = mit.arguments().get(0); if(SyntacticEquivalence.areEquivalent(leftOp, rightOp)) { reportIssue( rightOp, "Identical sub-expressions on both sides of equals.", ImmutableList.of(new JavaFileScannerContext.Location("", leftOp)), null); } } } else if (DEEP_EQUALS_MATCHER.matches(mit) || OBJECTS_EQUALS_MATCHER.matches(mit)) { ExpressionTree leftOp = mit.arguments().get(0); ExpressionTree rightOp = mit.arguments().get(1); if(SyntacticEquivalence.areEquivalent(leftOp, rightOp)) { reportIssue( rightOp, "Both arguments are identical sub-expressions.", ImmutableList.of(new JavaFileScannerContext.Location("", leftOp)), null); } } return; } BinaryExpressionTree binaryExpressionTree = (BinaryExpressionTree) tree; ExpressionTree rightOperand = binaryExpressionTree.rightOperand(); ExpressionTree equivalentOperand = equivalentOperand(binaryExpressionTree, rightOperand); if (equivalentOperand != null) { reportIssue( rightOperand, "Correct one of the identical sub-expressions on both sides of operator \"" + binaryExpressionTree.operatorToken().text() + "\"", ImmutableList.of(new JavaFileScannerContext.Location("", equivalentOperand)), null); } }</code><technical_language>consider extracting this method handling MIT case</technical_language>

Target:
public void visitNode(Tree tree) { if (tree.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) tree; checkEqualsMethods(mit); return; } BinaryExpressionTree binaryExpressionTree = (BinaryExpressionTree) tree; ExpressionTree rightOperand = binaryExpressionTree.rightOperand(); ExpressionTree equivalentOperand = equivalentOperand(binaryExpressionTree, rightOperand); if (equivalentOperand != null) { reportIssue( rightOperand, "Correct one of the identical sub-expressions on both sides of operator \"" + binaryExpressionTree.operatorToken().text() + "\"", ImmutableList.of(new JavaFileScannerContext.Location("", equivalentOperand)), null); } }
Source:
<code>public void addString(String string, float x, float y, Font font) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (font == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); x = DPIUtil.autoScaleUp(x); y = DPIUtil.autoScaleUp(y); <START> FontData fd = font.getFontData()[0]; <END> Font scaledFont = new Font(font.getDevice(), fd.getName(), DPIUtil.autoScaleUp(fd.getHeight()), fd.getStyle()); addStringInPixels(string, x, y, scaledFont); scaledFont.dispose(); }</code><technical_language>Suggest loop complete FontData array</technical_language>

Target:
public void addString(String string, float x, float y, Font font) { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (font == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); x = DPIUtil.autoScaleUp(x); y = DPIUtil.autoScaleUp(y); FontData fd = font.getFontData()[0]; fd.setHeight(DPIUtil.autoScaleUp(fd.getHeight())); Font scaledFont = new Font(font.getDevice(), fd); addStringInPixels(string, x, y, scaledFont); scaledFont.dispose(); }
Source:
<code><START> public static synchronized void removeFromCache(String key){ <END> if (key != null){ attestationValues.remove(key); } }</code><technical_language>remove method of ConcurrentHashMap performs synchronization, "synchronized" modifier is required</technical_language>

Target:
public void removeFromCache(String key) { if (key != null) { attestationValues.remove(key); } }
Source:
<code>protected CompletableFuture<List<SimpleEntry<String, String>>> processInternal() { CPSubsystemManagementService cpService = nodeEngine.getHazelcastInstance().getCPSubsystem().getCPSubsystemManagementService(); return cpService.getCPMembers().toCompletableFuture() .thenApply(cpMembers -> { <START> List<SimpleEntry<String, String>> result = new ArrayList<>(); <END> for (CPMember cpMember : cpMembers) { String address = "[" + cpMember.getAddress().getHost() + "]:" + cpMember.getAddress().getPort(); result.add(new SimpleEntry<>(cpMember.getUuid().toString(), address)); } return result; }); }</code><technical_language>do List<Entry<String, String>> instead of CPMemberDTO</technical_language>

Target:
protected CompletableFuture<List<SimpleEntry<UUID, Address>>> processInternal() { CPSubsystemManagementService cpService = nodeEngine.getHazelcastInstance().getCPSubsystem().getCPSubsystemManagementService(); return cpService.getCPMembers().toCompletableFuture() .thenApply(cpMembers -> { List<SimpleEntry<UUID, Address>> result = new ArrayList<>(cpMembers.size()); for (CPMember cpMember : cpMembers) { result.add(new SimpleEntry<>(cpMember.getUuid(), cpMember.getAddress())); } return result; }); }
Source:
<code>private boolean allBranchOperationsSucceeded( final @NonNull Map<Repository, CheckoutResult> results) { return <START> results.entrySet().stream() .map(Map.Entry::getValue) .allMatch(r <END> -> r.getStatus() == CheckoutResult.Status.OK); }</code><technical_language>results.values().stream().allMatch(...)</technical_language>

Target:
private boolean allBranchOperationsSucceeded( final @NonNull Map<Repository, CheckoutResult> results) { return results.values().stream() .allMatch(r -> r.getStatus() == CheckoutResult.Status.OK); }
Source:
<code>private static StageExecutionPlan createPlan(ConnectorSplitSource splitSource) { Symbol symbol = new Symbol("column"); PlanNodeId tableScanNodeId = new PlanNodeId("plan_id"); TableScanNode tableScan = new TableScanNode( tableScanNodeId, <START> new TableHandle(CONNECTOR_ID, new TestingMetadata.TestingTableHandle()), <END> ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); RemoteSourceNode remote = new RemoteSourceNode(new PlanNodeId("remote_id"), new PlanFragmentId("plan_fragment_id"), ImmutableList.of()); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("plan_id"), new JoinNode(new PlanNodeId("join_id"), INNER, tableScan, remote, ImmutableList.of(), ImmutableList.<Symbol>builder() .addAll(tableScan.getOutputSymbols()) .addAll(remote.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(JoinNode.DistributionType.PARTITIONED)), ImmutableMap.of(symbol, VARCHAR), SOURCE_DISTRIBUTION, ImmutableList.of(tableScanNodeId), new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), ImmutableList.of(symbol))); return new StageExecutionPlan( testFragment, ImmutableMap.of(tableScanNodeId, new ConnectorAwareSplitSource(CONNECTOR_ID, TestingTransactionHandle.create(), splitSource)), ImmutableList.of()); }</code><technical_language>static import</technical_language>

Target:
private static StageExecutionPlan createPlan(ConnectorSplitSource splitSource) { Symbol symbol = new Symbol("column"); PlanNodeId tableScanNodeId = new PlanNodeId("plan_id"); TableScanNode tableScan = new TableScanNode( tableScanNodeId, new TableHandle(CONNECTOR_ID, new TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); RemoteSourceNode remote = new RemoteSourceNode(new PlanNodeId("remote_id"), new PlanFragmentId("plan_fragment_id"), ImmutableList.of()); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("plan_id"), new JoinNode(new PlanNodeId("join_id"), INNER, tableScan, remote, ImmutableList.of(), ImmutableList.<Symbol>builder() .addAll(tableScan.getOutputSymbols()) .addAll(remote.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(JoinNode.DistributionType.PARTITIONED)), ImmutableMap.of(symbol, VARCHAR), SOURCE_DISTRIBUTION, ImmutableList.of(tableScanNodeId), new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), ImmutableList.of(symbol))); return new StageExecutionPlan( testFragment, ImmutableMap.of(tableScanNodeId, new ConnectorAwareSplitSource(CONNECTOR_ID, TestingTransactionHandle.create(), splitSource)), ImmutableList.of()); }
Source:
<code>public synchronized void start(StartContext context) throws StartException { final String deploymentName = deploymentUnit.getParent() == null ? deploymentUnit.getName() : deploymentUnit.getParent().getName() + "." + deploymentUnit.getName(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); final ClassLoader classLoader = module.getClassLoader(); ApplicationSecurityDomain applicationSecurityDomain = this.applicationSecurityDomain.getOptionalValue(); if (applicationSecurityDomain != null) { <START> BiFunction<String, ClassLoader, Registration> securityFunction = applicationSecurityDomain != null ? applicationSecurityDomain.getSecurityFunction() : null; <END> if (securityFunction != null) { Registration registration = securityFunction.apply(deploymentName, classLoader); cleanUpTask = registration::cancel; } } else { final SecurityDomain securityDomain = this.securityDomain.getValue(); if (isChecking()) { doPrivileged((PrivilegedAction<Void>) () -> { securityDomain.registerWithClassLoader(classLoader); return null; }); } else { securityDomain.registerWithClassLoader(classLoader); } cleanUpTask = new Runnable() { @Override public void run() { if (WildFlySecurityManager.isChecking()) { doPrivileged((PrivilegedAction<Void>) () -> { unregisterClassLoader(classLoader); return null; }); } else { unregisterClassLoader(classLoader); } } }; } }</code><technical_language>Nit: need null check more line ensures false</technical_language>

Target:
public synchronized void start(StartContext context) throws StartException { final String deploymentName = deploymentUnit.getParent() == null ? deploymentUnit.getName() : deploymentUnit.getParent().getName() + "." + deploymentUnit.getName(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); final ClassLoader classLoader = module.getClassLoader(); ApplicationSecurityDomain applicationSecurityDomain = this.applicationSecurityDomain.getOptionalValue(); if (applicationSecurityDomain != null) { BiFunction<String, ClassLoader, Registration> securityFunction = applicationSecurityDomain.getSecurityFunction(); if (securityFunction != null) { Registration registration = securityFunction.apply(deploymentName, classLoader); cleanUpTask = registration::cancel; } } else { final SecurityDomain securityDomain = this.securityDomain.getValue(); if (isChecking()) { doPrivileged((PrivilegedAction<Void>) () -> { securityDomain.registerWithClassLoader(classLoader); return null; }); } else { securityDomain.registerWithClassLoader(classLoader); } cleanUpTask = new Runnable() { @Override public void run() { if (WildFlySecurityManager.isChecking()) { doPrivileged((PrivilegedAction<Void>) () -> { unregisterClassLoader(classLoader); return null; }); } else { unregisterClassLoader(classLoader); } } }; } }
Source:
<code>public void testListStatusIteratorFile() throws Throwable { describe("test the listStatusIterator(path) on a file"); Path f = touchf("listStItrFile"); List<FileStatus> statusList = (List<FileStatus>) iteratorToList( getFileSystem().listStatusIterator(f)); assertEquals("size of file list returned", 1, statusList.size()); assertIsNamedFile(f, statusList.get(0)); List<FileStatus> statusList2 = (List<FileStatus>) iteratorToListThroughNextCallsAlone( getFileSystem().listStatusIterator(f)); <START> assertEquals("size of file list returned through next() calls", <END> 1, statusList2.size()); assertIsNamedFile(f, statusList2.get(0)); }</code><technical_language>AssertionsAssertThat assert list size == 1</technical_language>

Target:
public void testListStatusIteratorFile() throws Throwable { describe("test the listStatusIterator(path) on a file"); Path f = touchf("listStItrFile"); List<FileStatus> statusList = (List<FileStatus>) iteratorToList( getFileSystem().listStatusIterator(f)); validateListingForFile(f, statusList, false); List<FileStatus> statusList2 = (List<FileStatus>) iteratorToListThroughNextCallsAlone( getFileSystem().listStatusIterator(f)); validateListingForFile(f, statusList2, true); }
Source:
<code>public void fetchThumbnailForEntityId(String entityId, int position) { compositeDisposable.add(depictsClient.getP18ForItem(entityId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(response -> { <START> Timber.e("line67" + response); <END> view.onImageUrlFetched(response,position); })); }</code><technical_language>Is this intended permanent? debug level :-)</technical_language>

Target:
public void fetchThumbnailForEntityId(String entityId, int position) { compositeDisposable.add(depictsClient.getP18ForItem(entityId) .subscribeOn(ioScheduler) .observeOn(mainThreadScheduler) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(response -> { view.onImageUrlFetched(response,position); })); }
Source:
<code>public List<IAnalysisModule> getAnalysisModules() { List<IAnalysisModule> modules = new ArrayList<IAnalysisModule>(); for (String key : fAnalysisTypeAttributes.keySet()) { <START> IConfigurationElement ce = fAnalysisTypeAttributes.get(key); <END> IAnalysisModule module; try { module = (IAnalysisModule) ce.createExecutableExtension(ANALYSIS_MODULE_ATTR); module.setName(ce.getAttribute(NAME_ATTR)); module.setId(ce.getAttribute(ID_ATTR)); module.setAutomatic(Boolean.valueOf(ce.getAttribute(AUTOMATIC_ATTR))); module.setIcon(ce.getAttribute(ICON_ATTR)); final IConfigurationElement[] parametersCE = ce.getChildren(PARAMETER_ELEM); for (IConfigurationElement element : parametersCE) { module.addParameter(element.getAttribute(NAME_ATTR)); String defaultValue = element.getAttribute(DEFAULT_VALUE_ATTR); if (defaultValue != null) { module.setParameter(element.getAttribute(NAME_ATTR), defaultValue); } } modules.add(module); } catch (CoreException e) { } } return modules; }</code><technical_language>avoid this map lookup if iterate entries instead of keys: for (Map.Entry<String, IConfigurationElement> entry : fAnalysisTypeAttributes.entrySet()) { IConfigurationElement ce = entry.getValue();</technical_language>

Target:
public List<IAnalysisModule> getAnalysisModules() { List<IAnalysisModule> modules = new ArrayList<IAnalysisModule>(); for (Map.Entry<String, IConfigurationElement> entry : fAnalysisTypeAttributes.entrySet()) { IConfigurationElement ce = entry.getValue(); IAnalysisModule module; try { module = (IAnalysisModule) ce.createExecutableExtension(ANALYSIS_MODULE_ATTR); module.setName(ce.getAttribute(NAME_ATTR)); module.setId(ce.getAttribute(ID_ATTR)); module.setAutomatic(Boolean.valueOf(ce.getAttribute(AUTOMATIC_ATTR))); module.setIcon(ce.getAttribute(ICON_ATTR)); final IConfigurationElement[] parametersCE = ce.getChildren(PARAMETER_ELEM); for (IConfigurationElement element : parametersCE) { module.addParameter(element.getAttribute(NAME_ATTR)); String defaultValue = element.getAttribute(DEFAULT_VALUE_ATTR); if (defaultValue != null) { module.setParameter(element.getAttribute(NAME_ATTR), defaultValue); } } modules.add(module); } catch (CoreException e) { Activator.logError("Error getting analysis modules from configuration files", e); } } return modules; }
Source:
<code>public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); ObservableList<ItemViewModel> items = new ObservableArrayList<>(); <START> items.add(new HeaderItemViewModel("我是header")); <END> for (int i = 0; i < 3; i++) { items.add(new NormalItemViewModel(i, true)); } viewModel = new ViewModel(true, items); }</code><technical_language>Hard-coded strings a good idea.... If put a string somewhere, strings.xml resource file (which allow localization; reads Hanzi...)</technical_language>

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); ObservableList<ItemViewModel> items = new ObservableArrayList<>(); items.add(new HeaderItemViewModel(getString(R.string.header))); for (int i = 0; i < 3; i++) { items.add(new NormalItemViewModel(i, true)); } viewModel = new ViewModel(true, items); }
Source:
<code>public long onInvalidTimestamp(final ConsumerRecord<Object, Object> record, final long recordTimestamp, final long partitionTime) throws StreamsException { if (partitionTime < 0) { throw new StreamsException("Could not infer new timestamp for input record " + record <START> + " because latest extracted valid timestamp is unknown."); <END> } return partitionTime; }</code><technical_language>partition time is unknown</technical_language>

Target:
public long onInvalidTimestamp(final ConsumerRecord<Object, Object> record, final long recordTimestamp, final long partitionTime) throws StreamsException { if (partitionTime < 0) { throw new StreamsException("Could not infer new timestamp for input record " + record + " because partition time is unknown."); } return partitionTime; }
Source:
<code>public Project(Project.NameKey nameKey) { name = nameKey; <START> submitType = defaultSubmitType; <END> }</code><technical_language>Do need for compatibility (i checked)? if support mode of this set entire project this represented a 'refs/*' entry instead? this is needed new UI is merged</technical_language>

Target:
public Project(Project.NameKey nameKey) { name = nameKey; submitType = defaultSubmitType; state = State.ACTIVE; }
Source:
<code><START> private boolean zipParentFolder(File toBeZippedDirectory, String zipFilePath) throws IOException { <END> Log.d(TAG, "Zipping directory" + toBeZippedDirectory.toString() + " to path " + zipFilePath); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath))); try { if (!toBeZippedDirectory.isDirectory()) { throw new RuntimeException("toBeZippedDirecory was not a directory. Bad."); } File[] formInstanceFolders = toBeZippedDirectory.listFiles(); for (File formInstanceFolder : formInstanceFolders) { File[] subFileArray = formInstanceFolder.listFiles(); zipInstanceFolder(subFileArray, zipFilePath, out); } } finally { out.close(); } return false; }</code><technical_language>static</technical_language>

Target:
private static boolean zipParentFolder(File toBeZippedDirectory, String zipFilePath) throws IOException { Log.d(TAG, "Zipping directory" + toBeZippedDirectory.toString() + " to path " + zipFilePath); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath))); try { if (!toBeZippedDirectory.isDirectory()) { throw new RuntimeException("toBeZippedDirecory was not a directory. Bad."); } File[] formInstanceFolders = toBeZippedDirectory.listFiles(); for (File formInstanceFolder : formInstanceFolders) { File[] subFileArray = formInstanceFolder.listFiles(); Log.d(TAG, "Zipping instance folder with files: " + Arrays.toString(subFileArray) + ", zipFilePath: " + zipFilePath); zipInstanceFolder(subFileArray, out); } out.finish(); } finally { out.close(); } return false; }
Source:
<code>public Resource minify(Resource originalResource) { if (!getEnabled()) { LOG.trace(MINIFICATION_IS_DISABLED_RETURNING_ORIGINAL_RESOURCE); return originalResource; } if (originalResource.getFilename() == null) { LOG.warn("Attempted to modify resource without a filename, returning non-minified resource"); return originalResource; } Integer filenameLength = originalResource.getFilename().length(); if (filenameLength >= JS_MIN.length()) { String lastSevenCharacters = originalResource.getFilename().substring(filenameLength-JS_MIN.length()); if (lastSevenCharacters.equals(JS_MIN)) { LOG.info("Minification already have done for this resource: " + originalResource.getFilename()); return originalResource; } <START> <END> } return minify(originalResource, originalResource.getFilename()); }</code><technical_language>need check delegating other minify method anyways. this method is file a name delegating</technical_language>

Target:
public Resource minify(Resource originalResource) { if (!getEnabled()) { LOG.trace(MINIFICATION_IS_DISABLED_RETURNING_ORIGINAL_RESOURCE); return originalResource; } if (originalResource.getFilename() == null) { LOG.warn("Attempted to modify resource without a filename, returning non-minified resource"); return originalResource; } return minify(originalResource, originalResource.getFilename()); }
Source:
<code>public void equals_hashCodeTest() { AirConditionerActions action = new AirConditionerActions(true, null); AliasAction<AirConditionerActions> aliasAction = new AliasAction<>("alias", action); Object[] sameObjects = { aliasAction, new AliasAction<>("alias", action)}; for(int i=0; i<sameObjects.length; i++) { Assert.assertEquals( "failed to test equals for ["+i+"]", aliasAction, sameObjects[i]); Assert.assertEquals( "failed to test hashCode for ["+i+"]", aliasAction, <START> sameObjects[i]); <END> } Object[] diffObjects = { null, new AliasAction<>("another alias", action), new AliasAction<>("humidity", new HumidityActions(45)), new AliasAction<>("alias", new HumidityActions(45)), 23 }; for (int i=0; i < diffObjects.length; i++) { Assert.assertFalse( "failed to test equals for ["+i+"]", aliasAction.equals(diffObjects[i])); if (diffObjects[i] != null) { Assert.assertFalse( "failed to test hashCode for [" + i + "]", aliasAction.hashCode() == diffObjects[i].hashCode()); } } }</code><technical_language>want check aliasAction.hashCode() you</technical_language>

Target:
public void equals_hashCodeTest() { AirConditionerActions action = new AirConditionerActions(true, null); AliasAction<AirConditionerActions> aliasAction = new AliasAction<>("alias", action); Object[] sameObjects = { aliasAction, new AliasAction<>("alias", action)}; for(int i=0; i<sameObjects.length; i++) { Assert.assertEquals( "failed to test equals for ["+i+"]", aliasAction, sameObjects[i]); Assert.assertEquals( "failed to test hashCode for ["+i+"]", aliasAction.hashCode(), sameObjects[i].hashCode()); } Object[] diffObjects = { null, new AliasAction<>("another alias", action), new AliasAction<>("humidity", new HumidityActions(45)), new AliasAction<>("alias", new HumidityActions(45)), 23 }; for (int i=0; i < diffObjects.length; i++) { Assert.assertFalse( "failed to test equals for ["+i+"]", aliasAction.equals(diffObjects[i])); if (diffObjects[i] != null) { Assert.assertFalse( "failed to test hashCode for [" + i + "]", aliasAction.hashCode() == diffObjects[i].hashCode()); } } }
Source:
<code>private IWorkingSetUpdater2 getUpdater() { <START> WorkingSetDescriptor descriptor = getDescriptor(); <END> WorkingSetManager manager = getWorkingSetManager(); if (manager != null && descriptor != null) { IWorkingSetUpdater updater = manager.getUpdater(descriptor); if (updater instanceof IWorkingSetUpdater2) { return (IWorkingSetUpdater2) updater; } } return null; }</code><technical_language>in adaptElements this is done if manager != null, this moved if(manger != null)</technical_language>

Target:
private IWorkingSetUpdater2 getUpdater() { WorkingSetManager manager = getWorkingSetManager(); if (manager != null) { WorkingSetDescriptor descriptor = getDescriptor(); if (descriptor != null) { IWorkingSetUpdater updater = manager.getUpdater(descriptor); if (updater instanceof IWorkingSetUpdater2) { return (IWorkingSetUpdater2) updater; } } } return null; }
Source:
<code>public BloomFilter readBloomFilter(ColumnChunkMetaData meta) { if (cache.containsKey(meta.getPath())) { return cache.get(meta.getPath()); } try { synchronized (cache) { if (!cache.containsKey(meta.getPath())) { BloomFilter bloomFilter = reader.readBloomFilter(meta); if (bloomFilter == null) return null; cache.put(meta.getPath(), bloomFilter); } } return cache.get(meta.getPath()); } catch (IOException e) { <START> throw new RuntimeException( <END> "Failed to read Bloom filter data", e); } }</code><technical_language>error reading a bloom filter block reading of data. For example if bloom filter is corrupt throw a RuntimeException blocks user read data. If is a level I/O problem fail IOException reading data anyway. I suggest logging issue return null instead of throwing exception</technical_language>

Target:
public BloomFilter readBloomFilter(ColumnChunkMetaData meta) { if (cache.containsKey(meta.getPath())) { return cache.get(meta.getPath()); } try { if (!cache.containsKey(meta.getPath())) { BloomFilter bloomFilter = reader.readBloomFilter(meta); if (bloomFilter == null) { return null; } cache.put(meta.getPath(), bloomFilter); } return cache.get(meta.getPath()); } catch (IOException e) { logger.error("Failed to read Bloom filter data", e); } return null; }
Source:
<code><START> private MappedRoleMapper(Map<String, Set<String>> roleMap) { <END> this.reverseRoleMap = new LinkedHashMap<>(); Set<Map.Entry<String, Set<String>>> entrySet = roleMap.entrySet(); for (Map.Entry<String, Set<String>> entry : entrySet) { for (String mappedRole : entry.getValue()) { Set<String> rolesToMappedRole = reverseRoleMap.get(mappedRole); if (rolesToMappedRole == null) { rolesToMappedRole = new LinkedHashSet<>(); reverseRoleMap.put(mappedRole, rolesToMappedRole); } rolesToMappedRole.add(entry.getKey()); } } }</code><technical_language>maybe, keeping map null better, ensure uninitialized mapper accidentally? (even NPE is complex debugging roles mapped...)</technical_language>

Target:
private MappedRoleMapper(Map<String, Set<String>> roleMap) { Set<Map.Entry<String, Set<String>>> entrySet = roleMap.entrySet(); for (Map.Entry<String, Set<String>> entry : entrySet) { for (String mappedRole : entry.getValue()) { Set<String> rolesToMappedRole = reverseRoleMap.get(mappedRole); if (rolesToMappedRole == null) { rolesToMappedRole = new LinkedHashSet<>(); reverseRoleMap.put(mappedRole, rolesToMappedRole); } rolesToMappedRole.add(entry.getKey()); } } initialized = true; }
Source:
<code>private boolean validationNecessaryForInvolvedTables() { <START> return !Sets.filter(involvedTables, tableRef -> isValidationNecessary(tableRef)).isEmpty(); <END> }</code><technical_language>nit: clearer as: return involvedTables.stream().anyMatch(this::isValidationNecessary)</technical_language>

Target:
private boolean validationNecessaryForInvolvedTables() { return involvedTables.stream().anyMatch(this::isValidationNecessary); }
Source:
<code>private HealthStatus pointEstimateTimeLockHealth() { Collection<ServiceHealthTracker.Service> services = FeedbackReportsSink.getTrackedServices(); int targetHealthyServices = services.size() * 2 / 3; services = services.stream().filter( service -> !service.nodes().isEmpty()).collect(Collectors.toList()); return services .stream() .filter(service -> ServiceHealthTracker.getHealthStatus(service) == HealthStatus.HEALTHY).count() <START> >= targetHealthyServices ? HealthStatus.HEALTHY : HealthStatus.UNHEALTHY; <END> }</code><technical_language>If services UNKNOWN, return a HEALTHY top level. (Debatable: UNKNOWN treated HEALTHY?)</technical_language>

Target:
public HealthStatus pointEstimateTimeLockHealth() { Collection<ServiceHealthTracker.Service> services = FeedbackReportsSink.getTrackedServices(); int targetUnhealthyServices = services.size() / 3; return services .stream() .filter(service -> ServiceHealthTracker.getHealthStatus(service) == HealthStatus.UNHEALTHY).count() >= targetUnhealthyServices ? HealthStatus.UNHEALTHY : HealthStatus.HEALTHY; }
Source:
<code>public String getUsage() { StringWriter wrt = new StringWriter(); <START> String indent = " "; <END> try (PrintWriter out = new PrintWriter(wrt)) { out.println(getPrologue()); for (Object o : usageSummary) { if (o instanceof String) { out.println((String)o); } else { out.println(indent + ((Option)o).getUsage()); } } if (epilogue != null) { out.println(epilogue); } out.flush(); } return wrt.toString(); }</code><technical_language>nice if indent configurable</technical_language>

Target:
public String getUsage() { return getUsage(" "); }
Source:
<code>public void setCommandExecuted() { <START> Transaction transaction = TransactionSupport.suspend(); <END> try { TaskManagerUtil.updateCommandExecuted(getCommandId()); } finally { TransactionSupport.resume(transaction); } }</code><technical_language>Ravi, if thread is in transaction, suspend() returns null. Is safe pass null resume</technical_language>

Target:
public void setCommandExecuted() { Transaction transaction = TransactionSupport.suspend(); try { TaskManagerUtil.updateCommandExecuted(getCommandId()); } finally { if (transaction != null) { TransactionSupport.resume(transaction); } } }
Source:
<code>public TestResultSummary(TestResult result) { <START> result.tally(); <END> failCount = result.getFailCount(); passCount = result.getPassCount(); skipCount = result.getSkipCount(); totalCount = result.getTotalCount(); }</code><technical_language>run called tally, do need call again</technical_language>

Target:
public TestResultSummary(TestResult result) { failCount = result.getFailCount(); passCount = result.getPassCount(); skipCount = result.getSkipCount(); totalCount = result.getTotalCount(); }
Source:
<code>public DataTransactionResult offerToStore(ValueContainer<?> container, Optional<UUID> value) { final ImmutableSpongeOptionalValue<UUID> proposedValue = new ImmutableSpongeOptionalValue<UUID>(Keys.TAMED_OWNER, value); if(container instanceof EntityTameable) { final DataTransactionBuilder builder = DataTransactionBuilder.builder(); final Optional<UUID> tamer = TameableDataProcessor.getTamer((EntityTameable) container); final ImmutableValue<Optional<UUID>> oldTamer = this.getApiValueFromContainer(container).get().asImmutable(); final ImmutableOptionalValue<UUID> newTamer = new ImmutableSpongeOptionalValue<UUID>(Keys.TAMED_OWNER, value); try { <START> ((EntityTameable) container).setOwnerId(TameableDataProcessor.asString(value)); <END> } catch (Exception e) { return DataTransactionBuilder.errorResult(newTamer); } return builder.success(newTamer).replace(oldTamer).result(DataTransactionResult.Type.SUCCESS).build(); } return DataTransactionBuilder.failResult(proposedValue); }</code><technical_language>add java return DataTransactionBuilder.successReplaceResult(oldTamer, newTamer); this line</technical_language>

Target:
public DataTransactionResult offerToStore(ValueContainer<?> container, Optional<UUID> value) { final ImmutableSpongeOptionalValue<UUID> proposedValue = ImmutableSpongeTameableData.createValue(value); if(container instanceof EntityTameable) { final DataTransactionBuilder builder = DataTransactionBuilder.builder(); final Optional<UUID> tamer = TameableDataProcessor.getTamer((EntityTameable) container); final ImmutableValue<Optional<UUID>> oldTamer = this.getApiValueFromContainer(container).get().asImmutable(); final ImmutableOptionalValue<UUID> newTamer = ImmutableSpongeTameableData.createValue(value); try { ((EntityTameable) container).setOwnerId(TameableDataProcessor.asString(value)); return builder.success(newTamer).replace(oldTamer).result(DataTransactionResult.Type.SUCCESS).build(); } catch (Exception e) { return DataTransactionBuilder.errorResult(newTamer); } } return DataTransactionBuilder.failResult(proposedValue); }
Source:
<code>private void handleResult(Document runInfo, RunId runId) { Elements result = runInfo.select("td#Result"); switch (result.text()) { case "N/A": this.result = Result.NA; break; case "NOT_AVAILABLE": this.result = Result.NOT_AVAILABLE; break; case "UNKNOWN": this.result = Result.UNKNOWN; break; <START> default: <END> throw new IllegalRunStatusException( "RunId " + runId + "returned illegal run info result " + result.text()); } }</code><technical_language>cases? Faban I PASSED for successful executions. good add a reference values from</technical_language>

Target:
private void handleResult(Document runInfo, RunId runId) { Elements result = runInfo.select("td#Result"); switch (result.text()) { case "PASSED": this.result = Result.PASSED; break; case "FAILED": this.result = Result.FAILED; break; case "N/A": this.result = Result.NA; break; case "NOT_AVAILABLE": this.result = Result.NOT_AVAILABLE; break; case "UNKNOWN": this.result = Result.UNKNOWN; break; default: throw new IllegalRunStatusException( "RunId " + runId + "returned illegal run info result " + result.text()); } }
Source:
<code><START> private static void checkAllInserted(int[] inserts, int size) throws IOException { <END> int sum = 0; for (int cur: inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } }</code><technical_language>static, this class</technical_language>

Target:
static void checkAllInserted(int[] inserts, int size) throws IOException { int sum = 0; for (int cur: inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } }
Source:
<code>public List<VdsmVm> perform( List<Pair<VmDynamic, VdsmVm>> monitoredVms, long fetchTime, VdsManager vdsManager, boolean updateStatistics) { if (monitoredVms.isEmpty()) { return Collections.emptyList(); } List<VmAnalyzer> vmAnalyzers = Collections.emptyList(); List<VdsmVm> dbVms = Collections.emptyList(); try { vmAnalyzers = analyzeVms(monitoredVms, fetchTime, vdsManager, updateStatistics); addUnmanagedVms(vmAnalyzers, vdsManager.getVdsId()); flush(vmAnalyzers); postFlush(vmAnalyzers, vdsManager); vdsManager.vmsMonitoringInitFinished(); dbVms = monitoredVms.stream(). filter(monitoredVm -> monitoredVm.getFirst() != null). <START> map(Pair::getSecond).collect(Collectors.toList()); <END> } catch (RuntimeException ex) { log.error("Failed during vms monitoring on host error is: {}", vdsManager.getVdsName(), ex); log.error("Exception:", ex); } finally { unlockVms(vmAnalyzers); } return dbVms; }</code><technical_language>is reason for putting this logic in PollVmStatsRefresher</technical_language>

Target:
public void perform( List<Pair<VmDynamic, VdsmVm>> monitoredVms, long fetchTime, VdsManager vdsManager, boolean updateStatistics) { if (monitoredVms.isEmpty()) { return; } List<VmAnalyzer> vmAnalyzers = Collections.emptyList(); try { vmAnalyzers = analyzeVms(monitoredVms, fetchTime, vdsManager, updateStatistics); addUnmanagedVms(vmAnalyzers, vdsManager.getVdsId()); flush(vmAnalyzers); postFlush(vmAnalyzers, vdsManager); vdsManager.vmsMonitoringInitFinished(); } catch (RuntimeException ex) { log.error("Failed during vms monitoring on host error is: {}", vdsManager.getVdsName(), ex); log.error("Exception:", ex); } finally { unlockVms(vmAnalyzers); } }
Source:
<code>public void testHardAffinityAssignment() { NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); TestingTransactionHandle transactionHandle = TestingTransactionHandle.create(); NodeSchedulerConfig nodeSchedulerConfig = new NodeSchedulerConfig() .setMaxSplitsPerNode(20) .setIncludeCoordinator(false) .setMaxPendingSplitsPerTask(10); NodeScheduler nodeScheduler = new NodeScheduler(new LegacyNetworkTopology(), nodeManager, nodeSchedulerConfig, nodeTaskMap); NodeSelector nodeSelector = nodeScheduler.createNodeSelector(CONNECTOR_ID, 3); Set<Split> splits = new HashSet<>(); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); SplitPlacementResult splitPlacementResult = nodeSelector.computeAssignments(splits, ImmutableList.of()); for (Split split : splitPlacementResult.getAssignments().values()) <START> { <END> assertEquals(split.getSplitContext().isCacheable(), true); } }</code><technical_language>this pass style check</technical_language>

Target:
public void testHardAffinityAssignment() { NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService); TestingTransactionHandle transactionHandle = TestingTransactionHandle.create(); NodeSchedulerConfig nodeSchedulerConfig = new NodeSchedulerConfig() .setMaxSplitsPerNode(20) .setIncludeCoordinator(false) .setMaxPendingSplitsPerTask(10); NodeScheduler nodeScheduler = new NodeScheduler(new LegacyNetworkTopology(), nodeManager, nodeSchedulerConfig, nodeTaskMap); NodeSelector nodeSelector = nodeScheduler.createNodeSelector(CONNECTOR_ID, 3); Set<Split> splits = new HashSet<>(); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); splits.add(new Split(CONNECTOR_ID, transactionHandle, new TestHardAffinitySplitRemote())); SplitPlacementResult splitPlacementResult = nodeSelector.computeAssignments(splits, ImmutableList.of()); for (Split split : splitPlacementResult.getAssignments().values()) { assertTrue(split.getSplitContext().isCacheable()); } }
Source:
<code>public void add(String label, String[] values) throws ParseException, InvalidParametersException { if ("after".equals(label)) { isFromDateInQuery = true; LocalDateTime localDateTime = TimeHelper.parseLocalDateTime(values[0] + " 00:00", "dd/MM/yyyy HH:mm"); fromDateValue = TimeHelper.convertLocalDateTimeToInstant( localDateTime, Const.SystemParams.ADMIN_TIME_ZONE_ID).toEpochMilli(); <START> } else if ("before".equals(label)) { <END> isToDateInQuery = true; LocalDateTime localDateTime = TimeHelper.parseLocalDateTime(values[0] + " 23:59", "dd/MM/yyyy HH:mm"); toDateValue = TimeHelper.convertLocalDateTimeToInstant( localDateTime, Const.SystemParams.ADMIN_TIME_ZONE_ID).toEpochMilli(); } else if ("receiver".equals(label)) { isReceiverInQuery = true; receiverValues = values; } else if ("subject".equals(label)) { isSubjectInQuery = true; subjectValues = values; } else if ("info".equals(label)) { isInfoInQuery = true; infoValues = values; } else { throw new InvalidParametersException("Invalid label"); } }</code><technical_language>This is a huge if/else tree. a return terminate if remove elses for cleaner syntax</technical_language>

Target:
public void add(String label, String[] values) throws ParseException, InvalidParametersException { if ("after".equals(label)) { isFromDateInQuery = true; LocalDateTime localDateTime = TimeHelper.parseLocalDate(values[0], "dd/MM/yyyy").atStartOfDay(); fromDateValue = TimeHelper.convertLocalDateTimeToInstant( localDateTime, Const.SystemParams.ADMIN_TIME_ZONE).toEpochMilli(); return; } if ("before".equals(label)) { isToDateInQuery = true; LocalDateTime localDateTime = TimeHelper.parseLocalDate(values[0], "dd/MM/yyyy").atTime(LocalTime.MAX); toDateValue = TimeHelper.convertLocalDateTimeToInstant( localDateTime, Const.SystemParams.ADMIN_TIME_ZONE).toEpochMilli(); return; } if ("receiver".equals(label)) { isReceiverInQuery = true; receiverValues = values; return; } if ("subject".equals(label)) { isSubjectInQuery = true; subjectValues = values; return; } if ("info".equals(label)) { isInfoInQuery = true; infoValues = values; return; } throw new InvalidParametersException("Invalid label"); }
Source:
<code>private static void addInputPath(Job job, Iterable<String> pathStrings, Class<? extends InputFormat> inputFormatClass) { Configuration conf = job.getConfiguration(); StringBuilder inputFormats = new StringBuilder(Strings.nullToEmpty(conf.get(MultipleInputs.DIR_FORMATS))); for (String pathString : pathStrings) { if (inputFormats.length() > 0) { inputFormats.append(','); } inputFormats.append(pathString).append(';').append(inputFormatClass.getName()); } conf.set(MultipleInputs.DIR_FORMATS, inputFormats.toString()); <START> job.setInputFormatClass(DelegatingInputFormat.class); <END> }</code><technical_language>do need DelegatingInputFormat, do work it? minimize changes here</technical_language>

Target:
private static void addInputPath(Job job, Iterable<String> pathStrings, Class<? extends InputFormat> inputFormatClass) { Configuration conf = job.getConfiguration(); StringBuilder inputFormats = new StringBuilder(Strings.nullToEmpty(conf.get(MultipleInputs.DIR_FORMATS))); String[] paths = Iterables.toArray(pathStrings, String.class); for (int i = 0; i < paths.length - 1; i++) { if (inputFormats.length() > 0) { inputFormats.append(','); } inputFormats.append(paths[i]).append(';').append(inputFormatClass.getName()); } if (inputFormats.length() > 0) { conf.set(MultipleInputs.DIR_FORMATS, inputFormats.toString()); } MultipleInputs.addInputPath(job, new Path(paths[paths.length - 1]), inputFormatClass); }
Source:
<code>public void testEnumDepth1() { test(" var a = {b: 0, c: 1};", "var a$b = 0; var a$c = 1;"); <START> test(" var a = { b: 0, c: 1};", <END> "var a$c = 1; var a = {b: 0};"); }</code><technical_language>Enums kinds of properties (it distinguish kinds in this pass, sure). kind is properties declared in enum's object literal. enumerated values, allow nocollapse (if possible). kind is properties added enum declaration. This is enum is treated a namespace, allow nocollapse for properties. Actually, John mentioned stop supporting enums namespaces. So, if distinguish kinds of enum properties here, disallow nocollapse enum properties altogether</technical_language>

Target:
public void testEnumDepth1() { test(" var a = {b: 0, c: 1};", "var a$b = 0; var a$c = 1;"); test(" var a = { b: 0, c: 1};", "var a$b = 0; var a$c = 1;", null, CollapseProperties.INVALID_NOCOLLAPSE); }
Source:
<code>public ModelAndView getCommentFeed(@SiteParam Site site, @PathVariable String feedType) throws IOException { <START> String requestAddress = String.format("/journals/%s?comments&limit=%d", site.getJournalKey(), 30); <END> List comments = soaService.requestObject(requestAddress, List.class); ModelAndView mav = new ModelAndView(); FeedMetadataField.SITE.putInto(mav, site); FeedMetadataField.TITLE.putInto(mav, "Comments"); FeedMetadataField.FEED_INPUT.putInto(mav, comments); mav.setView(FeedType.getView(commentFeedView, feedType)); return mav; }</code><technical_language>30 extracted a field this point, is shared for homepage RSS</technical_language>

Target:
public ModelAndView getCommentFeed(@SiteParam Site site, @PathVariable String feedType) throws IOException { String requestAddress = String.format("/journals/%s?comments&limit=%d", site.getJournalKey(), getFeedLength(site)); List comments = soaService.requestObject(requestAddress, List.class); ModelAndView mav = new ModelAndView(); FeedMetadataField.SITE.putInto(mav, site); FeedMetadataField.TITLE.putInto(mav, "Comments"); FeedMetadataField.FEED_INPUT.putInto(mav, comments); mav.setView(FeedType.getView(commentFeedView, feedType)); return mav; }
Source:
<code>private static void logEntry(Connection connection, DataSource dataSource, ProceedingJoinPoint joinPoint, HttpServletRequest request, boolean mustCheck, String formattedOrgIds) { StringBuilder sb = new StringBuilder(); if (DataSourceUtils.isConnectionTransactional(connection, dataSource)) { sb.append("-----------\n"); sb.append("connection is transactional\n"); sb.append("URL IS ").append(request.getRequestURI()).append("\n"); sb.append(request.getRequestURL()).append("\n"); sb.append(joinPoint).append("\n"); sb.append("public url: ").append(isCurrentlyInAPublicUrlRequest()).append("\n"); if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) { sb.append("auth is ").append(SecurityContextHolder.getContext().getAuthentication().getName()).append("\n"); } else { sb.append("no user\n"); } sb.append("must check row access: ").append(mustCheck).append("\n"); if(mustCheck) { sb.append("org ids are: ").append(formattedOrgIds).append("\n"); } sb.append("-----------\n"); } else { sb.append("-----------\n"); sb.append("connection is NOT transactional so the check will not be done!\n"); sb.append("URL IS ").append(request.getRequestURI()).append("\n"); sb.append(joinPoint).append("\n"); sb.append("-----------\n"); } <START> log.debug(sb.toString()); <END> }</code><technical_language>above, if TRACE</technical_language>

Target:
private static void logEntry(Connection connection, DataSource dataSource, ProceedingJoinPoint joinPoint, HttpServletRequest request, boolean mustCheck, String formattedOrgIds) { StringBuilder sb = new StringBuilder(); if (DataSourceUtils.isConnectionTransactional(connection, dataSource)) { sb.append("-----------\n"); sb.append("connection is transactional\n"); sb.append("URL IS ").append(request.getRequestURI()).append("\n"); sb.append(request.getRequestURL()).append("\n"); sb.append(joinPoint).append("\n"); sb.append("public url: ").append(isCurrentlyInAPublicUrlRequest()).append("\n"); if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) { sb.append("auth is ").append(SecurityContextHolder.getContext().getAuthentication().getName()).append("\n"); } else { sb.append("no user\n"); } sb.append("must check row access: ").append(mustCheck).append("\n"); if(mustCheck) { sb.append("org ids are: ").append(formattedOrgIds).append("\n"); } sb.append("-----------\n"); } else { sb.append("-----------\n"); sb.append("connection is NOT transactional so the check will not be done!\n"); sb.append("URL IS ").append(request.getRequestURI()).append("\n"); sb.append(joinPoint).append("\n"); sb.append("-----------\n"); } log.trace(sb.toString()); }
Source:
<code>private Map<String, Pair<Class, Object>> getOverriddenReturnTypes(){ Map<String, Pair<Class, Object>> map = new HashMap<>(); <START> return map; <END> }</code><technical_language>This throw redundancy warnings in IntelliJ</technical_language>

Target:
private Map<String, Pair<Class, Object>> getOverriddenReturnTypes(){ return new HashMap<>(); }
Source:
<code>public CmdLineParser(Object bean, ParserProperties parserProperties) { if (bean==null) return; new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } <START> setUsageWidth(parserProperties.getUsageWidth()); <END> }</code><technical_language>I store reference for future enhancements instead of copying content. I love idea of a configuration object :+1:</technical_language>

Target:
public CmdLineParser(Object bean, ParserProperties parserProperties) { this.parserProperties = parserProperties; if (bean==null) return; new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } }