auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public DRepresentationDescriptor getRepresentationDescriptor() { DRepresentationDescriptor result = null; if (representation instanceof DSemanticDecorator) { if (session == null) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) representation).getTarget()); } if (session != null) { Collection<EStructuralFeature.Setting> usages = session.getSemanticCrossReferencer().getInverseReferences(representation); for (EStructuralFeature.Setting setting : usages) { if (ViewpointPackage.Literals.DREPRESENTATION_DESCRIPTOR.isInstance(setting.getEObject()) && setting.getEStructuralFeature() == ViewpointPackage.Literals.DREPRESENTATION_DESCRIPTOR__REPRESENTATION) { <START> result = (DRepresentationDescriptor) setting.getEObject(); <END> } } if (result == null) { EObject eObject = session.getAllSessionResources().iterator().next().getContents().get(0); if (eObject instanceof DAnalysis) { EList<DView> ownedViews = ((DAnalysis) eObject).getOwnedViews(); for (DView view : ownedViews) { EList<DRepresentationDescriptor> ownedRepresentationDescriptors = view.getOwnedRepresentationDescriptors(); for (DRepresentationDescriptor descriptor : ownedRepresentationDescriptors) { DRepresentation representationTemp = descriptor.getRepresentation(); if (representation.equals(representationTemp)) { result = descriptor; break; } } } } } } } return result; }</code><technical_language>add a break instruction stop iteration soon find valid</technical_language>

Target:
public DRepresentationDescriptor getRepresentationDescriptor() { DRepresentationDescriptor result = null; if (representation instanceof DSemanticDecorator) { if (session == null) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) representation).getTarget()); } if (session != null) { result = findDescriptorFromCrossReferencer(); if (result == null) { result = findDescriptorFromAnalysis(); } } } return result; }
Source:
<code>public void testAddMessageWillWaitWhenCapacityIsFull() throws InterruptedException { AddMessage addMessage = new AddMessage(); new Thread(addMessage).start(); assertThat("Should never exceed capacity", list.size(), lessThanOrEqualTo(capacity)); long wait = 500; Thread.sleep(wait); list.completeMessage(p1); <START> Thread.sleep(100); <END> assertThat("Should never exceed capacity", list.size(), lessThanOrEqualTo(capacity)); long elapse = addMessage.end - addMessage.start; assertThat("Should have waited message to be completed", elapse, greaterThan(wait)); }</code><technical_language>sleep() is unavoidable, replace this a join() AddMessage thread</technical_language>

