auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected AbstractFixedIntervalTask( String id, START TaskResource taskResource, END String dataSource, Interval interval ) { this(id, id, taskResource, dataSource, interval); } there is already a constr, which takes (id,groupId,resource, dataSource,interval) Can we use that in indexTask, instead of adding a new one ?

Target:
protected AbstractFixedIntervalTask( String id, TaskResource taskResource, String dataSource, Interval interval ) { this( id, id, taskResource == null ? new TaskResource(id, 1) : taskResource, dataSource, interval ); }
Source:
private Object[][] finderSupportedResourceTypeData() { return new Object[][] START { END { FinderSupportedAssociationDataResource.class }, { FinderSupportedComplexKeyDataResource.class }, { FinderWithActionResource.class } }; } You can use the expectedExceptions and expectedExceptionsMessageRegExp attributes of the @Test annotation

Target:
private Object[][] finderSupportedResourceTypeData() { return new Object[][] { { FinderSupportedAssociationDataResource.class }, { FinderSupportedComplexKeyDataResource.class } }; }
Source:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); START doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); END ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } We actually don't need this line at all. The test check something else

Target:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }
Source:
public void mercury_topbar_wikiaLogoRedirectsToFandomPage() { TopBar topBar = new ArticlePage() .open(MercurySubpages.MAIN_PAGE) .getTopBar(); START Assertion.assertTrue(topBar.isLogoVisible()); END topBar.clickWikiaLogo(); Assertion.assertTrue(topBar.getCurrentUrl().contains("www.wikia.com/fandom")); } I think if it's not visible, click should fail, so is the assertion needed?

Target:
public void mercury_topbar_wikiaLogoRedirectsToFandomPage() { TopBar topBar = new ArticlePage() .open(MercurySubpages.MAIN_PAGE) .getTopBar(); topBar.clickWikiaLogo(); Assertion.assertTrue(topBar.getCurrentUrl().contains("www.wikia.com/fandom")); }
Source:
private ConfigurationServiceImplService getConfigService() throws ConnectionManagerException, MalformedURLException{ String url = oProxyHelper.getAdapterEndPointFromConnectionManager(DirectConfigConstants.DIRECT_CONFIG_SERVICE_NAME); if(cfService == null) { START cfService = new ConfigurationServiceImplService(new URL(url+"?wsdl")); END } return cfService; } Should this be initialized in a static / thread-safe context?

