auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (!nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); START success[0] = true; END } } }); return success[0]; } Please recheck the condition here, having `success=true` and `log("..failed..")` in the same block seems wrong.

Target:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { success[0] = true; } else { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); return success[0]; }
Source:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); START file.createNewFile(); END FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(content.getBytes("UTF-8")); } finally { if (fos != null) fos.close(); } } This isn't necessary, new FileOutputStream(file) will create the file if it doesn't exist yet.

Target:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); FileOutputStream fos = new FileOutputStream(file); try { fos.write(content.getBytes("UTF-8")); } finally { fos.close(); } }
Source:
public KomodoObject komodoServersNode(UnitOfWork transaction) throws KException { ArgCheck.isNotNull( transaction, "transaction" ); //$NON-NLS-1$ ArgCheck.isTrue( ( transaction.getState() == org.komodo.spi.repository.Repository.UnitOfWork.State.NOT_STARTED ), "transaction state is not NOT_STARTED" ); //$NON-NLS-1$ komodoEnvironment(transaction); START return create(transaction, SERVERS_ROOT, Environment.SERVERS); END } The SERVERS_ROOT grouping node is defined as nt:unstructured in the cnd, so the third arg (tko:servers type) throws an exception when the create is attempted. Changing the third arg to null will create it without issue.

Target:
public KomodoObject komodoServersNode(UnitOfWork transaction) throws KException { ArgCheck.isNotNull( transaction, "transaction" ); //$NON-NLS-1$ ArgCheck.isTrue( ( transaction.getState() == org.komodo.spi.repository.Repository.UnitOfWork.State.NOT_STARTED ), "transaction state is not NOT_STARTED" ); //$NON-NLS-1$ komodoEnvironment(transaction); return create(transaction, SERVERS_ROOT, null); }
Source:
public DefaultEquivalenceResultBuilder( ScoreCombiner<T> combiner, EquivalenceFilter<T> filter, List<EquivalenceExtractor<T>> extractors ) { this.combiner = combiner; this.filter = filter; this.extractors = extractors; START this.multipleCandidateExtractor = MultipleCandidateExtractor.create(); END } No longer used! rip this field out

Target:
public DefaultEquivalenceResultBuilder( ScoreCombiner<T> combiner, EquivalenceFilter<T> filter, List<EquivalenceExtractor<T>> extractors ) { this.combiner = combiner; this.filter = filter; this.extractors = extractors; }
Source:
public ParametersBuilder add(int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { START nanosecond = 0; END } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, 1970, 1, 1 ); } Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?

Target:
public ParametersBuilder add(int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, 1970, 1, 1 ); }
Source:
public void setUp() { START setting = new SettingImpl<>(Integer.class, SETTING_ID, END 50, new RangedNumberValidator<>(0, 100, false, false)); eventResult = -1; setting.subscribe(propertyChangeEvent -> eventResult = (int) propertyChangeEvent.getNewValue()); } @eviltak, you mentioned removing the need for the class parameter by checking on the type of the default value? Can you please do that?

Target:
public void setUp() { setting = new SettingImpl<>(SETTING_ID, 50, new RangedNumberValidator<>(0, 100, false, false)); eventResult = -1; setting.subscribe(propertyChangeEvent -> eventResult = (int) propertyChangeEvent.getNewValue()); }
Source:
START private void check(Rule rule) { END if (rule.att().contains("unblock")) return; resetVars(); gatherVars(rule.body()); gatherVars(rule.requires()); gatherVars(rule.ensures()); check(rule.body()); check(rule.requires()); check(rule.ensures()); } Instead of `check(Rule...` and `check(Context...` (which may be enriched with others in the future, simply have a `DefinitionTransformer` pass that does nothing but this check, or use the `AbstractReflectiveVisitor`.

Target:
private void check(Rule rule) { resetVars(); gatherVars(rule.body()); check(rule.body(), true); check(rule.requires(), false); check(rule.ensures(), false); }
Source:
public void writeTo(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { START entityStream.write(participantStatus.toString().getBytes()); END } It is better to use ``` java participantStatus.name() ``` since it cannot be overridden whereas toString() can.

Target:
public void writeTo(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(participantStatus.name().getBytes()); }
Source:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; super.stop(context); fgBundleContext = null; START if (fMemoryRetrievalFactory != null) { END Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } } I'd move this above super.stop() for safety. but not the fgBundle... line

Target:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; if (fMemoryRetrievalFactory != null) { Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } super.stop(context); fgBundleContext = null; }
Source:
public void setEventList(List<ITimeEvent> eventList) { START fEventList = eventList; END } It's unsafe to store lists directly (whoever has the reference can still modify the list afterwards). Perhaps it'd be worth making fEventList final, and have this method do a .clear() and shallow-copy the list contents over.

Target:
public void setEventList(List<ITimeEvent> eventList) { fEventList = new ArrayList<ITimeEvent>(eventList); }
Source:
public static HostInfo fromBytes(byte[] bytes) throws JSONException { final JSONObject obj = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); START return new HostInfo(obj.getString(HOST_IP), obj.getString(GROUP), (int)obj.getLong(LOCAL_SITES_COUNT)); END } there is a `getInt` variant

Target:
public static HostInfo fromBytes(byte[] bytes) throws JSONException { final JSONObject obj = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); return new HostInfo(obj.getString(HOST_IP), obj.getString(GROUP), obj.getInt(LOCAL_SITES_COUNT)); }
Source:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { rawRequestContents.add(httpContent); START ReferenceCountUtil.retain(httpContent); END } } it has to be otherway round

