auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FieldConstraint asFieldConstraint(final RuleModel m, final FactPattern factPattern) { CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.setCompositeJunctionType(connector.equals("&&") ? CompositeFieldConstraint.COMPOSITE_TYPE_AND : CompositeFieldConstraint.COMPOSITE_TYPE_OR); for (Expr expr : subExprs) { comp.addConstraint(expr.asFieldConstraint(m, factPattern)); } String fieldName = ""; for (FieldConstraint field : comp.getConstraints()) { <START> if (SingleFieldConstraint.class.isAssignableFrom(field.getClass())) { <END> SingleFieldConstraint constraint = (SingleFieldConstraint) field; if (StringUtils.isEmpty(constraint.getFieldName()) && !StringUtils.isEmpty(constraint.getOperator()) && (constraint.getOperator().equals("matches") || constraint.getOperator().equals("not matches"))) { constraint.setFieldName(fieldName); } fieldName = constraint.getFieldName(); } } return comp; }</code><technical_language>I instanceof in places. Is is change this for consistency is isAssignableFrom check needed</technical_language>

Target:
public FieldConstraint asFieldConstraint(final RuleModel m, final FactPattern factPattern) { final CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.setCompositeJunctionType(connector.equals("&&") ? CompositeFieldConstraint.COMPOSITE_TYPE_AND : CompositeFieldConstraint.COMPOSITE_TYPE_OR); for (final Expr expr : subExprs) { comp.addConstraint(expr.asFieldConstraint(m, factPattern)); } convertLegacyMatchesToNewFormat(comp); return comp; }
Source:
<code>public void invalidateAll() throws StoreAccessException { invalidateAllObserver.begin(); StoreAccessException exception = null; long errorCount = 0; Iterator<Cache.Entry<K, ValueHolder<V>>> iterator = iterator(); <START> while (iterator.hasNext()) { <END> try { invalidate(iterator.next().getKey()); } catch (StoreAccessException e) { errorCount++; if (exception == null) { exception = e; } } } if (exception != null) { invalidateAllObserver.end(LowerCachingTierOperationsOutcome.InvalidateAllOutcome.FAILURE); throw new StoreAccessException("invalidateAll failed - error count: " + errorCount, exception); } invalidateAllObserver.end(LowerCachingTierOperationsOutcome.InvalidateAllOutcome.SUCCESS); }</code><technical_language>reason for a for loop here</technical_language>

Target:
public void invalidateAll() throws StoreAccessException { invalidateAllObserver.begin(); StoreAccessException exception = null; long errorCount = 0; for (K k : backingMap().keySet()) { try { invalidate(k); } catch (StoreAccessException e) { errorCount++; if (exception == null) { exception = e; } } } if (exception != null) { invalidateAllObserver.end(LowerCachingTierOperationsOutcome.InvalidateAllOutcome.FAILURE); throw new StoreAccessException("invalidateAll failed - error count: " + errorCount, exception); } invalidateAllObserver.end(LowerCachingTierOperationsOutcome.InvalidateAllOutcome.SUCCESS); }
Source:
<code>public Connection findOrNew(SocketAddress address, Bootstrap bootstrap) throws InterruptedException { Peer peer = peers.get(address); if (peer == null) { <START> synchronized (peers) { <END> peer = new Peer(this, address); peer.connect(bootstrap); peers.put(address, peer); } } Connection conn = peer.getConnection(ConnectionState.IDENTIFIED); return conn; }</code><technical_language>ConcurentHashMap</technical_language>

Target:
public Connection findOrNew(SocketAddress address, Bootstrap bootstrap) throws InterruptedException { Peer peer = peers.get(address); if (peer == null) { peer = new Peer(this, address); peers.putIfAbsent(address, peer); peer = peers.get(address); } return peer.connect(bootstrap); }
Source:
<code>private String getAnswerString(FeedbackQuestionAttributes question, FeedbackResponseDetails response) { switch(response.getQuestionType()) { case TEXT: case NUMSCALE: case RANK_RECIPIENTS: return response.getAnswerString(); case MCQ: case MSQ: <START> return response.getAnswerString().replace(", ", "\n"); <END> case RUBRIC: return getRubricAnsString((FeedbackRubricQuestionDetails) question.getQuestionDetails(), (FeedbackRubricResponseDetails) response); case RANK_OPTIONS: return getRankOptionsAnsString((FeedbackRankOptionsQuestionDetails) question.getQuestionDetails(), (FeedbackRankOptionsResponseDetails) response); case CONSTSUM: return getConstSumOptionsAnsString((FeedbackConstantSumQuestionDetails) question.getQuestionDetails(), (FeedbackConstantSumResponseDetails) response); case CONTRIB: return getContribAnsString((FeedbackContributionResponseDetails) response); default: throw new RuntimeException("Unknown question type: " + response.getQuestionType()); } }</code><technical_language>\n -> System.lineSeparator</technical_language>

