auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int available() throws IOException { final FSDataInputStream inLocal = in; synchronized (inLocal) { START int avail = inLocal.available(); END if (pos + avail > end) { avail = (int) (end - pos); } return avail; } } It seems like the method should seek before calling available. Like the following : ``` java synchronized (inLocal) { inLocal.seek(pos); int avail = inLocal.available(); . . . } ```

Target:
public int available() throws IOException { return (int) (end - pos); }
Source:
public void finish() throws IOException { START if (!closed) { END synchronized (in) { if (!closed) { try { in.close(); } finally { closed = true; if (decompressor != null) { try { compressAlgo.returnDecompressor(decompressor); } finally { decompressor = null; } } } } } } } Whats the purpose of this double check? Is it an optimization to avoid sync? I suspect that in the majority of cases where this is called, closed will be false. Therefore this double check will usually result in an extra round trip to memory (reading closed twice from main memory) in the majority of cases. So this may slow down the majority case.

Target:
public void finish() throws IOException { synchronized (in) { if (!closed) { try { in.close(); } finally { closed = true; if (decompressor != null) { try { compressAlgo.returnDecompressor(decompressor); } finally { decompressor = null; } } } } } }
Source:
START public Shell() throws IOException END Can remove the `throws IOException` as it won't affect callers at all. They were already expecting the IOException -- if we don't throw that anymore, that's fine.

Target:
public Shell()
Source:
static Key sanityCheck(Key prev, Key current, Key shortened) { if (prev.compareTo(shortened) >= 0) { START LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + prev + " >= " + shortened); END return null; } if (current.compareTo(shortened) <= 0) { LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + current + " <= " + shortened); return null; } return shortened; } Make one Logger instance?

Target:
static Key sanityCheck(Key prev, Key current, Key shortened) { if (prev.compareTo(shortened) >= 0) { log.warn("Bug in key shortening code, please open an issue " + prev + " >= " + shortened); return prev; } if (current.compareTo(shortened) <= 0) { log.warn("Bug in key shortening code, please open an issue " + current + " <= " + shortened); return prev; } return shortened; }
Source:
private List getUniqKVCount(List<MemKey> memKeys) { START List<Integer> kvCounts = new ArrayList<Integer>(); END for (MemKey m : memKeys) { kvCounts.add(m.getKVCount()); } return ImmutableSet.copyOf(kvCounts).asList(); } Was this intended to be a `Set<Integer>`?

Target:
private int getUniqKVCount(List<MemKey> memKeys) { List<Integer> kvCounts = new ArrayList<Integer>(); for (MemKey m : memKeys) { kvCounts.add(m.getKVCount()); } return ImmutableSet.copyOf(kvCounts).size(); }
Source:
private Durability getMincEventDurability(KeyExtent extent) { TableConfiguration conf; START if (extent.isMeta() || extent.isRootTablet()) { END conf = confFactory.getTableConfiguration(RootTable.ID); } else { conf = confFactory.getTableConfiguration(MetadataTable.ID); } Durability durability = DurabilityImpl.fromString(conf.get(Property.TABLE_DURABILITY)); return durability; } This check is a bit confusing. To me it reads "If the extent is for the metadata table or the root tablet, use the root tablet's configuration. Otherwise, use the metadata configuration." Is there some other setting for user tables that's more appropriate? `KeyExtent#isMeta` already returns whether or not it's for the metadata table or the root tablet, so the `|| extent.isRootTablet()` is redundant. However, I think refactoring `KeyExtent#isMeta` is more appropriate to make it more clear about what it is checking.

