auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FilterDescriptor getFilterDescriptorByKey(final String filterKey) { final FilterDescriptor defaultFilter = this.loadedFilters.values().stream().filter(filterDescriptor -> filterDescriptor.isDefaultFilter()).findAny().get(); if(!UtilMethods.isSet(filterKey)){ return defaultFilter; } return this.loadedFilters.getOrDefault(filterKey,defaultFilter); <START> } <END></code><technical_language>This refactored return !UtilMethods.isSet(filterKey)? this.loadedFilters.values().stream().filter(FilterDescriptor::isDefaultFilter()).findFirst().get(): this.loadedFilters.containsKey(filterKey)? this.loadedFilters.get(filterKey) : this.loadedFilters.values().stream().filter(FilterDescriptor::isDefaultFilter()).findFirst().get(); In addition create a method called getDefaultFilter, basically returns this this.loadedFilters.values().stream().filter(FilterDescriptor::isDefaultFilter()).findFirst().get() call this: return !UtilMethods.isSet(filterKey)? this.getDefaultFilter(): this.loadedFilters.containsKey(filterKey)? this.loadedFilters.get(filterKey) : this.getDefaultFilter();</technical_language>

Target:
public FilterDescriptor getFilterDescriptorByKey(final String filterKey) { final FilterDescriptor defaultFilter = getDefaultFilter(); return !UtilMethods.isSet(filterKey) ? defaultFilter : this.loadedFilters.getOrDefault(filterKey,defaultFilter); }
Source:
<code>public static String formatStopDistance(float distance) { int distanceSmoots = (int) (distance * TourUtils.METERS_TO_SMOOTS); float distanceMiles = distance * TourUtils.METERS_TO_MILES; String milesString = String.valueOf(distanceMiles).substring(0, 3); <START> return distanceSmoots + " miles (" + milesString + " smoots) "; <END> }</code><technical_language>I variables mixed up, switched</technical_language>

Target:
public static String formatStopDistance(float distance) { int distanceSmoots = (int) (distance * TourUtils.METERS_TO_SMOOTS); float distanceMiles = distance * TourUtils.METERS_TO_MILES; String milesString = String.valueOf(distanceMiles).substring(0, 3); return milesString + " miles (" + distanceSmoots + " smoots) "; }
Source:
<code><START> private DataBuffer readChunk() throws IOException { <END> Preconditions.checkState(!mClient.get().isShutdown(), "Data reader is closed while reading data chunks."); DataBuffer buffer = null; ReadResponse response = null; response = mStream.receive(mDataTimeoutMs); if (response != null) { Preconditions.checkState(response.hasChunk() && response.getChunk().hasData(), "response should always contain chunk"); ByteBuffer byteBuffer = response.getChunk().getData().asReadOnlyByteBuffer(); buffer = new NioDataBuffer(byteBuffer, byteBuffer.remaining()); } else { return null; } mPosToRead += buffer.readableBytes(); try { mStream.send(mReadRequest.toBuilder().setOffsetReceived(mPosToRead).build()); } catch (Exception e) { LOG.debug("Failed to send receipt of data to worker for request {}: {}.", mAddress, mReadRequest, e.getMessage()); } Preconditions.checkState(mPosToRead - mReadRequest.getOffset() <= mReadRequest.getLength()); return buffer; }</code><technical_language>marking @Nullablewhenever is possible. IDE a lot warn null check in invokers</technical_language>