Target:
private String getAnswerString(FeedbackQuestionAttributes question, FeedbackResponseDetails response) { switch(response.getQuestionType()) { case TEXT: case NUMSCALE: case RANK_RECIPIENTS: return response.getAnswerString(); case MCQ: case MSQ: return response.getAnswerString().replace(", ", System.lineSeparator()); case RUBRIC: return getRubricAnsString((FeedbackRubricQuestionDetails) question.getQuestionDetails(), (FeedbackRubricResponseDetails) response); case RANK_OPTIONS: return getRankOptionsAnsString((FeedbackRankOptionsQuestionDetails) question.getQuestionDetails(), (FeedbackRankOptionsResponseDetails) response); case CONSTSUM: return getConstSumOptionsAnsString((FeedbackConstantSumQuestionDetails) question.getQuestionDetails(), (FeedbackConstantSumResponseDetails) response); case CONTRIB: return getContribAnsString((FeedbackContributionResponseDetails) response); default: throw new RuntimeException("Unknown question type: " + response.getQuestionType()); } }
Source:
<code>private List<String> installLinux(List<String> urls, String saveAs) { log.info("Installing "+getEntity()+" using couchbase-server-{} {}", getCommunityOrEnterprise(), getVersion()); String apt = chainGroup( "export DEBIAN_FRONTEND=noninteractive", "which apt-get", sudo("apt-get update"), sudo("apt-get install -y python-httplib2"), sudo("apt-get install -y libssl0.9.8"), sudo(format("dpkg -i %s", saveAs))); String yum = chainGroup( "which yum", ok(sudo("sed -i.bk s/^enabled=1$/enabled=0/ /etc/yum/pluginconf.d/subscription-manager.conf")), ok(sudo("yum check-update")), sudo("yum install -y pkgconfig"), sudo("[ -f /etc/redhat-release ] && (grep -i \"red hat\" /etc/redhat-release && sudo yum install -y openssl098e) || :"), sudo(format("rpm --install %s", saveAs))); String link = new DownloadProducerFromUrlAttribute().apply(new BasicDownloadRequirement(this)).getPrimaryLocations().iterator().next(); return ImmutableList.<String>builder() .add(INSTALL_CURL) .addAll(Arrays.asList(INSTALL_CURL, BashCommands.require(BashCommands.alternatives(BashCommands.simpleDownloadUrlAs(urls, saveAs), <START> "curl -f -L -k "+link <END> + " -H 'Referer: <LINK_1>'" + " -o "+saveAs), "Could not retrieve "+saveAs+" (from "+urls.size()+" sites)", 9))) .add(alternatives(apt, yum)) .build(); }</code><technical_language>safest wrap link in quotes. e.g. BashCommands.simpleDownloadUrlAs()</technical_language>

Target:
private List<String> installLinux(List<String> urls, String saveAs) { log.info("Installing "+getEntity()+" using couchbase-server-{} {}", getCommunityOrEnterprise(), getVersion()); String apt = chainGroup( "export DEBIAN_FRONTEND=noninteractive", "which apt-get", sudo("apt-get update"), sudo("apt-get install -y python-httplib2"), sudo("apt-get install -y libssl0.9.8"), sudo(format("dpkg -i %s", saveAs))); String yum = chainGroup( "which yum", ok(sudo("sed -i.bk s/^enabled=1$/enabled=0/ /etc/yum/pluginconf.d/subscription-manager.conf")), ok(sudo("yum check-update")), sudo("yum install -y pkgconfig"), sudo("[ -f /etc/redhat-release ] && (grep -i \"red hat\" /etc/redhat-release && sudo yum install -y openssl098e) || :"), sudo(format("rpm --install %s", saveAs))); String link = new DownloadProducerFromUrlAttribute().apply(new BasicDownloadRequirement(this)).getPrimaryLocations().iterator().next(); return ImmutableList.<String>builder() .add(INSTALL_CURL) .addAll(Arrays.asList(INSTALL_CURL, BashCommands.require(BashCommands.alternatives(BashCommands.simpleDownloadUrlAs(urls, saveAs), "curl -f -L -k "+BashStringEscapes.wrapBash(link) + " -H 'Referer: <LINK_1>'" + " -o "+saveAs), "Could not retrieve "+saveAs+" (from "+urls.size()+" sites)", 9))) .add(alternatives(apt, yum)) .build(); }
Source:
<code>public void embargoedBitstreamForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity) .withName("Collection 1") .build(); String bitstreamContent = "Embargoed!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald") .build(); Bitstream bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withEmbargoPeriod("3 months") .build(); <START> context.restoreAuthSystemState(); <END> String authToken = getAuthToken(eperson.getEmail(), password); getClient(authToken).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isForbidden()); checkNumberOfStatsRecords(bitstream, 0); } }</code><technical_language>move this context.restoreAuthSystemState() this *outside* of try clause? I try needs BitstreamBuilder, misunderstanding something</technical_language>