Target:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { rawRequestContents.add(ReferenceCountUtil.retain(httpContent)); } }
Source:
private String extractConnectionKey(final iOSVariant iOSVariant) { START final StringBuilder sb = new StringBuilder() END .append(iOSVariant.getVariantID()) .append(iOSVariant.isProduction() ? "-prod" : "-dev"); return sb.toString(); } No need to assign to a temporary variable.

Target:
private String extractConnectionKey(final iOSVariant iOSVariant) { return new StringBuilder() .append(iOSVariant.getVariantID()) .append(iOSVariant.isProduction() ? "-prod" : "-dev") .toString(); }
Source:
START public void execute() { END if (!hasLightGrenade) { if (hasPowerFailure) player.endTurn(); return; } // The square the player stepped on has a light grenade and should // always cause a decrease of at least three actions at this point. player.skipNumberOfActions(3 + (hasPowerFailure ? 1 : 0)); } zeer matig geschreven methode maar bon ...

Target:
public void execute() { if (!hasLightGrenade) { if (hasPowerFailure) player.endTurn(); } else { // The square the player stepped on has a light grenade and should // always cause a decrease of at least three actions at this point. player.skipNumberOfActions(3 + (hasPowerFailure ? 1 : 0)); } }
Source:
public String getName() { START return this.name; END } [minor] I think we use `return name` (i.e. no `this`) elsewhere in jclouds?

Target:
public String getName() { return name; }
Source:
public GetDeviceListQueryParameters() { privateStorageType = StorageType.UNKNOWN; START checkStatus = false; END } This too should call this(...) somehow, it's becoming clunky

Target:
public GetDeviceListQueryParameters() { this(null, StorageType.UNKNOWN, false, null); }
Source:
public void testImportWithoutPadding() throws IOException { if(failWithoutExtraArgs){ thrown.expect(IOException.class); thrown.expectMessage("Failure during job; return status 1"); START NumericTypesTestUtils.configureJunitToExpectFailure(thrown); END } ArgumentArrayBuilder builder = getArgsBuilder(); String[] args = builder.build(); runImport(args); if (!failWithoutExtraArgs) { verify(); } } This method seems to be doing the same thing as the previous line.

Target:
public void testImportWithoutPadding() throws IOException { if(failWithoutExtraArgs){ NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); String[] args = builder.build(); runImport(args); if (!failWithoutExtraArgs) { verify(); } }
Source:
void addReferencesToBlobs(PortAndAssignment pna, BlobChangingCallback cb) throws IOException, KeyNotFoundException, AuthorizationException { List<LocalResource> localResourceList = getLocalResources(pna); if (!localResourceList.isEmpty()) { getBlobs(localResourceList, pna, cb); } START pna.complete(); END } just one more nit: put this outside of this method since the method `addReferencesToBlobs` doesn't indicate `complete`

Target:
void addReferencesToBlobs(PortAndAssignment pna, BlobChangingCallback cb) throws IOException, KeyNotFoundException, AuthorizationException { List<LocalResource> localResourceList = getLocalResources(pna); if (!localResourceList.isEmpty()) { getBlobs(localResourceList, pna, cb); } }
Source:
public void visitFunctionDeclaration(FunctionDeclarationTree tree) { super.visitFunctionDeclaration(tree); START checkFunction(tree); END } @ivandalbosco No need to change order if we don't rely on visitor for finding "try"

Target:
public void visitFunctionDeclaration(FunctionDeclarationTree tree) { checkFunction(tree); super.visitFunctionDeclaration(tree); }
Source:
private boolean isBufferFilled() { int available = fileBuffer.size(); START return available > 0 && available >= Math.min(MIN_BYTES_READ_IN, this.fileBytesLeft); END } Can we surround the return in parenthesis

Target:
private boolean isBufferFilled() { int available = fileBuffer.size(); return available > 0 && available >= MIN_BYTES_READ_IN; }
Source:
public boolean consumeRetry() { START return --remainingRetries >= 0; END } the previous code had pretty bad readability. The new one is better, but not much. Maybe we can be a little more expressive than `--remainingRetries >=0`?

Target:
boolean consumeRetry() { return --remainingRetries >= 0; }
Source:
public String getDisplayName(int tokenType) { START if (tokenType >= Token.MIN_USER_TOKEN_TYPE && tokenType < displayNames.length) { END String displayName = displayNames[tokenType]; if (displayName != null) { return displayName; } } String literalName = getLiteralName(tokenType); if (literalName != null) { return literalName; } String symbolicName = getSymbolicName(tokenType); if (symbolicName != null) { return symbolicName; } return Integer.toString(tokenType); } ❗️ This prevents a user from assigning a custom display name to `Token.INVALID_TYPE`. Adding this as a restriction doesn't seem to provide any benefit to the user.

Target:
public String getDisplayName(int tokenType) { if (tokenType >= 0 && tokenType < displayNames.length) { String displayName = displayNames[tokenType]; if (displayName != null) { return displayName; } } String literalName = getLiteralName(tokenType); if (literalName != null) { return literalName; } String symbolicName = getSymbolicName(tokenType); if (symbolicName != null) { return symbolicName; } return Integer.toString(tokenType); }
Source:
private boolean hasPersistentPower() { final PackageManager pm = START this.getPackageManager(); END return (pm != null && (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))); } Nit: while you're at it, this "this." is not necessary, I think.

Target:
private boolean hasPersistentPower() { // Cars and TVsets are always connected to the persistent power source final PackageManager pm = getPackageManager(); return (pm != null && (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))); }
Source:
public Boolean attachStdin() { START return (attachStdin != null) ? attachStdin : Boolean.FALSE; END } if these Boolean methods can never be null why not have the return type be boolean instead of Boolean ?

Target:
public boolean attachStdin() { return attachStdin; }
Source:
private boolean validatePage() { if START (dcc.getDirectory() == null || dcc.getDirectory().equals("")) { END //$NON-NLS-1$ setErrorMessage("Destination not selected!"); return false; } if(0 == systemTree.getCheckedElements().length){ setErrorMessage("Nothing selected for FMU generation!"); return false; } if (!isSomeLibrarySelected()){ setErrorMessage("No libraries selected to include"); return false; } setErrorMessage(null); return true; } by switching to "".eqauls(dcc.getDirectory()) you don't need the null check

Target:
private boolean validatePage() { if ("".equals(dcc.getDirectory())){ //$NON-NLS-1$ setErrorMessage("Destination not selected!"); return false; } if(0 == systemTree.getCheckedElements().length){ setErrorMessage("Nothing selected for FMU generation!"); return false; } if (!isSomeLibrarySelected()){ setErrorMessage("No libraries selected to include"); return false; } setErrorMessage(null); return true; }
Source:
public boolean StorageDomainRemoved(storage_domain_static storageDomain) { storage_server_connections connection = DbFacade.getInstance().getStorageServerConnectionDAO().get(storageDomain.getstorage()); START END if (connection != null) DbFacade.getInstance().getStorageServerConnectionDAO().remove(connection.getid()); return true; } Please add

Target:
public boolean StorageDomainRemoved(storage_domain_static storageDomain) { storage_server_connections connection = DbFacade.getInstance().getStorageServerConnectionDAO().get(storageDomain.getstorage()); if (connection != null) { DbFacade.getInstance().getStorageServerConnectionDAO().remove(connection.getid()); } return true; }
Source:
public void open() throws IOException { writer = CompressionFactory.getDoubleSerializer( ioPeon, START String.format("%s.double_column", filenameBase), END byteOrder, compression ); writer.open(); } StringUtils

Target:
public void open() throws IOException { writer = CompressionFactory.getDoubleSerializer( ioPeon, StringUtils.format("%s.double_column", filenameBase), byteOrder, compression ); writer.open(); }
Source:
public LeaderElectorImp(Map conf, List<String> servers, CuratorFramework zk, String leaderlockPath, String id, AtomicReference<LeaderLatch> leaderLatch, AtomicReference<LeaderLatchListener> leaderLatchListener) { this.conf = conf; this.servers = servers; this.zk = zk; this.leaderLatch = leaderLatch; this.id = id; START this.leaderLatch = leaderLatch; END this.leaderLatchListener = leaderLatchListener; } duplicately here

Target:
public LeaderElectorImp(Map conf, List<String> servers, CuratorFramework zk, String leaderlockPath, String id, AtomicReference<LeaderLatch> leaderLatch, AtomicReference<LeaderLatchListener> leaderLatchListener) { this.conf = conf; this.servers = servers; this.zk = zk; this.leaderlockPath = leaderlockPath; this.id = id; this.leaderLatch = leaderLatch; this.leaderLatchListener = leaderLatchListener; }
Source:
START protected Class<?> loadRepositoryInterface(RepositoryConfiguration<?> configuration, ResourceLoader loader) { END String repositoryInterface = configuration.getRepositoryInterface(); ClassLoader classLoader = loader.getClassLoader(); try { return org.springframework.util.ClassUtils.forName(repositoryInterface, classLoader); } catch (ClassNotFoundException | LinkageError e) { LOGGER.warn(String.format(CLASS_LOADING_ERROR, getModuleName(), repositoryInterface, classLoader), e); } return null; } What's the reason we need to make this `protected`?

Target:
private Class<?> loadRepositoryInterface(RepositoryConfiguration<?> configuration, ResourceLoader loader) { String repositoryInterface = configuration.getRepositoryInterface(); ClassLoader classLoader = loader.getClassLoader(); try { return org.springframework.util.ClassUtils.forName(repositoryInterface, classLoader); } catch (ClassNotFoundException | LinkageError e) { LOGGER.warn(String.format(CLASS_LOADING_ERROR, getModuleName(), repositoryInterface, classLoader), e); } return null; }
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), START "'outputChannel' or 'outputChannelName' is required"); END } Well, I think now this should be moved to the `onInit()` raise error ASAP.

Target:
protected void doStart() { }
Source:
protected DocumentModel createDocument(boolean withBlobContent) { DocumentModel documentModel = session.createDocumentModel("/", "MyFile", "File"); if (withBlobContent) { documentModel.setPropertyValue(FILE_CONTENT_PROPERTY, (Serializable) Blobs.createBlob(FILE_CONTENT)); } START documentModel = session.createDocument(documentModel); return documentModel; END } ``` return session.createDocument(documentModel); ```

Target:
protected DocumentModel createDocument(boolean withBlobContent) { DocumentModel documentModel = session.createDocumentModel("/", "MyFile", "File"); if (withBlobContent) { documentModel.setPropertyValue(FILE_CONTENT_PROPERTY, (Serializable) Blobs.createBlob(FILE_CONTENT)); } return session.createDocument(documentModel); }
Source:
private boolean checkPresentOrNullable(Invocation invocation, String paramKey, int argIndex, Object arg) { START if (arg == null && !Reflection2.getInvokableParameters(invocation.getInvokable()).get(argIndex).isAnnotationPresent(Nullable.class)) END throw new NullPointerException(format("param{%s} for invocation %s.%s", paramKey, invocation.getInvokable() .getOwnerType().getRawType().getSimpleName(), invocation.getInvokable().getName())); return true; } Static import of `Reflection2.getInvokableParameters`?

Target:
private boolean checkPresentOrNullable(Invocation invocation, String paramKey, int argIndex, Object arg) { if (arg == null && !getInvokableParameters(invocation.getInvokable()).get(argIndex).isAnnotationPresent(Nullable.class)) throw new NullPointerException(format("param{%s} for invocation %s.%s", paramKey, invocation.getInvokable() .getOwnerType().getRawType().getSimpleName(), invocation.getInvokable().getName())); return true; }
Source:
START public void optOutTracking() { END getAnalyticsMessages().emptyTrackingQueues(new AnalyticsMessages.MixpanelDescription(mToken)); if (getPeople().isIdentified()) { getPeople().deleteUser(); getPeople().clearCharges(); } mPersistentIdentity.clearPreferences(); synchronized (mEventTimings) { mEventTimings.clear(); mPersistentIdentity.clearTimeEvents(); } mPersistentIdentity.clearReferrerProperties(); mPersistentIdentity.setOptOutTracking(true); } is it allowed to flush the events on the device after the user opt out in gdpr?

Target:
public void optOutTracking() { getAnalyticsMessages().emptyTrackingQueues(new AnalyticsMessages.MixpanelDescription(mToken)); if (getPeople().isIdentified()) { getPeople().deleteUser(); getPeople().clearCharges(); } mPersistentIdentity.clearPreferences(); synchronized (mEventTimings) { mEventTimings.clear(); mPersistentIdentity.clearTimeEvents(); } mPersistentIdentity.clearReferrerProperties(); mPersistentIdentity.setOptOutTracking(true, mToken); }
Source:
START protected org.robolectric.bytecode.ShadowMap createShadowMap() { END return super.createShadowMap() .newBuilder() .addShadowClass(ShadowCrashlytics.class) .addShadowClass(ShadowMapView.class) .addShadowClass(ShadowGLMatrix.class) .build(); } why the fully qualified package name here?

Target:
protected ShadowMap createShadowMap() { return super.createShadowMap() .newBuilder() .addShadowClass(ShadowCrashlytics.class) .addShadowClass(ShadowMapView.class) .addShadowClass(ShadowGLMatrix.class) .build(); }
Source:
public static String serialize(ColumnStatisticMetadata value) { return value.getStatisticType().name() + ":" + value.getColumnName(); START } END What does "column name" refer to? The plan IR shouldn't have any references to column names, but should be using column handles, instead.

Target:
static String serialize(ColumnStatisticMetadata value) { return value.getStatisticType().name() + ":" + value.getColumnName(); }
Source:
private static void deleteFileIfExists(File to) throws IOException { START boolean fileDoesNotExist = to.exists(); END if (fileDoesNotExist) { return; } boolean deleteOk = to.delete(); if (deleteOk) { return; } throw new IOException("Unable to delete file: " + to.getAbsolutePath()); } There seems to be a `!` missing.

Target:
private static void deleteFileIfExists(File to) throws IOException { boolean fileDoesNotExist = !to.exists(); if (fileDoesNotExist) { return; } boolean deleteOk = to.delete(); if (deleteOk) { return; } throw new IOException("Unable to delete file: " + to.getAbsolutePath()); }
Source:
public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); final K key = entry.getKey(); final Collection<V> value = entry.getValue(); START return new UnmodifiableMapEntry<>(key, value); END } You can just inline `key` and `value` IMO.

Target:
public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); return new UnmodifiableMapEntry<>(entry.getKey(), entry.getValue()); }
Source:
public void basicInvocation(Runnable call) throws Exception { DistributedExecutorService des = createDES(getCache()); START des.submit(call); END } I believe, we should call get on the future: ``` des.submit(call).get() ```

