auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGaelicLanguageIsSetForAlbaChannel() { Film film = createAlbaNitroFilm(); ExtendedOnDemandProgramType onDemand = (ExtendedOnDemandProgramType) Iterables.getOnlyElement(generator.generate(film)); InstanceDescriptionType instanceDesc = onDemand.getInstanceDescription(); CaptionLanguageType captionLanguage = Iterables.getOnlyElement(instanceDesc.getCaptionLanguage()); assertTrue(captionLanguage.isClosed()); <START> assertEquals(captionLanguage.getValue(), "gla"); <END> }</code><technical_language>more language fields set this? is a main audio language element, no</technical_language>

Target:
public void testGaelicLanguageIsSetForAlbaChannel() { Film film = createAlbaNitroFilm(); ItemOnDemandHierarchy hierarchy = hierarchyFrom(film); String onDemandImi = idGenerator.generateOnDemandImi(hierarchy.item(), hierarchy.version(), hierarchy.encoding(), hierarchy.location()); ExtendedOnDemandProgramType onDemand = (ExtendedOnDemandProgramType) generator.generate(hierarchy, onDemandImi); InstanceDescriptionType instanceDesc = onDemand.getInstanceDescription(); CaptionLanguageType captionLanguage = Iterables.getOnlyElement(instanceDesc.getCaptionLanguage()); assertTrue(captionLanguage.isClosed()); assertEquals(captionLanguage.getValue(), "gla"); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { EObject selection = getSelection(event); if (selection == null) return new IContributionItem[0]; ResourceSet resourceSet = selection.eResource().getResourceSet(); if (!(resourceSet instanceof ModelSet)) return new IContributionItem[0]; final Shell shell = Display.getCurrent().getActiveShell(); <START> ArchitectureDialogs.openSwitchArchitectureContext((ModelSet)resourceSet, <END> shell); return null; }</code><technical_language>idea... this is common pattern in Papyrus</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { EObject selection = getSelection(event); if (selection == null) return new IContributionItem[0]; ResourceSet resourceSet = selection.eResource().getResourceSet(); if (!(resourceSet instanceof ModelSet)) return new IContributionItem[0]; final Shell shell = Display.getCurrent().getActiveShell(); ArchitectureUIUtils.switchArchitectureContext((ModelSet)resourceSet, shell, true); return null; }
Source:
<code>public int getGenre() { <START> if (id3v2Tag != null && id3v2Tag.getGenre() != -1) { <END> return id3v2Tag.getGenre(); } else if (id3v1Tag != null) { return id3v1Tag.getGenre(); } else { return -1; } }</code><technical_language>This changes default behaviour lead results a consumer updates mp3agic. do in future decision prefer id3v2 id3v1 consistent in library. This another pull request signed @mpatric before</technical_language>

Target:
public int getGenre() { if (id3v1Tag != null && id3v1Tag.getGenre() != -1) { return id3v1Tag.getGenre(); } else if (id3v2Tag != null) { return id3v2Tag.getGenre(); } else { return -1; } }
Source:
<code>public FlatRow finishRow() { ImmutableList.Builder<FlatRow.Cell> combined = ImmutableList.builderWithExpectedSize(totalCellCount); <START> for (Set<FlatRow.Cell> familyCellList : cells.values()) { <END> combined.addAll(familyCellList); } return new FlatRow(this.currentKey, combined.build()); }</code><technical_language>Please compare current previous for following: FlatRow.Cell previous; for(FlatRow.Cell c : cells.values) { if(previous == null || !c.getLables().isEmpty() || !keysMatch(c, previous)){ combined.add(c); } }</technical_language>

Target:
public FlatRow finishRow() { ImmutableList.Builder<FlatRow.Cell> combined = ImmutableList.builderWithExpectedSize(totalCellCount); for (List<FlatRow.Cell> familyCellList : cells.values()) { FlatRow.Cell previous = null; for (FlatRow.Cell c : familyCellList) { if (previous == null || !c.getLabels().isEmpty() || !keysMatch(c, previous)) { combined.add(c); } previous = c; } } return new FlatRow(this.currentKey, combined.build()); }
Source:
<code>protected Deconvolution2D(BaseConvBuilder<?> builder) { super(builder); this.hasBias = builder.hasBias; this.convolutionMode = builder.convolutionMode; this.dilation = builder.dilation; if (builder.kernelSize.length != 2) throw new IllegalArgumentException("Kernel size of should be rows x columns (a 2d array)"); this.kernelSize = builder.kernelSize; if (builder.stride.length != 2) throw new IllegalArgumentException("Stride should include stride for rows and columns (a 2d array)"); this.stride = builder.stride; if (builder.padding.length != 2) throw new IllegalArgumentException("Padding should include padding for rows and columns (a 2d array)"); this.padding = builder.padding; this.cudnnAlgoMode = builder.cudnnAlgoMode; this.cudnnFwdAlgo = builder.cudnnFwdAlgo; this.cudnnBwdFilterAlgo = builder.cudnnBwdFilterAlgo; <START> this.cudnnBwdDataAlgo = builder.cudnnBwdDataAlgo; <END> initializeConstraints(builder); }</code><technical_language>of builder args (like, 16 lines) handled in superclass constructor already... a reason for this</technical_language>

Target:
protected Deconvolution2D(BaseConvBuilder<?> builder) { super(builder); initializeConstraints(builder); }
Source:
<code>private void visitConnect(IProject project, final Map<IProject, File> projects) throws CoreException { if (RepositoryMapping.getMapping(project) != null) { return; } RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) { return; } RepositoryFinder f = new RepositoryFinder(project); f.setFindInChildren(false); Collection<RepositoryMapping> mappings = f.find(new NullProgressMonitor()); if (mappings.isEmpty()) { return; } RepositoryMapping m = mappings.iterator().next(); IPath gitDirPath = m.getGitDirAbsolutePath(); if (gitDirPath == null || gitDirPath.segmentCount() == 0) { return; } IPath workingDir = gitDirPath.removeLastSegments(1); if (workingDir.isRoot()) { return; } File userHome = FS.DETECTED.userHome(); if (userHome != null) { Path userHomePath = new Path(userHome.getAbsolutePath()); if (workingDir.isPrefixOf(userHomePath)) { return; } } File repositoryDir = gitDirPath.toFile(); projects.put(project, repositoryDir); if (mappings.size() > 1) { IPath lastPath = null; <START> for (RepositoryMapping mapping : mappings) { <END> lastPath = mapping.getGitDirAbsolutePath(); } if (lastPath != null) { repositoryDir = lastPath.toFile(); } } try { Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } catch (IllegalArgumentException e) { logError(CoreText.Activator_AutoSharingFailed, e); } }</code><technical_language>strange Collection interface reveal is ordered rely ordering. I List interface, this allow access entry</technical_language>