Target:
public void embargoedBitstreamForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity) .withName("Collection 1") .build(); String bitstreamContent = "Embargoed!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald") .build(); bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withEmbargoPeriod("3 months") .build(); } context.restoreAuthSystemState(); String authToken = getAuthToken(eperson.getEmail(), password); getClient(authToken).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isForbidden()); getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isUnauthorized()); checkNumberOfStatsRecords(bitstream, 0); }
Source:
<code>private void timer() { state.startTimer(); Runnable timerWorker = new Runnable() { @Override public void run() { try { ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.timer(coordinator); containerMetrics.timerNs().update(clock.nanoTime() - startTime); coordinatorRequests.update(coordinator); state.doneTimer(); } catch (Throwable t) { <START> log.error("Task commit failed", task.taskName(), t); <END> abort(t); } finally { log.trace("Task commit completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task commits on the thread pool", task.taskName()); threadPool.submit(timerWorker); } else { log.trace("Task commits on the run loop thread", task.taskName()); timerWorker.run(); } }</code><technical_language>Update log messages refer timer instead of commit, in this class</technical_language>

Target:
private void timer() { state.startTimer(); Runnable timerWorker = new Runnable() { @Override public void run() { try { ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); long startTime = clock.nanoTime(); task.timer(coordinator); containerMetrics.timerNs().update(clock.nanoTime() - startTime); coordinatorRequests.update(coordinator); state.doneTimer(); } catch (Throwable t) { log.error("Task timer failed", task.taskName(), t); abort(t); } finally { log.trace("Task timer completed", task.taskName()); resume(); } } }; if (threadPool != null) { log.trace("Task timer runs on the thread pool", task.taskName()); threadPool.submit(timerWorker); } else { log.trace("Task timer runs on the run loop thread", task.taskName()); timerWorker.run(); } }
Source:
<code>public ExceptionalCheckBasedYield(Type exceptionType, Class<? extends SECheck> check, Node node, MethodBehavior behavior) { super(node, behavior); this.check = check; <START> this.behavior = behavior; <END> Preconditions.checkArgument(exceptionType != null, "exceptionType is required"); super.setExceptionType(exceptionType); }</code><technical_language>I point of storing behavior in this case... varargs enough..</technical_language>

Target:
public ExceptionalCheckBasedYield(Type exceptionType, Class<? extends SECheck> check, Node node, MethodBehavior behavior) { super(node, behavior); this.check = check; this.isMethodVarargs = behavior.isMethodVarArgs(); Preconditions.checkArgument(exceptionType != null, "exceptionType is required"); super.setExceptionType(exceptionType); }
Source:
<code>public static String getPolicyId(PolicyApi policyApi) { for ( ScalingPolicyResponse policy : policyApi.list() ) { if (policy.getName().equals(NAME)) return policy.getId(); } <START> throw new RuntimeException("Policy not found"); <END> }</code><technical_language>[minor] IllegalArgException</technical_language>

Target:
public static String getPolicyId(PolicyApi policyApi) { for ( ScalingPolicyResponse policy : policyApi.list() ) { if (policy.getName().equals(NAME)) return policy.getId(); } throw new IllegalArgumentException("Policy not found"); }
Source:
<code>public Result saveImportRecord(SkynetTransaction transaction, CoverageImport coverageImport) throws OseeCoreException { if (coverageImport == null) { return Result.FalseResult; } Artifact importRecordArt = null; for (Artifact artifact : getArtifact(false).getChildren()) { if (artifact.getName().equals(IMPORT_RECORD_NAME)) { importRecordArt = artifact; break; } } if (importRecordArt == null) { importRecordArt = ArtifactTypeManager.addArtifact(CoreArtifactTypes.GeneralDocument, artifact.getBranch(), IMPORT_RECORD_NAME); importRecordArt.setSoleAttributeFromString(CoreAttributeTypes.Extension, "zip"); getArtifact(false).addChild(importRecordArt); getArtifact(false).persist(transaction); } String home = System.getProperty("user.home"); <START> File tempFolder = new File(home, "coverage_temp_" + Lib.getDateTimeString()); <END> tempFolder.mkdirs(); tempFolder.deleteOnExit(); File zipFile = new File(tempFolder, "coverage.zip"); InputStream inputStream = null; try { Lib.compressFiles(coverageImport.getImportDirectory(), coverageImport.getImportRecordFiles(), zipFile.getAbsolutePath()); inputStream = new BufferedInputStream(new FileInputStream(zipFile)); importRecordArt.setSoleAttributeFromStream(CoreAttributeTypes.NativeContent, inputStream); } catch (IOException ex) { OseeExceptions.wrapAndThrow(ex); } finally { Lib.close(inputStream); zipFile.delete(); } importRecordArt.persist(transaction); return Result.TrueResult; }</code><technical_language>File.createTemporaryFolder instead of writing users home directory</technical_language>

Target:
public Result saveImportRecord(SkynetTransaction transaction, CoverageImport coverageImport) throws OseeCoreException { if (coverageImport == null) { return Result.FalseResult; } Artifact importRecordArt = null; for (Artifact artifact : getArtifact(false).getChildren()) { if (artifact.getName().equals(IMPORT_RECORD_NAME)) { importRecordArt = artifact; break; } } if (importRecordArt == null) { importRecordArt = ArtifactTypeManager.addArtifact(CoreArtifactTypes.GeneralDocument, artifact.getBranch(), IMPORT_RECORD_NAME); importRecordArt.setSoleAttributeFromString(CoreAttributeTypes.Extension, "zip"); getArtifact(false).addChild(importRecordArt); getArtifact(false).persist(transaction); } File tempFolder = Files.createTempDir(); tempFolder.deleteOnExit(); File zipFile = new File(tempFolder, "coverage.zip"); InputStream inputStream = null; try { Lib.compressFiles(coverageImport.getImportDirectory(), coverageImport.getImportRecordFiles(), zipFile.getAbsolutePath()); inputStream = new BufferedInputStream(new FileInputStream(zipFile)); importRecordArt.setSoleAttributeFromStream(CoreAttributeTypes.NativeContent, inputStream); } catch (IOException ex) { OseeExceptions.wrapAndThrow(ex); } finally { Lib.close(inputStream); zipFile.delete(); } importRecordArt.persist(transaction); return Result.TrueResult; }
Source:
<code>public ResourceGroupStateInfo getQueryStateInfos(@PathParam("resourceGroupId") String resourceGroupIdString) { if (!isNullOrEmpty(resourceGroupIdString)) { <START> try { <END> return resourceGroupManager.getResourceGroupStateInfo(new ResourceGroupId( newArrayList(resourceGroupIdString.split("/")).stream() .map(ResourceGroupStateInfoResource::urlDecode).collect(toImmutableList()))); } catch (NoSuchElementException e) { throw new WebApplicationException(NOT_FOUND); } } throw new WebApplicationException(NOT_FOUND); }</code><technical_language>Arrays.stream() easier, collect call a newline. like: java try { return resourceGroupManager.getResourceGroupStateInfo( new ResourceGroupId( Arrays.stream(resourceGroupIdString.split("/")) .map(ResourceGroupStateInfoResource::urlDecode) .collect(toImmutableList()))); }</technical_language>

Target:
public ResourceGroupStateInfo getQueryStateInfos(@PathParam("resourceGroupId") String resourceGroupIdString) { if (!isNullOrEmpty(resourceGroupIdString)) { try { return resourceGroupManager.getResourceGroupStateInfo( new ResourceGroupId( Arrays.stream(resourceGroupIdString.split("/")) .map(ResourceGroupStateInfoResource::urlDecode) .collect(toImmutableList()))); } catch (NoSuchElementException e) { throw new WebApplicationException(NOT_FOUND); } } throw new WebApplicationException(NOT_FOUND); }
Source:
<code>protected String getNamespaceName(Workspace workspace) throws InfrastructureException { String namespace = workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE); if (namespace == null) { NamespaceResolutionContext resolutionCtx = new NamespaceResolutionContext( workspace.getId(), EnvironmentContext.getCurrent().getSubject().getUserId(), EnvironmentContext.getCurrent().getSubject().getUserName()); namespace = evaluateLegacyNamespaceName(resolutionCtx); LOG.warn( "Workspace '{}' doesn't have an explicit namespace assigned." + " The legacy namespace resolution resolved it to '{}'.", workspace.getId(), namespace); } if (!NamespaceNameValidator.isValid(namespace)) { Subject subj = EnvironmentContext.getCurrent().getSubject(); if (!subj.isAnonymous()) { NamespaceResolutionContext resolutionCtx = new NamespaceResolutionContext(workspace.getId(), subj.getUserId(), subj.getUserName()); String defaultNamespace = evaluateNamespaceName(resolutionCtx); LOG.warn( "The namespace '{}' of the workspace '{}' is not valid. Trying to recover" + " from this situation using a default namespace which resolved to '{}'.", namespace, workspace.getId(), defaultNamespace); namespace = defaultNamespace; } else { <START> LOG.warn( <END> "The namespace '{}' of the workspace '{}' is not valid but we currently don't have" + " an active user to try an recover from this situation.", namespace, workspace.getId(), new Exception()); } } return namespace; }</code><technical_language>this case hit workspaces recovery</technical_language>