Target:
public void basicInvocation(Runnable call) throws Exception { DistributedExecutorService des = createDES(getCache()); des.submit(call).get(); }
Source:
public void aggregate(ByteBuffer buf, int position) { final int oldPosition = buf.position(); buf.position(position); bufferAdd(buf); START buf.position(oldPosition); END } The position adjustment and restore should be wrapped in a try/finally, because we don't want the buffer to be left in an invalid state if an exception is thrown.

Target:
public void aggregate(ByteBuffer buf, int position) { final int oldPosition = buf.position(); try { buf.position(position); bufferAdd(buf); } finally { buf.position(oldPosition); } }
Source:
public List<Put> getJobPuts() { START if (jobHistoryListener != null) END return jobHistoryListener.getJobPuts(); else return null; } nit: add braces for each if/else statement

Target:
public List<Put> getJobPuts() { if (jobHistoryListener != null) { return jobHistoryListener.getJobPuts(); } else { return null; } }
Source:
private boolean isTemplate(String expression) { START return expression.startsWith(PARSER_CONTEXT.getExpressionPrefix()) && expression.endsWith(PARSER_CONTEXT.getExpressionSuffix()); END } This is not correct. The expression can be like this: `foo#{bar.value}.baz`. With meaning to evaluate a template part and concatenate it with the rest as strings. See `ParserContext` JavaDocs. Also that doesn't make sense to deprecate private method. The point was to log `warn` that templating is deprecated. Nothing more we can do from the context of variable.