Target:
private void visitConnect(IProject project, final Map<IProject, File> projects) throws CoreException { if (RepositoryMapping.getMapping(project) != null) { return; } RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) { return; } RepositoryFinder f = new RepositoryFinder(project); f.setFindInChildren(false); List<RepositoryMapping> mappings = f .find(new NullProgressMonitor()); if (mappings.isEmpty()) { return; } RepositoryMapping m = mappings.get(0); IPath gitDirPath = m.getGitDirAbsolutePath(); if (gitDirPath == null || gitDirPath.segmentCount() == 0) { return; } IPath workingDir = gitDirPath.removeLastSegments(1); if (workingDir.isRoot()) { return; } File userHome = FS.DETECTED.userHome(); if (userHome != null) { Path userHomePath = new Path(userHome.getAbsolutePath()); if (workingDir.isPrefixOf(userHomePath)) { return; } } File repositoryDir = gitDirPath.toFile(); projects.put(project, repositoryDir); int nofMappings = mappings.size(); if (nofMappings > 1) { IPath lastPath = mappings.get(nofMappings - 1) .getGitDirAbsolutePath(); if (lastPath != null) { repositoryDir = lastPath.toFile(); } } try { Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } catch (IllegalArgumentException e) { logError(CoreText.Activator_AutoSharingFailed, e); } }
Source:
<code>void issue200EnumConstantsWithCommentsForceVerticalAlignment() { <START> CompilationUnit cu = StaticJavaParser.parse("public enum X {" + EOL + <END> " " + EOL + " BORDER_CONSTANT," + EOL + " " + EOL + " ANOTHER_CONSTANT" + EOL + "}"); assertEqualsNoEol("public enum X {\n" + "\n" + " \n" + " BORDER_CONSTANT,\n" + " \n" + " ANOTHER_CONSTANT\n" + "}\n", cu.toString()); }</code><technical_language>is a TestParser in project, is meant configuration for tests</technical_language>

Target:
void issue200EnumConstantsWithCommentsForceVerticalAlignment() { CompilationUnit cu = TestParser.parseCompilationUnit("public enum X {" + EOL + " " + EOL + " BORDER_CONSTANT," + EOL + " " + EOL + " ANOTHER_CONSTANT" + EOL + "}"); assertEqualsNoEol("public enum X {\n" + "\n" + " \n" + " BORDER_CONSTANT,\n" + " \n" + " ANOTHER_CONSTANT\n" + "}\n", cu.toString()); }
Source:
<code>GraphLabelProvider() { <START> absoluteFormatter = DateFormat.getInstance(); <END> }</code><technical_language>I this Mac OS X 10.6.8 Language set English German date format. German date format set in Mac System Preferences respected in Eclipse, I get short EN_us date format in History View this change is used</technical_language>

Target:
GraphLabelProvider() { absoluteFormatter = DateFormat.getDateTimeInstance(); }
Source:
<code>private static boolean inheritsFromBaseException(@Nullable Symbol symbol) { if (symbol == null || symbol.kind() != CLASS) { return true; } <START> return ((ClassSymbol) symbol).isOrExtends("BaseException") || ((ClassSymbol) symbol).hasUnresolvedTypeHierarchy(); <END> }</code><technical_language>I cast ClassSymbol</technical_language>

Target:
private static boolean inheritsFromBaseException(@Nullable Symbol symbol) { if (symbol == null || symbol.kind() != CLASS) { return true; } ClassSymbol classSymbol = (ClassSymbol) symbol; return classSymbol.isOrExtends("BaseException") || classSymbol.hasUnresolvedTypeHierarchy(); }
Source:
<code>protected void inject(Injector injector) throws Exception { super.inject(injector); environment = injector.getInstance(IEdxEnvironment.class); <START> config = injector.getInstance(Config.class); <END> }</code><technical_language>config is initialized in BaseTestCase.java</technical_language>

Target:
protected void inject(Injector injector) throws Exception { super.inject(injector); environment = injector.getInstance(IEdxEnvironment.class); }
Source:
<code>public void registerType(HierarchicalTypeDefinition<?> typeDef) throws Exception { if (metadataService.getTypeNamesList().contains(typeDef.typeName)) { log.info("Given type: is already registered.", typeDef.typeName); <START> return; <END> } final String typeDefJson = TypesSerialization.toJson(typeDef, false); final JSONObject type = metadataService.createType(typeDefJson); log.info("####### registered type ", type); final List<String> typeNamesList = metadataService.getTypeNamesList(); log.debug("####### registered typeNames ", typeNamesList); }</code><technical_language>logging right. log this in else part remove return</technical_language>