Target:
private Durability getMincEventDurability(KeyExtent extent) { TableConfiguration conf; if (extent.isMeta()) { conf = confFactory.getTableConfiguration(RootTable.ID); } else { conf = confFactory.getTableConfiguration(MetadataTable.ID); } Durability durability = DurabilityImpl.fromString(conf.get(Property.TABLE_DURABILITY)); return durability; }
Source:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { START if (iteratorSamplerConfig != null && !new SamplerConfigurationImpl(iteratorSamplerConfig).equals(new SamplerConfigurationImpl(scannerSamplerConfig))) { END throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; } Can the instantiation of the objects in the equals method be broken out of the if condition? There's a lot going on for a simple equality check that would be easier to follow if the impls are instantiated earlier IMO

Target:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { if (iteratorSamplerConfig != null && !iteratorSamplerConfig.equals(scannerSamplerConfig)) { throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }
Source:
public TabletIteratorEnvironment(IteratorScope scope, AccumuloConfiguration config) { if (scope == IteratorScope.majc) throw new IllegalArgumentException("must set if compaction is full"); this.scope = scope; this.trm = null; this.config = config; this.fullMajorCompaction = false; this.authorizations = Authorizations.EMPTY; START this.topLevelIterators = new ArrayList<SortedKeyValueIterator<Key,Value>>(); END } Unnecessary SKVI<K,V> parameterization?

Target:
public TabletIteratorEnvironment(IteratorScope scope, AccumuloConfiguration config) { if (scope == IteratorScope.majc) throw new IllegalArgumentException("must set if compaction is full"); this.scope = scope; this.trm = null; this.config = config; this.fullMajorCompaction = false; this.authorizations = Authorizations.EMPTY; this.topLevelIterators = new ArrayList<>(); }
Source:
START protected static boolean isBatchScan(JobContext context) { END return InputConfigurator.isIsolated(CLASS, context.getConfiguration()); } Why JobContext here? And why not public?

Target:
public static boolean isBatchScan(JobContext context) { return InputConfigurator.isBatchScan(CLASS, context.getConfiguration()); }
Source:
private List<String> getJavaBuildPathLibraries(PropertyDialog pd) { START pd.select("Java Build Path"); END BuildPathsPropertyPage bppp = new BuildPathsPropertyPage(pd); bppp.activateLibrariesTab(); List<String> libs = new ArrayList<String>(); libs.addAll(bppp.getLibraries()); log.debug("Libraries found after conversion:"); for (String i : libs) { log.debug(" " + i); } return libs; } Instead of this use something similar with select, see https://github.com/eclipse/reddeer/blob/5791383f991e4b2503988d5db59cc85b93055cfc/tests/org.eclipse.reddeer.eclipse.test/src/org/eclipse/reddeer/eclipse/test/jdt/ui/preferences/BuildPathsPropertyPageTest.java#L81 (to hide "Java Build Path" string in reddeer)

Target:
private List<String> getJavaBuildPathLibraries(PropertyDialog pd) { pd.select(new BuildPathsPropertyPage(pd)); BuildPathsPropertyPage bppp = new BuildPathsPropertyPage(pd); bppp.activateLibrariesTab(); List<String> libs = new ArrayList<String>(); libs.addAll(bppp.getLibraries()); log.debug("Libraries found after conversion:"); for (String i : libs) { log.debug(" " + i); } return libs; }
Source:
public static void setup() { WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); MavenSettingsPreferencePage prefPage = new MavenSettingsPreferencePage(preferenceDialog); preferenceDialog.select(prefPage); START preferenceDialog.ok(); END new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); // activate central editor new DefaultEditor(CENTRAL_LABEL); } @zcervink lines 60-64 were related to setting settings.xml in preferences, and now this code is useless, so please remove it.

Target:
public static void setup() { new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); // activate central editor new DefaultEditor(CENTRAL_LABEL); }
Source:
private AddIfSystemPropertyDialog invokeDefaultAddIfSystemPropertyDialog(String property){ new ContextMenu().getItem("Add System Property").select(); START new WaitUntil(new ShellIsAvailable("Add If System Property")); END new DefaultShell("Add If System Property"); return new AddIfSystemPropertyDialog(); } no need for the wait

Target:
private AddIfSystemPropertyDialog invokeDefaultAddIfSystemPropertyDialog(String property){ new ContextMenu().getItem("Add System Property").select(); new DefaultShell("Add If System Property"); return new AddIfSystemPropertyDialog(); }
Source:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; START for (int i = 0; i < 7; i++) { END if (ti.getText(i).contains(text)) { return true; } } return false; } What is 7 in this context?

Target:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; if (ti.getText().contains(text)) { return true; } return false; }
Source:
public String toString() { return "Account{" + "id=" + id + ", description='" + description + '\'' + ", creationDate='" + creationDate + '\'' + ", limits=" + limits + ", blurb=" + blurb.stream().map(Arrays::toString).collect(Collectors.toList()) + START ", unknownFieldSet='" + unknownFieldSet + '\'' + END ", currencies='" + Arrays.toString(currencies) + '\'' + '}'; } I'd prefer to have the unknownFieldSet as the last printed stuff.

Target:
public String toString() { return "Account{" + "id=" + id + ", description='" + description + '\'' + ", creationDate='" + creationDate + '\'' + ", limits=" + limits + ", blurb=" + blurb.stream().map(Arrays::toString).collect(Collectors.toList()) + ", currencies='" + Arrays.toString(currencies) + '\'' + ", unknownFieldSet='" + unknownFieldSet + '\'' + '}'; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; START return fullName.equals(that.fullName) && name.equals(that.name); END } Why include the name in the comparison? fullName should be enough.

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; return fullName.equals(that.fullName); }
Source:
public PoolConfig() { maxIdleTimeMillis = DEFAULT_MAX_IDLE_TIME_MILLIS; START idleConnCleanupTicker = Observable.interval(maxIdleTimeMillis, TimeUnit.MILLISECONDS); END idleConnectionsHolder = new FIFOIdleConnectionsHolder<>(); limitDeterminationStrategy = UnboundedPoolLimitDeterminationStrategy.INSTANCE; } Sorry, one more. This should have an initial delay so that it doesn't try to clean up immediately. It's less important on creation, but if there are errors it will keep emitting right after each failure. This means a failure will keep triggering as fast as it can instead of just every `maxIdleTimeMillis`. ``` idleConnCleanupTicker = Observable.interval(maxIdleTimeMillis, maxIdleTimeMillis, TimeUnit.MILLISECONDS); ```