Target:
protected ConfigurationServiceImplService getConfigService() throws ConnectionManagerException, MalformedURLException{ return cfService; }
Source:
void testDtoListResponses() { FlowJsonObjectReader reader = new FlowJsonObjectReader(); TypeReference<SurveyGroupDto> typeReference = new TypeReference<SurveyGroupDto>() {}; List<SurveyGroupDto> surveyList = null; try { surveyList = reader.readDtoListObject(DTO_LIST_JSON_OBJECT, typeReference); } catch (IOException e) { // } assertNotEquals(surveyList, null); assertEquals(surveyList.size(), 1); START assertEquals(surveyList.get(0).getName(),"1.10.36 all questions"); END } This is a minor detail but the the assertZZZ methods work like this assertZZZ(expected, actual), this is valid for the whole of your test files. Also please format the file as some "," have no space after them.

Target:
void testDtoListResponses() { FlowJsonObjectReader reader = new FlowJsonObjectReader(); TypeReference<SurveyGroupDto> typeReference = new TypeReference<SurveyGroupDto>() {}; List<SurveyGroupDto> surveyList = null; try { surveyList = reader.readDtoListObject(DTO_LIST_JSON_OBJECT, typeReference); } catch (IOException e) { // ignoring exception } assertNotEquals(null, surveyList); assertEquals(1, surveyList.size()); assertEquals("1.10.36 all questions", surveyList.get(0).getName()); }
Source:
public GroupScan clone(List<SchemaPath> columns) { START HBaseUtils.verifyColumns(columns, hTableDesc); END HBaseGroupScan newScan = new HBaseGroupScan(this); newScan.columns = columns == null ? ALL_COLUMNS : columns; return newScan; } We should replace null columns with all_columns before verification or we will get exception. You have changed initial order of statements.

Target:
public GroupScan clone(List<SchemaPath> columns) { HBaseGroupScan newScan = new HBaseGroupScan(this); newScan.columns = columns == null ? ALL_COLUMNS : columns; HBaseUtils.verifyColumns(columns, hTableDesc); return newScan; }
Source:
START static <T, U> Function<T, Result<U>> reportMissing(Class<?> expectedClass) { END return t -> Result.failure( "Not yet implemented: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); } Can be private method.

Target:
private static <T, U> Function<T, Result<U>> reportMissing(Class<?> expectedClass) { return t -> Result.failure( "Not yet implemented: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); }
Source:
private void rematchAllNetworksAndRequests() { // TODO: This may be slow, and should be optimized. final long now = SystemClock.elapsedRealtime(); final NetworkReassignment changes = computeNetworkReassignment(); if (VDBG || DDBG) log(changes.toString()); applyNetworkReassignment(changes, START oldDefaultNetwork, now); END } hmm, I don't think this can get build pass.

Target:
private void rematchAllNetworksAndRequests() { // TODO: This may be slow, and should be optimized. final long now = SystemClock.elapsedRealtime(); final NetworkReassignment changes = computeNetworkReassignment(); if (VDBG || DDBG) log(changes.toString()); applyNetworkReassignment(changes, now); }
Source:
public String getScroller() { START return scroller == null ? DEFAULT_SCROLLER : scroller; END } wdyt if we replace it by ` return Objects.requireNonNullElse(scroller, DEFAULT_SCROLLER)` if you agree you will have some adaptation on 10.10 (java 8)

Target:
public String getScroller() { return scroller; }
Source:
public String getMessage(){ START return this.message; END } Nit: unnecessary this.

Target:
public String getMessage(){ return message; }
Source:
public Type convertReadValueToType(String pvReadValue) { Type lvType = convertReadValueToUnmodifiedType(pvReadValue); for (InterfaceOneWireTypeModifier lvTypeModifier : getTypeModifieryList()) { logger.debug("type of before modifier:{} type={}", getDevicePropertyPath(), START lvTypeModifier.getModifierName(), lvType.toString()); END lvType = lvTypeModifier.modify4Read(lvType); logger.debug("type of after modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType.toString()); } return lvType; } no need for `.toString()`

Target:
public Type convertReadValueToType(String pvReadValue) { Type lvType = convertReadValueToUnmodifiedType(pvReadValue); for (InterfaceOneWireTypeModifier lvTypeModifier : getTypeModifieryList()) { logger.debug("type of before modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType); lvType = lvTypeModifier.modify4Read(lvType); logger.debug("type of after modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType); } return lvType; }
Source:
START public void clear() { END this.domainsVisibility.clear(); } this should be synchronized as well

Target:
public synchronized void clear() { this.domainsVisibility.clear(); }
Source:
public static Comment newComment(long issueId, int newCommentId, String comment) { DateTime now = DateTime.now(); START Long id = Long.parseLong(issueId + "0" + newCommentId); END URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId + "/comment"); return new Comment(selfUri, comment, null, null, now, null, null, id); } Since you are at it, can you please change this to `long` primitive type? :)

Target:
public static Comment newComment(long issueId, int newCommentId, String comment) { DateTime now = DateTime.now(); long id = Long.parseLong(issueId + "0" + newCommentId); URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId + "/comment"); return new Comment(selfUri, comment, null, null, now, null, null, id); }
Source:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { START synchronized (context) { END context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } } while (context != null); } I don't think this works. We're swapping out `context` with a different instance. We should probably use a constant as a monitor.

Target:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } while (context != null); }
Source:
private String truncateMessageLength(String message, int maxLength) { if (message.length() > maxLength) { START message = message.substring(0, maxLength + 1); END } return message; } This line will actually return a substring of length maxLength + 1. If the substring indeed needs to be no longer than maxLength, then replace "maxLength + 1" with just "maxLength".

Target:
private String truncateMessageLength(String message, int maxLength) { if (message.length() > maxLength) { message = message.substring(0, maxLength); } return message; }
Source:
public void testErrorReceived() { TestObserver<Object> ts = new TestObserver<Object>(); TestException ex = new TestException("boo"); Flowable.error(ex).ignoreElements().subscribe(ts); ts.assertNoValues(); START ts.assertTerminated();; END ts.assertError(TestException.class); ts.assertErrorMessage("boo"); } double `;`

Target:
public void testErrorReceived() { TestObserver<Object> ts = new TestObserver<Object>(); TestException ex = new TestException("boo"); Flowable.error(ex).ignoreElements().subscribe(ts); ts.assertNoValues(); ts.assertTerminated(); ts.assertError(TestException.class); ts.assertErrorMessage("boo"); }
Source:
public boolean select(Viewer viewer, Object parentElement, START Object element) { END if (!(element instanceof DisplayItem)) { return false; } if (actionSet == null) { return false; } return CustomizePerspectiveDialog.includeInSetStructure((DisplayItem) element, actionSet); } unnecessary linebreak

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (!(element instanceof DisplayItem) || actionSet == null) { return false; } return CustomizePerspectiveDialog.includeInSetStructure((DisplayItem) element, actionSet); }
Source:
public static void runJSTestSuite() throws InterruptedException { // FIXME Update this when we stop using ARM Emulators int timeout = Build.SUPPORTED_ABIS[0].contains("armeabi") ? 180 : 60; START JSTestCase.runJSTestSuite(JS_SUITE, data(), timeout); END } Why not just bump it up to `180` across the board?

Target:
public static void runJSTestSuite() throws InterruptedException { // FIXME Change timeout back to 60 when we stop using ARM Emulators JSTestCase.runJSTestSuite(JS_SUITE, data(), 180); }
Source:
public Map<String, String> getSystemSessionProperties(SessionConfigurationContext context) { START HashMap<String, String> combinedProperties = new HashMap<>(); END for (SessionMatchSpec sessionMatchSpec : sessionMatchSpecs) { combinedProperties.putAll(sessionMatchSpec.match(context)); } return ImmutableMap.copyOf(combinedProperties); } Nit: declare as `Map`

Target:
public Map<String, String> getSystemSessionProperties(SessionConfigurationContext context) { // later properties override earlier properties Map<String, String> combinedProperties = new HashMap<>(); for (SessionMatchSpec sessionMatchSpec : sessionMatchSpecs) { combinedProperties.putAll(sessionMatchSpec.match(context)); } return ImmutableMap.copyOf(combinedProperties); }
Source:
public static void logAccess(Integer requestId, InetAddress remoteAddress, Principal principal, String operation) { new ThriftAccessLogger().log( String.format("Request ID: access from: principal: operation: {}", requestId, remoteAddress, principal, operation)); START } END I thought it would be something like ``` LOG.info("Request ID: access from: principal: operation: {}", requestId, remoteAddress, principal, operation); ``` and ThriftAccessLogger.log would just go away

Target:
public static void logAccess(Integer requestId, InetAddress remoteAddress, Principal principal, String operation) { LOG.info("Request ID: access from: principal: operation: {}", requestId, remoteAddress, principal, operation); }
Source:
public static List<String> getComputerNames() { final ArrayList<String> names = new ArrayList<String>(); START for (Computer c : Jenkins.getActiveInstance().getComputers()) { END if (!c.getName().isEmpty()) { names.add(c.getName()); } } return names; } `getActiveInstance` is deprecated, please use good old `getInstance`.

Target:
public static List<String> getComputerNames() { final ArrayList<String> names = new ArrayList<String>(); for (Computer c : Jenkins.getInstance().getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } return names; }
Source:
public void unbind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); START final Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); END synchronized (lock) { if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { eventNameToListenerMap.remove(eventName); } } } } As above, you must perform both the read and the write in the critical section, otherwise there's no guarantee of consistency.

Target:
public void unbind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); synchronized (lock) { final Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { eventNameToListenerMap.remove(eventName); } } } }
Source:
public Iterable<AccountGroup> all() { START final List<AccountGroup> groups = new LinkedList<AccountGroup>(); END for (final AccountGroup.NameKey groupName : list.get(ListKey.ALL)) { final AccountGroup group = get(groupName); if (group != null) { groups.add(group); } } return Collections.unmodifiableList(groups); } If list.get(ListKey.ALL) returns a reasonable upper bounds for the size, I think that an ArrayList would likely be faster.

Target:
public Iterable<AccountGroup> all() { final List<AccountGroup> groups = new ArrayList<AccountGroup>(); for (final AccountGroup.NameKey groupName : list.get(ListKey.ALL)) { final AccountGroup group = get(groupName); if (group != null) { groups.add(group); } } return Collections.unmodifiableList(groups); }
Source:
public void terminate(HazelcastInstance instance) { try { Address address = getNode(instance).address; terminateInstance(instance); if (isMockNetwork) { registry.removeInstance(address); } } finally { START TestJmxLeakHelper.checkJmxBeans(instance.getName()); END } } We have a large number of tests that don't use `TestHazelcastInstanceFactory` at all and call `Hazelcast.newHazelcastInstance()` directly (in combination with `Hazelcast.shutdownAll()` / `HazelcastInstanceFactory.shutdownAll()` / `HazelcastInstanceFactory.terminateAll()`). Shouldn't those be checked as well, somehow?

Target:
public void terminate(HazelcastInstance instance) { Address address = getNode(instance).address; terminateInstance(instance); if (isMockNetwork) { registry.removeInstance(address); } }
Source:
public void endSuccessfully() { super.endSuccessfully(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); // No reason for this to happen, but checking just to make sure if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); START getReturnValue().setSucceeded(true); END } please change to setSucceeded

Target:
public void endSuccessfully() { super.endSuccessfully(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); // No reason for this to happen, but checking just to make sure if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); setSucceeded(true); }
Source:
START void validate() { END // No-op, no validation required } Interesting wrapping style :)

Target:
public void validate() { // No-op, no validation required }
Source:
private void scheduleImmediateDelivery() { cancelDelayedDelivery(); while (state == State.RUNNING) { DeliveryAttempt previous = immediateDelivery.get(); if (previous != null && !previous.isDone()) START previous.cancel(); END DeliveryAttempt current = new DeliveryAttempt(); if (immediateDelivery.compareAndSet(previous, current)) { current.executeNow(); return; } } } deliverEvents does not handle interruptions, so this is essentially a no-op if `previous` is already executing.

Target:
private void scheduleImmediateDelivery() { cancelDelayedDelivery(); while (state == State.RUNNING) { DeliveryAttempt previous = immediateDelivery.get(); if (previous != null) previous.cancel(); DeliveryAttempt current = new DeliveryAttempt(); if (immediateDelivery.compareAndSet(previous, current)) { current.executeNow(); return; } } }
Source:
private static ObjectNode handleGaugeRollup(GaugeRollup rollup) { ObjectNode rollupNode = JsonNodeFactory.instance.objectNode(); START rollupNode.put("timestamp", rollup.getTimestamp()); END SimpleNumber rollupValue = rollup.getLatestValue(); rollupNode.put("latestVal", rollupValue.getDataType() == (SimpleNumber.Type.DOUBLE) ? rollupValue.getValue().doubleValue() : rollupValue.getValue().longValue()); return handleBasicRollup(rollup, rollupNode); } Why do gauges get timestamp twice?

Target:
private static ObjectNode handleGaugeRollup(GaugeRollup rollup) { ObjectNode rollupNode = JsonNodeFactory.instance.objectNode(); SimpleNumber rollupValue = rollup.getLatestValue(); rollupNode.put("latestVal", rollupValue.getDataType() == (SimpleNumber.Type.DOUBLE) ? rollupValue.getValue().doubleValue() : rollupValue.getValue().longValue()); return handleBasicRollup(rollup, rollupNode); }
Source:
public GarruksWarsteed(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}"); this.subtype.add(SubType.RHINO); this.power = new MageInt(3); this.toughness = new MageInt(5); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // When Garruk's Warsteed enters the battlefield, you may search your library and/or graveyard for a card named Garruk, Savage Herald, reveal it, and put it into your hand. If you search your library this way, shuffle it. START this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter, false, true), true)); END } this doesn't need to have the ability and effect both be optional, just the ability is fine.

Target:
public GarruksWarsteed(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}"); this.subtype.add(SubType.RHINO); this.power = new MageInt(3); this.toughness = new MageInt(5); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // When Garruk's Warsteed enters the battlefield, you may search your library and/or graveyard for a card named Garruk, Savage Herald, reveal it, and put it into your hand. If you search your library this way, shuffle it. this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter, false, true))); }
Source:
private void releaseFileChannel(long logId, CachedFileChannel cachedFileChannel) { lock.writeLock().lock(); try { if (cachedFileChannel.markDead()) { START try { END cachedFileChannel.fileChannel.close(); } catch (IOException e) { LOG.warn("Exception occurred in ReferenceCountedFileChannel" + " while closing channel for log file: {}", cachedFileChannel); } finally { IOUtils.close(LOG, cachedFileChannel.fileChannel); } // to guarantee the removed cachedFileChannel is what we want to remove. fileChannels.remove(logId, cachedFileChannel); } } finally { lock.writeLock().unlock(); } } markDead doesn't need to be under a lock. The caller should call tryRetain() after receiving, which will either prevent markDead from having an effect, if it is called before it.

Target:
private void releaseFileChannel(long logId, CachedFileChannel cachedFileChannel) { if (cachedFileChannel.markDead()) { // to guarantee the removed cachedFileChannel is what we want to remove. fileChannels.remove(logId, cachedFileChannel); // close corresponding fileChannel try { cachedFileChannel.fileChannel.close(); } catch (IOException e) { LOG.warn("Exception occurred in ReferenceCountedFileChannel" + " while closing channel for log file: {}", cachedFileChannel); } finally { IOUtils.close(LOG, cachedFileChannel.fileChannel); } } }
Source:
private static File getDefaultFile() { START File netrc; END File home = new File(System.getProperty("user.home")); //$NON-NLS-1$ netrc = new File(home, ".netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; netrc = new File(home, "_netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; return null; } no need to declare this here, instead declare the type in line 141

Target:
private static File getDefaultFile() { File home = new File(System.getProperty("user.home")); //$NON-NLS-1$ File netrc = new File(home, ".netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; netrc = new File(home, "_netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; return null; }
Source:
START static synchronized ServiceContext getServiceContext() { END if (serviceContext == null) { synchronized (Context.class) { if (serviceContext == null) { log.error("serviceContext is null. Creating new ServiceContext()"); serviceContext = ServiceContext.getInstance(); } } } log.trace("serviceContext: {}", serviceContext); return ServiceContext.getInstance(); } I can see that the method body was already synchronised. Can you instead remove the outer if (serviceContext == null)? Because i see it duplicated in the inner block.

Target:
static synchronized ServiceContext getServiceContext() { synchronized (Context.class) { if (serviceContext == null) { log.error("serviceContext is null. Creating new ServiceContext()"); serviceContext = ServiceContext.getInstance(); } } log.trace("serviceContext: {}", serviceContext); return ServiceContext.getInstance(); }
Source:
public synchronized void activate() { START OTELog.getLogger("test").debug("something"); END listener = new Slf4jLogListener(); logService.addLogListener(listener); } remove this line

Target:
public synchronized void activate() { listener = new Slf4jLogListener(); logService.addLogListener(listener); }
Source:
START public void testDeserialization() throws Exception { END for (Short version : versions) { composedBlobIdAndDeserialize(version); } } I don't understand the need of this test. We have the next one which tests serialization and deserialization if I am not wrong. Or does this tests something more than the next one ?

Target:
public void testDeserialization() throws Exception { composedBlobIdAndDeserialize(version); }
Source:
private List<VMWithPlugInfo> getVmsWithPlugInfo(Guid id) { START List<VMWithPlugInfo> vmsWithPlugInfo = END getCallsHandler().executeReadList ("GetVmsByDiskId", VMWithPlugInfoRowMapper.instance, getCustomMapSqlParameterSource().addValue("disk_guid", id)); return vmsWithPlugInfo; } should be just return , no need for variable

Target:
private List<VMWithPlugInfo> getVmsWithPlugInfo(Guid id) { return getCallsHandler().executeReadList ("GetVmsByDiskId", VMWithPlugInfoRowMapper.instance, getCustomMapSqlParameterSource().addValue("disk_guid", id)); }
Source:
public Jedis createResource() { START Jedis jedis = new Jedis(this); END try { jedis.select(db); } catch(JedisException e) { log.log(Level.SEVERE, "Can't select database due a Redis connection problem", e); } return jedis; } @nykolaslima How about handling selecting db by constructor of BinaryJedis, as authentication takes place?

Target:
public Jedis createResource() { return new Jedis(this); }
Source:
public JSchUIConnectionManager(IRemoteServices services) { fConnMgr = (JSchConnectionManager) services.getConnectionManager(); START fConnMgr.setDefaultAuthenticatorFactory(new IUserAuthenticatorFactory() { END @Override public IUserAuthenticator createUserAuthenticator(IRemoteConnection conn) { return new RemoteAuthenticator(conn); } }); } Please keep initialization code out of the Activator class.

Target:
public JSchUIConnectionManager(IRemoteServices services) { fConnMgr = (JSchConnectionManager) services.getConnectionManager(); }
Source:
public BoltDeclarer addConfigurations(Map<String, Object> conf) { START if (conf != null && !conf.isEmpty()) { END component.componentConf.putAll(conf); } return this; } Nit: I think putAll is a no-op when the conf is empty, so you probably don't need to check.

Target:
public BoltDeclarer addConfigurations(Map<String, Object> conf) { if (conf != null) { component.componentConf.putAll(conf); } return this; }
Source:
public void startTrackingBpForProcess(final IContainerDMContext containerDmc, final RequestMonitor rm) { final IBreakpointsTargetDMContext targetBpDmc = DMContexts.getAncestorOfType(containerDmc, IBreakpointsTargetDMContext.class); IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(fDebugModelId); for (IBreakpoint breakpoint : breakpoints) { START if (supportsBreakpoint(breakpoint) && breakpoint instanceof ICBreakpoint) { END setTargetFilter((ICBreakpoint) breakpoint, containerDmc); } } startTrackingBreakpoints(targetBpDmc, rm); } Its a heavy read that bug! When you check if breakpoint applicable probably better reverse instanceof check and call. Instanceof is cheaper

Target:
public void startTrackingBpForProcess(final IContainerDMContext containerDmc, final RequestMonitor rm) { final IBreakpointsTargetDMContext targetBpDmc = DMContexts.getAncestorOfType(containerDmc, IBreakpointsTargetDMContext.class); IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(fDebugModelId); for (IBreakpoint breakpoint : breakpoints) { if (breakpoint instanceof ICBreakpoint && supportsBreakpoint(breakpoint)) { setTargetFilter((ICBreakpoint) breakpoint, containerDmc); } } startTrackingBreakpoints(targetBpDmc, rm); }
Source:
protected void startCompaction(CorfuRuntime rt, LogUnitServer logUnitServer) { // stop periodical tasks to prevent race condition rt.getGarbageInformer().stop(); // wait until all garbage decisions are sent to logUnit servers. rt.getGarbageInformer().waitUntilAllTasksFinish(); // send garbage decisions to logUnit servers START while (rt.getGarbageInformer().getGarbageReceivingQueue().size() > 0) { rt.getGarbageInformer().gcUnsafe(); } END // run compaction on LogUnit servers logUnitServer.runCompaction(); rt.getAddressSpaceView().resetCaches(); rt.getAddressSpaceView().invalidateServerCaches(); } Put this logic into GarbageInformer together with waitUntilAllTasksFinish as we discussed.

Target:
protected void startCompaction(CorfuRuntime rt, LogUnitServer logUnitServer) { // stop periodical tasks to prevent race condition rt.getGarbageInformer().stop(); // wait until all garbage decisions are sent to logUnit servers. rt.getGarbageInformer().waitUntilAllTasksFinish(); // run compaction on LogUnit servers logUnitServer.runCompaction(); rt.getAddressSpaceView().resetCaches(); rt.getAddressSpaceView().invalidateServerCaches(); }
Source:
private void writeToChannelVersionOne(WritableByteChannel channel) throws IOException { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); START return; END } } This addition is pointless

Target:
private void writeToChannelVersionOne(WritableByteChannel channel) throws IOException { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); } }
Source:
protected void setUp() throws Exception { super.setUp(); Statement stmt = con.createStatement(); /* Drop the test table if it already exists for some reason. It is not an error if it doesn't exist. */ TestUtil.createTable(con, "testtz", "col1 INTEGER, col2 TIMESTAMP"); stmt.close(); /* Generally recommended with batch updates. By default we run all tests in this test case with autoCommit disabled. */ START con.setAutoCommit(false); END } Please remove that

Target:
protected void setUp() throws Exception { super.setUp(); Statement stmt = con.createStatement(); /* Drop the test table if it already exists for some reason. It is not an error if it doesn't exist. */ TestUtil.createTable(con, "testtz", "col1 INTEGER, col2 TIMESTAMP"); stmt.close(); }
Source:
public List<Currency> getCurrencyForName(final String name) { List<Currency> list = _namesToCurrency.get(name); START if (list == null) { END return new ArrayList<>(); } return _namesToCurrency.get(name); } These null checks will disappear if using a multimap

Target:
public List<Currency> getCurrencyForName(final String name) { return _namesToCurrency.get(name); }
Source:
private static boolean parseAllowAlias(List<Option> options) { Option option = Option.findByName(options, "allow_alias"); if (option != null) { Object value = option.getValue(); START return value instanceof Boolean ? (Boolean) value : "true".equals(value); END } return false; } What is the actual possible runtime type for the value? This seems overly defensive - I would expect the value will either be a string or a Boolean, not randomly changing from run to run.

Target:
private static boolean parseAllowAlias(List<Option> options) { Option option = Option.findByName(options, "allow_alias"); if (option != null) { Object value = option.getValue(); return value instanceof Boolean && (Boolean) value; } return false; }
Source:
public WebArchive createDeployment() { START if (resourceLocal) { END archive.addClasses( MemberRegistrationWithResourceLocal.class, ResourceLocalResources.class ); } else { archive.addClasses( MemberRegistrationWithJta.class, JtaResources.class ); } return archive; } Interesting approach. I guess I'd have tried to use qualifiers or the CDI alternative mechanism, but this seems the simplest.

Target:
public WebArchive createDeployment() { if (resourceLocal) { archive.addClasses( MemberRegistrationWithResourceLocal.class ); } else { archive.addClasses( MemberRegistrationWithJta.class, JtaResources.class ); } return archive; }
Source:
private StorageDomain recoverStorageDomain(String sdUUID) { START log.info("about to recover SD {}", sdUUID); END StorageDomain storageDomain = new StorageDomain(); storageDomain.setId(sdUUID); updateStorageDomain(storageDomain); return storageDomain; } log.debug ?

Target:
private StorageDomain recoverStorageDomain(String sdUUID) { log.warn("about to recover SD {}", sdUUID); StorageDomain storageDomain = new StorageDomain(); storageDomain.setId(sdUUID); updateStorageDomain(storageDomain); return storageDomain; }
Source:
public Event complianceCreated(Consumer consumer, Set<Entitlement> entitlements, ComplianceStatus compliance) { return new Event(Event.Type.CREATED, Event.Target.COMPLIANCE, consumer.getName(), principalProvider.get(), consumer.getOwner().getId(), consumer.getUuid(), START consumer.getId(), null, buildComplianceDataJson(consumer, entitlements, compliance), null, END null); } We'll need the second usage of consumer.getId() replaced with consumer.getUuid() as well.

Target:
public Event complianceCreated(Consumer consumer, Set<Entitlement> entitlements, ComplianceStatus compliance) { // Instead of an internal db id, compliance.created events now use // UUID for the 'consumerId' and 'entityId' fields, since Katello // is concerned only with the consumer UUID field. This is the first // part of a larger piece of work to simplify Event consumption. return new Event(Event.Type.CREATED, Event.Target.COMPLIANCE, consumer.getName(), principalProvider.get(), consumer.getOwner().getId(), consumer.getUuid(), consumer.getUuid(), null, buildComplianceDataJson(consumer, entitlements, compliance), null, null); }
Source:
public static String toHexString(byte[] digest) { START StringBuffer buf END = new StringBuffer(); for (int i = 0; i < digest.length; i++) { if ((digest[i] & 0xFF) < 0x10) buf.append('0'); buf.append(Integer.toHexString(digest[i] & 0xFF)); } return buf.toString(); } Use StringBuilder please.

Target:
public static String toHexString(byte[] digest) { StringBuilder buf = new StringBuilder(); for (byte element : digest) { if ((element & 0xFF) < 0x10) buf.append('0'); buf.append(Integer.toHexString(element & 0xFF)); } return buf.toString(); }
Source:
private boolean isLastKilledQueryGone() { boolean lastKilledQueryIsGone = (lastKilledQuery == null); START if (!lastKilledQueryIsGone) { END ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); if (generalPool != null) { lastKilledQueryIsGone = generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery); } } return lastKilledQueryIsGone; } Invert this so it returns early

Target:
private boolean isLastKilledQueryGone() { if (lastKilledQuery == null) { return true; } ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); if (generalPool == null) { return false; } return generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery); }
Source:
public Batcher(ScheduledExecutorService workExecutor, int capacity, long delay, BatchProcessor<T> processor) { this.workExecutor = workExecutor; this.capacity = capacity; this.delay = delay; this.processor = processor; this.inbox = new ArrayList<T>(); this.scheduled = false; START this.lastProcessedTime = 0; END } Is this change that makes batcher immediately execute after create new instance of Batcher and then added tasks smaller than capacity size?

Target:
public Batcher(ScheduledExecutorService workExecutor, int capacity, long delay, BatchProcessor<T> processor) { this.workExecutor = workExecutor; this.capacity = capacity; this.delay = delay; this.processor = processor; }
Source:
public static void removeMagicResponseContextFields(Map<String, Object> responseContext) { START responseContext.remove(DirectDruidClient.QUERY_FAIL_TIME); END responseContext.remove(DirectDruidClient.QUERY_TOTAL_BYTES_GATHERED); } This line should also be removed.

Target:
public static void removeMagicResponseContextFields(Map<String, Object> responseContext) { responseContext.remove(DirectDruidClient.QUERY_TOTAL_BYTES_GATHERED); }
Source:
private void validateAndClose() throws Exception { try { info("Validating static and Helix cluster maps"); verifyEquivalencyWithStaticClusterMap(staticClusterMap.hardwareLayout, staticClusterMap.partitionLayout); if (validatingHelixClusterManager != null) { START ensureOrThrow(validatingHelixClusterManager.getErrorCount() == 0, END "Helix cluster manager should not have encountered any errors"); } } finally { if (validatingHelixClusterManager != null) { validatingHelixClusterManager.close(); } for (HelixAdmin admin : adminForDc.values()) { admin.close(); } } } no Exception is thrown in this method

Target:
private void validateAndClose() { try { info("Validating static and Helix cluster maps"); verifyEquivalencyWithStaticClusterMap(staticClusterMap.hardwareLayout, staticClusterMap.partitionLayout); if (validatingHelixClusterManager != null) { ensureOrThrow(validatingHelixClusterManager.getErrorCount() == 0, "Helix cluster manager should not have encountered any errors"); } } finally { if (validatingHelixClusterManager != null) { validatingHelixClusterManager.close(); } for (HelixAdmin admin : adminForDc.values()) { admin.close(); } } }
Source:
public int size() { if (currentOffset == NO_VALUES) { return 0; } START return maxOffset - currentOffset - 1; END } Consider: `return currentOffset == NO_VALUES ? 0 : maxOffset - currentOffset - 1;`

Target:
public int size() { return isEmpty() ? 0 : maxOffset - currentOffset; }
Source:
START public void updateEditorPages(int activatedPage) { END removeAllPages(); addPages(); if (backToActivePage > 0 && backToActivePage < this.getPageCount()) { setActivePage(backToActivePage); } else { //Set active page if the backToActivePage is out of the range setActivePage(0); } setPartName(getPartName()); } activatedPage is not used anymore

Target:
public void updateEditorPages(int activatedPage) { updateEditorPages(); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { START Object checkCompositeRename= HandlerUtil.getVariable(event, LTK_CHECK_COMPOSITE_RENAME_PARAMETER_KEY); END if (checkCompositeRename != null) { return checkForCompositeRename(event, checkCompositeRename); } else { performRename(event); } return null; } Looking at other HandlerUtil.getVariable() calls, the usual logic is to look for an instance of what you were looking for (in this case Boolean) and to treat any other situation as if null was provided. This would remove the need to check for Boolean in checkForCompositeRename and having code to issue an error log message which should never occur.

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Object checkCompositeRename= HandlerUtil.getVariable(event, LTK_CHECK_COMPOSITE_RENAME_PARAMETER_KEY); if (checkCompositeRename instanceof Boolean) { return checkForCompositeRename(event); } else { performRename(event); } return null; }
Source:
START public Arguments setUntypedNullArgument(Argument untypedNullArgument) { END if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; return this; } Another non-permissible change

Target:
public void setUntypedNullArgument(Argument untypedNullArgument) { if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; }
Source:
private DebtRemediationFunction remediationFunction(DebtRemediationFunctions drf) { if (func.startsWith("Constant")) { START return drf.constantPerIssue(constantCost.replace("mn", "min")); END } if ("Linear".equals(func)) { return drf.linear(linearFactor.replace("mn", "min")); } return drf.linearWithOffset(linearFactor.replace("mn", "min"), linearOffset.replace("mn", "min")); } @ivandalbosco I see that you just copied this piece from JS, but it's not perfect there :) We can drop `.replace("mn", "min")` everywhere (3 places). This was done as many RSPECs had legacy `mn` for minutes. It should be fixed now. It there is still some RSPEC using `mn` and plugin fails, then you better update this RSPEC

Target:
private DebtRemediationFunction remediationFunction(DebtRemediationFunctions drf) { if (func.startsWith("Constant")) { return drf.constantPerIssue(constantCost); } if ("Linear".equals(func)) { return drf.linear(linearFactor); } return drf.linearWithOffset(linearFactor, linearOffset); }
Source:
public void setAnalysisCache(final AnalysisCache cache) { if (cache == null && isAnalysisCacheFunctional()) { analysisCache = new NoopAnalysisCache(); // Log warning only once, if not explicitly disabled if (!isIgnoreIncrementalAnalysis() && LOG.isLoggable(Level.WARNING)) { final String version = PMDVersion.isUnknown() || PMDVersion.isSnapshot() ? "latest" : "pmd-" + PMDVersion.VERSION; START LOG.warning("This analysis could be faster, please consider using Incremental Analysis: " END + "https://pmd.github.io/" + version + "/pmd_userdocs_getting_started.html#incremental-analysis"); } } else if (!isIgnoreIncrementalAnalysis()) { // ignore new value if incr. analysis is disabled analysisCache = cache; } } I find it very unintuitive to find this here... I'd suggest moving the log to `PMD.doPMD`, which is guaranteed to run once and a little more natural

Target:
public void setAnalysisCache(final AnalysisCache cache) { // the doc says it's a noop if incremental analysis was disabled, // but it's actually the getter that enforces that this.analysisCache = cache == null ? new NoopAnalysisCache() : cache; }
Source:
private static double sortableLongToDouble(long value) { START value = value ^ (value >> 63) & Long.MAX_VALUE; END return Double.longBitsToDouble(value); } Same here. Add clarifying parenthesis

Target:
private static double sortableLongToDouble(long value) { value = value ^ ((value >> 63) & Long.MAX_VALUE); return Double.longBitsToDouble(value); }
Source:
public static Exception extractExecutionExceptionCause(Exception e) { if (!(e instanceof ExecutionException)) { return e; } Throwable cause = e.getCause(); return cause == null ? e : (cause instanceof Exception ? (Exception) cause : new Exception(cause)); START } END ``` if (!(e instanceof ExecutionException) || e.getCause() == null) { return e; } Throwable cause = e.getCause(); return cause instanceof Exception ? (Exception) cause : new Exception(cause); ``` How about making return statement simpler?

Target:
public static Exception extractExecutionExceptionCause(Exception e) { Throwable cause = e.getCause(); if (!(e instanceof ExecutionException) || cause == null) { return e; } return cause instanceof Exception ? (Exception) cause : new Exception(cause); }
Source:
boolean isEmpty() { START return (validIndexSegments.isEmpty()); END } minor: braces unnecessary

Target:
boolean isEmpty() { return validIndexSegments.isEmpty(); }
Source:
Set getDefaultIgnoreTypeNames() { Set ignored = new HashSet(); String[] ignore = {"org.eclipse.core.runtime.Plugin", "java.lang.ClassLoader", "org.eclipse.team.internal.ccvs.core.CVSTeamProvider", "org.eclipse.core.internal.events.BuilderPersistentInfo", "org.eclipse.core.internal.resources.Workspace", "org.eclipse.core.internal.events.EventStats", "java.net.URL"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-6$ START for (String element : ignore) { END ignored.add(element); } return ignored; } Please do only whitespace changes in this commit.

Target:
Set getDefaultIgnoreTypeNames() { Set ignored = new HashSet(); String[] ignore = {"org.eclipse.core.runtime.Plugin", "java.lang.ClassLoader", "org.eclipse.team.internal.ccvs.core.CVSTeamProvider", "org.eclipse.core.internal.events.BuilderPersistentInfo", "org.eclipse.core.internal.resources.Workspace", "org.eclipse.core.internal.events.EventStats", "java.net.URL"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-6$ for (int i = 0; i < ignore.length; i++) { ignored.add(ignore[i]); } return ignored; }
Source:
public static boolean delete(File file) { if (!file.exists()) return true; if (file.isDirectory()) { File[] children = file.listFiles(); for (File START children1 : END children) { delete(children1); } } return file.delete(); } child

Target:
public static boolean delete(File file) { if (!file.exists()) return true; if (file.isDirectory()) { File[] children = file.listFiles(); for (File child : children) { delete(child); } } return file.delete(); }
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { START bugzillaClient.authenticate(monitor); END } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; } Why do we call authenticate to log out? If we aren't already authenticated, why do we need to log out?

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); userID = -1; token = null; return; }
Source:
private double cleanNumber(double dirtyNumber) { START double clean; END if (dirtyNumber < 1) clean = 0; else clean = dirtyNumber; return clean; } Could be simplified to: ```java return dirtyNumber < 1 ? 0 : dirtyNumber; ```

Target:
private double cleanNumber(double dirtyNumber) { return dirtyNumber < 1 ? 0 : dirtyNumber; }
Source:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { START return paymentProcessor.getPayments(offset, limit, pluginName, withPluginInfo, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); END } Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`

Target:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getPayments(offset, limit, pluginName, withPluginInfo, withAttempts, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); }
Source:
START private static Map<String, String> readMessagesFromBundle() { END try { ResourceBundle bundle = ResourceBundle.getBundle(APP_ERRORS_MESSAGES_FILE_NAME); Map<String, String> messages = new HashMap<String, String>(); for (String key : bundle.keySet()) { messages.put(key, bundle.getString(key)); } return messages; } catch (MissingResourceException e) { log.error("Could not load audit log messages from the file " + APP_ERRORS_MESSAGES_FILE_NAME); throw new ApplicationException(e); } } why do you need to convert the bundle to a map, instead of using it directly?

Target:
private static ResourceBundle readMessagesFromBundle() { try { return ResourceBundle.getBundle(APP_ERRORS_MESSAGES_FILE_NAME); } catch (MissingResourceException e) { log.error("Could not load audit log messages from the file " + APP_ERRORS_MESSAGES_FILE_NAME); throw new ApplicationException(e); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; START if (getClass() != obj.getClass()) return false; END BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); } Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }
Source:
private boolean isValidReviewer(Account member, ChangeControl control) { if (member.isActive()) { IdentifiedUser user = identifiedUserFactory.create(member.getId()); // Does not account for draft status as a user might want to let a // reviewer see a draft. START if (control.forUser(user).isRefVisible()) { return true; } END } return false; } [optional] this could be shortened to: return control.forUser(user).isRefVisible();

Target:
private boolean isValidReviewer(Account member, ChangeControl control) { if (member.isActive()) { IdentifiedUser user = identifiedUserFactory.create(member.getId()); // Does not account for draft status as a user might want to let a // reviewer see a draft. return control.forUser(user).isRefVisible(); } return false; }
Source:
private boolean support( ValueGroup[] valueGroups ) { START return valueGroups.length == 1 && ValueGroup.NUMBER.equals( valueGroups[0] ); END } please use == for enum comparisons like its done 2 lines above

Target:
private boolean support( ValueGroup[] valueGroups ) { return valueGroups.length == 1 && valueGroups[0] == ValueGroup.NUMBER; }
Source:
START public String getConfigFile() END { return configFile; } You can make this file `File`

Target:
public File getConfigFile() { return configFile; }