Target:
public void registerType(HierarchicalTypeDefinition<?> typeDef) throws Exception { if (metadataService.getTypeNamesList().contains(typeDef.typeName)) { LOG.info("Given type: is already registered.", typeDef.typeName); } else { final String typeDefJson = TypesSerialization.toJson(typeDef, false); final JSONObject type = metadataService.createType(typeDefJson); LOG.info("####### registered type ", type); final List<String> typeNamesList = metadataService.getTypeNamesList(); LOG.debug("####### registered typeNames ", typeNamesList); } }
Source:
<code><START> Closeables() { <END> }</code><technical_language>meant private Closeables() right? is need instantiate this class. TBH, I get rid of this constructor, class default access all..</technical_language>

Target:
private Closeables() { }
Source:
<code>public void setUp() throws Exception { <START> executeString("create database " + getCurrentDatabase()).close(); <END> }</code><technical_language>Current database is automatically created dropped. need do explicitly</technical_language>

Target:
public static void setUp() throws Exception { FileSystem fs = FileSystem.get(conf); Path rootDir = TajoConf.getWarehouseDir(testingCluster.getConfiguration()); Schema schema = new Schema(); schema.addColumn("n_nationkey", TajoDataTypes.Type.INT8); schema.addColumn("n_name", TajoDataTypes.Type.TEXT); schema.addColumn("n_regionkey", TajoDataTypes.Type.INT8); TableMeta meta = CatalogUtil.newTableMeta("TEXT", new KeyValueSet()); createExternalTableIncludedOnePartitionKeyColumn(fs, rootDir, schema, meta); createExternalTableIncludedMultiplePartitionKeyColumns(fs, rootDir, schema, meta); }
Source:
<code>private void prepareTest() { runner = spy(new LocalApplicationRunner(mockApp, config)); <START> localPlanner = spy((LocalJobConfigPlanner) Whitebox.getInternalState(runner, "planner")); <END> Whitebox.setInternalState(runner, "planner", localPlanner); }</code><technical_language>Instead of Whitebox, a test constructor accepts a planner? Reflection harder find usages do refactoring</technical_language>

Target:
private void prepareTest() { ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc = ApplicationDescriptorUtil.getAppDescriptor(mockApp, config); localPlanner = spy(new LocalJobPlanner(appDesc)); runner = spy(new LocalApplicationRunner(appDesc, localPlanner)); }
Source:
<code>public ElideResponse get(String path, MultivaluedMap<String, String> queryParams, User opaqueUser, String apiVersion, UUID requestId) { return handleRequest(true, opaqueUser, dataStore::beginReadTransaction, requestId, (tx, user) -> { JsonApiDocument jsonApiDoc = new JsonApiDocument(); RequestScope requestScope = new RequestScope(path, apiVersion, jsonApiDoc, tx, user, queryParams, requestId, elideSettings); EntityProjection projection = new EntityProjectionMaker(elideSettings.getDictionary(), requestScope).parsePath(path); requestScope.setEntityProjection(projection); BaseVisitor visitor = new GetVisitor(requestScope); <START> elideAcceptQuery(requestScope, opaqueUser, requestScope.getQueryParams(), path); <END> elideProcessQuery(projection, requestScope, tx); return visit(path, requestScope, visitor); }); }</code><technical_language>order is wrong. accept query build entity projection. entity projection includes parsing code throw exception/error. queries wont' get logged. - accepting a query move handleRequest function</technical_language>

Target:
public ElideResponse get(String path, MultivaluedMap<String, String> queryParams, User opaqueUser, String apiVersion, UUID requestId) { return handleRequest(true, opaqueUser, dataStore::beginReadTransaction, requestId, (tx, user) -> { JsonApiDocument jsonApiDoc = new JsonApiDocument(); RequestScope requestScope = new RequestScope(path, apiVersion, jsonApiDoc, tx, user, queryParams, requestId, elideSettings); elideAcceptQuery(requestScope, opaqueUser, requestScope.getQueryParams(), path); EntityProjection projection = new EntityProjectionMaker(elideSettings.getDictionary(), requestScope).parsePath(path); requestScope.setEntityProjection(projection); BaseVisitor visitor = new GetVisitor(requestScope); elideProcessQuery(projection, requestScope, tx); return visit(path, requestScope, visitor); }); }
Source:
<code>public void close() throws Exception { <START> super.close(); <END> getMeasured().close(); }</code><technical_language>please change this a bit? Stopping timer is important closing resource, if stopping timer throws kind of exception stop resource. do more like. try { super.close(); } finally { getMeasured().close(); } This guarantee close resource always, if exception is thrown in cases resource exception takes precedent in newer versions of java other exception show a Suppressed exception</technical_language>

Target:
public void close() throws Exception { try { super.close(); } finally { getMeasured().close(); } }
Source:
<code>public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean processResults; try { processResults = createAccountingDocumentService.createAccountingDocumentsFromXml(); } catch (Exception e) { <START> LOG.error("execute, An error has ocurred while processing input files.", e); <END> processResults = false; } LOG.info("execute, the processing results are: " + processResults); return processResults; }</code><technical_language>Minor typo in error message; "occurred" instead of "ocurred"</technical_language>

