auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void enqueueContentForDelivery(String content) { if (storeDirectory == null) { return; } String filename = getFilename(content); discardOldestFileIfNeeded(); lock.lock(); try { FileOutputStream fos = new FileOutputStream(filename); Writer out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); out.write(content); <START> out.close(); <END> } catch (Exception exception) { Logger.warn(String.format("Couldn't save unsent payload to disk (%s) ", filename), exception); } finally { lock.unlock(); } }</code><technical_language>This closed in a finally block</technical_language>

Target:
void enqueueContentForDelivery(String content) { if (storeDirectory == null) { return; } String filename = getFilename(content); discardOldestFileIfNeeded(); lock.lock(); Writer out = null; try { FileOutputStream fos = new FileOutputStream(filename); out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); out.write(content); } catch (Exception exception) { Logger.warn(String.format("Couldn't save unsent payload to disk (%s) ", filename), exception); } finally { try { if (out != null) { out.close(); } } catch (Exception exception) { Logger.warn(String.format("Failed to close unsent payload writer (%s) ", filename), exception); } lock.unlock(); } }
Source:
<code>public Subject createSubject(String sd) { Subject subject = delegator.createSubject(sd); <START> if (log.isTraceEnabled()) <END> { log.trace("Subject=" + subject); log.trace("Subject identity=" + System.identityHashCode(subject)); } return subject; }</code><technical_language>do this a static variable</technical_language>

Target:
public Subject createSubject(String sd) { Subject subject = delegator.createSubject(sd); if (trace) { log.trace("Subject=" + subject); log.trace("Subject identity=" + Integer.toHexString(System.identityHashCode(subject))); } return subject; }
Source:
<code>private PanmirrorEditingLocation savedEditingLocation() { String location = docUpdateSentinel_.getProperty(RMD_VISUAL_MODE_LOCATION, null); if (StringUtil.isNullOrEmpty(location)) return null; String[] parts = location.split(":"); if (parts.length != 2) return null; try { PanmirrorEditingLocation editingLocation = new PanmirrorEditingLocation(); editingLocation.pos = Integer.parseInt(parts[0]); editingLocation.scrollTop = Integer.parseInt(parts[1]); return editingLocation; } catch(Exception ex) { <START> return null; <END> } }</code><technical_language>LogDebugException here</technical_language>

Target:
private PanmirrorEditingLocation savedEditingLocation() { String location = docUpdateSentinel_.getProperty(RMD_VISUAL_MODE_LOCATION, null); if (StringUtil.isNullOrEmpty(location)) return null; String[] parts = location.split(":"); if (parts.length != 2) return null; try { PanmirrorEditingLocation editingLocation = new PanmirrorEditingLocation(); editingLocation.pos = Integer.parseInt(parts[0]); editingLocation.scrollTop = Integer.parseInt(parts[1]); return editingLocation; } catch(Exception ex) { Debug.logException(ex); return null; } }
Source:
<code>private RepoCollection createCollection(RepoCollection repoCollection, List<InputObject> inputObjects, Operation operation) throws SQLException, RepoException { Integer versionNumber = sqlService.getCollectionNextAvailableVersion(repoCollection.getBucketName(), repoCollection.getKey()); repoCollection.setVersionNumber(versionNumber); repoCollection.setUuid(UUID.randomUUID()); Integer collId = sqlService.insertCollection(repoCollection); if (collId == -1) { throw new RepoException("Error saving content to database"); } List<RepoObject> repoObjectList = new ArrayList<>(); <START> RepoObject repoObject = null; <END> for (InputObject inputObject : inputObjects) { UUID objectUUID = UUIDFormatter.getUuid(inputObject.getUuid()); repoObject = sqlService.getObject(repoCollection.getBucketName(), inputObject.getKey(), null, objectUUID, null); if (repoObject != null) { sqlService.insertCollectionObjects(collId, repoObject.getId()); repoObjectList.add(repoObject); } else { throw new RepoException(RepoException.Type.ObjectCollectionNotFound); } } repoCollection.addObjects(repoObjectList); auditOperation(new Audit.AuditBuilder(repoCollection.getBucketName(), operation) .setKey(repoCollection.getKey()) .setUuid(repoCollection.getUuid()) .build()); return repoCollection; }</code><technical_language>declaration for-loop</technical_language>

Target:
private RepoCollection createCollection(RepoCollection repoCollection, List<InputObject> inputObjects, Operation operation) throws SQLException, RepoException { Integer versionNumber = sqlService.getCollectionNextAvailableVersion(repoCollection.getBucketName(), repoCollection.getKey()); repoCollection.setVersionNumber(versionNumber); repoCollection.setUuid(UUID.randomUUID()); Integer collId = sqlService.insertCollection(repoCollection); if (collId == -1) { throw new RepoException("Error saving content to database"); } List<RepoObject> repoObjectList = new ArrayList<>(); for (InputObject inputObject : inputObjects) { UUID objectUUID = UUIDFormatter.getUuid(inputObject.getUuid()); log.debug("createCollection repoCollection=" + repoCollection.getBucketName() + "," + repoCollection.getKey() + " inputObjects=" + inputObject.getKey() + "," + inputObject.getUuid() + " collId=" + collId + " objectUUID=" + objectUUID.toString()); RepoObject repoObject = sqlService.getObject(repoCollection.getBucketName(), inputObject.getKey(), null, objectUUID, null, true, true); if (repoObject != null) { if (sqlService.insertCollectionObjects(collId, repoObject.getId())) { repoObjectList.add(repoObject); } } else { throw new RepoException(RepoException.Type.ObjectCollectionNotFound); } } repoCollection.addObjects(repoObjectList); auditOperation(new Audit.AuditBuilder(repoCollection.getBucketName(), operation) .setKey(repoCollection.getKey()) .setUuid(repoCollection.getUuid()) .build()); return repoCollection; }
Source:
<code>private void writeBackupTo(FileOutputStream outFileStream) { try { File currentDB = getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = outFileStream.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Snackbar.make(findViewById(R.id.import_export_layout), R.string.export_ok, Snackbar.LENGTH_SHORT).show(); } else { Snackbar.make(findViewById(R.id.import_export_layout), "Can not access current database", Snackbar.LENGTH_SHORT).show(); } <START> } catch (Exception e) { <END> e.printStackTrace(); Snackbar.make(findViewById(R.id.import_export_layout), e.getMessage(), Snackbar.LENGTH_SHORT).show(); } }</code><technical_language>pretty generic. exception more specific</technical_language>