Target:
public void testAddMessageWillWaitWhenCapacityIsFull() throws InterruptedException { AddMessage addMessage = new AddMessage(); Thread add = new Thread(addMessage); add.start(); assertThat("Should never exceed capacity", list.size(), is(capacity)); long wait = 500; Thread.sleep(wait); list.completeMessage(p1); add.join(); assertThat("Should never exceed capacity", list.size(), is(capacity)); long elapse = addMessage.end - addMessage.start; assertThat("Should have waited message to be completed", elapse, greaterThanOrEqualTo(wait)); }
Source:
<code>protected void executeCommand() { <START> if (isUnregisteredDiskExists()) { <END> addDiskMapping(); return; } MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { ImagesHandler.addDiskImageWithNoVmDevice(getImage()); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }</code><technical_language>validate() method updated support case, for example, space target domain checked (we fail it)</technical_language>

Target:
protected void executeCommand() { if (isUnregisteredDiskExistsForCopyTemplate()) { addDiskMapping(); return; } MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { ImagesHandler.addDiskImageWithNoVmDevice(getImage()); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }
Source:
<code>public void testMigrateCreateRequest() throws Exception { Result result = mock(Result.class); Metacard workspace = getWorkspaceMetacard("workspaceId"); <START> doReturn(workspace).when(result).getMetacard(); <END> doReturn(Collections.singletonList(result)).when(queryResponse).getResults(); ArgumentCaptor<CreateRequest> createRequestArgumentCaptor = ArgumentCaptor.forClass(CreateRequest.class); workspaceQueryMigration.migrateWorkspaces(); verify(catalogFramework, times(1)).create(createRequestArgumentCaptor.capture()); CreateRequest actualCreateRequest = createRequestArgumentCaptor.getValue(); List<Metacard> createMetacards = actualCreateRequest.getMetacards(); assertThat(createMetacards, hasSize(2)); assertThat(createMetacards.get(0).getTags(), is(ImmutableSet.of("query"))); assertThat(createMetacards.get(1).getTags(), is(ImmutableSet.of("query"))); }</code><technical_language>this extracted</technical_language>

Target:
public void testMigrateCreateRequest() throws Exception { ArgumentCaptor<CreateRequest> createRequestArgumentCaptor = ArgumentCaptor.forClass(CreateRequest.class); workspaceQueryMigration.migrate(); verify(catalogFramework, times(1)).create(createRequestArgumentCaptor.capture()); CreateRequest actualCreateRequest = createRequestArgumentCaptor.getValue(); List<Metacard> createMetacards = actualCreateRequest.getMetacards(); assertThat(createMetacards, hasSize(2)); assertThat(createMetacards.get(0).getTags(), is(ImmutableSet.of("query"))); assertThat(createMetacards.get(1).getTags(), is(ImmutableSet.of("query"))); }
Source:
<code>public void killOlderThan(long timestamp) throws IOException { log.info("Deleting all task logs from Azure storage location [bucket: '%s' prefix: '%s'] older than %s.", config.getContainer(), config.getPrefix(), new Date(timestamp) ); try { AzureUtils.deleteObjectsInPath( azureStorage, inputDataConfig, accountConfig, azureCloudBlobIterableFactory, config.getContainer(), config.getPrefix(), (object) -> object.getLastModifed().getTime() < timestamp ); } catch (Exception e) { <START> log.error("Error occurred while deleting task log files from s3. Error: %s", e.getMessage()); <END> throw new IOException(e); } }</code><technical_language>wrong cloud suggestion log.error("Error occurred while deleting task log files Azure. Error: %s", e.getMessage());</technical_language>

Target:
public void killOlderThan(long timestamp) throws IOException { log.info( "Deleting all task logs from Azure storage location [bucket: '%s' prefix: '%s'] older than %s.", config.getContainer(), config.getPrefix(), new Date(timestamp) ); try { AzureUtils.deleteObjectsInPath( azureStorage, inputDataConfig, accountConfig, azureCloudBlobIterableFactory, config.getContainer(), config.getPrefix(), (object) -> object.getLastModifed().getTime() < timestamp ); } catch (Exception e) { log.error("Error occurred while deleting task log files from Azure. Error: %s", e.getMessage()); throw new IOException(e); } }
Source:
<code>private static Quantity safeGet(Container parent, Container template, Function<ResourceRequirements, Map<String, Quantity>> resourceTypeMapper, String field) { Quantity templateField = resourceTypeMapper.apply(template.getResources()).get(field); <START> if (templateField != null && !Strings.isNullOrEmpty(templateField.getAmount())) { <END> return templateField; } else { return (parent.getResources() != null) && (resourceTypeMapper.apply(parent.getResources()) != null) ? resourceTypeMapper.apply(parent.getResources()).get(field) : new Quantity(""); } }</code><technical_language>clearer Optional.ofNullable in <LINK_0></technical_language>

Target:
private static Quantity safeGet(Container parent, Container template, Function<ResourceRequirements, Map<String, Quantity>> resourceTypeMapper, String field) { return Optional.ofNullable(template.getResources()) .map(resourceTypeMapper) .map(rT -> rT.get(field)) .filter(tF -> !Strings.isNullOrEmpty(tF.getAmount())) .orElse(Optional.ofNullable(parent.getResources()) .map(resourceTypeMapper) .map(rT -> rT.get(field)) .orElse(new Quantity("")) ); }
Source:
<code>public FastaReferenceWriter build() throws IOException { if (fastaFile == null && fastaOutput == null) { throw new IllegalArgumentException("Both fastaFile and fastaOutput were null. Please set one of them to be non-null."); } if (indexFile == null && indexOutput == null) { indexFile = defaultFaiFile(makeFaiOutput, fastaFile); } <START> if (dictFile == null && dictOutput == null) { <END> dictFile = defaultDictFile(makeDictOutput, fastaFile); } checkBasesPerLine(basesPerLine); if (fastaFile != null) { fastaOutput = Files.newOutputStream(fastaFile); } if (indexFile != null) { indexOutput = Files.newOutputStream(indexFile); } if (dictFile != null) { dictOutput = Files.newOutputStream(dictFile); } return new FastaReferenceWriter(basesPerLine, fastaOutput, indexOutput, dictOutput); }</code><technical_language>I detect error in case more of is / if is set output</technical_language>

Target:
public FastaReferenceWriter build() throws IOException { if (fastaFile == null && fastaOutput == null) { throw new IllegalArgumentException("Both fastaFile and fastaOutput were null. Please set one of them to be non-null."); } if(fastaFile != null) { if (indexFile == null && indexOutput == null) { indexFile = defaultFaiFile(makeFaiOutput, fastaFile); } else if (indexFile != null && indexOutput != null) { throw new IllegalArgumentException("Both indexFile and indexOutput were non-null. Please set one of them to be null."); } if (dictFile == null && dictOutput == null) { dictFile = defaultDictFile(makeDictOutput, fastaFile); } else if (dictFile != null && dictOutput != null) { throw new IllegalArgumentException("Both dictFile and dictOutput were non-null. Please set one of them to be null."); } } checkBasesPerLine(basesPerLine); if (fastaFile != null) { fastaOutput = Files.newOutputStream(fastaFile); } if (indexFile != null) { indexOutput = Files.newOutputStream(indexFile); } if (dictFile != null) { dictOutput = Files.newOutputStream(dictFile); } return new FastaReferenceWriter(basesPerLine, fastaOutput, indexOutput, dictOutput); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { <START> if (Companion.getDEBUG()) Log.e(TAG, "onOptionsItemSelected"); <END> switch (item.getItemId()) { case R.id.search_submit: search(); break; case R.id.select_forums: SearchForumsFragment frag = new SearchForumsFragment(this); frag.setStyle(DialogFragment.STYLE_NO_TITLE,0); frag.show(getFragmentManager(), "searchforums"); break; case R.id.search_threadid: insertSearchTerm(SEARCHTERM.THREADID); break; case R.id.search_intitle: insertSearchTerm(SEARCHTERM.INTITLE); break; case R.id.search_userid: insertSearchTerm(SEARCHTERM.USERID); break; case R.id.search_quoting: insertSearchTerm(SEARCHTERM.QUOTING); break; case R.id.search_username: insertSearchTerm(SEARCHTERM.USERNAME); break; default: return super.onOptionsItemSelected(item); } return true; }</code><technical_language>Timberrr</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { Timber.v("onOptionsItemSelected"); switch (item.getItemId()) { case R.id.search_submit: search(); break; case R.id.select_forums: SearchForumsFragment frag = new SearchForumsFragment(this); frag.setStyle(DialogFragment.STYLE_NO_TITLE,0); frag.show(getFragmentManager(), "searchforums"); break; case R.id.search_threadid: insertSearchTerm(SEARCHTERM.THREADID); break; case R.id.search_intitle: insertSearchTerm(SEARCHTERM.INTITLE); break; case R.id.search_userid: insertSearchTerm(SEARCHTERM.USERID); break; case R.id.search_quoting: insertSearchTerm(SEARCHTERM.QUOTING); break; case R.id.search_username: insertSearchTerm(SEARCHTERM.USERNAME); break; default: return super.onOptionsItemSelected(item); } return true; }
Source:
<code>public void unannounceSegment(DataSegment segment) throws IOException { final String path = segmentLookup.get(segment.getIdentifier()); Set<DataSegment> zkSegments = segmentReader.read(path); zkSegments.remove(segment); log.info("Unannouncing segment[%s] at path[%s]", segment.getIdentifier(), path); if (zkSegments.isEmpty()) { announcer.unannounce(path); } else if (zkSegments.size() < config.getSegmentsPerNode()) { <START> zNodes.put(path, zkSegments.size()); <END> announcer.update(path, jsonMapper.writeValueAsBytes(zkSegments)); } }</code><technical_language>I storing size, anywhere</technical_language>

Target:
public void unannounceSegment(DataSegment segment) throws IOException { final SegmentZNode segmentZNode = segmentLookup.remove(segment); segmentZNode.removeSegment(segment); log.info("Unannouncing segment[%s] at path[%s]", segment.getIdentifier(), segmentZNode.getPath()); if (segmentZNode.getCount() == 0) { availableZNodes.remove(segmentZNode); announcer.unannounce(segmentZNode.getPath()); } else { announcer.update(segmentZNode.getPath(), segmentZNode.getBytes()); availableZNodes.add(segmentZNode); } }
Source:
<code>public int hashCode() { int hash = 7; hash = 73 * hash + this.getMeta(); hash = 73 * hash + this.getDimId(); <START> hash = 73 * hash + this.getPos().hashCode(); <END> hash = 73 * hash + (this.getNbt() != null ? this.getNbt().hashCode() : 0); hash = 73 * hash + (this.getRegistryName() != null ? this.getRegistryName().hashCode() : 0); return hash; }</code><technical_language>If change hashcode, compatibility</technical_language>

Target:
public int hashCode() { int hash = 7; hash = 73 * hash + this.getMeta(); hash = 73 * hash + this.getDimId(); hash = 73 * hash + this.getPos().hashCode(); hash = 73 * hash + this.getRegistryName().hashCode(); hash = 73 * hash + Objects.hashCode(this.getNbt()); return hash; }
Source:
<code>private AuthenticationResult tryRT() throws AuthenticationException { final String user = getUser(); final TokenCacheItem regularRTItem = mTokenCacheAccessor.getRegularTokenCacheItemWithAT(mAuthRequest.getResource(), <START> mAuthRequest.getClientId(), user); <END> if (regularRTItem == null) { Logger.v(TAG, "Regular token cache entry does not exist, try with MRRT."); return tryMRRT(); } if (regularRTItem.getIsMultiResourceRefreshToken() || isMRRTExisted()) { Logger.v(TAG, "Regular token cache entry exists but it's marked as MRRT, try with MRRT."); return tryMRRT(); } Logger.v(TAG, "Send request to use regular RT for new AT."); return acquireTokenWithCachedItem(regularRTItem); }</code><technical_language>getUser</technical_language>

Target:
private AuthenticationResult tryRT() throws AuthenticationException { final TokenCacheItem regularRTItem = mTokenCacheAccessor.getRegularRefreshTokenCacheItem(mAuthRequest.getResource(), mAuthRequest.getClientId(), mAuthRequest.getUserFromRequest()); if (regularRTItem == null) { Logger.v(TAG, "Regular token cache entry does not exist, try with MRRT."); return tryMRRT(); } if (regularRTItem.getIsMultiResourceRefreshToken() || isMRRTEntryExisted()) { final String statusMessage = regularRTItem.getIsMultiResourceRefreshToken() ? "Found RT and it's also a MRRT, retry with MRRT" : "RT is found and there is a MRRT entry existed, try with MRRT"; Logger.v(TAG, statusMessage); return tryMRRT(); } Logger.v(TAG, "Send request to use regular RT for new AT."); return acquireTokenWithCachedItem(regularRTItem); }
Source:
<code>public Collection<RelatedArticleView> getRelatedArticles(Article article) { List<ArticleRelationship> rawRelationships = article.getRelatedArticles(); List<RelatedArticleView> relatedArticleViews = Lists.newArrayListWithCapacity(rawRelationships.size()); for (ArticleRelationship rawRelationship : rawRelationships) { <START> if (rawRelationship.getOtherArticleID() == null) { continue; } END> String otherArticleDoi = rawRelationship.getOtherArticleDoi(); Article relatedArticle = (Article) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", otherArticleDoi)))); RelatedArticleView relatedArticleView = (relatedArticle == null) ? new RelatedArticleView(rawRelationship, null, null) : new RelatedArticleView(rawRelationship, relatedArticle.getTitle(), relatedArticle.getAuthors()); relatedArticleViews.add(relatedArticleView); } return relatedArticleViews; }</code><technical_language>update line 996</technical_language>

Target:
public Collection<RelatedArticleView> getRelatedArticles(Article article) { List<ArticleRelationship> rawRelationships = article.getRelatedArticles(); List<RelatedArticleView> relatedArticleViews = Lists.newArrayListWithCapacity(rawRelationships.size()); for (ArticleRelationship rawRelationship : rawRelationships) { if (rawRelationship.getOtherArticleID() == null) { continue; } String otherArticleDoi = rawRelationship.getOtherArticleDoi(); Article relatedArticle = (Article) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", otherArticleDoi)))); RelatedArticleView relatedArticleView = new RelatedArticleView(rawRelationship, relatedArticle.getTitle(), relatedArticle.getAuthors()); relatedArticleViews.add(relatedArticleView); } return relatedArticleViews; }
Source:
<code>protected String getDefaultDocumentTypeName() { <START> return "AFU"; <END> }</code><technical_language>doc type moved a constant in a constants file</technical_language>

Target:
protected String getDefaultDocumentTypeName() { return CuFPConstants.AccountFundsUpdateDocumentConstants.ACCOUNT_FUNDS_UPDATE_DOCUMENT_TYPE_NAME; }
Source:
<code>public boolean verifyCredential(final Object credential) throws RealmUnavailableException { try { if (credential instanceof char[]) { <START> final Password password = map.get(name).getPassword(); <END> return PasswordFactory.getInstance(password.getAlgorithm()).verify(password, (char[]) credential); } else if (credential instanceof ClearPassword) { final Password password = map.get(name).getPassword(); return PasswordFactory.getInstance(password.getAlgorithm()).verify(password, ((ClearPassword) credential).getPassword()); } else { return false; } } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RealmUnavailableException(e); } }</code><technical_language>NPE if map name; IMO local var extraction/null check remain</technical_language>

Target:
public boolean verifyCredential(final Object credential) throws RealmUnavailableException { try { SimpleRealmEntry entry = map.get(name); if (entry == null) { return false; } if (credential instanceof char[]) { final Password password = entry.getPassword(); return PasswordFactory.getInstance(password.getAlgorithm()).verify(password, (char[]) credential); } else if (credential instanceof ClearPassword) { final Password password = entry.getPassword(); return PasswordFactory.getInstance(password.getAlgorithm()).verify(password, ((ClearPassword) credential).getPassword()); } else { return false; } } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RealmUnavailableException(e); } }
Source:
<code>private static void validateEntityLabel(EntityType entityType) { String label = entityType.getLabel(); <START> if (label.isEmpty()) <END> { throw new MolgenisValidationException( new ConstraintViolation(format("Label of EntityType [%s] is empty", entityType.getId()))); } else if (label.trim().equals("")) { throw new MolgenisValidationException(new ConstraintViolation( format("Label of EntityType [%s] contains only white space", entityType.getId()))); } }</code><technical_language>I smell incoming NPE here..</technical_language>

Target:
private static void validateEntityLabel(EntityType entityType) { String label = entityType.getLabel(); if (label != null) { if (label.isEmpty()) { throw new MolgenisValidationException( new ConstraintViolation(format("Label of EntityType [%s] is empty", entityType.getId()))); } else if (label.trim().equals("")) { throw new MolgenisValidationException(new ConstraintViolation( format("Label of EntityType [%s] contains only white space", entityType.getId()))); } } }
Source:
<code>public Set<String> getChangedFieldsForStatus(VmStatic source, VmStatic destination, VmManagementParametersBase params, VMStatus status) { List<String> fields = updateVmsStatic.getChangedFieldsForStatus(source, destination, status); for (VmDeviceUpdate device : getVmDevicesFieldsToUpdateOnNextRun(source.getId(), status, params)) { if (!device.getName().isEmpty()) { fields.add(device.getName()); } else { switch (device.getType()) { case UNKNOWN: <START> case VIRTIO: <END> fields.add(device.getGeneralType().name()); break; default: fields.add(device.getType().getName()); break; } } } return new HashSet<>(fields); }</code><technical_language>this special case trivially fixed default</technical_language>

Target:
public Set<String> getChangedFieldsForStatus(VmStatic source, VmStatic destination, VmManagementParametersBase params, VMStatus status) { List<String> fields = updateVmsStatic.getChangedFieldsForStatus(source, destination, status); List<VmDeviceUpdate> devices = getVmDevicesFieldsToUpdateOnNextRun(source.getId(), status, params); fields.addAll(devices.stream().map(d -> d.getName()).collect(Collectors.toList())); return new HashSet<>(fields); }
Source:
<code>protected void decode(ChannelHandlerContext ctx, HttpRequest msg, List<Object> out) throws Exception { CharSequence acceptedEncoding; List<String> acceptEncodingHeaders = msg.headers().getAll(ACCEPT_ENCODING); if (acceptEncodingHeaders.isEmpty()) { acceptedEncoding = HttpContentDecoder.IDENTITY; } else if (acceptEncodingHeaders.size() == 1) { acceptedEncoding = acceptEncodingHeaders.get(0); } else { acceptedEncoding = StringUtil.join(",", acceptEncodingHeaders.iterator()); <START> } <END> HttpMethod method = msg.method(); if (HttpMethod.HEAD.equals(method)) { acceptedEncoding = ZERO_LENGTH_HEAD; } else if (HttpMethod.CONNECT.equals(method)) { acceptedEncoding = ZERO_LENGTH_CONNECT; } acceptEncodingQueue.add(acceptedEncoding); out.add(ReferenceCountUtil.retain(msg)); }</code><technical_language>nit: this: java switch (acceptedEncodingHeaders.size()) { case 0: acceptedEncoding = HttpContentDecoder.IDENTITY; break; case 1: acceptedEncoding = acceptEncodingHeaders.get(0); break; default: // Multiple message-header fields <LINK_0> acceptedEncoding = StringUtil.join(",", acceptEncodingHeaders.iterator()); break; }</technical_language>

Target:
protected void decode(ChannelHandlerContext ctx, HttpRequest msg, List<Object> out) throws Exception { CharSequence acceptEncoding; List<String> acceptEncodingHeaders = msg.headers().getAll(ACCEPT_ENCODING); switch (acceptEncodingHeaders.size()) { case 0: acceptEncoding = HttpContentDecoder.IDENTITY; break; case 1: acceptEncoding = acceptEncodingHeaders.get(0); break; default: acceptEncoding = StringUtil.join(",", acceptEncodingHeaders); break; } HttpMethod method = msg.method(); if (HttpMethod.HEAD.equals(method)) { acceptEncoding = ZERO_LENGTH_HEAD; } else if (HttpMethod.CONNECT.equals(method)) { acceptEncoding = ZERO_LENGTH_CONNECT; } acceptEncodingQueue.add(acceptEncoding); out.add(ReferenceCountUtil.retain(msg)); }
Source:
<code>public void stop() { executorService.shutdownNow(); try { executorService.awaitTermination(4, TimeUnit.SECONDS); <START> } catch (InterruptedException e) { <END> e.printStackTrace(); } }</code><technical_language>stop() method throw exception instead of catching printing</technical_language>

Target:
public void stop() throws InterruptedException { executorService.shutdown(); executorService.awaitTermination(4, TimeUnit.SECONDS); }
Source:
<code><START> public boolean delete(String name) { <END> Path file = generateFileName(name); return FileUtils.moveToDeleted(file, this.deletedDataDir); }</code><technical_language>renamed move</technical_language>

Target:
public boolean delete(String name) { Path file = generateFileName(name); return FileUtils.move(file, this.deletedDataDir); }
Source:
<code>private Boolean checkMatchpassword(String password, String password2) { <START> if (!password.equals(password2)) { return false; } else { return true; } <END> }</code><technical_language>single line for this..</technical_language>

Target:
private Boolean checkMatchpassword(String password, String password2) { return (password.equals(password2)); }
Source:
<code>protected JavaPackageInfoSource updateTypeNames(String name) { <START> throw new ParserException(); <END> }</code><technical_language>throw new UnsupportedOperationException()</technical_language>

Target:
protected JavaPackageInfoSource updateTypeNames(String name) { throw new UnsupportedOperationException("A package-info doesn't contain any types which can be updated"); }
Source:
<code>public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { <START> List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<>(); <END> if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; }</code><technical_language>a compilation issue here, new ArrayList<>() new ArrayList\<String\>()</technical_language>

Target:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<String>(); if (roles == null || roles.isEmpty()) { roles = new ArrayList<String>(); roles.add(""); } return roles; }
Source:
<code>public void addValues(String key, Collection<String> values) { if (values == null || values.size() == 0) return; String[] existingvals = md.get(key); if (existingvals == null) { md.put(key, values.toArray(new String[values.size()])); return; } <START> ArrayList<String> existing = new ArrayList<String>(existingvals.length); <END> for (String v : existingvals) existing.add(v); existing.addAll(values); md.put(key, existing.toArray(new String[existing.size()])); }</code><technical_language>existingVals.length + values.size()</technical_language>

Target:
public void addValues(String key, Collection<String> values) { if (values == null || values.size() == 0) return; String[] existingvals = md.get(key); if (existingvals == null) { md.put(key, values.toArray(new String[values.size()])); return; } ArrayList<String> existing = new ArrayList<String>(existingvals.length + values.size()); for (String v : existingvals) existing.add(v); existing.addAll(values); md.put(key, existing.toArray(new String[existing.size()])); }
Source:
<code>public HasSelfVisitor(final RdfCloudTripleStoreConfiguration conf, final InferenceEngine inferenceEngine) { super(conf, inferenceEngine); <START> include = conf.isInferInverseOf(); <END> }</code><technical_language>Change to: include = true; (@jessehatfield, @meiercaleb) a config option for restriction? (i.e. conf.isInferHasSelf()) appears some visitors do a unique config option while some don't</technical_language>

Target:
public HasSelfVisitor(final RdfCloudTripleStoreConfiguration conf, final InferenceEngine inferenceEngine) { super(conf, inferenceEngine); include = conf.hasSelf(); }
Source:
<code>public SpliceCatalogUpgradeScripts(SpliceDataDictionary sdd,Splice_DD_Version catalogVersion,TransactionController tc){ this.sdd=sdd; this.catalogVersion=catalogVersion; this.tc=tc; ddComparator=new Comparator<Splice_DD_Version>(){ @Override public int compare(Splice_DD_Version version1,Splice_DD_Version version2){ long v1=version1.toLong(); long v2=version2.toLong(); if(v1<v2) return -1; else if(v1==v2) return 0; else return 1; } }; scripts=new TreeMap<>(ddComparator); scripts.put(new Splice_DD_Version(sdd,1,0,0),new UpgradeScriptForFuji(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,1,1,1),new LassenUpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,5,0),new K2UpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,7,1), new UpgradeScriptForModifySchemaPermission(sdd,tc)); <START> } <END></code><technical_language>intended add a script upgrade previous version 2.5</technical_language>

Target:
public SpliceCatalogUpgradeScripts(SpliceDataDictionary sdd,Splice_DD_Version catalogVersion,TransactionController tc){ this.sdd=sdd; this.catalogVersion=catalogVersion; this.tc=tc; ddComparator=new Comparator<Splice_DD_Version>(){ @Override public int compare(Splice_DD_Version version1,Splice_DD_Version version2){ long v1=version1.toLong(); long v2=version2.toLong(); if(v1<v2) return -1; else if(v1==v2) return 0; else return 1; } }; scripts=new TreeMap<>(ddComparator); scripts.put(new Splice_DD_Version(sdd,1,0,0),new UpgradeScriptForFuji(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,1,1,1),new LassenUpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,5,0),new K2UpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,5,1), new UpgradeScriptForModifySchemaPermission(sdd,tc)); }
Source:
<code>private static String typeAdapterGetter(Property prop, ClassName jsonAdapter, TypeMirror typeAdapterFactory, Types typeUtils, List<TypeVariableName> typeParams) { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; ParameterizedTypeName adp = ParameterizedTypeName.get(jsonAdapter, type); CodeBlock.Builder codeBuilder = CodeBlock.builder(); if (prop.typeAdapter != null) { if (typeUtils.isAssignable(prop.typeAdapter, typeAdapterFactory)) { if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { <START> codeBuilder.add("(($T) new $T().create(gson, $L))", adp, <END> TypeName.get(prop.typeAdapter), makeParameterizedType(prop.type, typeParams)); } else { codeBuilder.add("(new $T().create(gson, $T.get($T.class)))", TypeName.get(prop.typeAdapter), TypeToken.class, prop.type); } } else { codeBuilder.add("(new $T())", TypeName.get(prop.typeAdapter)); } } else if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { codeBuilder.add("(($T) gson.getAdapter($L))", adp, makeParameterizedType(prop.type, typeParams)); } else { codeBuilder.add("(gson.getAdapter($T.class))", type); } return codeBuilder.build().toString(); }</code><technical_language>ditch extra parenthesis? generated code a bit more complex read adding value</technical_language>

Target:
private static String typeAdapterGetter(Property prop, ClassName jsonAdapter, TypeMirror typeAdapterFactory, Types typeUtils, List<TypeVariableName> typeParams) { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; ParameterizedTypeName adp = ParameterizedTypeName.get(jsonAdapter, type); CodeBlock.Builder codeBuilder = CodeBlock.builder(); if (prop.typeAdapter != null) { if (typeUtils.isAssignable(prop.typeAdapter, typeAdapterFactory)) { if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { codeBuilder.add("($T) new $T().create(gson, $L)", adp, TypeName.get(prop.typeAdapter), makeParameterizedType(prop.type, typeParams)); } else { codeBuilder.add("new $T().create(gson, $T.get($T.class))", TypeName.get(prop.typeAdapter), TypeToken.class, prop.type); } } else { codeBuilder.add("new $T()", TypeName.get(prop.typeAdapter)); } } else if (prop.type instanceof ParameterizedTypeName || prop.type instanceof TypeVariableName) { codeBuilder.add("($T) gson.getAdapter($L)", adp, makeParameterizedType(prop.type, typeParams)); } else { codeBuilder.add("gson.getAdapter($T.class)", type); } return codeBuilder.build().toString(); }
Source:
<code>public synchronized void releaseContainer(ContainerId containerId, boolean releasedByNode) { RMContainer container = getContainer(containerId); super.releaseContainer(containerId, releasedByNode); if (container != null) { <START> removeContainerForPreemption(container); <END> } }</code><technical_language>This is nice see. done this with</technical_language>

Target:
public synchronized void releaseContainer(ContainerId containerId, boolean releasedByNode) { RMContainer container = getContainer(containerId); super.releaseContainer(containerId, releasedByNode); if (container != null) { containersForPreemption.remove(container); } }
Source:
<code><START> boolean selectConflictingRevision() throws CouchbaseLiteException { <END> try { if (!c4doc.getRawDoc().selectNextLeaf(false, true)) return false; setC4Doc(c4doc); } catch (LiteCoreException e) { Log.e(TAG, "Failed to selectNextLeaf: doc -> " + c4doc, e); return false; } return true; }</code><technical_language>Is CouchbaseLiteException thrown in this method? return void throw CouchbaseLiteException instead</technical_language>

Target:
boolean selectConflictingRevision() { try { if (!c4doc.getRawDoc().selectNextLeaf(false, true)) return false; setC4Doc(c4doc); } catch (LiteCoreException e) { Log.e(TAG, "Failed to selectNextLeaf: doc -> " + c4doc, e); return false; } return true; }
Source:
<code>private void initDisplayProtocol() { <START> ArrayList<EntityModel> displayProtocolOptions = new ArrayList<EntityModel>(); <END> getDisplayProtocol().setItems(displayProtocolOptions); getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }</code><technical_language>inlined setItems(new ArrayList...)</technical_language>

Target:
private void initDisplayProtocol() { getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }
Source:
<code>public void abortProcessInstance(Long processInstanceId) { ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId); <START> if (piDesc == null || piDesc.getState() != 1) { <END> throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found"); } abortProcessInstance(piDesc.getDeploymentId(), processInstanceId); }</code><technical_language>change ProcessInstance.STATE_ACTIVE</technical_language>

Target:
public void abortProcessInstance(Long processInstanceId) { ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId); if (piDesc == null || piDesc.getState() != ProcessInstance.STATE_ACTIVE) { throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found"); } abortProcessInstance(piDesc.getDeploymentId(), processInstanceId); }
Source:
<code>public D[] getAllUserData(D[] array) { if (this.data == null) { <START> return (D[]) Array.newInstance(array.getClass(),0); <END> } return this.data.toArray(array); }</code><technical_language>Caution: array parameter null</technical_language>

Target:
public D[] getAllUserData(D[] array) { if (this.data == null) { return null; } return this.data.toArray(array); }
Source:
<code>public Response deleteContentTypeFieldByVar(@PathParam("typeId") final String typeId, @PathParam("fieldVar") final String fieldVar, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { <START> Field field = fieldAPI.byContentTypeIdAndVar(typeId, fieldVar); <END> fieldAPI.delete(field, user); response = Response.ok(new ResponseEntityView(null)).build(); } catch (Exception e) { response = ResponseUtil.mapExceptionResponse(e); } return response; }</code><technical_language>I field declared final</technical_language>

Target:
public Response deleteContentTypeFieldByVar(@PathParam("typeId") final String typeId, @PathParam("fieldVar") final String fieldVar, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final Field field = fieldAPI.byContentTypeIdAndVar(typeId, fieldVar); fieldAPI.delete(field, user); response = Response.ok(new ResponseEntityView(null)).build(); } catch (Exception e) { response = ResponseUtil.mapExceptionResponse(e); } return response; }
Source:
<code>public static double get(MetricKey<ASTAnyTypeDeclaration> key, ASTAnyTypeDeclaration node, MetricVersion version) { <START> if (!key.getCalculator().supports(node)) { <END> return Double.NaN; } MetricVersion safeVersion = (version == null) ? Version.STANDARD : version; return TOP_LEVEL_PACKAGE.compute(key, node, false, safeVersion); }</code><technical_language>shortcut key.supports(node),</technical_language>

Target:
public static double get(MetricKey<ASTAnyTypeDeclaration> key, ASTAnyTypeDeclaration node, MetricVersion version) { if (!key.supports(node)) { return Double.NaN; } MetricVersion safeVersion = (version == null) ? Version.STANDARD : version; return TOP_LEVEL_PACKAGE.compute(key, node, false, safeVersion); }
Source:
<code>public void addHeader(String name, String value) { <START> if (name.equalsIgnoreCase("COOKIE")) { <END> this.cookieInHeaders=value; } else if (!NOT_ADD_HEADERS.contains(name)) { headers.put(name, value); } }</code><technical_language>Try constant null values in front for comparison methods, is chance for a NPE. "COOKIE".equalsIgnoreCase(name)</technical_language>

Target:
public void addHeader(String name, String value) { if ("COOKIE".equalsIgnoreCase(name)) { this.cookieInHeaders = value; } else if (!HEADERS_TO_IGNORE.contains(name)) { headers.put(name, value); } }
Source:
<code>private GitResourceVariantTreeProvider createTreeProviderWithDeletions() throws Exception { file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); testRepo.untrack(file2); testRepo.commit("Removed file2 in branch."); testRepo.checkoutBranch(MASTER); testRepo.untrack(file1); testRepo.commit("Removed file1 in master."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new <START> NameConflictTreeWalk(repo); <END> tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }</code><technical_language>a NameConflictTreeWalk</technical_language>

Target:
private GitResourceVariantTreeProvider createTreeProviderWithDeletions() throws Exception { file1 = testRepo.createFile(iProject, "file1"); testRepo.appendContentAndCommit(iProject, file1, INITIAL_CONTENT_1, "Creation of file1 in branch1."); file2 = testRepo.createFile(iProject, "file2"); testRepo.appendContentAndCommit(iProject, file2, INITIAL_CONTENT_2, "Creation of file2 in branch2."); testRepo.createBranch(MASTER, BASE); testRepo.createAndCheckoutBranch(MASTER, BRANCH); testRepo.untrack(file2); testRepo.commit("Removed file2 in branch."); testRepo.checkoutBranch(MASTER); testRepo.untrack(file1); testRepo.commit("Removed file1 in master."); iProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); try (RevWalk walk = new RevWalk(repo)) { RevTree baseTree = walk.parseTree(repo.resolve(BASE)); RevTree sourceTree = walk.parseTree(repo.resolve(MASTER)); RevTree remoteTree = walk.parseTree(repo.resolve(BRANCH)); TreeWalk tw = new TreeWalk(repo); tw.addTree(baseTree); tw.addTree(sourceTree); tw.addTree(remoteTree); return new TreeWalkResourceVariantTreeProvider(repo, tw, 0, 1, 2); } }
Source:
<code>private static <T> Object[] toArray(Iterable<T> elements) { <START> if (elements instanceof Array) { <END> final Array<T> array = (Array<T>) elements; return array.delegate; } else if (elements instanceof java.util.Collection) { final java.util.Collection<T> collection = (java.util.Collection<T>) elements; return collection.toArray(); } else { final java.util.Iterator<? extends T> it = elements.iterator(); final java.util.List<T> list = new java.util.ArrayList<>(); while (it.hasNext()) { list.add(it.next()); } return list.toArray(); } }</code><technical_language>good call, this save a double copy! :)</technical_language>