Target:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean processResults; try { processResults = createAccountingDocumentService.createAccountingDocumentsFromXml(); } catch (Exception e) { LOG.error("execute, An error has occurred while processing input files.", e); processResults = false; } if (processResults) { LOG.info("execute, The job ran successfully"); } else { LOG.warn("execute, there were non business rules errors that caused this job to fail"); } return processResults; }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (divBy != 0 && children.get(0).evaluate(tuple, ptr)) { Timestamp ts = (Timestamp)PDataType.TIMESTAMP.toObject(ptr, children.get(0).getColumnModifier()); Timestamp roundedTs; <START> if(divBy == 1 && ts.getNanos() > java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(1)/2) { <END> roundedTs = new Timestamp(roundTime(ts.getTime() + 1)); } else { roundedTs = new Timestamp(roundTime(ts.getTime())); } byte[] byteValue = getDataType().toBytes(roundedTs , children.get(0).getColumnModifier()); ptr.set(byteValue); return true; } return false; }</code><technical_language>Define this static constant: java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(1)/2</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (children.get(0).evaluate(tuple, ptr)) { ColumnModifier columnModifier = children.get(0).getColumnModifier(); PDataType dataType = getDataType(); int nanos = dataType.getNanos(ptr, columnModifier); if(nanos / divBy >= HALF_OF_NANOS_IN_MILLI) { long timeMillis = dataType.getMillis(ptr, columnModifier); Timestamp roundedTs = new Timestamp(timeMillis + 1); byte[] byteValue = dataType.toBytes(roundedTs); ptr.set(byteValue); } return true; } return false; }
Source:
<code>public boolean exchangeableCoupon(long couponId, String loginName){ <START> long exchange_point = couponExchangeMapper.findByCouponId(couponId).getExchangePoint(); <END> long availablePoint = accountMapper.findUsersAccountAvailablePoint(loginName); CouponModel couponModel = couponMapper.lockById(couponId); return availablePoint >= exchange_point && couponModel.getIssuedCount() <= couponModel.getTotalCount(); }</code><technical_language>exchangePoint</technical_language>

Target:
public boolean exchangeableCoupon(long couponId, String loginName){ long exchangePoint = couponExchangeMapper.findByCouponId(couponId).getExchangePoint(); long availablePoint = accountMapper.findUsersAccountAvailablePoint(loginName); CouponModel couponModel = couponMapper.lockById(couponId); return availablePoint >= exchangePoint && couponModel.getIssuedCount() <= couponModel.getTotalCount(); }
Source:
<code>private Set<HistoricalChannelEntry> calculateChannelHistory(Channel input) { Builder<HistoricalChannelEntry> entries = ImmutableSet.builder(); for (TemporalField<String> title : input.getAllTitles()) { if (title.getStartDate() == null) { continue; } HistoricalChannelEntry entry = new HistoricalChannelEntry(title.getStartDate()); entry.setTitle(title.getValue()); Iterable<Image> primaryImages = Iterables.filter( input.getImagesForDate(title.getStartDate()), Channel.IS_PRIMARY_IMAGE ); if (!Iterables.isEmpty(primaryImages)) { entry.setImage(Iterables.getOnlyElement(primaryImages).getCanonicalUri()); } entry.setImages(Iterables.transform( input.getImagesForDate(title.getStartDate()), <START> input1 -> imageSimplifier.simplify(input1, ImmutableSet.of(), null) <END> )); entries.add(entry); } for (TemporalField<Image> image : input.getAllImages()) { if (image.getStartDate() == null) { continue; } HistoricalChannelEntry entry = new HistoricalChannelEntry(image.getStartDate()); entry.setTitle(input.getTitleForDate(image.getStartDate())); entry.setImage(image.getValue().getCanonicalUri()); entry.setImages(Iterables.transform( input.getImagesForDate(image.getStartDate()), input12 -> imageSimplifier.simplify(input12, ImmutableSet.of(), null) )); entries.add(entry); } return entries.build(); }</code><technical_language>Ditto input1</technical_language>