Target:
public PoolConfig() { maxIdleTimeMillis = DEFAULT_MAX_IDLE_TIME_MILLIS; idleConnCleanupTicker = Observable.interval(maxIdleTimeMillis, maxIdleTimeMillis, TimeUnit.MILLISECONDS); idleConnectionsHolder = new FIFOIdleConnectionsHolder<>(); limitDeterminationStrategy = UnboundedPoolLimitDeterminationStrategy.INSTANCE; }
Source:
public static void addSortedParams(UriBuilder uriBuilder, DataMap params) { START convertRawProjectionFieldsToMaskTree(params); END Map<String, String> map = dataMapToQueryParams(params); addSortedParams(uriBuilder, map); } Agree with Evan, also the projection parameters are already available as MaskTree in resourContext. So a better fix would be to update the `buildCriteriaURI()` method in BatchFinderResponseBuilder to replace the projection params with masktree objects.

Target:
public static void addSortedParams(UriBuilder uriBuilder, DataMap params) { Map<String, String> map = dataMapToQueryParams(params); addSortedParams(uriBuilder, map); }
Source:
START protected static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) END throws CloneNotSupportedException { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); DataMap queryParams = extractQueryParamsFromResourceContext(resourceContext); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, queryParams, resourceContext.getRestliProtocolVersion()); } I'd suggest making private methods package-private if they need to be accessed by a unit test. Making it protected opens the access too much and implies an intended inheritance relationship.

Target:
static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, resourceContext.getParameters(), resourceContext.getRestliProtocolVersion()); }
Source:
public void testBuildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri, START URI expectedURI) throws CloneNotSupportedException END { URI generatedURI = BatchFinderResponseBuilder.buildCriteriaURI(resourceContext, criteria, batchParameterName, uri); Assert.assertEquals(generatedURI.toString(), expectedURI.toString()); } remove CloneNotSupportedException

Target:
public void testBuildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri, URI expectedURI) { URI generatedURI = BatchFinderResponseBuilder.buildCriteriaURI(resourceContext, criteria, batchParameterName, uri); Assert.assertEquals(generatedURI.toString(), expectedURI.toString()); }
Source:
private Token finishToken(Token token) { _currentToken = token; START if (_currentToken == START_OBJECT) END { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue << 1; } else if (_currentToken == START_ARRAY) { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue; } else if (_currentToken != NOT_AVAILABLE) { _currComplexObjTokenSize--; } return _currentToken; } switch instead of if else here?

Target:
private Token finishToken(Token token) { _currentToken = token; switch (_currentToken) { case START_OBJECT: if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } // Stores map size as 2*size since map is serialized as list of key-value (2 tokens) pairs _currComplexObjTokenSize = _intValue << 1; break; case START_ARRAY: if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue; break; case NOT_AVAILABLE: break; default: _currComplexObjTokenSize--; } return _currentToken; }
Source:
START public JacksonTraverseCallback(JsonGenerator generator) END { this(generator, false); } Why did we make this public?

Target:
protected JacksonTraverseCallback(JsonGenerator generator) { this(generator, false); }
Source:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); START generator.flush(); END } } My point is about consistency between different codecs. Protobuf codec assumes the callback handles the flush, while this code has to call it explicitly. We should make it consistent and set the expectation that the traverse callback should handle flushing/closing the generator. Then the codec's would just close the traverse callback.

Target:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); } }
Source:
public ClasspathResourceDataSchemaResolver(ClassLoader classLoader) { for (DataSchemaParserFactory parserForFormat: BUILTIN_FORMAT_PARSER_FACTORIES) { SingleFormatClasspathSchemaResolver resolver = new SingleFormatClasspathSchemaResolver(parserForFormat); START resolver.setExtension("." + parserForFormat.getLanguageExtension()); END addResolver(resolver); } _classLoader = classLoader; } why do we need this setter exposed? Should constructor handle this automatically?

Target:
public ClasspathResourceDataSchemaResolver(ClassLoader classLoader) { for (DataSchemaParserFactory parserForFormat: BUILTIN_FORMAT_PARSER_FACTORIES) { addResolver(new SingleFormatClasspathSchemaResolver(parserForFormat)); } _classLoader = classLoader; }
Source:
public boolean handleRequest(RestRequest originalRequest, RestRequest darkRequest, RequestContext requestContext) { START int numRequestDuplicates = getNumDuplicateRequests(_random.nextFloat()); END return _baseDarkClusterDispatcher.sendRequest(originalRequest, darkRequest, requestContext, numRequestDuplicates); } no need to include _random as an argument since it's already an instance variable.

Target:
public boolean handleRequest(RestRequest originalRequest, RestRequest darkRequest, RequestContext requestContext) { int numRequestDuplicates = getNumDuplicateRequests(); return _baseDarkClusterDispatcher.sendRequest(originalRequest, darkRequest, requestContext, numRequestDuplicates); }
Source:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { START return traverseMapBySortedKeyOrder? new JacksonTraverseCallbackMapKeyOrdered(generator): new JacksonTraverseCallback(generator); END } space before ?