Target:
private static <T> Object[] toArray(Iterable<T> elements) { if (elements instanceof Array) { final Array<T> array = (Array<T>) elements; return array.delegate; } else { return Collections.withSize(elements).toArray(); } }
Source:
<code>protected FileInfo addFile(InputStream inputStream, FileInfo fileInfo) throws Exception { <START> final String updatedFileStorageName = getFileStorageName(fileInfo.getName()); <END> fileInfo.setStoredFileName(updatedFileStorageName); log.info("Uploading File with fileInfo [{}]", fileInfo); final String uploadedFileStoragePath = catalogService.uploadFileToStorage(inputStream, updatedFileStorageName); log.info("Received File with fileInfo is uploaded to [{}]", uploadedFileStoragePath); fileInfo.setTimestamp(System.currentTimeMillis()); return catalogService.addFile(fileInfo); }</code><technical_language>extract duplicated file upload logic: FileInfo -> uploadedFileStorageName</technical_language>

Target:
protected FileInfo addFile(InputStream inputStream, FileInfo fileInfo) { uploadFile(inputStream, fileInfo); return catalogService.addFile(fileInfo); }
Source:
<code>public ICredentialsFactory asCredentialsFactory(ClassLoader cl) { if (implementation != null) { return implementation; } else { try { ICredentialsFactory credentialsFactory = ClassLoaderUtil.newInstance(cl, className); <START> credentialsFactory.init(properties); <END> return credentialsFactory; } catch (Exception e) { throw new IllegalArgumentException("Could not create instance of '" + className + "', cause: " + e.getMessage(), e); } } }</code><technical_language>Is expected create credentialsFactory time? cache it</technical_language>