Target:
private Set<HistoricalChannelEntry> calculateChannelHistory(Channel input) { Builder<HistoricalChannelEntry> entries = ImmutableSet.builder(); for (TemporalField<String> title : input.getAllTitles()) { if (title.getStartDate() == null) { continue; } HistoricalChannelEntry entry = new HistoricalChannelEntry(title.getStartDate()); entry.setTitle(title.getValue()); Iterable<Image> primaryImages = input.getImagesForDate(title.getStartDate()).stream() .filter(Channel.IS_PRIMARY_IMAGE::apply) .collect(Collectors.toList()); if (!Iterables.isEmpty(primaryImages)) { entry.setImage(Iterables.getOnlyElement(primaryImages).getCanonicalUri()); } entry.setImages(input.getImagesForDate(title.getStartDate()).stream() .map(imageForDate -> imageSimplifier.simplify(imageForDate, ImmutableSet.of(), null)) .collect(Collectors.toList()) ); entries.add(entry); } for (TemporalField<Image> image : input.getAllImages()) { if (image.getStartDate() == null) { continue; } HistoricalChannelEntry entry = new HistoricalChannelEntry(image.getStartDate()); entry.setTitle(input.getTitleForDate(image.getStartDate())); entry.setImage(image.getValue().getCanonicalUri()); entry.setImages(input.getImagesForDate(image.getStartDate()).stream() .map(imageForDate -> imageSimplifier.simplify(imageForDate, ImmutableSet.of(), null)) .collect(Collectors.toList()) ); entries.add(entry); } return entries.build(); }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTreeImpl methodTree = (MethodTreeImpl) tree; if (BooleanUtils.isFalse(methodTree.isOverriding())) { MethodSymbol methodSymbol = methodTree.symbol(); TypeSymbol owner = (TypeSymbol) methodSymbol.owner(); Type superClass = owner.superClass(); if(superClass != null && !SERIALIZATION_METHOD_NAME.contains(methodSymbol.name())) { checkMethod(methodTree.simpleName(), methodSymbol, superClass); superClass = superClass.symbol().superClass(); while (superClass != null) { <START> checkStaticMethod(methodTree.simpleName(), methodSymbol, superClass); <END> superClass = superClass.symbol().superClass(); } } } }</code><technical_language>If is methods in hierarchy, this call raise issue</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTreeImpl methodTree = (MethodTreeImpl) tree; if (BooleanUtils.isFalse(methodTree.isOverriding())) { MethodSymbol methodSymbol = methodTree.symbol(); TypeSymbol owner = (TypeSymbol) methodSymbol.owner(); Type superClass = owner.superClass(); if(superClass != null && !SERIALIZATION_METHOD_NAME.contains(methodSymbol.name())) { boolean reportStaticIssue = checkMethod(methodTree.simpleName(), methodSymbol, superClass); superClass = superClass.symbol().superClass(); while (superClass != null && !reportStaticIssue) { reportStaticIssue = checkStaticMethod(methodTree.simpleName(), methodSymbol, superClass); superClass = superClass.symbol().superClass(); } } } }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) .add("host", host) .add("port", port) .add("username", username) <START> .add("type", type) <END> .add("nonProxyHosts", nonProxyHosts) .toString(); }</code><technical_language>This removed, displayed redacted: .add("password", "[credentials redacted]")</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("host", host) .add("port", port) .add("username", username) .add("password", password == null ? "null" : "*********") .add("type", type) .add("nonProxyHosts", nonProxyHosts) .toString(); }
Source:
<code>public BooleanWrapper createNodeSource(String nodeSourceName, String infrastructureType, Object[] infrastructureParameters, String policyType, Object[] policyParameters, boolean nodesRecoverable) { if (nodeSourceName == null) { throw new IllegalArgumentException("Node Source name cannot be null"); } nodeSourceName = nodeSourceName.trim(); NodeSourceData nodeSourceData = new NodeSourceData(nodeSourceName, infrastructureType, infrastructureParameters, policyType, policyParameters, caller, nodesRecoverable); boolean added = dbManager.addNodeSource(nodeSourceData); try { return createNodeSource(nodeSourceData, nodesRecoverable); } catch (RuntimeException ex) { logger.error(ex.getMessage(), ex); <START> if (added && !(ex instanceof NodeSourceNameAlreadyExistException)) { <END> dbManager.removeNodeSource(nodeSourceName); } throw ex; } }</code><technical_language>catch NodeSourceNameAlreadyExistException instead of checking type</technical_language>

Target:
public BooleanWrapper createNodeSource(String nodeSourceName, String infrastructureType, Object[] infrastructureParameters, String policyType, Object[] policyParameters, boolean nodesRecoverable) { if (nodeSourceName == null) { throw new IllegalArgumentException("Node Source name cannot be null"); } nodeSourceName = nodeSourceName.trim(); NodeSourceData nodeSourceData = new NodeSourceData(nodeSourceName, infrastructureType, infrastructureParameters, policyType, policyParameters, caller, nodesRecoverable); boolean added = dbManager.addNodeSource(nodeSourceData); try { return createNodeSource(nodeSourceData, nodesRecoverable); } catch (NodeSourceNameAlreadyExistException e) { logger.error(e.getMessage(), e); throw e; } catch (RuntimeException ex) { logger.error(ex.getMessage(), ex); if (added) { dbManager.removeNodeSource(nodeSourceName); } throw ex; } }
Source:
<code>public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(httpResponse -> { try { httpResponse.getBody().subscribe().dispose(); <START> } catch (Throwable ignored) { <END> } }) .map(res -> res.getHeaderValue(WWW_AUTHENTICATE)) .map(header -> extractChallenge(header, BEARER_TOKEN_PREFIX)) .flatMap(map -> { cache.setTokenRequest(new TokenRequestContext().addScopes(map.get("resource") + "/.default")); return cache.getToken(); }) .flatMap(token -> { context.getHttpRequest().setHeader(AUTHORIZATION, BEARER_TOKEN_PREFIX + token.getToken()); return next.process(); }); }</code><technical_language>this throwable logged warning</technical_language>

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(httpResponse -> { try { httpResponse.getBody().subscribe().dispose(); } catch (RuntimeException ignored) { logger.logExceptionAsWarning(ignored); } }) .map(res -> res.getHeaderValue(WWW_AUTHENTICATE)) .map(header -> extractChallenge(header, BEARER_TOKEN_PREFIX)) .flatMap(map -> { cache.setTokenRequest(new TokenRequestContext().addScopes(map.get("resource") + "/.default")); return cache.getToken(); }) .flatMap(token -> { context.getHttpRequest().setHeader(AUTHORIZATION, BEARER_TOKEN_PREFIX + token.getToken()); return next.process(); }); }
Source:
<code>public void start( StageExecution execution ) { StringBuilder names = new StringBuilder(); <START> names.append( names.length() > 0 ? ", " : "" ).append( execution.getStageName() ); <END> out.println( format( "%n>>>>> EXECUTING STAGE(s) %s <<<<<%n", names ) ); }</code><technical_language>This message construction simplified stage now, reason names variable, EXECUTING STAGE STAGES</technical_language>

Target:
public void start( StageExecution execution ) { out.println( format( "%n>>>>> EXECUTING STAGE %s <<<<<%n", execution.getStageName() ) ); }
Source:
<code><START> private static IBinding resolveGetFunction(ICompositeType classType, IASTNode point, ICPPEvaluation argument, <END> ICPPEvaluation index) { IBinding[] allGetBindings = CPPSemantics.findBindings(classType.getCompositeScope(), GET_NAME, false); ICPPFunction[] functions = Arrays.stream(allGetBindings).filter(IFunction.class::isInstance) .map(IFunction.class::cast).toArray(ICPPFunction[]::new); ICPPTemplateArgument[] arguments = new ICPPTemplateArgument[] { new CPPTemplateNonTypeArgument(index) }; LookupData lookupGet = new LookupData(GET_NAME, arguments, point); lookupGet.setFunctionArguments(true, argument); try { return CPPSemantics.resolveFunction(lookupGet, functions, true, true); } catch (DOMException e) { return null; } }</code><technical_language>this function handles a member get() function, a non-member get() function? Structured bindings work either</technical_language>