Target:
private void writeBackupTo(FileOutputStream outFileStream) { FileChannel src = null; FileChannel dst = null; try { File currentDB = getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { src = new FileInputStream(currentDB).getChannel(); dst = outFileStream.getChannel(); dst.transferFrom(src, 0, src.size()); Snackbar.make(findViewById(R.id.import_export_layout), R.string.export_ok, Snackbar.LENGTH_SHORT).show(); } else { Snackbar.make(findViewById(R.id.import_export_layout), "Can not access current database", Snackbar.LENGTH_SHORT).show(); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); Snackbar.make(findViewById(R.id.import_export_layout), e.getLocalizedMessage(), Snackbar.LENGTH_SHORT).show(); } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }
Source:
<code>public static Map<String, Object> request(OP op, String uri, Map<String, String> headers, Map<String, Object> body, ContentType contentType) throws Exception { switch (op) { case DELETE: return handleRequest(new HttpDelete(uri), headers); case GET: return handleRequest(new HttpGet(uri), headers); case POST: HttpPost post = new HttpPost(uri); if (body != null) { if (contentType == ContentType.MULTIPART_FORM_DATA) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry<String, Object> entry : body.entrySet()) { builder.addTextBody(entry.getKey(), (String) entry.getValue()); } post.setEntity(builder.build()); } else { JSONObject jsonBody = new JSONObject(body); StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON); post.setEntity(strBody); } } return handleRequest(post, headers); case PUT: HttpPut put = new HttpPut(uri); if (body != null) { if (contentType == ContentType.MULTIPART_FORM_DATA) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry<String, Object> entry : body.entrySet()) { builder.addTextBody(entry.getKey(), (String) entry.getValue()); } put.setEntity(builder.build()); } else { JSONObject jsonBody = new JSONObject(body); StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON); put.setEntity(strBody); } } <START> return handleRequest(put, headers); <END> default: throw new Exception("Unrecognized OP type... Perhaps your binaries are the wrong version?"); } }</code><technical_language>PUT POST pretty code case. refactor this. Put code out put in a private method represent HttpPut HttpPost HttpEntityEnclosingRequestBase</technical_language>

Target:
public static Map<String, Object> request(OP op, String uri, Map<String, String> headers, Map<String, Object> body, ContentType contentType) throws Exception { if (!verifyBody(body)) { throw new CandybeanException("Body is not representable as JSON"); } switch (op) { case DELETE: return handleRequest(new HttpDelete(uri), headers); case GET: return handleRequest(new HttpGet(uri), headers); case POST: HttpPost post = new HttpPost(uri); addBodyToRequest(post, body, contentType); return handleRequest(post, headers); case PUT: HttpPut put = new HttpPut(uri); addBodyToRequest(put, body, contentType); return handleRequest(put, headers); default: throw new Exception("Unrecognized OP type... Perhaps your binaries are the wrong version?"); } }
Source:
<code>public EntitlerJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) <START> .addConstraint(JobConstraints.uniqueByArgument(OWNER_KEY)); <END> }</code><technical_language>constraint consumer key, job TARGET_TYPE is a consumer, TARGET_ID consumer uuid</technical_language>

Target:
public EntitlerJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) .addConstraint(JobConstraints.uniqueByArguments(CONSUMER_UUID_KEY)); }
Source:
<code>private static boolean checkpointsEqual(BooleanStreamCheckpoint left, BooleanStreamCheckpoint right) { <START> if (left == null && right == null) { <END> return true; } if (left == null || right == null) { return false; } if (left.getOffset() != right.getOffset()) { return false; } ByteStreamCheckpoint leftCheckpoint = left.getByteStreamCheckpoint(); ByteStreamCheckpoint rightCheckpoint = right.getByteStreamCheckpoint(); if (leftCheckpoint == null && rightCheckpoint == null) { return true; } if (leftCheckpoint == null || rightCheckpoint == null) { return false; } return leftCheckpoint.getInputStreamCheckpoint() == rightCheckpoint.getInputStreamCheckpoint() && leftCheckpoint.getOffset() == rightCheckpoint.getOffset(); }</code><technical_language>do get nulls here</technical_language>

Target:
private static boolean checkpointsEqual(BooleanStreamCheckpoint left, BooleanStreamCheckpoint right) { assertNotNull(left); assertNotNull(right); if (left.getOffset() != right.getOffset()) { return false; } ByteStreamCheckpoint leftCheckpoint = left.getByteStreamCheckpoint(); ByteStreamCheckpoint rightCheckpoint = right.getByteStreamCheckpoint(); assertNotNull(leftCheckpoint); assertNotNull(rightCheckpoint); return leftCheckpoint.getInputStreamCheckpoint() == rightCheckpoint.getInputStreamCheckpoint() && leftCheckpoint.getOffset() == rightCheckpoint.getOffset(); }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) <START> .add("history", history) <END> .toString(); }</code><technical_language>This implementation useful, dozens of those. I print number of events it</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("size", history.size()) .toString(); }
Source:
<code><START> private Function<Version, Iterable<Broadcast>> toBroadcasts() { <END> return new Function<Version, Iterable<Broadcast>>() { @Override public Iterable<Broadcast> apply(Version input) { return input.getBroadcasts(); } }; }</code><technical_language>2 functions constants? need create new instances time methods called</technical_language>