Target:
public ICredentialsFactory asCredentialsFactory(ClassLoader cl) { if (implementation == null) { try { implementation = ClassLoaderUtil.newInstance(cl, className); implementation.init(properties); } catch (Exception e) { throw new IllegalArgumentException("Could not create instance of '" + className + "', cause: " + e.getMessage(), e); } } return implementation; }
Source:
<code>public String getClientToken(String params) { <START> try (Scope orderSpanScope = TracingUtil.buildSpan(CommandType.GET_CLIENT_TOKEN.toString(), true)) { <END> TracingUtil.setTag("end-point", "/get-client-token"); return process(CommandType.GET_CLIENT_TOKEN, params, GetClientTokenParams.class, null); } }</code><technical_language>put this tracing wrapper process. CommandType, need. In case wish log path, pass @Context UriInfo uriInfo uriInfo.getAbsolutePath()</technical_language>

Target:
public String getClientToken(String params) { return process(CommandType.GET_CLIENT_TOKEN, params, GetClientTokenParams.class, null, uriInfo); }
Source:
<code>@Override public void start0() throws IgniteCheckedException { CacheConfiguration cfg = cctx.config(); if (cctx.isNear()) { plc = (cfg.getNearConfiguration().getNearEvictionPolicyFactory() != null) ? (EvictionPolicy)cfg.getNearConfiguration().getNearEvictionPolicyFactory().create() : cfg.getNearConfiguration().getNearEvictionPolicy(); } else if (cfg.getEvictionPolicyFactory() != null) plc = (EvictionPolicy)cfg.getEvictionPolicyFactory().create(); else plc = cfg.getEvictionPolicy(); plcEnabled = plc != null; filter = cfg.getEvictionFilter(); if (plcEnabled) <START> cctx.kernalContext().cache().prepare(cctx.config(),plc,cctx.isNear()); <END> if (log.isDebugEnabled()) log.debug("Eviction manager started on node: " + cctx.nodeId()); }</code><technical_language>copy prepare() cleanup() GridCacheProcessor GridCacheEvictionManager. This is a duplication, of (which great), a separation of concerns encapsulation (which is good). Also, cfg variable access cache config there</technical_language>