Target:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { return new JacksonTraverseCallback(generator, traverseMapBySortedKeyOrder); }
Source:
private static DataSchema backfillSchemaIfPossible(Class<?> type) { // These are all the classes used for type specs that are "schema-less". if (type == CompoundKey.class || type == ComplexResourceKey.class || type == Void.class START || (!DataSchemaUtil.isPrimitiveClass(type) && DataTemplateUtil.hasCoercer(type))) END { return null; } try { return DataTemplateUtil.getSchema(type); // could be a primitive, DataTemplate, TyperefInfo, or enum } catch (TemplateRuntimeException e) { // can happen in case of custom types return null; } } Why don't you just keep track of registered custom classes in `Custom.java`? I think that would be simpler

Target:
private static DataSchema backfillSchemaIfPossible(Class<?> type) { // These are all the classes used for type specs that are "schema-less". if (type == CompoundKey.class || type == ComplexResourceKey.class || type == Void.class) { return null; } try { return DataTemplateUtil.getSchema(type); // could be a primitive, DataTemplate, TyperefInfo, or enum } catch (TemplateRuntimeException e) { // can happen in case of custom types return null; } }
Source:
public void testPattern() { DateTime dateTime = new DateTime().withDate(1995, 7, 4).withTime(14, 32, 12, 0); START try { END shouldCompileTo("{{jodaPatternHelper this \"y-MMM-d H:m:s\"}}", dateTime, "1995-Jul-4 14:32:12"); } catch (IOException e) { Assert.fail("IOException thrown"); } } you don't need the `try/catch` for valid tests. The test will fail anyway when an exception occurs

Target:
public void testPattern() throws IOException { DateTime dateTime = new DateTime().withDate(1995, 7, 4).withTime(14, 32, 12, 0); shouldCompileTo("{{jodaPatternHelper this \"y-MMM-d H:m:s\"}}", dateTime, "1995-Jul-4 14:32:12"); }
Source:
public MethodCall(String methodName, Object[] args, Map<String, String> metaData, List<String> classes) { super(); START init(methodName, args, classes, metaData); END } Why would this make sense? Just because of the order?

Target:
public MethodCall(String methodName, Object[] args, Map<String, String> metaData, List<String> classes) { super(); this.methodName = methodName; this.args = args; this.classes = classes; this.metaData = metaData; }
Source:
private String checkStage(EDBStage stage) { START if (stage != null) { END return stage.getStageId(); } return null; } just write return stage != null ? stage.getStageId() : null; spare some lines : )

Target:
private String checkStage(EDBStage stage) { return stage != null ? stage.getStageId() : null; }
Source:
public void testConstructorWithUnparseablePath() throws IOException { Path unparseablePath = (new File(".")).toPath().resolve("UnparseableTagFolderName"); try { Tag tag = new ConfigurationTag(unparseablePath); START } catch (ParseException e) { END //This exception is expected to be thrown; Assert.assertTrue(true); return; } Assert.assertTrue("Error: ParseException has not been thrown!", false); } y not use @Test (expected...)

Target:
public void testConstructorWithUnparseablePath() throws IOException, ParseException { Path unparseablePath = (new File(".")).toPath().resolve("UnparseableTagFolderName"); Tag tag = new ConfigurationTag(unparseablePath); }
Source:
public void start(BundleContext bc) throws Exception { START if (webDavHandler == null) { END webDavHandler = WebDavHandler.getInstance(); } webDavHandler.setBundleContext(bc); webDavHandler.start(); } the if here is'nt too useful, is it?

Target:
public void start(BundleContext bc) throws Exception { webDavHandler = WebDavHandler.getInstance(); webDavHandler.setBundleContext(bc); webDavHandler.start(); }
Source:
START public AdvancedModelWrapper(OpenEngSBModel model) { END super(model); } I think a static method for construction might still fit better

Target:
protected AdvancedModelWrapper(OpenEngSBModel model) { super(model); }
Source:
public Boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); START if (list.isEmpty()) { END return false; } return true; } catch (PersistenceException e) { throw new RuntimeException(e); } } you could just return here !list.isEmpty() to save the branching :)

Target:
public Boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); return !list.isEmpty(); } catch (PersistenceException e) { throw new RuntimeException(e); } }
Source:
public void init() { START registry = ModelRegistryService.getInstance(null); END graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); } use a constant instead of null to make the code easier to read at this place pls

Target:
public void init() { registry = ModelRegistryService.getInstance(context); graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }
Source:
private Boolean shouldHandleEvent(BundleEvent event) { if (event.getType() != BundleEvent.STARTED && event.getType() != BundleEvent.STOPPED) { return false; } String symbolicName = event.getBundle().getSymbolicName(); START if (symbolicName.equals("org.apache.servicemix.bundles.xmlbeans")) { END return false; } if (symbolicName.equals("org.ops4j.pax.wicket.service")) { return false; } return true; } I don't like it; we need a better way to handle optional imports; a more general one; there could be always others more libs

Target:
private Boolean shouldHandleEvent(BundleEvent event) { if (event.getType() != BundleEvent.STARTED && event.getType() != BundleEvent.STOPPED) { return false; } return true; }
Source:
public void openSite_shouldShowAuditLog() { START tester.debugComponentTrees(); END tester.assertVisible("auditsContainer:audits"); tester.assertVisible("auditsContainer:audits:0:audit"); tester.assertVisible("auditsContainer:audits:1:audit"); int i = 0; for (Event event : domain.getAllAudits()) { tester.assertLabel("auditsContainer:audits:" + i + ":audit", event.getName()); i++; } } remove that one from commit again