Target:
private static Function<Version, Iterable<Broadcast>> toBroadcasts() { return new Function<Version, Iterable<Broadcast>>() { @Override public Iterable<Broadcast> apply(Version input) { return input.getBroadcasts(); } }; }
Source:
<code>SlotSharingExecutionSlotAllocator( <START> PhysicalSlotProvider slotProvider, <END> boolean slotWillBeOccupiedIndefinitely, SlotSharingStrategy slotSharingStrategy, SharedSlotProfileRetrieverFactory sharedSlotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.slotSharingStrategy = slotSharingStrategy; this.sharedSlotProfileRetrieverFactory = sharedSlotProfileRetrieverFactory; this.sharedSlots = new HashMap<>(); }</code><technical_language>Is expected implement factory of SlotSharingExecutionSlotAllocator in another task</technical_language>

Target:
SlotSharingExecutionSlotAllocator( PhysicalSlotProvider slotProvider, boolean slotWillBeOccupiedIndefinitely, SlotSharingStrategy slotSharingStrategy, SharedSlotProfileRetrieverFactory sharedSlotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.slotSharingStrategy = slotSharingStrategy; this.sharedSlotProfileRetrieverFactory = sharedSlotProfileRetrieverFactory; this.sharedSlots = new IdentityHashMap<>(); }
Source:
<code>public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { <START> if (sharedPref.getBoolean("settings_clear_backbuffer_on_track_change", true)) { <END> backBuffer.clear(); } }</code><technical_language>I is a misunderstanding here. onTracksChanged is is. talking case station broadcasts live metadata - IcyDataSource.readMetaData of case station is changed. I of trigger onTracksChanged</technical_language>