Target:
private DataBuffer readChunk() throws IOException { Preconditions.checkState(!mClient.get().isShutdown(), "Data reader is closed while reading data chunks."); DataBuffer buffer = null; ReadResponse response = null; response = mStream.receive(mDataTimeoutMs); if (response == null) { return null; } Preconditions.checkState(response.hasChunk() && response.getChunk().hasData(), "response should always contain chunk"); ByteBuffer byteBuffer = response.getChunk().getData().asReadOnlyByteBuffer(); buffer = new NioDataBuffer(byteBuffer, byteBuffer.remaining()); mPosToRead += buffer.readableBytes(); try { mStream.send(mReadRequest.toBuilder().setOffsetReceived(mPosToRead).build()); } catch (Exception e) { LOG.debug("Failed to send receipt of data to worker for request {}: {}.", mAddress, mReadRequest, e.getMessage()); } Preconditions.checkState(mPosToRead - mReadRequest.getOffset() <= mReadRequest.getLength()); return buffer; }
Source:
<code>public void cancelUpdateProfile() { doAIA(); loginPage.login("test-user@localhost", "password"); updateProfilePage.assertCurrent(); updateProfilePage.cancel(); <START> assertRedirectSuccess(); <END> appPage.logout(); loginPage.open(); loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); updateProfilePage.assertCurrent(); }</code><technical_language>This check error response is Keycloak (<LINK_0> error code/description app AIA cancelled login</technical_language>

Target:
public void cancelUpdateProfile() { doAIA(); loginPage.login("test-user@localhost", "password"); updateProfilePage.assertCurrent(); updateProfilePage.cancel(); assertRedirectSuccess(); assertCancelMessage(); appPage.logout(); loginPage.open(); loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); updateProfilePage.assertCurrent(); }
Source:
<code>private ILaunch attachRemoteDebugger(IServer server, int localDebugPort, IProgressMonitor monitor) throws CoreException { monitor.subTask("Attaching remote debugger..."); ILaunch ret = null; DebugLaunchConfigs launchConfigs = DebugLaunchConfigs.get(); if( launchConfigs == null ) { <START> throw toCoreException(NLS.bind("Could not modify launch config for server {0}", server.getName())); <END> } ILaunchConfiguration debuggerLaunchConfig = launchConfigs.getRemoteDebuggerLaunchConfiguration(server); ILaunchConfigurationWorkingCopy workingCopy = getLaunchConfigWorkingCopy(server, launchConfigs, debuggerLaunchConfig); if (workingCopy == null) { throw toCoreException(NLS.bind("Could not modify launch config for server {0}", server.getName())); } IProject project = OpenShiftServerUtils.getDeployProject(server); launchConfigs.setupRemoteDebuggerLaunchConfiguration(workingCopy, project, localDebugPort); debuggerLaunchConfig = workingCopy.doSave(); ret = lauchDebugger(debuggerLaunchConfig, localDebugPort, monitor); if (ret == null) { throw toCoreException( NLS.bind("Could not start remote debugger to (forwarded) port {0} on localhost", localDebugPort)); } monitor.worked(10); return ret; }</code><technical_language>get launch config for server {0} attach remote debugger, not? This in some related action 'Attaching remote debugger' obvious attached</technical_language>

Target:
private ILaunch attachRemoteDebugger(IServer server, int localDebugPort, IProgressMonitor monitor) throws CoreException { monitor.subTask("Attaching remote debugger..."); ILaunch ret = null; DebugLaunchConfigs launchConfigs = DebugLaunchConfigs.get(); if( launchConfigs == null ) { throw toCoreException(NLS.bind("Could not get launch config for server {0} to attach remote debugger", server.getName())); } ILaunchConfiguration debuggerLaunchConfig = launchConfigs.getRemoteDebuggerLaunchConfiguration(server); ILaunchConfigurationWorkingCopy workingCopy = getLaunchConfigWorkingCopy(server, launchConfigs, debuggerLaunchConfig); if (workingCopy == null) { throw toCoreException(NLS.bind("Could not modify launch config for server {0}", server.getName())); } IProject project = OpenShiftServerUtils.getDeployProject(server); launchConfigs.setupRemoteDebuggerLaunchConfiguration(workingCopy, project, localDebugPort); debuggerLaunchConfig = workingCopy.doSave(); ret = lauchDebugger(debuggerLaunchConfig, localDebugPort, monitor); if (ret == null) { throw toCoreException( NLS.bind("Could not start remote debugger to (forwarded) port {0} on localhost", localDebugPort)); } monitor.worked(10); return ret; }
Source:
<code><START> default public State as(Class<? extends State> target) { <END> if (target != null && target.isInstance(this)) { return this; } else { return null; } }</code><technical_language>is permitted, discouraged a matter of style, redundantly public and/or abstract modifier for a method declared in interface. <LINK_0></technical_language>

Target:
default State as(Class<? extends State> target) { if (target != null && target.isInstance(this)) { return this; } else { return null; } }
Source:
<code>public boolean finishInErrorTask(String jobId, String taskName) throws NotConnectedException, UnknownJobException, UnknownTaskException, PermissionException { final JobId jobIdObject = JobIdImpl.makeJobId(jobId); <START> frontendState.checkJobOwner("finishTaskInError", frontendState.getIdentifiedJob(jobIdObject), <END> "You do not have permission to finish this task!"); return schedulingService.finishInErrorTask(jobIdObject, taskName); }</code><technical_language>checkowner changed : frontendState.checkPermissions("finishTaskInError", frontendState.getIdentifiedJob(jobIdObject), YOU_DO_NOT_HAVE_PERMISSION_TO_FINISH_THIS_TASK);</technical_language>