Target:
protected String getNamespaceName(Workspace workspace) throws InfrastructureException { String namespace = workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE); if (namespace == null) { NamespaceResolutionContext resolutionCtx = new NamespaceResolutionContext( workspace.getId(), EnvironmentContext.getCurrent().getSubject().getUserId(), EnvironmentContext.getCurrent().getSubject().getUserName()); namespace = evaluateLegacyNamespaceName(resolutionCtx); LOG.warn( "Workspace '{}' doesn't have an explicit namespace assigned." + " The legacy namespace resolution resolved it to '{}'.", workspace.getId(), namespace); } if (!NamespaceNameValidator.isValid(namespace)) { Subject subj = EnvironmentContext.getCurrent().getSubject(); if (!subj.isAnonymous()) { NamespaceResolutionContext resolutionCtx = new NamespaceResolutionContext(workspace.getId(), subj.getUserId(), subj.getUserName()); String defaultNamespace = evaluateNamespaceName(resolutionCtx); LOG.warn( "The namespace '{}' of the workspace '{}' is not valid. Trying to recover" + " from this situation using a default namespace which resolved to '{}'.", namespace, workspace.getId(), defaultNamespace); namespace = defaultNamespace; } else { LOG.warn( "The namespace '{}' of the workspace '{}' is not valid but we currently don't have" + " an active user to try an recover from this situation. We're letting the parent" + " workflow continue, but it may fail at some later point in time because of" + " the incorrect namespace name in use.", namespace, workspace.getId(), new Throwable()); } } return namespace; }
Source:
<code>public void deleteCreateCacheStorageTest() { CacheStorageImpl cache = new CacheStorageImpl(); <START> final Map<Identifier, OperatorState> queryState1= new HashMap<>(); <END> final Map<Identifier, OperatorState> queryState2= new HashMap<>(); queryState1.put(oid1, value1); queryState2.put(oid1, value2); cache.create(qid1, queryState1); Assert.assertEquals(value1, cache.read(qid1, oid1)); Assert.assertEquals(true, cache.delete(qid1)); Assert.assertEquals(true, cache.create(qid1, queryState2)); Assert.assertEquals(value2, cache.read(qid1, oid1)); }</code><technical_language>1 =</technical_language>

Target:
public void deleteCreateCacheStorageTest() { final CacheStorage cache = new CacheStorageImpl(); final Map<Identifier, OperatorState> queryState1 = new HashMap<>(); final Map<Identifier, OperatorState> queryState2 = new HashMap<>(); queryState1.put(oid1, value1); queryState2.put(oid1, value2); cache.create(qid1, queryState1); Assert.assertEquals(value1, cache.read(qid1, oid1)); Assert.assertTrue(cache.delete(qid1)); Assert.assertTrue(cache.create(qid1, queryState2)); Assert.assertEquals(value2, cache.read(qid1, oid1)); }
Source:
<code>private static String getInitials(String text) { String result = "NN"; if (!text.isEmpty() && text != null) { <START> String[] nameParts = text.split(" "); <END> result = nameParts[0].substring(0, 1).toUpperCase(); if (nameParts.length > 1) result += nameParts[1].substring(0, 1).toUpperCase(); } return result; }</code><technical_language>text != null is wrong side of && operator</technical_language>

Target:
private static String getInitials(String text) { String result = "NN"; if (text != null && !text.isEmpty()) { String[] nameParts = text.split(" "); result = nameParts[0].substring(0, 1).toUpperCase(); if (nameParts.length > 1) result += nameParts[1].substring(0, 1).toUpperCase(); } return result; }
Source:
<code>public ModuleList(Iterable<ModuleDefinitionResource> modules) { <START> checkState(modules != null); <END> modulesByType = TreeMultimap.create(index(modules, BY_TYPE)); }</code><technical_language>Please Spring's Asserts for that, for consistency rest of codebase</technical_language>