Target:
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { }
Source:
<code>private void setPartitionStatus(int partitionID, int state, String description) { String itemName; itemName = getItemName(DSCAlarmItemType.PARTITION_STATUS, partitionID, 0); <START> if (itemName != "") { <END> updateItem(itemName, state, description); } }</code><technical_language>I add this line, comparing a String operator work accidentally. change (and other occurrences) if (!("".equals(itemName)) if (StringUtils.isNotEmpty(itemName))</technical_language>

Target:
private void setPartitionStatus(int partitionID, int state, String description) { String itemName; itemName = getItemName(DSCAlarmItemType.PARTITION_STATUS, partitionID, 0); if (StringUtils.isNotEmpty(itemName)) { updateItem(itemName, state, description); } }
Source:
<code>public List<Contentlet> filterRelatedContent(Contentlet contentlet, Relationship rel, User user, boolean respectFrontendRoles, Boolean pullByParent, int limit, int offset, String sortBy) throws DotDataException, DotSecurityException { <START> return filterRelatedContent(contentlet, rel, user, respectFrontendRoles, pullByParent, limit, offset); <END> }</code><technical_language>log a warning well, this method longer respects sort other method</technical_language>

Target:
public List<Contentlet> filterRelatedContent(Contentlet contentlet, Relationship rel, User user, boolean respectFrontendRoles, Boolean pullByParent, int limit, int offset, String sortBy) throws DotDataException, DotSecurityException { Logger.warn(this, "This implementation of ContentletAPI.filterRelatedContent is deprecated and no longer respects the sort. " + "Please, use any of the getRelatedContent implementations existing in the ContentletAPI instead "); return filterRelatedContent(contentlet, rel, user, respectFrontendRoles, pullByParent, limit, offset); }
Source:
<code>void display(final PrintWriter out) throws NoSuchGroupException { final ColumnFormatter formatter = new ColumnFormatter(out, '\t'); for (final GroupInfo info : get()) { <START> formatter.addColumn(info.name != null ? info.name : "n/a"); <END> if (verboseOutput) { AccountGroup o = info.ownerId != null ? groupCache.get(new AccountGroup.UUID(Url.decode(info.ownerId))) : null; formatter.addColumn(Url.decode(info.id)); formatter.addColumn(Strings.nullToEmpty(info.description)); formatter.addColumn(o != null ? o.getName() : "n/a"); formatter.addColumn(o != null ? o.getGroupUUID().get() : ""); formatter.addColumn(Boolean.toString( Objects.firstNonNull(info.visibleToAll, Boolean.FALSE))); } formatter.nextLine(); } formatter.finish(); }</code><technical_language>Objects.firstNonNull(info.name, "n/a/")</technical_language>

Target:
void display(final PrintWriter out) throws NoSuchGroupException { final ColumnFormatter formatter = new ColumnFormatter(out, '\t'); for (final GroupInfo info : get()) { formatter.addColumn(Objects.firstNonNull(info.name, "n/a")); if (verboseOutput) { AccountGroup o = info.ownerId != null ? groupCache.get(new AccountGroup.UUID(Url.decode(info.ownerId))) : null; formatter.addColumn(Url.decode(info.id)); formatter.addColumn(Strings.nullToEmpty(info.description)); formatter.addColumn(o != null ? o.getName() : "n/a"); formatter.addColumn(o != null ? o.getGroupUUID().get() : ""); formatter.addColumn(Boolean.toString( Objects.firstNonNull(info.visibleToAll, Boolean.FALSE))); } formatter.nextLine(); } formatter.finish(); }
Source:
<code>private static void makeAndroidParamsRequest(String appId, String userId) { if (getRemoteParams() != null) return; <START> OneSignalRemoteParams.makeAndroidParamsRequest(appId, userId, new OneSignalRemoteParams.CallBack() { <END> @Override public void complete(OneSignalRemoteParams.Params params) { if (params.googleProjectNumber != null) googleProjectNumber = params.googleProjectNumber; remoteParamController.saveRemoteParams(params, trackerFactory, preferences, logger); NotificationChannelManager.processChannelList( OneSignal.appContext, params.notificationChannels ); } }); }</code><technical_language>CallBack Callback, this is word</technical_language>

Target:
private static void makeAndroidParamsRequest(String appId, String userId) { if (getRemoteParams() != null) return; OneSignalRemoteParams.makeAndroidParamsRequest(appId, userId, new OneSignalRemoteParams.Callback() { @Override public void complete(OneSignalRemoteParams.Params params) { if (params.googleProjectNumber != null) googleProjectNumber = params.googleProjectNumber; remoteParamController.saveRemoteParams(params, trackerFactory, preferences, logger); onRemoteParamSet(); NotificationChannelManager.processChannelList( OneSignal.appContext, params.notificationChannels ); } }); }
Source:
<code><START> public void testImmutableOriginalsWithConfigProvidersProps() { <END> Properties providers = new Properties(); providers.put("config.providers", "file"); providers.put("config.providers.file.class", "org.apache.kafka.common.config.provider.MockFileConfigProvider"); Properties props = new Properties(); props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}"); final Map<String, ?> immutableMap = convertPropertiesToMap(providers); TestIndirectConfigResolution config = new TestIndirectConfigResolution(props, immutableMap); assertEquals(config.originals().get("sasl.kerberos.key"), "testKey"); }</code><technical_language>this test fail change</technical_language>

Target:
public void testImmutableOriginalsWithConfigProvidersProps() { Properties providers = new Properties(); providers.put("config.providers", "file"); providers.put("config.providers.file.class", "org.apache.kafka.common.config.provider.MockFileConfigProvider"); Properties props = new Properties(); props.put("sasl.kerberos.key", "${file:/usr/kerberos:key}"); Map<?, ?> immutableMap = Collections.unmodifiableMap(props); Map<String, ?> provMap = convertPropertiesToMap(providers); TestIndirectConfigResolution config = new TestIndirectConfigResolution(immutableMap, provMap); assertEquals(config.originals().get("sasl.kerberos.key"), "testKey"); }
Source:
<code>public final void messageLogged( BuildEvent event ) { String msg = event.getMessage(); switch ( event.getPriority() ) { case Project.MSG_ERR: if ( msg.indexOf( "ar: creating archive" ) >= 0 ) { log.debug( msg ); } else if ( msg.indexOf( "warning" ) >= 0 ) { log.warn( msg ); } else { log.error( msg ); } break; case Project.MSG_WARN: log.warn( msg ); break; case Project.MSG_INFO: if ( ( msg.indexOf( "files were compiled" ) >= 0 ) || ( msg.indexOf( "Linking..." ) >= 0 ) ) { log.info( msg ); } else if ( msg.indexOf( "error" ) >= 0 ) { log.error( msg ); } else if ( msg.indexOf( "warning" ) >= 0 ) { log.warn( msg ); } else { log.info( msg ); <START> } <END> break; case Project.MSG_VERBOSE: log.debug( msg ); break; default: case Project.MSG_DEBUG: log.debug( msg ); break; } }</code><technical_language>I agree is a bug fix. is a bug fix do commit message's rationale explain, needs commit: <LINK_0></technical_language>

Target:
public final void messageLogged( BuildEvent event ) { String msg = event.getMessage(); switch ( event.getPriority() ) { case Project.MSG_ERR: if ( msg.indexOf( "ar: creating archive" ) >= 0 ) { log.debug( msg ); } else if ( msg.indexOf( "warning" ) >= 0 ) { log.warn( msg ); } else { log.error( msg ); } break; case Project.MSG_WARN: log.warn( msg ); break; case Project.MSG_INFO: log.info( msg ); break; case Project.MSG_VERBOSE: log.debug( msg ); break; default: case Project.MSG_DEBUG: log.debug( msg ); break; } }
Source:
<code>private void reloadDashboard() { Log.i(TAG, "reloadDashboard"); <START> IProgramRepository programLocalDataSource = new ProgramLocalDataSource(); <END> IMainExecutor mainExecutor = new UIThreadExecutor(); IAsyncExecutor asyncExecutor = new AsyncExecutor(); GetUserProgramUIDUseCase getUserProgramUIDUseCase = new GetUserProgramUIDUseCase( programLocalDataSource, mainExecutor, asyncExecutor); getUserProgramUIDUseCase.execute(new GetUserProgramUIDUseCase.Callback() { @Override public void onSuccess(String uid) { List<Survey> unsentSurveys = Survey.getAllUnsentMalariaSurveys(uid); List<Survey> sentSurveys = Survey.getAllSentMalariaSurveys(uid); Session.putServiceValue(ALL_UNSENT_SURVEYS_ACTION, unsentSurveys); Session.putServiceValue(ALL_SENT_SURVEYS_ACTION, sentSurveys); LocalBroadcastManager.getInstance(SurveyService.this).sendBroadcast( new Intent(ALL_UNSENT_SURVEYS_ACTION)); LocalBroadcastManager.getInstance(SurveyService.this).sendBroadcast( new Intent(ALL_SENT_SURVEYS_ACTION)); } @Override public void onError() { Log.e(TAG, "error getting user program"); } }); }</code><technical_language>this dependencies created in reload method same, refactor for create time in service entry point (constructor onCreate)</technical_language>

Target:
private void reloadDashboard() { Log.i(TAG, "reloadDashboard"); getProgramUID(new Callback() { @Override public void onSuccess(String uid) { List<Survey> unsentSurveys = Survey.getAllUnsentMalariaSurveys(uid); List<Survey> sentSurveys = Survey.getAllSentMalariaSurveys(uid); Session.putServiceValue(ALL_UNSENT_SURVEYS_ACTION, unsentSurveys); Session.putServiceValue(ALL_SENT_SURVEYS_ACTION, sentSurveys); LocalBroadcastManager.getInstance(SurveyService.this).sendBroadcast( new Intent(ALL_UNSENT_SURVEYS_ACTION)); LocalBroadcastManager.getInstance(SurveyService.this).sendBroadcast( new Intent(ALL_SENT_SURVEYS_ACTION)); } }); }
Source:
<code>private void startBulkRegionOperation(boolean writeLockNeeded) <START> throws NotServingRegionException, IOException { <END> if (this.closing.get()) { throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closing"); } if (writeLockNeeded) lock(lock.writeLock()); else lock(lock.readLock()); if (this.closed.get()) { if (writeLockNeeded) lock.writeLock().unlock(); else lock.readLock().unlock(); throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closed"); } regionLockHolders.add(Thread.currentThread()); }</code><technical_language>nit: remove NSRE</technical_language>