Target:
public boolean finishInErrorTask(String jobId, String taskName) throws NotConnectedException, UnknownJobException, UnknownTaskException, PermissionException { final JobId jobIdObject = JobIdImpl.makeJobId(jobId); frontendState.checkJobOwner("finishTaskInError", frontendState.getIdentifiedJob(jobIdObject), "You do not have permission to finish this task!"); frontendState.checkPermissions("finishTaskInError", frontendState.getIdentifiedJob(jobIdObject), YOU_DO_NOT_HAVE_PERMISSION_TO_FINISH_THIS_TASK); return schedulingService.finishInErrorTask(jobIdObject, taskName); }
Source:
<code>public String attemptRequest() throws RemoteServiceException { evaluateState(); if (state == State.OPEN) { <START> return "This is stale response from API"; <END> } else { try { var response = service.call(); recordSuccess(); return response; } catch (RemoteServiceException ex) { recordFailure(); throw ex; } } }</code><technical_language>Instead of hard coded string, cache response return it</technical_language>

Target:
public String attemptRequest() throws RemoteServiceException { evaluateState(); if (state == State.OPEN) { return this.lastFailureResponse; } else { try { var response = service.call(); recordSuccess(); return response; } catch (RemoteServiceException ex) { recordFailure(ex.getMessage()); throw ex; } } }
Source:
<code>public void writeContent(Content content) { if (content instanceof Brand) { contentWriter.createOrUpdate((Brand) content); } else if (content instanceof Series) { contentWriter.createOrUpdate((Series) content); } else if (content instanceof Episode) { contentWriter.createOrUpdate((Episode) content); } else if (content instanceof Film) { contentWriter.createOrUpdate((Film) content); } else if (content instanceof Item) { contentWriter.createOrUpdate((Item) content); <START> } <END> }</code><technical_language>worth exploding fail fast</technical_language>

Target:
public void writeContent(Content content) { if (content instanceof Brand) { contentWriter.createOrUpdate((Brand) content); } else if (content instanceof Series) { contentWriter.createOrUpdate((Series) content); } else if (content instanceof Episode) { contentWriter.createOrUpdate((Episode) content); } else if (content instanceof Film) { contentWriter.createOrUpdate((Film) content); } else if (content instanceof Item) { contentWriter.createOrUpdate((Item) content); } else { throw new RuntimeException("Unexpected instance type: " + content.getClass().getName()); } }
Source:
<code><START> @Override protected void afterTest() { <END> stopAllGrids(); }</code><technical_language>Missing super method invocation</technical_language>

Target:
@Override protected void afterTest() throws Exception { stopAllGrids(); super.afterTest(); }
Source:
<code>public void handleBackupWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { <START> if (!walletLock.isWalletLocked(wallet)) { <END> handleBackupWallet(); } } }); return; } if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) showBackupWalletDialog = true; else ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_BACKUP_WALLET); }</code><technical_language>this line is removed: BackupWalletDialogFragment.show(getSupportFragmentManager()); backup dialog is shown onResume() is called</technical_language>

Target:
public void handleBackupWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { handleBackupWallet(); } } }); return; } if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) BackupWalletDialogFragment.show(getSupportFragmentManager()); else ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_BACKUP_WALLET); }
Source:
<code>public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); <START> JsonSerializerProviders.createInstance().serialize(outputStream, data); <END> return new BinaryData(outputStream.toByteArray()); }</code><technical_language>@JonathanGiles, @srnagar, create a guideline default serializer passed. In some locations JsonSerializer/ObjectSerializer in others default JacksonAdapter. I a feeling need route of falling JacksonAdapter, serialization formats previously support Avro Protobuf, JsonSerializerProviders.createInstance result in customer applications throwing exception previously didn't. This restriction apply logic in azure-core accept ObjectSerializer/JsonSerializer a dependency implementation libraries</technical_language>

Target:
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
Source:
<code>private void addRecentPage(int page, boolean shouldDelete) { ContentValues contentValues = new ContentValues(); contentValues.put(LastPagesTable.PAGE, page); <START> contentValues.put(LastPagesTable.ADDED_DATE, System.currentTimeMillis() / 1000); <END> if (db.replace(LastPagesTable.TABLE_NAME, null, contentValues) != -1 && shouldDelete) { db.execSQL("DELETE FROM " + LastPagesTable.TABLE_NAME + " WHERE " + LastPagesTable.ID + " NOT IN( SELECT " + LastPagesTable.ID + " FROM " + LastPagesTable.TABLE_NAME + " ORDER BY " + LastPagesTable.ADDED_DATE + " DESC LIMIT ? )", new Object[] { Constants.MAX_RECENT_PAGES }); } }</code><technical_language>necessary - defaults TIMESTAMP DEFAULT CURRENT_TIMESTAMP</technical_language>