Target:
private static IBinding resolveGetFunction(ICompositeType classType, IASTNode point, ICPPEvaluation argument, ICPPEvaluation index) { IBinding[] allGetBindings = CPPSemantics.findBindings(classType.getCompositeScope(), GET_NAME, false, point); ICPPFunction[] functions = Arrays.stream(allGetBindings).filter(IFunction.class::isInstance) .map(IFunction.class::cast).toArray(ICPPFunction[]::new); ICPPTemplateArgument[] arguments = new ICPPTemplateArgument[] { new CPPTemplateNonTypeArgument(index) }; LookupData lookupGet = new LookupData(GET_NAME, arguments, point); lookupGet.setFunctionArguments(true, argument); try { return CPPSemantics.resolveFunction(lookupGet, functions, true, true); } catch (DOMException e) { return null; } }
Source:
<code><START> private boolean isWatchListFilter(String filter) { <END> return filter.isEmpty() || filter.matches(WATCH_LIST_FILTER_REGEX); }</code><technical_language>This static</technical_language>

Target:
public static boolean isWatchListFilter(String filter) { return filter.isEmpty() || filter.matches(WATCH_LIST_FILTER_REGEX); }
Source:
<code>public void testAlterReplicaLogDirsUnrequested() throws Exception { Node node0 = new Node(0, "localhost", 8120); Node node1 = new Node(1, "localhost", 8121); try (AdminClientUnitTestEnv env = mockClientEnv()) { createAlterLogDirsResponse(env, node0, Errors.NONE, 0); createAlterLogDirsResponse(env, node1, Errors.NONE, 1, 2); TopicPartitionReplica tpr0 = new TopicPartitionReplica("topic", 0, 0); <START> TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 0, 1); <END> Map<TopicPartitionReplica, String> logDirs = new HashMap<>(); logDirs.put(tpr0, "/data0"); logDirs.put(tpr1, "/data1"); AlterReplicaLogDirsResult result = env.adminClient().alterReplicaLogDirs(logDirs); TestUtils.assertFutureError(result.values().get(tpr1), IllegalStateException.class); } }</code><technical_language>Do intentionally a TopicPartitionReplica is provided in response here? I guess is ensure future is completed, it</technical_language>

Target:
public void testAlterReplicaLogDirsUnrequested() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { createAlterLogDirsResponse(env, env.cluster().nodeById(0), Errors.NONE, 1, 2); TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 1, 0); Map<TopicPartitionReplica, String> logDirs = new HashMap<>(); logDirs.put(tpr1, "/data1"); AlterReplicaLogDirsResult result = env.adminClient().alterReplicaLogDirs(logDirs); assertNull(result.values().get(tpr1).get()); } }
Source:
<code>protected void cleanup(Context context) throws IOException, InterruptedException{ String strNumOfRegions = PhoenixConfigurationUtil.getNumOfRegions(context.getConfiguration()); if (strNumOfRegions != null) { String fullTableName = PhoenixConfigurationUtil.getInputTableName(context.getConfiguration()); int newNumRegions = regionCountForTesting != null ? regionCountForTesting : IndexUtil.getNumOfRegions(context.getConfiguration(), fullTableName); int prevNumRegions = Integer.parseInt(strNumOfRegions); if (newNumRegions != prevNumRegions) { <START> throw new IOException(String.format("Data table split/merge happened during Index rebuild. Old region cnt=%d, New region cnt = %d" <END> , prevNumRegions, newNumRegions)); } } try { IndexToolUtil.updateIndexState(context.getConfiguration(), PIndexState.ACTIVE); updateTasksTable(context); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } }</code><technical_language>nit: please extract message a static string</technical_language>

Target:
protected void cleanup(Context context) throws IOException, InterruptedException{ String strNumOfRegions = PhoenixConfigurationUtil.getNumOfRegions(context.getConfiguration()); if (strNumOfRegions != null) { String fullTableName = PhoenixConfigurationUtil.getInputTableName(context.getConfiguration()); final Properties overrideProps = new Properties(); try { final Connection connection = ConnectionUtil.getOutputConnection(context.getConfiguration(), overrideProps); int newNumRegions = regionCountForTesting != null ? regionCountForTesting : IndexUtil.getNumOfRegions(connection, fullTableName); int prevNumRegions = Integer.parseInt(strNumOfRegions); if (newNumRegions != prevNumRegions) { throw new IOException(String.format(SPLIT_MERGE_ERROR_STR_FMT, prevNumRegions, newNumRegions)); } } catch (SQLException e) { LOGGER.error("Failed get the number of regions"); throw new RuntimeException(e.getMessage()); } } try { IndexToolUtil.updateIndexState(context.getConfiguration(), PIndexState.ACTIVE); updateTasksTable(context); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } }
Source:
<code>public void init(Config config, TaskContext taskContext) { int numberOfTasks = taskContext.getSamzaContainerContext().taskNames.size(); this.tagToRateLimiterMap = Collections.unmodifiableMap(tagToTargetRateMap.entrySet().stream() .map(e -> { String tag = e.getKey(); Integer ratePerTask = e.getValue() / numberOfTasks; return new ImmutablePair<String, com.google.common.util.concurrent.RateLimiter>( <START> tag, com.google.common.util.concurrent.RateLimiter.create(ratePerTask)); <END> }) .collect(Collectors.toMap(ImmutablePair::getKey, ImmutablePair::getValue)) ); }</code><technical_language>nit: log effective rate here</technical_language>