Target:
private boolean isTemplate(String expression) { return expression.contains(PARSER_CONTEXT.getExpressionPrefix()) && expression.contains(PARSER_CONTEXT.getExpressionSuffix()); }
Source:
public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("revision", revision.getName()) START .add("oldRevision", oldRevision.getName()) END .add("path", path) .toString(); } can't these be null?

Target:
public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("revision", revision.getName()) .add("oldRevision", oldRevision != null ? oldRevision.getName() : null) .add("path", path) .toString(); }
Source:
public void testListImages() { List<ImageSummary> listImages = api().listImages(); assertNotNull(listImages); ImageSummary taggedImage = Iterables.find(listImages, new Predicate<ImageSummary>() { @Override public boolean apply(ImageSummary input) { return input.repoTags().contains("jclouds:testTag"); } START }); END assertNotNull(taggedImage); } The `find` method will throw an exception if not found, so the assertion below is redundant. Use `tryFind` if you want to be explicit or just remove the assertion.

Target:
public void testListImages() { List<ImageSummary> listImages = api().listImages(); assertNotNull(listImages); Iterables.find(listImages, new Predicate<ImageSummary>() { @Override public boolean apply(ImageSummary input) { return input.repoTags().contains("jclouds:testTag"); } }); }
Source:
private static void resetJsonReaderEscapeAnyChar() { START client.alterSession(ExecConstants.JSON_READER_ESCAPE_ANY_CHAR, false); END } No need to have above methods as `static`. `private void` is fine.