Target:
private void startBulkRegionOperation(boolean writeLockNeeded) throws IOException { if (this.closing.get()) { throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closing"); } if (writeLockNeeded) lock(lock.writeLock()); else lock(lock.readLock()); if (this.closed.get()) { if (writeLockNeeded) lock.writeLock().unlock(); else lock.readLock().unlock(); throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closed"); } regionLockHolders.put(Thread.currentThread(), true); }
Source:
<code>private Dialog createDeleteDialog(){ <START> return new AlertDialog.Builder(this, R.style.Theme_Syncthing_Dialog) <END> .setMessage(R.string.remove_device_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeDevice(mDevice.deviceID); finish(); }) .setNegativeButton(android.R.string.no, null) .create(); }</code><technical_language>tests, values-night allows omit this (in multiple places)</technical_language>

Target:
private Dialog createDeleteDialog(){ return Util.getAlertDialogBuilder(this) .setMessage(R.string.remove_device_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeDevice(mDevice.deviceID); finish(); }) .setNegativeButton(android.R.string.no, null) .create(); }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { Set<PermissionSubject> permissionSet = new HashSet<>(); permissionSet.add(new PermissionSubject(getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); if (getClusterId() != null) { permissionSet.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CREATE_VM)); <START> } <END> return new ArrayList<>(permissionSet); }</code><technical_language>some permissions in common in ImportVmCommand ImportVmFromExternalProviderCommand, move code currently exists in ImportVmCommandBase#getPermissionCheckSubjects ImportVmCommand permission check destination cluster in ImportVmCommandBase is common import commands, do think</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); permissionList.add(new PermissionSubject(getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); return permissionList; }
Source:
<code>public Optional<Value<Entity>> getApiValueFromContainer(ValueContainer<?> container) { if (container instanceof net.minecraft.entity.Entity) { net.minecraft.entity.Entity currentEntity = (net.minecraft.entity.Entity) container; while (currentEntity != null && currentEntity.isRiding()) { currentEntity = currentEntity.ridingEntity; } <START> final Entity baseVehicle = (Entity) currentEntity; <END> return Optional.<Value<Entity>>of(new SpongeValue<Entity>(Keys.BASE_VEHICLE, baseVehicle)); } return Optional.absent(); }</code><technical_language>double check currentEntity container, otherwise, returning a "base vehicle" of entity itself, in cases, true</technical_language>

Target:
public Optional<Value<Entity>> getApiValueFromContainer(ValueContainer<?> container) { if (container instanceof net.minecraft.entity.Entity) { net.minecraft.entity.Entity currentEntity = ((net.minecraft.entity.Entity) container).ridingEntity; while (currentEntity != null && currentEntity.isRiding()) { currentEntity = currentEntity.ridingEntity; } final Entity baseVehicle = (Entity) currentEntity; return Optional.<Value<Entity>>of(new SpongeValue<Entity>(Keys.BASE_VEHICLE, baseVehicle)); } return Optional.absent(); }
Source:
<code>@Test public void requestConverterFactorySkippedNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory(); NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory1) .addConverterFactory(nonMatchingFactory2) .build(); try { retrofit.nextRequestBodyConverter(nonMatchingFactory1, type, annotations); <START> } catch (IllegalArgumentException e) { <END> assertThat(e).hasMessage("" + "Could not locate RequestBody converter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory1.called).isFalse(); assertThat(nonMatchingFactory2.called).isTrue(); }</code><technical_language>fail</technical_language>

Target:
@Test public void requestConverterFactorySkippedNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory(); NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory1) .addConverterFactory(nonMatchingFactory2) .build(); try { retrofit.nextRequestBodyConverter(nonMatchingFactory1, type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate RequestBody converter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory1.called).isFalse(); assertThat(nonMatchingFactory2.called).isTrue(); }
Source:
<code>private void writeVGpu() { String mdevTypes = vmCustomProperties.remove("mdev_type"); if (mdevTypes != null) { String[] mdevDevices = mdevTypes.split(","); for (String mdevType : mdevDevices) { writer.writeStartElement("hostdev"); writer.writeAttributeString("mode", "subsystem"); writer.writeAttributeString("type", "mdev"); writer.writeAttributeString("model", "vfio-pci"); writer.writeStartElement("source"); String address = Guid.newGuid().toString(); writer.writeStartElement("address"); writer.writeAttributeString("uuid", address); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); String mdevTypeMeta = mdevType; if (FeatureSupported.isVgpuPlacementSupported(vm.getCompatibilityVersion())) { VgpuPlacementEnum vgpuPlacement = hostVgpuPlacementSupplier.get(); String vgpuPlacementString; if (vgpuPlacement == VgpuPlacementEnum.COMPACT) { vgpuPlacementString = "compact"; } else if (vgpuPlacement == VgpuPlacementEnum.SEPARATE) { vgpuPlacementString = "separate"; } else { <START> log.error("Unrecognized <END> vGPU placement type (using `{}' instead): {}", VgpuPlacementEnum.COMPACT, vgpuPlacement); vgpuPlacementString = "compact"; } mdevTypeMeta = mdevTypeMeta + "|" + vgpuPlacementString; } mdevMetadata.put(address, Collections.singletonMap("mdevType", mdevTypeMeta)); } } }</code><technical_language>fail this takes a default warning level more here</technical_language>