Target:
public ModuleList(Iterable<ModuleDefinitionResource> modules) { Assert.state(modules != null); modulesByType = TreeMultimap.create(index(modules, BY_TYPE)); iteratorsByType = transformValues(modulesByType.asMap(), new Function<Collection<ModuleDefinitionResource>, Iterator<ModuleDefinitionResource>>() { @Override public Iterator<ModuleDefinitionResource> apply(Collection<ModuleDefinitionResource> input) { return input.iterator(); } }); }
Source:
<code>public void testClassWithPrivateCtorAndNestedExtendingSubclass() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(FinalClassCheck.class); final String[] expected = { <START> "10:5: " + getCheckMessage(MSG_KEY, "B"), <END> "16:5: " + getCheckMessage(MSG_KEY, "C"), }; verify(checkConfig, getNonCompilablePath( "InputFinalClassClassWithPrivateCtorWithNestedExtendingClass.java"), expected); }</code><technical_language>do expect new violations. explain appeared deleted package name class</technical_language>

Target:
public void testClassWithPrivateCtorAndNestedExtendingSubclass() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(FinalClassCheck.class); final String[] expected = { "16:5: " + getCheckMessage(MSG_KEY, "C"), }; verify(checkConfig, getNonCompilablePath( "InputFinalClassClassWithPrivateCtorWithNestedExtendingClass.java"), expected); }
Source:
<code><START> public static List<File> getDirectories(File file) { <END> return Arrays.stream(Objects.requireNonNull(file.listFiles())) .filter(File::isDirectory) .sorted(Comparator.comparing(File::getName)) .collect(Collectors.toList()); }</code><technical_language>Cosmetic: please change indentation in accordance coding convention? (Here else PR applied)</technical_language>

Target:
public static List<File> getDirectories(File file) { File[] files = file.listFiles(); if (files == null) return Collections.emptyList(); return Arrays.stream(files) .filter(File::isDirectory) .sorted(Comparator.comparing(File::getName)) .collect(Collectors.toList()); }
Source:
<code>List<String> getTypes() { List<String> types = new ArrayList(counts.keySet()); <START> Collections.sort(types); <END> return types; }</code><technical_language>This method build warning</technical_language>

Target:
List<String> getTypes() { List<String> types = new ArrayList<>(counts.keySet()); Collections.sort(types); return types; }
Source:
<code>protected String renderTable() { <START> StringBuilder csvOut = new StringBuilder(); <END> csvOut.append(CELL_QUOTE); csvOut.append(Joiner.on(CELL_SEPARATOR).join(getHeaders())); csvOut.append(CELL_QUOTE); csvOut.append(LINE_SEPARATOR); String[][] body = formatTableContents(); for(String[] line : body) { csvOut.append(CELL_QUOTE); csvOut.append(Joiner.on(CELL_SEPARATOR).join(line)); csvOut.append(CELL_QUOTE); csvOut.append(LINE_SEPARATOR); } return csvOut.toString(); }</code><technical_language>Missing final</technical_language>

Target:
protected String renderTable() { final Appendable outs = new StringWriter(); try { final CSVPrinter csv = new CSVPrinter(outs, CSVFormat.EXCEL); csv.printRecord(getHeaders()); final String[][] body = formatTableContents(); for (final String[] line : body) { csv.printRecord(line); } csv.flush(); csv.close(); } catch (final IOException e) { LOG.error("Failed to create CSV output", e); return "ERROR: Failed to create CSV output"; } return outs.toString(); }
Source:
<code>private int[] setMask(int key) { <START> int[] mask = new int[BITS_SET_PER_BLOCK]; <END> for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = key * SALT[i]; } for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = mask[i] >>> 27; } for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = 0x1 << mask[i]; } return mask; }</code><technical_language>generated mask is read privately create reuse array</technical_language>

Target:
private int[] setMask(int key) { for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = key * SALT[i]; } for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = mask[i] >>> 27; } for (int i = 0; i < BITS_SET_PER_BLOCK; ++i) { mask[i] = 0x1 << mask[i]; } return mask; }
Source:
<code>private void applyContainerSettings(String pid, Document foxml, Model model, boolean hasDescription) { if (foxml == null) { return; } ContainerSettings settings = new ContainerSettings(foxml.getRootElement().getChildren().get(0)); if (settings.getViews().size() == 0) { if (hasDescription) { settings.setViews(defaultViewsDescriptive); } else { settings.setViews(defaultViews); } } if (settings.getDefaultView() == null) { settings.setDefaultView(ContainerView.STRUCTURE.name()); } if (settings.getViews().contains(ContainerView.DEPARTMENTS.name())) { SearchResultResponse result = queryLayer.getDepartmentList(GroupsThreadStore.getGroups(), pid); model.addAttribute("departmentFacets", result.getFacetFields().get(0)); } if (settings.getViews().contains(ContainerView.LIST_CONTENTS.name())) { SearchState searchState = stateFactory.createSearchState(); searchState.setResourceTypes( <START> Arrays.asList(ResourceType.Aggregate.name())); <END> SearchRequest listContentsRequest = new SearchRequest(); listContentsRequest.setSearchState(searchState); listContentsRequest.setRetrieveFacets(false); listContentsRequest.setApplyCutoffs(false); listContentsRequest.setRootPid(pid); listContentsRequest.getSearchState().setRollup(false); SearchResultResponse contentListResponse = queryLayer.performSearch(listContentsRequest); model.addAttribute("contentListResponse", contentListResponse); } model.addAttribute("containerSettings", settings); }</code><technical_language>below, standalone files</technical_language>