Target:
public void init(Config config, TaskContext taskContext) { this.tagToRateLimiterMap = Collections.unmodifiableMap(tagToTargetRateMap.entrySet().stream() .map(e -> { String tag = e.getKey(); int effectiveRate = e.getValue(); if (taskContext != null) { effectiveRate /= taskContext.getSamzaContainerContext().taskNames.size(); LOGGER.info(String.format("Effective rate limit for task %s and tag %s is %d", taskContext.getTaskName(), tag, effectiveRate)); } return new ImmutablePair<String, com.google.common.util.concurrent.RateLimiter>( tag, com.google.common.util.concurrent.RateLimiter.create(effectiveRate)); }) .collect(Collectors.toMap(ImmutablePair::getKey, ImmutablePair::getValue)) ); }
Source:
<code>public void setProviders( Map<String, Map.Entry<String, BlobStore>> providers) { <START> this.providers = providers; <END> }</code><technical_language>this defensively copy, instead offer add remove interface</technical_language>

Target:
public void setProviders( Map<String, Map.Entry<String, BlobStore>> providers) { this.providers = ImmutableMap.copyOf(providers); }
Source:
<code>private void pipelined(int depth) throws Exception { System.out.println("Starting pipelined with depth:"+depth); long startMs = System.currentTimeMillis(); Random random = new Random(); for (int i = 0; i < iterations; i++) { Pipeline pipeline = new Pipeline(depth); for (long k = 0; k < getsPerIteration; k++) { int key = random.nextInt(keyDomain); pipeline.add(map.getAsync(key)); } pipeline.results(); } long duration = System.currentTimeMillis(); <START> System.out.println("Pipedlined with depth:" + depth + ", duration:" + (duration - startMs) + " ms"); <END> }</code><technical_language>typo: "Pipedlined"</technical_language>