Target:
private void resetJsonReaderEscapeAnyChar() { client.alterSession(ExecConstants.JSON_READER_ESCAPE_ANY_CHAR, false); }
Source:
private int getNumberOfPartitionsForTopic(final String topic) throws ExecutionException, InterruptedException { START try (AdminClient adminClient = createAdminClient()) { END final TopicDescription topicDescription = adminClient.describeTopics(Collections.singleton(topic)) .values() .get(topic) .get(); return topicDescription.partitions().size(); } } Ah, yeah, there are some limitations to the linter. Thanks for taking care of it.

Target:
private int getNumberOfPartitionsForTopic(final String topic) throws Exception { try (final AdminClient adminClient = createAdminClient()) { final TopicDescription topicDescription = adminClient.describeTopics(Collections.singleton(topic)) .values() .get(topic) .get(); return topicDescription.partitions().size(); } }
Source:
public List<String> getHeaders(String name) { MultivaluedMap<String, String> headers = requestContext.getMutableHeaders(); START System.out.println(headers.get(name)); END return headers.get(name); } Need to remove this leftover debug output

Target:
public List<String> getHeaders(String name) { MultivaluedMap<String, String> headers = requestContext.getMutableHeaders(); return headers.get(name); }
Source:
public boolean startWork(String id) { START synchronized (mLock) END { return startWork(id, null); } } Nit: You don't really need the synchronized here.

Target:
public boolean startWork(String id) { return startWork(id, null); }
Source:
public WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request) { loggerContext.log("msg-in.txt", new UpdateLogCallback(updates)); START final UpdateResponse updateResponse = updateRequestHandler.handle(new UpdateRequest(origin, keyword, updates), updateContext); END return performUpdates(request, updateContext, updates); } Add a TODO to use the response, if there aren't any side-effects?