Target:
private void addRecentPage(int page, boolean shouldDelete) { ContentValues contentValues = new ContentValues(); contentValues.put(LastPagesTable.PAGE, page); if (db.replace(LastPagesTable.TABLE_NAME, null, contentValues) != -1 && shouldDelete) { db.execSQL("DELETE FROM " + LastPagesTable.TABLE_NAME + " WHERE " + LastPagesTable.ID + " NOT IN( SELECT " + LastPagesTable.ID + " FROM " + LastPagesTable.TABLE_NAME + " ORDER BY " + LastPagesTable.ADDED_DATE + " DESC LIMIT ? )", new Object[] { Constants.MAX_RECENT_PAGES }); } }
Source:
<code>public void start() { queueModeHelper.initialize(); <START> queueModeHelper.createServer((int) queueModeHelper.awaketime * 1000); <END> queueModeHelper.server.start(); queueModeHelper.createClient(); }</code><technical_language>I store awaketime attribute of this class remove if queueModelHelper</technical_language>

Target:
public void start() { queueModeHelper.initialize(); queueModeHelper.createServer((int) awaketime * 1000); queueModeHelper.server.start(); queueModeHelper.createClient(); }
Source:
<code>public void testGetDocContent_excludedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar", "filenet.excludedMetadata", "bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), <START> mockProperty("bar", "barValue")), <END> new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata(ImmutableMap.of("foo", "fooValue").entrySet()), response.getMetadata()); }</code><technical_language>include a baz here, too</technical_language>

Target:
public void testGetDocContent_excludedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar", "filenet.excludedMetadata", "bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), mockProperty("bar", "barValue"), mockProperty("baz", "bazValue")), new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata(ImmutableMap.of("foo", "fooValue").entrySet()), response.getMetadata()); }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || !(o instanceof RyaType)) { return false; } final RyaType ryaType = (RyaType) o; if (data != null ? !data.equals(ryaType.data) : ryaType.data != null) { return false; } <START> return dataType != null ? dataType.equals(ryaType.dataType) : ryaType.dataType == null; <END> }</code><technical_language>While in here, equals() method EqualsBuilder inline-if's removed: public boolean equals(final Object o) { if (o == this) { return true; } if (o == null || !(o instanceof RyaType)) { return false; } final RyaType other = (RyaType) o; final EqualsBuilder builder = new EqualsBuilder() .append(getData(), other.getData()) .append(getDataType(), other.getDataType()); return builder.isEquals(); }</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || !(o instanceof RyaType)) { return false; } final RyaType other = (RyaType) o; final EqualsBuilder builder = new EqualsBuilder() .append(getData(), other.getData()) .append(getDataType(), other.getDataType()); return builder.isEquals(); }
Source:
<code>private boolean sortToRelationshipGroups(SnomedConcepts referencedComponents, String relationshipTypeId) { Map<Integer, Integer> groupsAndCounts = Maps.newHashMap(); <START> AtomicBoolean occoursAsUngrouped = new AtomicBoolean(false); <END> AtomicBoolean noOccurance = new AtomicBoolean(false); referencedComponents.getItems().stream() .forEach(concept -> { AtomicInteger i = new AtomicInteger(); concept.getRelationships().getItems().stream() .filter(relationship -> relationship.getType().getId().equals(relationshipTypeId)) .forEach(relationship -> { if (relationship.getGroup() == 0) { occoursAsUngrouped.set(true); } else { groupsAndCounts.merge(relationship.getGroup(), 1, (key, oldValue) -> oldValue + 1 ); } i.incrementAndGet(); }); if (i.get() == 1) { noOccurance.set(true); } groupsAndCounts.entrySet().stream().forEach(entry -> { groupedRelationships.compute(entry.getKey(), (key, oldValue) -> { LinkedHashMap<String, Integer> relationshipTypeOccurence = ofNullable(oldValue).orElseGet(LinkedHashMap::new); relationshipTypeOccurence.merge(relationshipTypeId, entry.getValue(), (innerKey, innerOldValue) -> Math.max(innerOldValue, entry.getValue())); return relationshipTypeOccurence; }); }); } ); return occoursAsUngrouped.get() || noOccurance.get(); }</code><technical_language>(Occurs, occurrence, if get fancy, coccurrence in UK dialects.)</technical_language>