Target:
public void openSite_shouldShowAuditLog() { tester.assertVisible("auditsContainer:audits"); tester.assertVisible("auditsContainer:audits:0:audit"); tester.assertVisible("auditsContainer:audits:1:audit"); int i = 0; for (Event event : domain.getAllAudits()) { tester.assertLabel("auditsContainer:audits:" + i + ":audit", event.getName()); i++; } }
Source:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); START fail("Exception should be thrown that the command does not exist"); END cs.close(); } maybe the CommandSession should be closed before the call of fail?

Target:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); cs.close(); fail("Exception should be thrown that the command does not exist"); }
Source:
START static List<EntryElement> makeEntryElementList(Object... value) { END List<EntryElement> valueElements = new ArrayList<EntryElement>(); for (Object o : value) { Class<?> type = ClassUtils.primitiveToWrapper(o.getClass()); EntryElement entryElement = new EntryElement(type.getName(), o.toString()); valueElements.add(entryElement); } return valueElements; } why not public?

Target:
public static List<EntryElement> makeEntryElementList(Object... value) { List<EntryElement> valueElements = new ArrayList<EntryElement>(); for (Object o : value) { Class<?> type = ClassUtils.primitiveToWrapper(o.getClass()); EntryElement entryElement = new EntryElement(type.getName(), o.toString()); valueElements.add(entryElement); } return valueElements; }
Source:
START static <T> Collection<T> convertAllBeanDataToObjects(Collection<? extends BeanData> data) { END return Collections2.transform(data, new BeanDataToObjectFunction<T>()); } why not public

Target:
public static <T> Collection<T> convertAllBeanDataToObjects(Collection<? extends BeanData> data) { return Collections2.transform(data, new BeanDataToObjectFunction<T>()); }
Source:
START public ConfigPersistenceService getPersistence() { END return OpenEngSBCoreServices .getConfigPersistenceService("WORKFLOW"); } do you really want to make this public?

Target:
private ConfigPersistenceService getPersistence() { return OpenEngSBCoreServices .getConfigPersistenceService("WORKFLOW"); }
Source:
START public void testWorkflowRepresentationMarshalling_shouldMarshallWorkflowCorrectly() throws END SAXException, IOException, JAXBException { WorkflowRepresentation representation = createWorkflow(); WorkflowRepresentationConverter workflowRepresentationMarshaller = new WorkflowRepresentationConverter(); String converted = workflowRepresentationMarshaller.marshallWorkflow(representation); WorkflowRepresentation rep = workflowRepresentationMarshaller.unmarshallWorkflow(converted); compareActionRepresentation(representation.getRoot(), rep.getRoot()); } throws exception?

Target:
public void testWorkflowRepresentationMarshalling_shouldMarshallWorkflowCorrectly() throws JAXBException { WorkflowRepresentation representation = createWorkflow(); WorkflowRepresentationConverter workflowRepresentationMarshaller = new WorkflowRepresentationConverter(); String converted = workflowRepresentationMarshaller.marshallWorkflow(representation); WorkflowRepresentation rep = workflowRepresentationMarshaller.unmarshallWorkflow(converted); compareActionRepresentation(representation.getRoot(), rep.getRoot()); }
Source:
public <T> List<T> listServices(Class<T> clazz, String filterString) throws InvalidSyntaxException { Filter filter = makeFilter(clazz, filterString); ServiceTracker tracker = new ServiceTracker(bundleContext, filter, null); return getListFromTracker(tracker); START END } one backspace too much

Target:
public <T> List<T> listServices(Class<T> clazz, String filterString) throws IllegalArgumentException { Filter filter = makeFilter(clazz, filterString); ServiceTracker tracker = new ServiceTracker(bundleContext, filter, null); return getListFromTracker(tracker); }
Source:
START public LocalizableString mockLocalizeableString(String value) { END LocalizableString mock2 = mock(LocalizableString.class); when(mock2.getString(any(Locale.class))).thenReturn(value); return mock2; } isn't protected sufficient for this method?

Target:
protected LocalizableString mockLocalizeableString(String value) { LocalizableString mock2 = mock(LocalizableString.class); when(mock2.getString(any(Locale.class))).thenReturn(value); return mock2; }
Source:
public static String shorten(String s, int len) { s = s.trim(); START if (s.length() > 12) { END s = s.substring(0, len - 3).trim() + "..."; } return s; } Do you mean `s.length() > len`?

Target:
public static String shorten(String s, int len) { s = s.trim(); if (s.length() > len) { s = s.substring(0, len - 3).trim() + "..."; } return s; }
Source:
public static String amountToDollars(int n){ String s = "$ " + (n / 100) + "."; START if (((n % 100) / 10) == 0) { END s += "0"; } s += (n % 100); return s; } Wouldn't this be clearer with the condition being `if ((n % 100) < 10)`?

Target:
public static String amountToDollars(int n){ String s = "$ " + (n / 100) + "."; if ((n % 100) < 10) { s += "0"; } s += (n % 100); return s; }
Source:
void shouldReturnEmptyPropertyString() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "", Function.identity()); String actualProperty = statistics.getProperty(); assertThat(actualProperty).isEmpty(); START } END Der Fall "" bietet keinen Mehrwert zu "category", oder? Test entfernen oder alternativ (dann gibt es kein Duplizieren): ``` @ParameterizedTest(name = "[{index}] Category name = {0}") @ValueSource(strings = {"category", ""}) ```