Target:
private void pipelined(int depth) throws Exception { System.out.println("Starting pipelined with depth:" + depth); long startMs = System.currentTimeMillis(); Random random = new Random(); for (int i = 0; i < iterations; i++) { Pipelining<String> pipelining = new Pipelining<String>(depth); for (long k = 0; k < getsPerIteration; k++) { int key = random.nextInt(keyDomain); pipelining.add(map.getAsync(key)); } List<String> results = pipelining.results(); if (results.size() != getsPerIteration) { throw new RuntimeException(); } } long duration = System.currentTimeMillis(); System.out.println("Pipelined with depth:" + depth + ", duration:" + (duration - startMs) + " ms"); }
Source:
<code>public ResponseEntity<?> createLibrary(@RequestBody LibraryDto libraryDto, UriComponentsBuilder b) throws IOException { if (libraryDto == null) { log.error( "Received null libraryDto from front end; cannot convert to Library. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Library", Status.BAD_REQUEST); } Long id = null; try { Library library = Dtos.to(libraryDto); library.setCreationDate(new Date()); library.setSample(sampleService.get(libraryDto.getParentSampleId())); library.inheritPermissions(library.getSample()); <START> libraryService.save(library); <END> } catch (ConstraintViolationException | IllegalArgumentException e) { log.error("Error while creating library. ", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); if (e instanceof ConstraintViolationException) { restException.addData("constraintName", ((ConstraintViolationException) e).getConstraintName()); } throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(id); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }</code><technical_language>creationDate, sample fetch, permissions handled in Service</technical_language>

Target:
public ResponseEntity<?> createLibrary(@RequestBody LibraryDto libraryDto, UriComponentsBuilder b) throws IOException { if (libraryDto == null) { log.error( "Received null libraryDto from front end; cannot convert to Library. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Library", Status.BAD_REQUEST); } Long id = null; try { Library library = Dtos.to(libraryDto); libraryService.create(library); } catch (ConstraintViolationException | IllegalArgumentException e) { log.error("Error while creating library. ", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); if (e instanceof ConstraintViolationException) { restException.addData("constraintName", ((ConstraintViolationException) e).getConstraintName()); } throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(id); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }
Source:
<code>public boolean hasExplicitPermission(String sid, Permission p) { Set<String> set = grantedPermissions.get(p); if (set != null && p.getEnabled()) { if (set.contains(sid)) return true; <START> final SecurityRealm securityRealm = Jenkins.getInstance().getSecurityRealm(); <END> final IdStrategy groupIdStrategy = securityRealm.getGroupIdStrategy(); final IdStrategy userIdStrategy = securityRealm.getUserIdStrategy(); for (String s: set) { if (userIdStrategy.equals(s, sid) || groupIdStrategy.equals(s, sid)) { return true; } } } return false; }</code><technical_language>Null check</technical_language>

Target:
public boolean hasExplicitPermission(String sid, Permission p) { Set<String> set = grantedPermissions.get(p); if (set != null && p.getEnabled()) { if (set.contains(sid)) return true; final SecurityRealm securityRealm = Jenkins.getActiveInstance().getSecurityRealm(); final IdStrategy groupIdStrategy = securityRealm.getGroupIdStrategy(); final IdStrategy userIdStrategy = securityRealm.getUserIdStrategy(); for (String s: set) { if (userIdStrategy.equals(s, sid) || groupIdStrategy.equals(s, sid)) { return true; } } } return false; }
Source:
<code>public void testLayerDisabledServiceResponse() throws Exception { <START> enableWFS(); <END> String layerName = "cite:RoadSegments"; LayerInfo linfo = getCatalog().getLayerByName(layerName); ResourceInfo ri = linfo.getResource(); ri.setServiceConfiguration(true); ri.setDisabledServices(new ArrayList<>(Arrays.asList("WFS"))); getCatalog().save(ri); getCatalog().save(linfo); Document doc = getAsDOM( "wfs?request=GetFeature&typeName=" + layerName + "&version=1.0.0&service=wfs"); assertEquals("ServiceExceptionReport", doc.getDocumentElement().getNodeName()); }</code><technical_language>a Capatabilities test for completeness (checking feature type is gone, others there)</technical_language>

Target:
public void testLayerDisabledServiceResponse() throws Exception { enableWFS(); String layerName = "cite:RoadSegments"; FeatureTypeInfo ftinfo = getCatalog().getFeatureTypeByName(layerName); ftinfo.setServiceConfiguration(true); ftinfo.setDisabledServices(new ArrayList<>(Arrays.asList("WFS"))); getCatalog().save(ftinfo); Document doc = getAsDOM( "wfs?request=GetFeature&typeName=" + layerName + "&version=1.0.0&service=wfs"); assertEquals("ServiceExceptionReport", doc.getDocumentElement().getNodeName()); doc = getAsDOM("wfs?service=WFS&version=1.1.0&request=getCapabilities"); XMLAssert.assertXpathNotExists( " }
Source:
<code>public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { ObjectUtil.checkPositiveOrZero(offset, "offset"); ObjectUtil.checkPositiveOrZero(length, "length"); <START> this.file = ObjectUtil.checkNotNull(file, "file"); <END> this.chunkSize = ObjectUtil.checkPositive(chunkSize, "chunkSize"); this.offset = startOffset = offset; endOffset = offset + length; file.seek(offset); }</code><technical_language>move this assignment check in method change behaviour</technical_language>

Target:
public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { ObjectUtil.checkNotNull(file, "file"); ObjectUtil.checkPositiveOrZero(offset, "offset"); ObjectUtil.checkPositiveOrZero(length, "length"); ObjectUtil.checkPositive(chunkSize, "chunkSize"); this.file = file; this.offset = startOffset = offset; this.endOffset = offset + length; this.chunkSize = chunkSize; file.seek(offset); }
Source:
<code>public void testDRepresentationContainerRemovalMigrationDone() { ResourceSet set = new ResourceSetImpl(); DAnalysis analysis = null; try { analysis = (DAnalysis) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), set); } catch (IOException e) { failCheckData(); } assertNotNull("Check the representation file test data.", analysis); assertTrue("Check the migration logic.", ((XMLResource) <START> analysis.eResource()).getEObjectToExtensionMap().size() == 0); <END> String version = analysis.getVersion(); assertTrue("Before save, the migration framework will return true even if the migration has been done during load.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); try { analysis.eResource().save(Collections.emptyMap()); } catch (IOException e) { failCheckData(); } version = analysis.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); checkFileContainsDRepresentationContainer(analysis.eResource().getURI(), false, "After migration, the resource should not contains any DRepresentationContainer."); assertFalse(getErrorLoggersMessage(), doesAnErrorOccurs()); }</code><technical_language>isEmpty</technical_language>

Target:
public void testDRepresentationContainerRemovalMigrationDone() { ResourceSet set = new ResourceSetImpl(); DAnalysis analysis = null; try { analysis = (DAnalysis) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), set); } catch (IOException e) { failCheckData(); } assertNotNull("Check the representation file test data.", analysis); assertTrue("Check the migration logic.", ((XMLResource) analysis.eResource()).getEObjectToExtensionMap().isEmpty()); String version = analysis.getVersion(); assertTrue("Before save, the migration framework will return true even if the migration has been done during load.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); try { analysis.eResource().save(Collections.emptyMap()); } catch (IOException e) { failCheckData(); } version = analysis.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", RepresentationsFileMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); checkFileContainsDRepresentationContainer(analysis.eResource().getURI(), false, "After migration, the resource should not contains any DRepresentationContainer."); assertFalse(getErrorLoggersMessage(), doesAnErrorOccurs()); }
Source:
<code>public void validate_shouldFailIfTheObjectParameterIsNull() throws Exception { Errors errors = new BindException(null, "concept"); new ConceptValidator().validate(null, errors); <START> Assert.assertTrue(errors.hasFieldErrors()); <END> }</code><technical_language>changing this? If object is null, of fields validate i expect filed errors</technical_language>

Target:
public void validate_shouldFailIfTheObjectParameterIsNull() throws Exception { Errors errors = new BindException(null, "concept"); new ConceptValidator().validate(null, errors); Assert.assertTrue(errors.hasErrors()); }
Source:
<code>private File[] listFiles( final File folder, final String fileExtension ) throws IOException { <START> if ( folder.exists() && folder.isDirectory() && folder.canRead() ) { <END> return folder.listFiles( new FileFilter() { @Override public boolean accept( File f ) { return f.isFile() && f.getName().toLowerCase().endsWith( fileExtension ); } } ); } else { logger.error( folder.getAbsolutePath() + " is not a valid directory" ); } return null; }</code><technical_language>ERROR messages need externalinzed (anything other DEBUG, really)</technical_language>

Target:
private File[] listFiles( final File folder, final String fileExtension ) { if ( folder.isDirectory() && folder.canRead() ) { return folder.listFiles( new FileFilter() { @Override public boolean accept( File f ) { return f.isFile() && f.getName().toLowerCase().endsWith( fileExtension ); } } ); } else { logger.error( folder.getAbsolutePath() + " is not a valid directory" ); } return null; }