Target:
private void applyContainerSettings(String pid, Document foxml, Model model, boolean hasDescription) { if (foxml == null) { return; } ContainerSettings settings = new ContainerSettings(foxml.getRootElement().getChildren().get(0)); if (settings.getViews().size() == 0) { if (hasDescription) { settings.setViews(defaultViewsDescriptive); } else { settings.setViews(defaultViews); } } if (settings.getDefaultView() == null) { settings.setDefaultView(ContainerView.STRUCTURE.name()); } if (settings.getViews().contains(ContainerView.DEPARTMENTS.name())) { SearchResultResponse result = queryLayer.getDepartmentList(GroupsThreadStore.getGroups(), pid); model.addAttribute("departmentFacets", result.getFacetFields().get(0)); } if (settings.getViews().contains(ContainerView.LIST_CONTENTS.name())) { SearchState searchState = stateFactory.createSearchState(); searchState.setResourceTypes( Arrays.asList(ResourceType.Aggregate.name(), ResourceType.File.name())); searchState.setIncludeParts(false); SearchRequest listContentsRequest = new SearchRequest(); listContentsRequest.setSearchState(searchState); listContentsRequest.setRetrieveFacets(false); listContentsRequest.setApplyCutoffs(false); listContentsRequest.setRootPid(pid); listContentsRequest.getSearchState().setRollup(false); SearchResultResponse contentListResponse = queryLayer.performSearch(listContentsRequest); model.addAttribute("contentListResponse", contentListResponse); } model.addAttribute("containerSettings", settings); }
Source:
<code>public boolean isCommander(Person person) { Person commander = getCommander(); <START> return (null != commander) && person.getId().equals(commander.getId()); <END> }</code><technical_language>add a null-check for "person" safe side</technical_language>

Target:
public boolean isCommander(Person person) { Person commander = getCommander(); return (null != person) && (null != commander) && person.getId().equals(commander.getId()); }
Source:
<code>public static void inputReal(QuantileDigestState state, long value, long weight, double accuracy) <START> { <END> input(state, floatToSortableInt(intBitsToFloat((int) value)), weight, accuracy); }</code><technical_language>switch instead (and add sanity check way)</technical_language>