Target:
void shouldReturnEmptyPropertyString() { Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "", Function.identity()); String actualProperty = statistics.getProperty(); assertThat(actualProperty).isEmpty(); }
Source:
void shouldReturnEmptyDisplayNameString() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); START PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); END String actualDisplayName = statistics.getDisplayName(""); assertThat(actualDisplayName).isEmpty(); } Hier wäre noch ein Test schön, wo nicht identify verwendet wird.

Target:
void shouldReturnEmptyDisplayNameString() { Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); String actualDisplayName = statistics.getDisplayName(""); assertThat(actualDisplayName).isEmpty(); }
Source:
void shouldReturnCountEmpty() { //Given final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); START assertThrows(NullPointerException.class, ()->statistics.getCount("key")); END } Das ist eigentlich ein "Bug". Schöner wäre, wenn da eine `NoSuchElementException` mit passender Meldung fliegt. Wenn Sie wollen, dürfen Sie das SUT auch abändern.

Target:
void shouldReturnCountEmpty() { Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); assertThrows(NullPointerException.class, ()->statistics.getCount("key")); }
Source:
void shouldReturnUnmodifiedOutputForEmptyInput() { START final EnvironmentResolver environmentResolver = new EnvironmentResolver(); END final String expanded = environmentResolver.expandEnvironmentVariables(new EnvVars(), ""); assertThat(expanded).isEmpty(); } final für locals kann entfallen

Target:
void shouldReturnUnmodifiedOutputForEmptyInput() { EnvironmentResolver environmentResolver = new EnvironmentResolver(); String expanded = environmentResolver.expandEnvironmentVariables(new EnvVars(), ""); assertThat(expanded).isEmpty(); }
Source:
void shouldReturnAdjustedOutputForAGivenInputBasedOnDollarSigns() { final EnvironmentResolver environmentResolver = new EnvironmentResolver(); final EnvVars envVars = new EnvVars(); envVars.put(KEY, VALUE); START final String previous = "$$Test$$Testing$TestString$$Testing$Test"; END final String expanded = environmentResolver.expandEnvironmentVariables(envVars, previous); final String expected = "$Test$Testing$TestString$Testing$Test"; assertThat(expanded).isEqualTo(expected); } Das war mit gar nicht bewusst, dass $$ durch $ ersetzt wird. (Das ist ja auch ein Feature der aufgerufenen Methode in Jenkins Core). Wäre es in unserem Fall nicht leichter zu verstehen, wenn 1. "Test" so bleib wie es ist 2. "$KEY" durch "$VALUE" ersetzt wird. "$VALUE" aber nicht weiter 3. "$KEY" durch "$VALUE" ersetzt wird und dann "$VALUE" durch was weiteres Ergibt drei Tests...

Target:
void shouldReturnAdjustedOutputForAGivenInputBasedOnDollarSigns() { EnvironmentResolver environmentResolver = new EnvironmentResolver(); EnvVars envVars = new EnvVars(); envVars.put(KEY, VALUE); String previous = "$$Test$$Testing$TestString$$Testing$Test"; String expanded = environmentResolver.expandEnvironmentVariables(envVars, previous); String expected = "$Test$Testing$TestString$Testing$Test"; assertThat(expanded).isEqualTo(expected); }
Source:
void shouldReturnTheExpectedIdNameForAListContainingTheExpectedId() { START applyGetMethodAndCheckResult(ID_NAME_1, 0, ID_NAME_1, ID_NAME_2, ID_NAME_3); END applyGetMethodAndCheckResult(ID_NAME_1, 1, ID_NAME_2, ID_NAME_1, ID_NAME_3); applyGetMethodAndCheckResult(ID_NAME_1, 2, ID_NAME_3, ID_NAME_2, ID_NAME_1); } Für die Branch Interior Path Coverage überprüft man i.A. 0, 1, 2 Schleifendurchläufe.

Target:
void shouldReturnTheExpectedIdNameForAListContainingTheExpectedId() { applyGetMethodAndCheckResult(ID_NAME_1, 0, ID_NAME_1, ID_NAME_2); applyGetMethodAndCheckResult(ID_NAME_1, 1, ID_NAME_2, ID_NAME_1); }
Source:
void shouldReturnCorrectStringRepresentationForAGivenIdBasedOnAHardcodedClassname() { final ByIdResultSelector byIdResultSelector = new ByIdResultSelector("ID-Name"); assertThat(byIdResultSelector.toString()).isEqualTo( START "io.jenkins.plugins.analysis.core.views.ResultAction with ID ID-Name"); END } Gute Frage ob man toString testen sollte oder nicht. Aus meiner Sicht würde reichten contains("ID-Name"). (Ist aber nicht falsch so)

Target:
void shouldReturnCorrectStringRepresentationForAGivenIdBasedOnAHardcodedClassname() { ByIdResultSelector byIdResultSelector = new ByIdResultSelector("ID-Name"); assertThat(byIdResultSelector.toString()).contains("ID-Name"); }
Source:
START public HealthAwareRecorder(String pluginName) { END this.pluginName = "[" + pluginName + "] "; } Note that it would be clearer for this to be marked `protected`: the class is `abstract` so this constructor could only be called by subclass constructors.