Target:
private void writeVGpu() { String mdevTypes = vmCustomProperties.remove("mdev_type"); if (mdevTypes != null) { String[] mdevDevices = mdevTypes.split(","); for (String mdevType : mdevDevices) { writer.writeStartElement("hostdev"); writer.writeAttributeString("mode", "subsystem"); writer.writeAttributeString("type", "mdev"); writer.writeAttributeString("model", "vfio-pci"); writer.writeStartElement("source"); String address = Guid.newGuid().toString(); writer.writeStartElement("address"); writer.writeAttributeString("uuid", address); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); String mdevTypeMeta = mdevType; if (FeatureSupported.isVgpuPlacementSupported(vm.getCompatibilityVersion())) { VgpuPlacementEnum vgpuPlacement = hostVgpuPlacementSupplier.get(); String vgpuPlacementString; if (vgpuPlacement == VgpuPlacementEnum.COMPACT) { vgpuPlacementString = "compact"; } else if (vgpuPlacement == VgpuPlacementEnum.SEPARATE) { vgpuPlacementString = "separate"; } else { log.warn("Unrecognized vGPU placement type (using `{}' instead): {}", VgpuPlacementEnum.COMPACT, vgpuPlacement); vgpuPlacementString = "compact"; } mdevTypeMeta = mdevTypeMeta + "|" + vgpuPlacementString; } mdevMetadata.put(address, Collections.singletonMap("mdevType", mdevTypeMeta)); } } }
Source:
<code>public void updateUserWithEmailAsUsername() { switchRegistrationEmailAsUsername(true); String id = createUser(); UserResource user = realm.users().get(id); UserRepresentation userRep = user.toRepresentation(); <START> assertEquals("user1@localhost", userRep.getEmail()); <END> userRep.setEmail("user11@localhost"); updateUser(user, userRep); userRep = realm.users().get(id).toRepresentation(); assertEquals("user11@localhost", userRep.getEmail()); switchRegistrationEmailAsUsername(false); }</code><technical_language>this userRep.getUsername()</technical_language>

Target:
public void updateUserWithEmailAsUsername() { switchRegistrationEmailAsUsername(true); String id = createUser(); UserResource user = realm.users().get(id); UserRepresentation userRep = user.toRepresentation(); assertEquals("user1@localhost", userRep.getUsername()); userRep.setEmail("user11@localhost"); updateUser(user, userRep); userRep = realm.users().get(id).toRepresentation(); assertEquals("user11@localhost", userRep.getUsername()); switchRegistrationEmailAsUsername(false); }
Source:
<code>public void testHttpIngestionInvalidPastCollectionTime() throws Exception { long time = System.currentTimeMillis() - 600000 - Configuration.getInstance().getLongProperty( CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS ); HttpPost post = new HttpPost(getMetricsURI()); HttpEntity entity = new StringEntity( JSONMetricsContainerTest.generateJSONMetricsData( time ) , ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); assertEquals( 400, response.getStatusLine().getStatusCode() ); String[] output = getBodyArray( response ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 1 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 2 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 3 ] ) ); <START> EntityUtils.consume(response.getEntity()); END> }</code><technical_language>Is harmful if done? sounds needs in finally{} block</technical_language>

Target:
public void testHttpIngestionInvalidPastCollectionTime() throws Exception { long time = System.currentTimeMillis() - 600000 - Configuration.getInstance().getLongProperty( CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS ); HttpPost post = new HttpPost(getMetricsURI()); HttpEntity entity = new StringEntity( JSONMetricsContainerTest.generateJSONMetricsData( time ) , ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); assertEquals( 400, response.getStatusLine().getStatusCode() ); String[] output = getBodyArray( response ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 1 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 2 ] ) ); assertTrue( Pattern.matches( JSONMetricsContainerTest.PAST_COLLECTION_TIME_REGEX, output[ 3 ] ) ); }
Source:
<code>public void setVmBackup(VmBackup value) { <START> vmBackup = value; <END> }</code><technical_language>This is a bug, setter nothing, 'this'</technical_language>

Target:
public void setVmBackup(VmBackup value) { this.vmBackup = value; }
Source:
<code>public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) { checkNotNull(resourceGroup, "resourceGroup cannot be null"); checkNotNull(vaultUri, "vaultUri cannot be null"); return retry(new Predicate<String>() { @Override public boolean apply(final String name) { boolean present = false; checkNotNull(name, "name cannot be null"); DeletedKeyBundle key = api.getVaultApi(resourceGroup).getDeletedKey(vaultUri, name); if (shouldBePresent) { return key != null; } else { return key == null; <START> } <END> } }, operationTimeout, initialPeriod, maxPeriod); }</code><technical_language>Just? java return shouldBePresent == (key != null);</technical_language>