Target:
public static void inputReal(QuantileDigestState state, long value, long weight, double accuracy) { inputBigint(state, floatToSortableInt(intBitsToFloat((int) value)), weight, accuracy); }
Source:
<code><START> public void test2() throws Exception { <END> final File fileToProcess = new File(getNonCompilablePath("SuppressionXpathRegression2.java")); final DefaultConfiguration moduleConfig = createModuleConfig(PackageDeclarationCheck.class); final String[] expectedViolation = { "1:1: " + getCheckMessage(PackageDeclarationCheck.class, PackageDeclarationCheck.MSG_KEY_MISSING), }; final List<String> expectedXpathQueries = Arrays.asList( "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]/MODIFIERS", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]/MODIFIERS/LITERAL_PUBLIC" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }</code><technical_language>test2 test1? Please swap order</technical_language>

Target:
public void test2() throws Exception { final File fileToProcess = new File(getNonCompilablePath("SuppressionXpathRegression2.java")); final DefaultConfiguration moduleConfig = createModuleConfig(PackageDeclarationCheck.class); final String[] expectedViolation = { "3:1: " + getCheckMessage(PackageDeclarationCheck.class, PackageDeclarationCheck.MSG_KEY_MISSING), }; final List<String> expectedXpathQueries = Arrays.asList( "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]/MODIFIERS", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegression2']]/MODIFIERS/LITERAL_PUBLIC" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }
Source:
<code>public void testSearchAllResources() throws Exception { final var resources = createResources(3); final var condition = fedora_id + "=*"; final String searchUrl = getSearchEndpoint() + "condition=" + encode(condition); try (final CloseableHttpResponse response = execute(new HttpGet(searchUrl))) { assertEquals(OK.getStatusCode(), getStatus(response)); final ObjectMapper objectMapper = new ObjectMapper(); final SearchResult result = objectMapper.readValue(response.getEntity().getContent(), SearchResult.class); assertNotNull(result); assertNotNull(result.getPagination()); assertTrue(result.getItems().size() >= 3); final var resultingFedoraIds = result.getItems().stream().map(x -> x.get("fedora_id")).collect(Collectors.toList()); <START> assertTrue("results must contain all newly created resources", <END> resultingFedoraIds.containsAll(resources)); } }</code><technical_language>running mvn clean install, more times not, this test/assertion fails... although, always</technical_language>

Target:
public void testSearchAllResources() throws Exception { final var resources = createResources(3); final var condition = FEDORA_ID + "=*"; final String searchUrl = getSearchEndpoint() + "condition=" + encode(condition); try (final CloseableHttpResponse response = execute(new HttpGet(searchUrl))) { assertEquals(OK.getStatusCode(), getStatus(response)); final ObjectMapper objectMapper = new ObjectMapper(); final SearchResult result = objectMapper.readValue(response.getEntity().getContent(), SearchResult.class); assertNotNull(result); assertNotNull(result.getPagination()); assertTrue(result.getItems().size() >= 3); final var resultingFedoraIds = result.getItems().stream().map(x -> x.get("fedora_id")).collect(Collectors.toList()); assertTrue("results must contain all newly created resources", resultingFedoraIds.containsAll(resources)); } }
Source:
<code>public HashMap<Category, ImList<CategorizedTime>> groupTimes() { Function1<CategorizedTime, Category> f = new Function1<CategorizedTime, Category>() { @Override public Category apply(CategorizedTime ct) { return ct.category; } }; <START> return DefaultImList.create(times).groupBy(f); <END> }</code><technical_language>I a lambda here: return DefaultImList.create(times).groupBy(t -> t.category);</technical_language>

Target:
public HashMap<Category, ImList<CategorizedTime>> groupTimes() { return DefaultImList.create(times).groupBy(t -> t.category); }
Source:
<code>public void configure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { try { IProjectDescription description = project.getDescription(); String[] oldNatures = description.getNatureIds(); List<String> natureList = new ArrayList<String>(); <START> natureList.addAll(Arrays.asList(oldNatures)); <END> if( !project.hasNature(HybridAppNature.NATURE_ID ) ){ natureList.add(HybridAppNature.NATURE_ID); } if( !project.hasNature( JavaScriptCore.NATURE_ID )){ natureList.add(JavaScriptCore.NATURE_ID); } description.setNatureIds(natureList.toArray(new String[natureList.size()])); project.setDescription(description, monitor); } catch (CoreException ex) { Activator.getDefault().getLog().log(new Status( IStatus.ERROR, Activator.getDefault().getBundle().getSymbolicName(), ex.getMessage(), ex)); } }</code><technical_language>API for this purpose org.eclipse.thym.ui.wizard.project.HybridProjectCreator.convertProject(IProject, IProgressMonitor) I switch</technical_language>

Target:
public void configure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { try { new HybridProjectCreator().convertProject(project, monitor); } catch (CoreException ex) { ThymImporterActivator.getDefault().getLog().log(new Status( IStatus.ERROR, ThymImporterActivator.getDefault().getBundle().getSymbolicName(), ex.getMessage(), ex)); } }
Source:
<code>public void unshareButtonPressed(OCShare share) { mListener.removeShare(share); <START> Log_OC.d(TAG, "Unshare - " + share.getSharedWithDisplayName()); <END> }</code><technical_language>Remove</technical_language>

Target:
public void unshareButtonPressed(OCShare share) { Log_OC.d(TAG, "Removed private share with " + share.getSharedWithDisplayName()); mListener.removeShare(share); }
Source:
<code><START> public JsonFeature( <END> String name, String id, @Nullable String version, @Nullable String description, FeatureState state, boolean required, @Nullable String region, @Nullable String repository, int startLevel) { Validate.notNull(name, "invalid null name"); Validate.notNull(id, " invalid null id"); Validate.notNull(state, "invalid null state"); this.name = name; this.id = id; this.version = version; this.description = description; this.state = state; this.required = required; this.region = region; this.repository = repository; this.startLevel = startLevel; }</code><technical_language>Wish easy create a Builder class for scenarios these</technical_language>

Target:
JsonFeature( String name, String id, @Nullable String version, @Nullable String description, FeatureState state, boolean required, @Nullable String region, @Nullable String repository, int startLevel) { Validate.notNull(name, "invalid null name"); Validate.notNull(id, " invalid null id"); Validate.notNull(state, "invalid null state"); this.name = name; this.id = id; this.version = version; this.description = description; this.state = state; this.required = required; this.region = region; this.repository = repository; this.startLevel = startLevel; }
Source:
<code>public boolean isBoundToCreatedVm(){ <START> return isBoundToVm() && this.getBroker().equals(this.getVm().getBroker()) && this.getVm().isCreated(); <END> }</code><technical_language>short-circuit operands "&&", placing complex calls (when change expected result) improves performance. getVm().isCreated() is 2 simple calls, while getBroker().equals(getVm().getBroker()) is 4 calls (that simple too). suggestion return isBoundToVm() && this.getVm().isCreated() && this.getBroker().equals(this.getVm().getBroker());</technical_language>

Target:
public boolean isBoundToCreatedVm(){ return isBoundToVm() && this.getVm().isCreated() && this.getBroker().equals(this.getVm().getBroker()); }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Sort sort = call.rel(0); final DruidRel druidRel = call.rel(1); final DefaultLimitSpec limitSpec = GroupByRules.toLimitSpec(druidRel.getQueryBuilder().getRowOrder(), sort); if (limitSpec == null) { return; } <START> if (limitSpec.getColumns().isEmpty()) { <END> call.transformTo( druidRel.withQueryBuilder( druidRel.getQueryBuilder().withLimitSpec(limitSpec) ) ); } }</code><technical_language>a sql retrieve latest 10 records is handled druid select query is totally removed rules? > select a,b,c datasource order __time desc limit 10 This sql translated druid select query descending=true fast if limit is a small number. If handle this kind of sql here, kind of druid query is bypass this rule</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Sort sort = call.rel(0); final DruidRel druidRel = call.rel(1); final DefaultLimitSpec limitSpec = GroupByRules.toLimitSpec(druidRel.getQueryBuilder().getRowOrder(), sort); if (limitSpec == null) { return; } final List<OrderByColumnSpec> orderBys = limitSpec.getColumns(); if (orderBys.isEmpty() || (orderBys.size() == 1 && orderBys.get(0).getDimension().equals(Column.TIME_COLUMN_NAME))) { call.transformTo( druidRel.withQueryBuilder( druidRel.getQueryBuilder().withLimitSpec(limitSpec) ) ); } }
Source:
<code>public StripedWriterReaderPhaser(final int stripes) { assert stripes > 0 && (stripes & (stripes - 1)) == 0; this.stripes = stripes; <START> startEpoch = new AtomicLongArray(stripes); <END> evenEndEpoch = new AtomicLongArray(stripes); oddEndEpoch = new AtomicLongArray(stripes); stride = 1 + Long.MAX_VALUE / stripes; for (int i=0; i<stripes; i++) { startEpoch.set(i, i * stride); evenEndEpoch.set(i, i * stride); oddEndEpoch.set(i, Long.MIN_VALUE + i * stride); } }</code><technical_language>I suspect benefit avoided collisions need wrap long 2 cache lines (prefetcher size) avoid false sharing them</technical_language>

Target:
public StripedWriterReaderPhaser(final int stripes) { if (stripes <= 0 || (stripes & (stripes - 1)) != 0) { throw new IllegalArgumentException("The number of stripes must be a power of 2, not " + stripes); } if (stripes > MAX_STRIPES) { throw new IllegalArgumentException("There must be at most " + MAX_STRIPES + " stripes, not " + stripes); } this.stripes = stripes; this.stripeMask = stripes - 1; final int paddedStripes = stripes * STRIDE; startEpoch = new AtomicLongArray(paddedStripes); evenEndEpoch = new AtomicLongArray(paddedStripes); oddEndEpoch = new AtomicLongArray(paddedStripes); for (int i = 0; i < stripes; i++) { oddEndEpoch.set(i * STRIDE, Long.MIN_VALUE); } }
Source:
<code>public ByteBuf encode(ByteBuf buf, PlayParticleMessage message) throws IOException { buf.writeInt(message.getParticle()); buf.writeBoolean(message.isLongDistance()); buf.writeFloat(message.getX()); buf.writeFloat(message.getY()); buf.writeFloat(message.getZ()); buf.writeFloat(message.getOfsX()); buf.writeFloat(message.getOfsY()); buf.writeFloat(message.getOfsZ()); buf.writeFloat(message.getExtData()); buf.writeInt(message.getCount()); <START> for (int extData : message.getData()) { <END> ByteBufUtils.writeVarInt(buf, extData); } return buf; }</code><technical_language>Change int data. confusing right due mismatched names</technical_language>

Target:
public ByteBuf encode(ByteBuf buf, PlayParticleMessage message) throws IOException { buf.writeInt(message.getParticle()); buf.writeBoolean(message.isLongDistance()); buf.writeFloat(message.getX()); buf.writeFloat(message.getY()); buf.writeFloat(message.getZ()); buf.writeFloat(message.getOfsX()); buf.writeFloat(message.getOfsY()); buf.writeFloat(message.getOfsZ()); buf.writeFloat(message.getData()); buf.writeInt(message.getCount()); for (int extData : message.getExtData()) { ByteBufUtils.writeVarInt(buf, extData); } return buf; }
Source:
<code>public static boolean inRange(int value, int min, int max) { <START> return (value <= max) & (value >= min); <END> }</code><technical_language>nit: && &</technical_language>

Target:
public static boolean inRange(int value, int min, int max) { return (value <= max) && (value >= min); }
Source:
<code>public void cleanup() { <START> myIdeFrame = <END> null; myNavigationHelper.cleanup(); myNavigationHelper = null; myStateComponent = null; myTaskContext = null; }</code><technical_language>Generally speaking, need null out fields of object if is hold reference object afterwards. GC is do job, need help. :)</technical_language>