Target:
private boolean sortToRelationshipGroups(SnomedConcepts referencedComponents, String relationshipTypeId) { Map<Integer, Integer> groupsAndCounts = Maps.newHashMap(); AtomicBoolean occursAsUngrouped = new AtomicBoolean(false); AtomicBoolean noOccurance = new AtomicBoolean(false); referencedComponents.getItems().stream() .forEach(concept -> { AtomicInteger i = new AtomicInteger(); concept.getRelationships().getItems().stream() .filter(relationship -> relationship.getType().getId().equals(relationshipTypeId)) .forEach(relationship -> { if (relationship.getGroup() == 0) { occursAsUngrouped.set(true); } else { groupsAndCounts.merge(relationship.getGroup(), 1, (key, oldValue) -> oldValue + 1 ); } i.incrementAndGet(); }); if (i.get() == 1) { noOccurance.set(true); } groupsAndCounts.entrySet().stream().forEach(entry -> { groupedRelationships.compute(entry.getKey(), (key, oldValue) -> { LinkedHashMap<String, Integer> relationshipTypeOccurence = ofNullable(oldValue).orElseGet(LinkedHashMap::new); relationshipTypeOccurence.merge(relationshipTypeId, entry.getValue(), (innerKey, innerOldValue) -> Math.max(innerOldValue, entry.getValue())); return relationshipTypeOccurence; }); }); } ); return occursAsUngrouped.get() || noOccurance.get(); }
Source:
<code>public static Principal[] getGrantedRoles(SecurityIdentity securityIdentity) { Set<String> roles = new HashSet<>(); for (String s : securityIdentity.getRoles("ejb")) { roles.add(s); } List<Principal> list = new ArrayList<>(); Function<String, Principal> mapper = roleName -> (Principal) () -> roleName; for (String role : roles) { Principal principal = mapper.apply(role); list.add(principal); } <START> return list.toArray(new Principal[0]); <END> }</code><technical_language>This is a throw-away array allocation might, class name, hot request path</technical_language>

Target:
public static Principal[] getGrantedRoles(SecurityIdentity securityIdentity) { Set<String> roles = new HashSet<>(); for (String s : securityIdentity.getRoles("ejb")) { roles.add(s); } List<Principal> list = new ArrayList<>(); Function<String, Principal> mapper = roleName -> (Principal) () -> roleName; for (String role : roles) { Principal principal = mapper.apply(role); list.add(principal); } return list.toArray(NO_PRINCIPALS); }
Source:
<code>public final void testSessionVariables() throws IOException, TajoException, InterruptedException { String prefixName = "key_"; String prefixValue = "val_"; List<String> unsetList = client.getAllSessionVariables().entrySet().stream() <START> .map(Map.Entry<String, String>::getKey).collect(Collectors.toList()); <END> client.unsetSessionVariables(unsetList); for (int i = 0; i < 10; i++) { String key = prefixName + i; String val = prefixValue + i; assertEquals(i + 4, client.getAllSessionVariables().size()); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); Map<String, String> map = Maps.newHashMap(); map.put(key, val); client.updateSessionVariables(map); assertEquals(i + 5, client.getAllSessionVariables().size()); assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); } int totalSessionVarNum = client.getAllSessionVariables().size(); for (int i = 0; i < 10; i++) { String key = prefixName + i; assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); client.unsetSessionVariables(Lists.newArrayList(key)); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); } assertEquals(totalSessionVarNum - 10, client.getAllSessionVariables().size()); }</code><technical_language>I next is more readable: java List<String> unsetList = new ArrayList<>(client.getAllSessionVariables().keySet());</technical_language>

Target:
public final void testSessionVariables() throws IOException, TajoException, InterruptedException { String prefixName = "key_"; String prefixValue = "val_"; List<String> unsetList = new ArrayList<>(client.getAllSessionVariables().keySet()); client.unsetSessionVariables(unsetList); for (int i = 0; i < 10; i++) { String key = prefixName + i; String val = prefixValue + i; assertEquals(i + 4, client.getAllSessionVariables().size()); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); Map<String, String> map = Maps.newHashMap(); map.put(key, val); client.updateSessionVariables(map); assertEquals(i + 5, client.getAllSessionVariables().size()); assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); } int totalSessionVarNum = client.getAllSessionVariables().size(); for (int i = 0; i < 10; i++) { String key = prefixName + i; assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); client.unsetSessionVariables(Lists.newArrayList(key)); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); } assertEquals(totalSessionVarNum - 10, client.getAllSessionVariables().size()); }
Source:
<code>public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { if (certificateVerifier == null) { <START> AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, <END> session.getPeer()); throw new HandshakeException("Certificate chain could not be validated", alert); } certificateVerifier.verifyCertificate(message, session); } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }</code><technical_language>certificateVerifier is a bug side ? launch a BAD_CERTIFICATE error ? internal error more</technical_language>