Target:
public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) { checkNotNull(resourceGroup, "resourceGroup cannot be null"); checkNotNull(vaultUri, "vaultUri cannot be null"); return retry(new Predicate<String>() { @Override public boolean apply(final String name) { checkNotNull(name, "name cannot be null"); boolean present = false; DeletedKeyBundle key = api.getVaultApi(resourceGroup).getDeletedKey(vaultUri, name); return shouldBePresent == (key != null); } }, operationTimeout, initialPeriod, maxPeriod); }
Source:
<code>private String getStringFromIS(InputStream stream) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { return reader.lines().collect(Collectors.joining("\n")); } catch (IOException e) { e.printStackTrace(); <START> return null; <END> } }</code><technical_language>necesary</technical_language>

Target:
private String getStringFromIS(InputStream stream) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { return reader.lines().collect(Collectors.joining("\n")); } catch (IOException e) { e.printStackTrace(); return ""; } }
Source:
<code>protected List<PurApAccountingLine> getItemSourceAccountingLines(PurchaseOrderAmendmentDocument document) { return getAccountingLinesFromItems(document, <START> (itemStream) -> itemStream.flatMap(this::getItemSourceAccountingLinesAsStream)); <END> }</code><technical_language>this lambda expression similar refactored understanding, some naming</technical_language>

Target:
protected List<PurApAccountingLine> getItemSourceAccountingLines(PurchaseOrderAmendmentDocument document) { List<PurApItem> items = (List<PurApItem>) document.getItems(); return items.stream() .flatMap((item) -> item.getSourceAccountingLines().stream()) .collect(Collectors.toCollection(ArrayList::new)); }
Source:
<code><START> private void showAttachmentDialog(final Receipt receipt) { <END> highlightedReceipt = receipt; BetterDialogBuilder dialogBuilder = new BetterDialogBuilder(getActivity()); dialogBuilder.setTitle(receipt.getName()) .setNegativeButton(android.R.string.cancel, (dialog, which) -> dialog.cancel()); LayoutInflater inflater = this.getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_receipt_attachment, null); dialogBuilder.setView(dialogView); final AlertDialog dialog = dialogBuilder.create(); dialogView.findViewById(R.id.attach_photo).setOnClickListener(v -> { imageUri = receiptAttachmentManager.attachPhoto(ReceiptsListFragment.this); dialog.cancel(); }); dialogView.findViewById(R.id.attach_picture).setOnClickListener(v -> { if (!receiptAttachmentManager.attachPicture(ReceiptsListFragment.this)) { Toast.makeText(getContext(), getString(R.string.error_no_file_intent_dialog_title), Toast.LENGTH_SHORT).show(); } dialog.cancel(); }); dialogView.findViewById(R.id.attach_file).setOnClickListener(v -> { if (!receiptAttachmentManager.attachFile(this)) { Toast.makeText(getContext(), getString(R.string.error_no_file_intent_dialog_title), Toast.LENGTH_SHORT).show(); } dialog.cancel(); }); dialog.show(); }</code><technical_language>Is this launch a DialogFragment instead? code good (and limited highlightedReceipt stuff), insure this handle rotation. flow work otherwise: 1. Launch showAttachmentDialog 2. Wait for dialog 3. Rotate I dialog auto-dismissed in this case? Switching a DialogFragment handle this for us</technical_language>

Target:
private void showAttachmentDialog(final Receipt receipt) { highlightedReceipt = receipt; ReceiptAttachmentDialogFragment.newInstance(receipt).show(getChildFragmentManager(), ReceiptAttachmentDialogFragment.class.getSimpleName()); }
Source:
<code>public boolean isValid(Integer value, ConstraintValidatorContext context) { boolean result = value == null ? true : value >= min && value <= max; if (!result) { <START> context.buildConstraintViolationWithTemplate(rangeMessage); <END> } return result; }</code><technical_language>rangeMessage is relevant in case of a failure, locally evaluated here. is motivation rangeMessage instance variable</technical_language>

Target:
public boolean isValid(Integer value, ConstraintValidatorContext context) { boolean result = value == null ? true : value >= min && value <= max; if (!result) { context.buildConstraintViolationWithTemplate(rangeMessage).addConstraintViolation(); } return result; }
Source:
<code>public void update(T data, Query query) { assertDatabaseOpen(); ContentValues contentValues = new ContentValues(); getContentValuesPopulator().populate(contentValues, data); int num = database.update(getName(), contentValues, query.getWhereClause(), query.getWhereClauseValues()); <START> Log.d(getLoggerTag(), "Updated " + num + "number of cols"); <END> }</code><technical_language>want change this logging while</technical_language>

Target:
public void update(T data, Query query) { assertDatabaseOpen(); ContentValues contentValues = new ContentValues(); getContentValuesPopulator().populate(contentValues, data); int num = database.update(getName(), contentValues, query.getWhereClause(), query.getWhereClauseValues()); logger.debug("Updated number of cols", num); }
Source:
<code>public void destroy() { <START> throw new NoSuchMethodError("Thread.destroy()"); END> }</code><technical_language>TODO remove</technical_language>