Target:
public void cleanup() { myNavigationHelper.cleanup(); }
Source:
<code>protected void executeIrsBrokerCommand() { storageDomainHelper.checkNumberOfLVsForBlockDomain(getParameters().getStorageDomainId()); setReturnValue(Guid.Empty); log.info("-- executeIrsBrokerCommand: calling 'createVolume' with two new parameters: description and UUID"); String imageInitSize = null; if (getParameters().getImageInitialSizeInBytes() != 0) { imageInitSize = Long.valueOf(getParameters().getImageInitialSizeInBytes()).toString(); } <START> String diskType = FeatureSupported.isContentTypeSupported(getParameters().getCompatibilityVersion()) ? <END> getParameters().getDiskContentType().getStorageValue() : DiskContentType.LEGACY_DISK_TYPE; uuidReturn = getIrsProxy().createVolume( getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getImageGroupId().toString(), Long.valueOf(getParameters().getImageSizeInBytes()).toString(), getParameters().getVolumeFormat().getValue(), getParameters().getImageType().getValue(), diskType, getParameters().getNewImageID().toString(), getParameters().getNewImageDescription(), Guid.Empty.toString(), Guid.Empty.toString(), imageInitSize); proceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.uuid); createdImageId = getParameters().getNewImageID().toString(); setReturnValue(new Guid(createdImageId)); getVDSReturnValue().setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.createVolume, getParameters() .getStoragePoolId())); }</code><technical_language>making this check in caller (only AddImageFromScratchCommand)? i.e. instead of passing version vds command params</technical_language>

Target:
protected void executeIrsBrokerCommand() { storageDomainHelper.checkNumberOfLVsForBlockDomain(getParameters().getStorageDomainId()); setReturnValue(Guid.Empty); log.info("-- executeIrsBrokerCommand: calling 'createVolume' with two new parameters: description and UUID"); String imageInitSize = null; if (getParameters().getImageInitialSizeInBytes() != 0) { imageInitSize = Long.valueOf(getParameters().getImageInitialSizeInBytes()).toString(); } String diskType = FeatureSupported.isContentTypeSupported(getParameters().getPoolCompatibilityVersion()) ? getParameters().getDiskContentType().getStorageValue() : DiskContentType.LEGACY_DISK_TYPE; uuidReturn = getIrsProxy().createVolume( getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getImageGroupId().toString(), Long.valueOf(getParameters().getImageSizeInBytes()).toString(), getParameters().getVolumeFormat().getValue(), getParameters().getImageType().getValue(), diskType, getParameters().getNewImageID().toString(), getParameters().getNewImageDescription(), Guid.Empty.toString(), Guid.Empty.toString(), imageInitSize); proceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.uuid); createdImageId = getParameters().getNewImageID().toString(); setReturnValue(new Guid(createdImageId)); getVDSReturnValue().setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.createVolume, getParameters() .getStoragePoolId())); }
Source:
<code>public OSMMaxAxleLoadParser() { <START> this.maxAxleLoadEncoder = MaxAxleLoad.create(); <END> }</code><technical_language>I remove this. I additional constructor is a meaningful addition, user increase decrease precision. (same for other parsers)</technical_language>

Target:
public OSMMaxAxleLoadParser() { this(MaxAxleLoad.create()); }