Target:
public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { certificateVerifier.verifyCertificate(message, session); } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }
Source:
<code>public List<Concept> get(String targetTable, String targetField) { <START> if (!this.containsKey(targetTable, targetField)) { <END> return null; } return this.conceptMap.get(targetTable).get(targetField); }</code><technical_language>alternative implementation of method: java return conceptMap.getOrDefault(targetTable, Collections.emptyMap()).get(targetField);</technical_language>

Target:
public List<Concept> get(String targetTable, String targetField) { return conceptMap.getOrDefault(targetTable, Collections.emptyMap()).get(targetField); }
Source:
<code><START> ClusteredStateRepository(ClusteringService.ClusteredCacheIdentifier clusterCacheIdentifier, String id, EhcacheClientEntity clientEntity) { <END> this.clusterCacheIdentifier = clusterCacheIdentifier; this.clientEntity = clientEntity; }</code><technical_language>Do id more</technical_language>

Target:
ClusteredStateRepository(ClusteringService.ClusteredCacheIdentifier clusterCacheIdentifier, String id, EhcacheClientEntity clientEntity) { this.clusterCacheIdentifier = clusterCacheIdentifier; this.composedId = clusterCacheIdentifier.getId() + "-" + id; this.clientEntity = clientEntity; }
Source:
<code>public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override <START> public boolean apply(@Nullable Location input) { <END> return Objects.equal(input.getId(), val); } }; }</code><technical_language>input is @Nullable, remove annotation add null check</technical_language>

Target:
public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getId(), val); } }; }
Source:
<code>public Object processInvocation(final InterceptorContext context) throws Exception { <START> latch.countDown(); <END> return context.proceed(); }</code><technical_language>This counts bean is initialised</technical_language>

Target:
public Object processInvocation(final InterceptorContext context) throws Exception { countdown.markAsPrivileged(); try { return context.proceed(); } finally { countdown.unmarkAsPrivileged(); countdown.countDown(); } }
Source:
<code><START> public Boolean verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { <END> return withContext(context -> client.verify(algorithm, digest, signature, context)).block(); }</code><technical_language>Boolean [](start = 11, length = 7) VerifyResult property isValid</technical_language>

Target:
public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); }
Source:
<code>public void addAssetSource(AssetSource newSource) { String idKey = newSource.getSourceId().toLowerCase(Locale.ENGLISH); AssetSource originalSource = assetSources.get(idKey); if (null == originalSource) { assetSources.put(idKey, newSource); for (AssetUri asset : newSource.list()) { uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } } else { AssetSourceCollection combinedSource = new AssetSourceCollection(idKey, originalSource, newSource); assetSources.put(idKey, combinedSource); <START> for (AssetUri asset : newSource.list()) { <END> uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } } }</code><technical_language>This if-else</technical_language>

Target:
public void addAssetSource(AssetSource newSource) { String idKey = newSource.getSourceId().toLowerCase(Locale.ENGLISH); AssetSource originalSource = assetSources.get(idKey); if (null == originalSource) { assetSources.put(idKey, newSource); } else { AssetSourceCollection combinedSource = new AssetSourceCollection(idKey, originalSource, newSource); assetSources.put(idKey, combinedSource); } for (AssetUri asset : newSource.list()) { uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } }
Source:
<code>public void addFieldsFromClient(SolrClient client) { if (client == null) { LOGGER.debug("Solr client is null, could not add fields to cache."); return; } SolrQuery query = new SolrQuery(); query.add("numterms", "0"); query.setRequestHandler("/admin/luke"); try { QueryResponse response = client.query(query); NamedList<?> fields = (SimpleOrderedMap<?>) (response.getResponse().get(FIELDS_KEY)); <START> if (fields != null) { <END> for (Entry<String, ?> e : fields) { if (e != null) { fieldsCache.add(e.getKey()); if (e.getKey().endsWith(SchemaFields.TEXT_SUFFIX)) { anyTextFieldsCache.add(e.getKey()); } } } } } catch (SolrServerException | SolrException | IOException e) { LOGGER.info("Could not update cache for field names.", e); } }</code><technical_language>return if fields== null instead of nesting for loop</technical_language>