Target:
protected HealthAwareRecorder(String pluginName) { this.pluginName = "[" + pluginName + "] "; }
Source:
public void getReserveScopes() { START Set<SystemScope> reserved = SystemScopeService.reservedScopes; END assertThat(service.getReserved(), equalTo(reserved)); } No need to pull this out as a separate variable, just reference it in the test below

Target:
public void getReserveScopes() { assertThat(service.getReserved(), equalTo(SystemScopeService.reservedScopes)); }
Source:
public String getTestSrc() { START return testSrcs.get(0); END } You require `srcs` to be non-empty, but you don't require `testSrcs` to be non-empty. So this line can throw an exception.

Target:
public String getTestSrc() { return testSrcs.isEmpty() ? null : testSrcs.get(0); }
Source:
public static Mode getMode(Run run) { return Optional.ofNullable(run.get(LaunchUtils.Mode.class.getName())) START .map(s -> valueOf(s)) END .orElse(UNSET); } Isn't this more simply: ```java .map(Mode::valueOf) ```

Target:
public static Mode getMode(Run run) { return Optional.ofNullable(run.get(LaunchUtils.Mode.class.getName())) .map(Mode::valueOf) .orElse(UNSET); }
Source:
public static Run setMode(Run run, Mode mode) { run.set(LaunchUtils.Mode.class.getName(), mode.name()); START return run; END } Returning `Run` here seems a bit cheeky for this method as API.

Target:
public static void setMode(Run run, Mode mode) { run.set(LaunchUtils.Mode.class.getName(), mode.name()); }
Source:
protected void launchJavaElements(List<IJavaElement> elements, String mode) throws CoreException { START launch(elements.iterator().next().getJavaProject().getProject().getFullPath(), mode); END } Up above you used `elements.get(0).getJava...`. Here it is `elements.iterator().next().getJava...`. Lets make them consistent. Since `elements` is a list, lets use `get(0)` here to match the code above.

Target:
protected void launchJavaElements(List<IJavaElement> elements, String mode) throws CoreException { launch(elements.get(0).getJavaProject().getProject().getFullPath(), mode); }
Source:
public static IResource getTargetResource(ILaunchConfiguration configuration) throws CoreException { String target = getTargetName(configuration); START END IResource targetResource = ResourcesPlugin.getWorkspace().getRoot().findMember(target); return targetResource; } This null check is still necessary since you do not want to pass null to findMember.

Target:
public static IResource getTargetResource(ILaunchConfiguration configuration) throws CoreException { String target = getTargetName(configuration); if (target == null) return null; IResource targetResource = ResourcesPlugin.getWorkspace().getRoot().findMember(target); return targetResource; }
Source:
private String getRemoteBranch() { if (params.branch == null) { return GitCloneTemplateParams.DEFAULT_BRANCH; } START if (params.branch.indexOf('/') == -1) { END return "origin/" + params.branch; } return params.branch; } This is not right. Branches can have `/` in them. Since the local "clone" determines what it calls the remote repo, I suspect jgit is always using origin. So the test needs to be `if (!params.branch.startsWith("origin/")`.

Target:
private String getRemoteBranch() { if (params.branch == null) { return GitCloneTemplateParams.DEFAULT_BRANCH; } if (!params.branch.startsWith("origin/")) { return "origin/" + params.branch; } return params.branch; }
Source:
public void setWireframe(boolean val) { if(chart.isSetWireframe()) chart.getWireframe().setVal(val); else chart.addNewWireframe().setVal(val); START } END all three above methods don't follow the project's formatting style

Target:
public void setWireframe(boolean val) { if (chart.isSetWireframe()) { chart.getWireframe().setVal(val); } else { chart.addNewWireframe().setVal(val); } }
Source:
boolean dispose() throws IOException { START try { END _out.close(); } finally { } return true; } I don't think exception should be swallowed

Target:
boolean dispose() throws IOException { _out.close(); return true; }
Source:
private void updateSheetTable(CTTable ctTable, String title, int index) { CTTableColumns tableColumnList = ctTable.getTableColumns(); CTTableColumn column = null; int columnCount = tableColumnList.getTableColumnList().size()-1; for( int i = columnCount; columnCount < index; i++) { column = tableColumnList.addNewTableColumn(); column.setId(i); ++columnCount; START } END column = tableColumnList.getTableColumnArray(index); column.setName(title); } Could you use this? ``` for (int i = columnCount; i < index; i++) { column = tableColumnList.addNewTableColumn(); column.setId(i); } ```

Target:
private void updateSheetTable(CTTable ctTable, String title, int index) { CTTableColumns tableColumnList = ctTable.getTableColumns(); CTTableColumn column = null; int columnCount = tableColumnList.getTableColumnList().size()-1; for( int i = columnCount; i < index; i++) { column = tableColumnList.addNewTableColumn(); column.setId(i); } column = tableColumnList.getTableColumnArray(index); column.setName(title); }
Source:
public static FormulaShifter createForRowShift(int externSheetIndex, String sheetName, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove, SpreadsheetVersion version) { FormulaShifter instance = new FormulaShifter(externSheetIndex, sheetName, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove, ShiftMode.RowMove, version); START return instance; END } `return new FormulaShifter(`... is fine. No need to store the returned value in `instance`.