Target:
public WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request) { loggerContext.log("msg-in.txt", new UpdateLogCallback(updates)); // todo: [TK] use response? updateRequestHandler.handle(new UpdateRequest(origin, keyword, updates), updateContext); return performUpdates(request, updateContext, updates); }
Source:
private V computeInternal(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, boolean computeIfPresent, Metadata metadata, long flags) { assertKeyNotNull(key); assertFunctionNotNull(remappingFunction); InvocationContext ctx = getInvocationContextWithImplicitTransaction(false, 1); ComputeCommand command = commandsFactory.buildComputeCommand(key, remappingFunction, computeIfPresent, metadata, flags); START ctx.setLockOwner(command.getKeyLockOwner()); END return (V) executeCommandAndCommitIfNeeded(ctx, command); } This needs to be changed to support locked stream syntax now.

Target:
private V computeInternal(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, boolean computeIfPresent, Metadata metadata, long flags) { return computeInternal(key, remappingFunction, computeIfPresent, metadata, flags, getInvocationContextWithImplicitTransaction(false, 1)); }
Source:
protected void addMappingsToConcepts(List<Object> explicitItems) { START log("Adding mappings to Concepts"); END if (MetadataSharing.getInstance().isAddLocalMappings()) { ConceptPubSubService pubsubService = Context.getService(ConceptPubSubService.class); for (Object explicitItem : explicitItems) { if (explicitItem instanceof Concept) { //MetadataSharing.getInstance().getConceptMapper().addSystemConceptMap((Concept) explicitItem); pubsubService.addLocalMappingToConcept((Concept) explicitItem); } } } } Put it inside the if.

Target:
protected void addMappingsToConcepts(List<Object> explicitItems) { if (MetadataSharing.getInstance().isAddLocalMappings()) { log("Adding mappings to Concepts"); ConceptPubSubService pubsubService = Context.getService(ConceptPubSubService.class); for (Object explicitItem : explicitItems) { if (explicitItem instanceof Concept) { pubsubService.addLocalMappingToConcept((Concept) explicitItem); } } } }
Source:
public Artifact getRequirementFromArtifactId(ArtifactId artId) { START for (Artifact art : directRequirements) { END if (art.getId().equals(artId.getId())) { return art; } } return null; } Nit: You should be able to do "if (art.equals(artId))"

Target:
public Artifact getRequirementFromArtifactId(ArtifactId artId) { for (Artifact art : directRequirements) { if (art.equals(artId)) { return art; } } return null; }
Source:
public Iterator<DataFactory<ENTITY>> iterator() { START return Iterators.iterator( new DataFactory<ENTITY>() END { @Override public Data<ENTITY> create( Configuration config ) { return new Data<ENTITY>() { @Override public CharReadable stream() { return last = factory.apply( config ); } @Override public Decorator<ENTITY> decorator() { return decorator; } }; } } ); } Great place for a lambda ;) ```java return Iterators.iterator( config -> new Data<ENTITY>() { @Override public CharReadable stream() { return last = factory.apply( config ); } @Override public Decorator<ENTITY> decorator() { return decorator; } } ); ```

Target:
public Iterator<DataFactory<ENTITY>> iterator() { return Iterators.iterator( config -> new Data<ENTITY>() { @Override public CharReadable stream() { return last = factory.apply( config ); } @Override public Decorator<ENTITY> decorator() { return decorator; } } ); }
Source:
public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); // get shard this locator would belong to long shard = (long) Util.getShard(locator.toString()); // bound values and execute BoundStatement bs = putValue.bind(shard, locator.toString(), ""); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { START session.execute(bs); END } finally { timer.stop(); } } May be the `BoundStatement` part also should be part of the timer execution?

Target:
public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); // get shard this locator would belong to long shard = (long) Util.getShard(locator.toString()); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { // bound values and execute BoundStatement bs = putValue.bind(shard, locator.toString(), ""); session.execute(bs); } finally { timer.stop(); } }
Source:
private Set<Type> interfacesWithSubstitution(Symbol.TypeSymbol symbol, TypeSubstitution substitution) { return symbol.interfaces().stream() START .map(interfaceType -> applySubstitution(interfaceType, substitution)) END .flatMap(substitutedInterfaceType -> supertypes(substitutedInterfaceType).stream()) .collect(Collectors.toSet()); } why 2 operations ? only one flatmap is sufficient no ?

Target:
private Set<Type> interfacesWithSubstitution(Symbol.TypeSymbol symbol, TypeSubstitution substitution) { return symbol.interfaces().stream() .flatMap(interfaceType -> supertypes(applySubstitution(interfaceType, substitution)).stream()) .collect(Collectors.toSet()); }
Source:
START public void setAdvancedRecentChangesCheckbox() { END selectTab(PreferencesPageObject.tabNames.UNDER); waitForElementClickableByElement(useAdvancedRecentChangesCheckbox); useAdvancedRecentChangesCheckbox.click(); PageObjectLogging.log("Use_advanced_recent_changes_checkbox", "Use_advanced_recent_changes_checkbox clicked", true); } fluent chaining would be nice

Target:
public PreferencesPageObject setAdvancedRecentChangesCheckbox() { selectTab(PreferencesPageObject.tabNames.UNDER); waitForElementClickableByElement(useAdvancedRecentChangesCheckbox); useAdvancedRecentChangesCheckbox.click(); PageObjectLogging.log("Use_advanced_recent_changes_checkbox", "Use_advanced_recent_changes_checkbox clicked", true); return this; }
Source:
START protected StringUtils() { END } Just curious, why do we need to change the access qualifier to protected?

Target:
private StringUtils() { }
Source:
public int readBatch() throws Exception { ColumnReader<?> firstColumnStatus = readState.getFirstColumnReader(); int currBatchNumRecords = readState.batchSizerMgr().getCurrentRecordsPerBatch(); long recordsToRead = Math.min(currBatchNumRecords, readState.getRemainingValuesToRead()); START int readCount = 0; END if (recordsToRead > 0) { readCount = readRecords(firstColumnStatus, recordsToRead); } readState.fillNullVectors(readCount); return readCount; } use `?`: `int readCount = recordsToRead > 0 ? ...`

Target:
public int readBatch() throws Exception { ColumnReader<?> firstColumnStatus = readState.getFirstColumnReader(); int currBatchNumRecords = readState.batchSizerMgr().getCurrentRecordsPerBatch(); long recordsToRead = Math.min(currBatchNumRecords, readState.getRemainingValuesToRead()); int readCount = recordsToRead > 0 ? readRecords(firstColumnStatus, recordsToRead) : 0; readState.fillNullVectors(readCount); return readCount; }
Source:
public List<Project> getProjects() { START List<Project> projects; END try { projects = projectLoader.fetchAllActiveProjects(); for (Project proj : projects) { loadAllProjectFlows(proj); } } catch (ProjectManagerException e) { throw new RuntimeException("Could not load projects from store.", e); } return projects; } initialize projects

Target:
public List<Project> getProjects() { List<Project> projects; try { projects = projectLoader.fetchAllActiveProjects(); } catch (ProjectManagerException e) { throw new RuntimeException("Could not load projects from store.", e); } return projects; }
Source:
public static Object encodeObject(Object dataToEncode) { Object returnValue = dataToEncode; if (dataToEncode instanceof byte[]) { returnValue = SafeEncoder.encode((byte[]) dataToEncode); START } else if (dataToEncode instanceof ArrayList) { ArrayList arrayToDecode = (ArrayList)dataToEncode; ArrayList returnValueArray = new ArrayList(arrayToDecode.size()); for (Object arrayEntry : arrayToDecode) { returnValueArray.add(encodeObject(arrayEntry)); } END returnValue = returnValueArray; } return returnValue; } I would have replace ArrayList with List. ``` if (dataToEncode instanceof List) { List arrayToDecode = (List)dataToEncode; List returnValueArray = new ArrayList(arrayToDecode.size()); for (Object arrayEntry : arrayToDecode) { returnValueArray.add(encodeObject(arrayEntry)); } ```

Target:
public static Object encodeObject(Object dataToEncode) { if (dataToEncode instanceof byte[]) { return SafeEncoder.encode((byte[]) dataToEncode); } if (dataToEncode instanceof List) { List arrayToDecode = (List)dataToEncode; List returnValueArray = new ArrayList(arrayToDecode.size()); for (Object arrayEntry : arrayToDecode) { // recursive call and add to list returnValueArray.add(encodeObject(arrayEntry)); } return returnValueArray; } return dataToEncode; }
Source:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { template = new MongoTemplate(factory); this.collectionName = (StringUtils.hasText(collectionName)) ? collectionName : DEFAULT_COLLECTION_NAME; START } END This ctor has to invoke the other one with similar logic as I described above. DRY - in other words.

Target:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { this(new MongoTemplate(factory), collectionName); }
Source:
private void scheduleJobs(long regularInterval, long initialInterval) { START executor.scheduleWithFixedDelay(() -> refresh(), END initialInterval, regularInterval, TimeUnit.MINUTES); } Why not this::refresh ?

Target:
private void scheduleJobs(long regularInterval, long initialInterval) { executor.scheduleWithFixedDelay(this::refresh, initialInterval, regularInterval, TimeUnit.MINUTES); }
Source:
public void accept(FluxSink<T> fluxSink) { START FluxSinkRecorderDelegate<T> previousDelegate = this.delegate; END synchronized (this) { delegate = new DirectDelegate<>(fluxSink); previousDelegate.accept(fluxSink); } } shouldn't this be synchronized as well?

Target:
public synchronized void accept(FluxSink<T> fluxSink) { FluxSinkRecorderDelegate<T> previousDelegate = this.delegate; delegate = new DirectDelegate<>(fluxSink); previousDelegate.accept(fluxSink); }
Source:
START public void shutdownBlobStore(PartitionId id){ END DiskManager diskManager = partitionToDiskManager.get(id); if(diskManager != null){ diskManager.shutdownBlobStore(id); } } doc

Target:
public boolean shutdownBlobStore(PartitionId id) { DiskManager diskManager = partitionToDiskManager.get(id); return diskManager != null && diskManager.shutdownBlobStore(id); }
Source:
public Class<?> getImplementationClass(CodeGenerator<?> cg) throws ClassTransformationException { try { return compileClass( cg ); } catch (CompileException | ClassNotFoundException e) { throw new ClassTransformationException(e); } catch (IOException e) { throw new ClassTransformationException(e); START } END } Multi-catch?

Target:
public Class<?> getImplementationClass(CodeGenerator<?> cg) throws ClassTransformationException { try { return compileClass(cg); } catch (CompileException | ClassNotFoundException|IOException e) { throw new ClassTransformationException(e); } }
Source:
public Meteor(ItemStack catalystStack, List<MeteorComponent> components, float explosionStrength, int radius) { this.catalystStack = catalystStack; this.components = components; this.explosionStrength = explosionStrength; this.radius = radius; int weight = 0; for (MeteorComponent component : components) weight += component.getWeight(); this.maxWeight = weight; START this.cost = 1000000; END } GSON initializes classes with reflection and not the constructor. The default definition should be set at the field declaration.

Target:
public Meteor(ItemStack catalystStack, List<MeteorComponent> components, float explosionStrength, int radius) { this.catalystStack = catalystStack; this.components = components; this.explosionStrength = explosionStrength; this.radius = radius; int weight = 0; for (MeteorComponent component : components) weight += component.getWeight(); this.maxWeight = weight; }
Source:
private byte[] getParticipantObjectQueryForResponse(PRPAIN201306UV02 response) throws JAXBException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); START if (response.getControlActProcess() != null && response.getControlActProcess().getQueryByParameter() != null) { END getMarshaller().marshal(response.getControlActProcess().getQueryByParameter(), baos); } return baos.toByteArray(); } Is response guaranteed to be non-null at this point?

Target:
private byte[] getParticipantObjectQueryForResponse(PRPAIN201306UV02 response) throws JAXBException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (response != null && response.getControlActProcess() != null && response.getControlActProcess().getQueryByParameter() != null) { getMarshaller().marshal(response.getControlActProcess().getQueryByParameter(), baos); } return baos.toByteArray(); }
Source:
public List<RpslObject> getByKeys(final ObjectType type, final Collection<CIString> searchKeys) { final List<RpslObject> result = new ArrayList<>(searchKeys.size()); for (final CIString searchKey : searchKeys) { try { result.add(getByKey(type, searchKey)); } catch (EmptyResultDataAccessException ignored) { START LOGGER.debug("EmptyResultDataAccessException in class ", ignored.getMessage(), ignored.getClass().getName()); END } } return result; } This is an expected exception, if there is no matching row in the database, can we ignore it instead?

Target:
public List<RpslObject> getByKeys(final ObjectType type, final Collection<CIString> searchKeys) { final List<RpslObject> result = new ArrayList<>(searchKeys.size()); for (final CIString searchKey : searchKeys) { try { result.add(getByKey(type, searchKey)); } catch (EmptyResultDataAccessException ignored) { } } return result; }
Source:
public void testParseCommodityCodeList() { byte[] content = commodityCodeUpdateService.getFileContent(DATA_FILE_PATH); START ArrayList<CommodityCode> someCommodityCodes = (ArrayList<CommodityCode>) commodityCodeUpdateService.parseCommodityCodeList(content); END assertNotEquals(content.length, 0); assertEquals(NUMBER_OF_RECORDS_IN_DATA_FILE, someCommodityCodes.size()); } I don't think it's necessary to cast the returned collection to an ArrayList, since the assertions below are only checking the collection's total size.

Target:
public void testParseCommodityCodeList() { byte[] content = commodityCodeUpdateService.getFileContent(DATA_FILE_PATH); Collection<CommodityCode> someCommodityCodes = commodityCodeUpdateService.parseCommodityCodeList(content); assertNotEquals(content.length, 0); assertEquals(NUMBER_OF_RECORDS_IN_DATA_FILE, someCommodityCodes.size()); }
Source:
START public static long getLeapYearsBefore(final long prolepticYear) { END long yearBefore = prolepticYear - 1; return (yearBefore / 4) - (yearBefore / 100) + (yearBefore / 400); } `getLeapYearsBefore(...)` should not be public.

Target:
static long getLeapYearsBefore(final long prolepticYear) { long yearBefore = prolepticYear - 1; return (yearBefore / 4) - (yearBefore / 100) + (yearBefore / 400); }
Source:
public void time() throws Exception { TimeStat stat = new TimeStat(ticker); START stat.time((Callable<Void>) () -> { END ticker.increment(10, TimeUnit.MILLISECONDS); return null; }); TimeDistribution allTime = stat.getAllTime(); assertEquals(allTime.getCount(), 1.0); assertEquals(allTime.getMin(), 0.010); assertEquals(allTime.getMax(), 0.010); } Is the cast needed? There is only one `time(x)` method

Target:
public void time() throws Exception { TimeStat stat = new TimeStat(ticker); stat.time(() -> { ticker.increment(10, TimeUnit.MILLISECONDS); return null; }); TimeDistribution allTime = stat.getAllTime(); assertEquals(allTime.getCount(), 1.0); assertEquals(allTime.getMin(), 0.010); assertEquals(allTime.getMax(), 0.010); }
Source:
public boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); START } END Maybe group this with wherever getTextMaxAngle is defined, just to make it easier to find related methods? Also, does this need to be public? Probably better if it is protected or private.