Target:
public void addFieldsFromClient(SolrClient client) { if (client == null) { LOGGER.debug("Solr client is null, could not add fields to cache."); return; } SolrQuery query = new SolrQuery(); query.add("numterms", "0"); query.setRequestHandler("/admin/luke"); QueryResponse response; try { response = client.query(query); } catch (SolrServerException | SolrException | IOException e) { LOGGER.info("Could not update cache for field names.", e); return; } NamedList<?> fields = (SimpleOrderedMap<?>) (response.getResponse().get(FIELDS_KEY)); if (fields == null) { return; } for (Entry<String, ?> e : fields) { String key = e.getKey(); fieldsCache.add(key); if (key.endsWith(SchemaFields.TEXT_SUFFIX)) { anyTextFieldsCache.add(key); } } }
Source:
<code>public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(1), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("max(1, ?) > 1", BigDecimal.valueOf(2), BigDecimal.class)); <START> assertTrue(expressionEvaluator.evaluateUnaryExpression("? = 2", BigDecimal.valueOf(2), BigDecimal.class)); <END> assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); }</code><technical_language>I meant : assertTrue(expressionEvaluator.evaluateUnaryExpression("? = 1*?", BigDecimal.valueOf(2), BigDecimal.class));</technical_language>

Target:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(1), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(-1), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("max(1, ?) > 1", BigDecimal.valueOf(2), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("max(1, ?) < 1", BigDecimal.valueOf(2), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("? = 2", BigDecimal.valueOf(2), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("? > 2", BigDecimal.valueOf(2), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("? + 1 > ?", BigDecimal.valueOf(2), BigDecimal.class)); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("? > 2", null, BigDecimal.class)) .isInstanceOf(NullPointerException.class); }
Source:
<code>public FailoverFeignTarget(Collection<String> servers, Class<T> type, BackoffStrategy backoffStrategy) { <START> this.servers = ImmutableList.copyOf(servers); <END> this.type = type; this.backoffStrategy = backoffStrategy; }</code><technical_language>do worth shuffling server list if servers start ordered list choose 0th server (and force load place)</technical_language>

Target:
public FailoverFeignTarget(Collection<String> servers, Class<T> type, BackoffStrategy backoffStrategy) { List<String> shuffledServers = new ArrayList<>(servers); Collections.shuffle(shuffledServers); this.servers = ImmutableList.copyOf(shuffledServers); this.type = type; this.backoffStrategy = backoffStrategy; }
Source:
<code><START> public void stop() throws Exception { <END> }</code><technical_language>please, for completeness.. call stop(true); (after method name change I asked you)</technical_language>

Target:
public void stop() throws Exception { stop(false); }
Source:
<code>public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { <START> ThriftIndexHandle thriftIndexHandle = (ThriftIndexHandle) indexHandle; <END> return new ThriftConnectorIndex(clientProvider, thriftIndexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }</code><technical_language>inline this</technical_language>

Target:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { return new ThriftConnectorIndex(clientProvider, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }
Source:
<code>public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) { Map<String, BinderType> binderTypes = new HashMap<>(); ClassLoader classLoader = configurableApplicationContext.getClassLoader(); if (classLoader == null) { classLoader = BinderFactoryConfiguration.class.getClassLoader(); } try { Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders"); if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) { throw new BeanCreationException("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath"); } while (resources.hasMoreElements()) { URL url = resources.nextElement(); UrlResource resource = new UrlResource(url); for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) { <START> if (!binderType.getDefaultName().equalsIgnoreCase("test")) { <END> binderTypes.put(binderType.getDefaultName(), binderType); } } } } catch (IOException | ClassNotFoundException e) { throw new BeanCreationException("Cannot create binder factory:", e); } return new DefaultBinderTypeRegistry(binderTypes); }</code><technical_language>rely a hardcoded binder name here</technical_language>

Target:
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) { Map<String, BinderType> binderTypes = new HashMap<>(); ClassLoader classLoader = configurableApplicationContext.getClassLoader(); if (classLoader == null) { classLoader = BinderFactoryConfiguration.class.getClassLoader(); } try { Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders"); if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) { throw new BeanCreationException("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath"); } while (resources.hasMoreElements()) { URL url = resources.nextElement(); UrlResource resource = new UrlResource(url); for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) { binderTypes.put(binderType.getDefaultName(), binderType); } } } catch (IOException | ClassNotFoundException e) { throw new BeanCreationException("Cannot create binder factory:", e); } return new DefaultBinderTypeRegistry(binderTypes); }
Source:
<code>public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } <START> if (labelHandle > 0 && OS.GTK_IS_LABEL (labelHandle)) { <END> OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }</code><technical_language>Style: Y u change '!=' '>' :-/</technical_language>

Target:
public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } if (labelHandle != 0 && OS.GTK_IS_LABEL (labelHandle)) { OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }
Source:
<code>List<ServiceIntegrationView> getAvailableDescriptorViews(final User user) throws DotSecurityException, DotDataException { final ImmutableList.Builder<ServiceIntegrationView> viewsBuilder = new ImmutableList.Builder<>(); final List<ServiceDescriptor> serviceDescriptors = serviceIntegrationAPI .getAvailableServiceDescriptors(user); <START> final List<Host> hosts = hostAPI.findAll(user, false); <END> for (final ServiceDescriptor serviceDescriptor : serviceDescriptors) { final String serviceKey = serviceDescriptor.getServiceKey(); final long configurationsCount = computeHostsWithConfigurations(serviceKey, hosts, user).size(); viewsBuilder.add(new ServiceIntegrationView(serviceDescriptor, configurationsCount)); } return viewsBuilder.build(); }</code><technical_language>Do need get configurations for Integration Service listing?, resource is this method return existing services I guess listing portlet, I needs get data for hosts, need basic service data in for listing</technical_language>

Target:
List<ServiceIntegrationView> getAvailableDescriptorViews(final User user) throws DotSecurityException, DotDataException { final List<ServiceIntegrationView> views = new ArrayList<>(); final List<ServiceDescriptor> serviceDescriptors = serviceIntegrationAPI.getServiceDescriptors(user); final List<Host> hosts = getHosts(user); for (final ServiceDescriptor serviceDescriptor : serviceDescriptors) { final String serviceKey = serviceDescriptor.getKey(); final long configurationsCount = computeSitesWithConfigurations(serviceKey, hosts, user).size(); views.add(new ServiceIntegrationView(serviceDescriptor, configurationsCount)); } return views.stream().sorted(compareByCountAndName).collect(CollectionsUtils.toImmutableList()); }
Source:
<code>private List<ElementTag> getCourseIdOptions(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession) { ArrayList<ElementTag> result = new ArrayList<ElementTag>(); for (CourseAttributes course : courses) { boolean isFilledFormForSessionInThisCourse = newFeedbackSession != null && course.id.equals(newFeedbackSession.courseId); boolean isEmptyFormForSessionInThisCourse = courseIdForNewSession != null && course.id.equals(courseIdForNewSession); if (instructors.get(course.id).isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION)) { ElementTag option = createOption(course.id, course.id, (isFilledFormForSessionInThisCourse || isEmptyFormForSessionInThisCourse)); result.add(option); } } ElementTag defaultOption; if (result.isEmpty() && !courses.isEmpty()) { defaultOption = createOption("No permission to modify courses!", "", true); result.add(defaultOption); <START> } if (result.isEmpty()) { <END> defaultOption = createOption("No active courses!", "", true); result.add(defaultOption); } return result; }</code><technical_language>behaviour's same, is supposed a newline else here? said, this represented a nested if for courses empty check. Also, if do intend this other option, do provide a more accurate message. lack of permission modify courses' sessions, courses themselves. I do if a single message for cases, though, "No usable courses found!". instructor capabilities in case. This a new issue</technical_language>

Target:
private List<ElementTag> getCourseIdOptions(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession) { ArrayList<ElementTag> result = new ArrayList<ElementTag>(); for (CourseAttributes course : courses) { boolean isFilledFormForSessionInThisCourse = newFeedbackSession != null && course.id.equals(newFeedbackSession.courseId); boolean isEmptyFormForSessionInThisCourse = courseIdForNewSession != null && course.id.equals(courseIdForNewSession); if (instructors.get(course.id).isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION)) { ElementTag option = createOption(course.id, course.id, (isFilledFormForSessionInThisCourse || isEmptyFormForSessionInThisCourse)); result.add(option); } } return result; }
Source:
<code>public StatementMetadata(byte[] value) throws RdfDAOException { <START> super(); <END> try { if (value == null) { metadataMap = new HashMap<>(); } else { String metadataString = new String(value, "UTF8"); metadataMap = gson.fromJson(metadataString, type); if (metadataMap == null) { metadataMap = new HashMap<>(); } } } catch (UnsupportedEncodingException e) { throw new RdfDAOException(e); } }</code><technical_language>whats super class here</technical_language>

Target:
public StatementMetadata(byte[] value) throws RdfDAOException { try { if (value == null) { metadataMap = new HashMap<>(); } else { String metadataString = new String(value, "UTF8"); metadataMap = gson.fromJson(metadataString, type); if (metadataMap == null) { metadataMap = new HashMap<>(); } } } catch (UnsupportedEncodingException e) { throw new RdfDAOException(e); } }