Target:
public static FormulaShifter createForRowShift(int externSheetIndex, String sheetName, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove, SpreadsheetVersion version) { return new FormulaShifter(externSheetIndex, sheetName, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove, ShiftMode.RowMove, version); }
Source:
START public void shift(int n) { END int rownum = getRowNum() + n; String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; for(Cell c : this){ ((XSSFCell)c).updateCellReferencesForShifting(msg); } setRowNum(rownum); } Does `protected` work?

Target:
protected void shift(int n) { int rownum = getRowNum() + n; String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; for(Cell c : this){ ((XSSFCell)c).updateCellReferencesForShifting(msg); } setRowNum(rownum); }
Source:
public boolean matches(URL url) { START return url.getProtocol().equals("file") && url.toExternalForm().endsWith(".jar"); END } Aren't there url's like this too? file://some/path/my.jar!org/foo/bar The ! is often used in java url's to indicate that it's inside zip (not sure if it's used in these kind though). I agree contains has false positives (like tony.jarvis) but endswith might have false negatives (like my.jar!org).

Target:
public boolean matches(URL url) { return url.getProtocol().equals("file") && url.toExternalForm().contains(".jar"); }
Source:
public boolean disablePearlDamage(boolean allow) { pearlDamage = allow; START return allow; END } No real need for a return type :P

Target:
public void disablePearlDamage(boolean allow) { pearlDamage = allow; }
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); Assert.notNull(callbackUri, "callbackUri must be configured."); Assert.notNull(idSiteOrganizationResolver, "idSiteOrganizationResolver must be configured."); Assert.notNull(alreadyLoggedInUri, "alreadyLoggedInUri must be configured."); START Assert.isTrue(!(preRegisterHandler != null && preLoginHandler != null), "This IDSite controller must contain only one of preRegisterHandler and preLoginHandler"); END } Why can you not have both a pre-login handler and a pre-register handler? You can when not using id site.

Target:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); Assert.notNull(callbackUri, "callbackUri must be configured."); Assert.notNull(idSiteOrganizationResolver, "idSiteOrganizationResolver must be configured."); Assert.notNull(alreadyLoggedInUri, "alreadyLoggedInUri must be configured."); }
Source:
public Phone setAccount(Account account) { if(((AbstractResource)account).isMaterialized()) { setResourceProperty(ACCOUNT,account); } else{ START setMaterializableResourceProperty(ACCOUNT,account); END } return this; } I think the `setMaterializableResourceProperty` should handle the materialized scenario itself. This means that this method can simply invoke `setMaterializableResourceProperty(ACCOUNT,account);` and then, the internal code of `setMaterializableResourceProperty` will check whether the account is materialized or not and then will relay on `setResourceProperty(ACCOUNT,account);` internally.

Target:
public Phone setAccount(Account account) { setMaterializableResourceProperty(ACCOUNT, account); return this; }
Source:
public boolean isAccountLinkingEnabled () { START return AccountLinkingStatus.ENABLED.equals(getStatus()) ? true : false; END } Can be simplified to `AccountLinkingStatus.ENABLED.equals(getStatus())`

Target:
public boolean isAccountLinkingEnabled () { return AccountLinkingStatus.ENABLED.equals(getStatus()); }
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); //this will not really have any affect on logout but we need to set it otherwise controller#init() will throw controller.init(); this.idSiteController = controller; START } END Why are you removing this? `LogoutController#init()` says `//If sub-classess override this method they MUST CALL super.init() at some point insider their custom implementation.` Removing an existing explicit invocation to a method in a parent class could cause uncaught errors if we are not sure about what we are doing. Please add it back in and we can solve any new issue that this could cause.

Target:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); //this will not really have any affect on logout but we need to set it otherwise controller#init() will throw controller.init(); this.idSiteController = controller; super.init(); }
Source:
public String createCsrfToken(HttpServletRequest request, HttpServletResponse response) { CsrfToken csrfToken = this.csrfTokenRepository.loadToken(request); START final boolean missingToken = csrfToken == null; END if (missingToken) { csrfToken = this.csrfTokenRepository.generateToken(request); this.csrfTokenRepository.saveToken(csrfToken, request, response); } return csrfToken.getToken(); } This line seems unnecessary. Why not: ``` if (csrfToken == null) { ... ```

Target:
public String createCsrfToken(HttpServletRequest request, HttpServletResponse response) { CsrfToken csrfToken = this.csrfTokenRepository.loadToken(request); if (csrfToken == null) { csrfToken = this.csrfTokenRepository.generateToken(request); this.csrfTokenRepository.saveToken(csrfToken, request, response); } return csrfToken.getToken(); }
Source:
public Account removeGroup(String hrefOrName) { GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { START if (aGroupMembership.getGroup().getName().equalsIgnoreCase(hrefOrName) || aGroupMembership.getGroup().getHref().equalsIgnoreCase(hrefOrName)) { END groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; } `href`s are case sensitive. Please do `aGroupMembership.getGroup().getHref().equals(hrefOrName))`

Target:
public Account removeGroup(String hrefOrName) { GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getName().equals(hrefOrName) || aGroupMembership.getGroup().getHref().equals(hrefOrName)) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; }