Target:
@Override public void start0() throws IgniteCheckedException { CacheConfiguration cfg = cctx.config(); if (cctx.isNear()) { plc = (cfg.getNearConfiguration().getNearEvictionPolicyFactory() != null) ? (EvictionPolicy)cfg.getNearConfiguration().getNearEvictionPolicyFactory().create() : cfg.getNearConfiguration().getNearEvictionPolicy(); } else if (cfg.getEvictionPolicyFactory() != null) plc = (EvictionPolicy)cfg.getEvictionPolicyFactory().create(); else plc = cfg.getEvictionPolicy(); plcEnabled = plc != null; if (plcEnabled) prepare(cfg, plc, cctx.isNear()); filter = cfg.getEvictionFilter(); if (log.isDebugEnabled()) log.debug("Eviction manager started on node: " + cctx.nodeId()); }
Source:
<code>public void shutdown() throws ReplicationException { try { <START> for (String datacenter : replicaThreadPools.keySet()) { <END> for (ReplicaThread replicaThread : replicaThreadPools.get(datacenter)) { replicaThread.shutdown(); } } persistor.write(true); } catch (Exception e) { logger.error("Error shutting down replica manager {}", e); throw new ReplicationException("Error shutting down replica manager"); } }</code><technical_language>simply iterate replicaThreadPools.values() instead of for loops</technical_language>

Target:
public void shutdown() throws ReplicationException { try { for (Map.Entry<String, List<ReplicaThread>> replicaThreads : replicaThreadPools.entrySet()) { if (replicaThreads.getKey().equals(dataNodeId.getDatacenterName())) { for (ReplicaThread replicaThread : replicaThreads.getValue()) { replicaThread.shutdown(); } } } for (Map.Entry<String, List<ReplicaThread>> replicaThreads : replicaThreadPools.entrySet()) { if (!replicaThreads.getKey().equals(dataNodeId.getDatacenterName())) { for (ReplicaThread replicaThread : replicaThreads.getValue()) { replicaThread.shutdown(); } } } persistor.write(true); } catch (Exception e) { logger.error("Error shutting down replica manager {}", e); throw new ReplicationException("Error shutting down replica manager"); } }
Source:
<code><START> public static String[] getRecommendedProtocols() { <END> String[] supportedProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2" }; return supportedProtocols; }</code><technical_language>Thanks @GabrielBrascher better</technical_language>

Target:
public static String[] getRecommendedProtocols() { return new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; }