Target:
private boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); }
Source:
public static Logger getLogger(Class<?> key) { START return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); END } I would suggest : ```java return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(name))); ``` for a better readability. Note parameter for `getLogger` has been changed from `key` to `name`.

Target:
public static Logger getLogger(Class<?> key) { return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(name))); }
Source:
public boolean verifyAddVm(List<String> reasons, int nicsCount, int vmPriority, MacPool macPool) { if (!verifyMacPool(reasons, nicsCount, macPool)) { return false; } START else if (!isVmPriorityValueLegal(vmPriority, reasons)) { return false; } return true; END } Why not just return else if isVmPriorityValueLegal(vmPriority, reasons); Instead of this whole else block?

Target:
public boolean verifyAddVm(List<String> reasons, int nicsCount, int vmPriority, MacPool macPool) { return !verifyMacPool(reasons, nicsCount, macPool) && isVmPriorityValueLegal(vmPriority, reasons); }
Source:
public boolean isTrue(State state, String[] params) { START if ((this.spaceName != null && !this.spaceName.equals("")) && !this.spaceName.equals(params[1])) { END return false; } ObjectInstance space = state.getObject(params[1]); return SpaceFactory.getOnOff(space); } !this.spaceName.equals("") -> !this.spaceName.isEmpty()

Target:
public boolean isTrue(State state, String[] params) { if ((this.spaceName != null && !this.spaceName.isEmpty()) && !this.spaceName.equals(params[1])) { return false; } ObjectInstance space = state.getObject(params[1]); return SpaceFactory.getOnOff(space); }
Source:
public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); START if (functionSymbol != null && functionSymbol.is(Symbol.Kind.FUNCTION) && parameters != null) { END FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); } I think `functionSymbol.is(Symbol.Kind.FUNCTION)` shouldn't be necessary

Target:
public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); if (functionSymbol != null && parameters != null) { FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); }
Source:
START public SavedStateRegistry<Bundle> END getBundleSavedStateRegistry() { return mSavedStateRegistry; } Make this final

Target:
public final SavedStateRegistry<Bundle> getBundleSavedStateRegistry() { return mSavedStateRegistry; }