Target:
public void destroy() { throw new UnsupportedOperationException(); }
Source:
<code>public void patchNameTest() throws Exception { context.turnOffAuthorisationSystem(); String testGroupName = "Test group"; Group group = GroupBuilder.createGroup(context) .withName(testGroupName) .build(); String newName = "New test name"; List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/name", newName); ops.add(replaceOperation); <START> String patchBody = getPatchContent(ops); <END> String token = getAuthToken(admin.getEmail(), password); getClient(token).perform( patch("/api/eperson/groups/" + group.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(jsonPath("$.name", Matchers.is(newName))) .andExpect(status().isOk()); }</code><technical_language>This test great. hardcoding JSON & GroupBuilder create a test Group. other tests this pattern easier read/review. **However, missing is a context.restoreAuthSystemState();**</technical_language>

Target:
public void patchNameTest() throws Exception { context.turnOffAuthorisationSystem(); String testGroupName = "Test group"; Group group = GroupBuilder.createGroup(context) .withName(testGroupName) .build(); context.restoreAuthSystemState(); String newName = "New test name"; List<Operation> ops = new ArrayList<>(); ReplaceOperation replaceOperation = new ReplaceOperation("/name", newName); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform( patch("/api/eperson/groups/" + group.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(jsonPath("$.name", Matchers.is(newName))) .andExpect(status().isOk()); }
Source:
<code>public void userOnMobileCanNotSeeThatPostWasEditedByAdministratorOnPostsListPage() { final PostEntity.Data data = updatePostAsStaffRemotely(createPostAsUserRemotely()); <START> final PostEntity post = new PostsListPage().open(data.getId()).getPost().findNewestPost(); <END> Assertion.assertFalse(post.hasEditedBySection(), SHOULD_NOT_HAVE_EDITED_BY_SECTION_MESSAGE); }</code><technical_language>a possibility - if this test group is executed in parallel another - post created newest list. assertions fail. Do find this post a page posts this user</technical_language>

Target:
public void userOnMobileCanNotSeeThatPostWasEditedByAdministratorOnPostsListPage() { final PostEntity.Data data = updatePostAsStaffRemotely(createPostAsUserRemotely()); final PostEntity post = new PostsListPage().open(data.getId()).getPost().findPostById(data.getId()); Assertion.assertFalse(post.hasEditedBySection(), SHOULD_NOT_HAVE_EDITED_BY_SECTION_MESSAGE); }
Source:
<code>private static void output(HttpAction action, String contentType, String charset, OutputContent proc, CacheAction cacheAction) { try { setHttpResponse(action, contentType, charset) ; action.response.setStatus(HttpSC.OK_200) ; OutputStream outServlet = action.response.getOutputStream(); <START> Cache cache = SPARQL_Query_Cache.getCache(); <END> OutputStream out = null; try { ByteArrayOutputStream outCache; byte[] data; if(CacheAction.Type.WRITE_CACHE == cacheAction.type) { outCache = new ByteArrayOutputStream(); out = new ResponseOutputStream(outServlet, outCache); proc.output(out); data = outCache.toByteArray(); CacheEntry cacheEntry = (CacheEntry) cache.getIfPresent(cacheAction.getKey()); cacheEntry.setData(data); cacheEntry.initialized(); cache.put(cacheAction.getKey(), cacheEntry); action.log.info("Writing cache "+ new String(data)); out.flush(); }else{ CacheEntry cacheEntry = (CacheEntry)cache.getIfPresent(cacheAction.getKey()); data = cacheEntry.getData(); outServlet.write(data); action.log.info("Reading cache "+ new String(data)); outServlet.flush(); } } catch (QueryCancelledException ex) { action.log.info(format("[%d] Query Cancelled - results truncated (but 200 already sent)", action.id)) ; out.flush() ; } } catch (IOException ex) { ServletOps.errorOccurred(ex) ; } }</code><technical_language>this properly parameterized</technical_language>

Target:
private static void output(HttpAction action, String contentType, String charset, OutputContent proc, CacheAction cacheAction) { try { setHttpResponse(action, contentType, charset) ; action.response.setStatus(HttpSC.OK_200) ; OutputStream outServlet = action.response.getOutputStream(); Cache cache = SPARQL_Query_Cache.getCache(SPARQL_Query_Cache.getDatasetUri(action)); OutputStream out = null; try { ByteArrayOutputStream outCache; byte[] data; if(CacheAction.Type.WRITE_CACHE == cacheAction.type) { outCache = new ByteArrayOutputStream(); out = new TeeOutputStream(outServlet,outCache); proc.output(out); data = outCache.toByteArray(); CacheEntry cacheEntry = (CacheEntry) cache.getIfPresent(cacheAction.getKey()); cacheEntry.setData(data); cacheEntry.initialized(); cache.put(cacheAction.getKey(), cacheEntry); action.log.debug("Writing cache "+ new String(data)); out.flush(); }else{ CacheEntry cacheEntry = (CacheEntry)cache.getIfPresent(cacheAction.getKey()); data = cacheEntry.getData(); outServlet.write(data); action.log.debug("Reading cache "+ new String(data)); outServlet.flush(); } } catch (QueryCancelledException ex) { action.log.info(format("[%d] Query Cancelled - results truncated (but 200 already sent)", action.id)) ; out.flush() ; } } catch (IOException ex) { ServletOps.errorOccurred(ex) ; } }
Source:
<code>public static <K, V> Duration getExpiryForCreation(K key, V value, ExpiryPolicy<? super K, ? super V> expiry) { Duration duration; try { duration = expiry.getExpiryForCreation(key, value); } catch (RuntimeException e) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0", e); <START> return null; <END> } try { if (Duration.ZERO.compareTo(duration) >= 0) { return null; } } catch(NullPointerException e) { LOG.error("Expiry for creation can't be null - Expiry duration will be 0", e); return null; } return duration; }</code><technical_language>I this method return null, Duration.ZERO</technical_language>

Target:
public static <K, V> Duration getExpiryForCreation(K key, V value, ExpiryPolicy<? super K, ? super V> expiry) { Duration duration; try { duration = expiry.getExpiryForCreation(key, value); } catch (RuntimeException e) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0", e); return Duration.ZERO; } if (duration == null) { LOG.error("Expiry for creation can't be null - Expiry duration will be 0"); return Duration.ZERO; } if (Duration.ZERO.compareTo(duration) >= 0) { return Duration.ZERO; } return duration; }