auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FolderListing getFolderListing( final Path path ) { final List<FolderItem> folderItems = new ArrayList<FolderItem>(); org.uberfire.java.nio.file.Path nioPath = Paths.convert( path ); while ( !Files.exists( nioPath ) ) { nioPath = nioPath.getParent(); } final Path basePath = Paths.convert( nioPath ); final DirectoryStream<org.uberfire.java.nio.file.Path> nioPaths = ioService.newDirectoryStream( nioPath, dotFileFilter ); for ( org.uberfire.java.nio.file.Path np : nioPaths ) { if ( Files.isRegularFile( np ) ) { final org.uberfire.backend.vfs.Path p = Paths.convert( np ); final String lockedBy = Paths.readLockedBy( p ); final FolderItem folderItem = new FolderItem( p, p.getFileName(), FolderItemType.FILE, false, lockedBy, metadataService.getMetadata( p ).getTags() ); folderItems.add( folderItem ); } else if ( Files.isDirectory( np ) ) { final org.uberfire.backend.vfs.Path p = Paths.convert( np ); boolean lockedItems = !lockService.retrieveLockInfos( Paths.convert( np ), true ).isEmpty(); final FolderItem folderItem = new FolderItem( p, p.getFileName(), FolderItemType.FOLDER, lockedItems, <START> null, null); <END> folderItems.add( folderItem ); } } Collections.sort( folderItems, Sorters.ITEM_SORTER ); return new FolderListing( toFolderItem( nioPath ), folderItems, getPathSegments( basePath ) ); }</code><technical_language>null passed in twice. I a bad example left in previous dev worked this part ;-) (I hope me)</technical_language>

Target:
public FolderListing getFolderListing( final Path path ) { final List<FolderItem> folderItems = new ArrayList<FolderItem>(); org.uberfire.java.nio.file.Path nioPath = Paths.convert( path ); while ( !Files.exists( nioPath ) ) { nioPath = nioPath.getParent(); } final Path basePath = Paths.convert( nioPath ); final DirectoryStream<org.uberfire.java.nio.file.Path> nioPaths = ioService.newDirectoryStream( nioPath, dotFileFilter ); for ( org.uberfire.java.nio.file.Path np : nioPaths ) { if ( Files.isRegularFile( np ) ) { final org.uberfire.backend.vfs.Path p = Paths.convert( np ); final String lockedBy = Paths.readLockedBy( p ); final FolderItem folderItem = new FolderItem( p, p.getFileName(), FolderItemType.FILE, false, lockedBy, metadataService.getMetadata( p ).getTags() ); folderItems.add( folderItem ); } else if ( Files.isDirectory( np ) ) { final org.uberfire.backend.vfs.Path p = Paths.convert( np ); boolean lockedItems = !lockService.retrieveLockInfos( Paths.convert( np ), true ).isEmpty(); final FolderItem folderItem = new FolderItem( p, p.getFileName(), FolderItemType.FOLDER, lockedItems, null, new ArrayList<String>( )); folderItems.add( folderItem ); } } Collections.sort( folderItems, Sorters.ITEM_SORTER ); return new FolderListing( toFolderItem( nioPath ), folderItems, getPathSegments( basePath ) ); }
Source:
<code>public static void runCleanupTask(Runnable task) { try { task.run(); <START> } catch (Throwable t) { <END> log.error("Failed to cleanup pre-commit condition", t); } }</code><technical_language>100% if want swallow Errors - this Exception</technical_language>

Target:
public static void runCleanupTask(Runnable task) { try { task.run(); } catch (Exception t) { log.error("Failed to cleanup pre-commit condition", t); } }
Source:
<code><START> @Override public String getProcName() { <END> return getClass().getSimpleName() + " region=" + region.getEncodedName() + (targetServer != null? ", server=" + targetServer: ""); }</code><technical_language>difference of ProcName StringClassDetails is? targetServer add toStringClassDetails</technical_language>

Target:
@Override public String getProcName() { return getClass().getSimpleName() + " " + region.getEncodedName(); }
Source:
<code>public BitmapDrawable getDrawable(final String url) { if (StringUtils.isBlank(url) || isCounter(url)) { return new BitmapDrawable(resources, getTransparent1x1Image()); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? "shared" : geocode; Bitmap imagePre = loadImageFromStorage(url, pseudoGeocode, shared); if (imagePre == null) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { file.setLastModified(System.currentTimeMillis()); } } } catch (Exception e) { Log.e("HtmlImage.getDrawable (downloading from web)", e); } } } if (onlySave) { return null; } if (imagePre == null) { imagePre = loadImageFromStorage(url, pseudoGeocode, shared); } if (imagePre == null) { Log.d("HtmlImage.getDrawable: Failed to obtain image"); if (returnErrorImage) { imagePre = BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded); } else { imagePre = getTransparent1x1Image(); } } <START> final BitmapDrawable image = ImageHelper.scaleBitmapToFitDisplay(imagePre); <END> return image; }</code><technical_language>Please do create a variable return next line. java return ImageHelper.scaleBitmapToFitDisplay(imagePre);</technical_language>

Target:
public BitmapDrawable getDrawable(final String url) { if (StringUtils.isBlank(url) || isCounter(url)) { return new BitmapDrawable(resources, getTransparent1x1Image()); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? "shared" : geocode; Bitmap imagePre = loadImageFromStorage(url, pseudoGeocode, shared); if (imagePre == null) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { file.setLastModified(System.currentTimeMillis()); } } } catch (Exception e) { Log.e("HtmlImage.getDrawable (downloading from web)", e); } } } if (onlySave) { return null; } if (imagePre == null) { imagePre = loadImageFromStorage(url, pseudoGeocode, shared); } if (imagePre == null) { Log.d("HtmlImage.getDrawable: Failed to obtain image"); if (returnErrorImage) { imagePre = BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded); } else { imagePre = getTransparent1x1Image(); } } return ImageHelper.scaleBitmapToFitDisplay(imagePre); }
Source:
<code>public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus status = new RefactoringStatus(); if (document == null) { return status; } try { <START> CompletableFuture<List<LanguageServer>> serverList = LanguageServiceAccessor.getLanguageServers(document, LSPRenameProcessor::isPrepareRenameProvider) ; <END> for (LanguageServer serverToTry : serverList.get()) { if (languageServer.equals(serverToTry)) { TextDocumentIdentifier identifier = new TextDocumentIdentifier(LSPEclipseUtils.toUri(document).toString()); TextDocumentPositionParams params = new TextDocumentPositionParams(); params.setTextDocument(identifier); params.setPosition(LSPEclipseUtils.toPosition(offset, document)); prepareRenameResult = languageServer.getTextDocumentService().prepareRename(params).get(1000, TimeUnit.MILLISECONDS); if (prepareRenameResult == null) { status.addFatalError(Messages.rename_invalidated); } } } } catch (Exception e) { handleError(e, status); return new RefactoringStatus(); } return status; }</code><technical_language>I try more "reactive" in code style chaining futures timeout for chain instead of a timeout for operation. a blocker moment</technical_language>

Target:
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus status = new RefactoringStatus(); if (document == null) { return status; } try { CompletableFuture<List<LanguageServer>> serverList = LanguageServiceAccessor.getLanguageServers(document, LSPRenameProcessor::isPrepareRenameProvider) ; for (LanguageServer serverToTry : serverList.get(500, TimeUnit.MILLISECONDS)) { if (languageServer.equals(serverToTry)) { TextDocumentIdentifier identifier = new TextDocumentIdentifier(LSPEclipseUtils.toUri(document).toString()); TextDocumentPositionParams params = new TextDocumentPositionParams(); params.setTextDocument(identifier); params.setPosition(LSPEclipseUtils.toPosition(offset, document)); prepareRenameResult = languageServer.getTextDocumentService().prepareRename(params).get(1000, TimeUnit.MILLISECONDS); if (prepareRenameResult == null) { status.addFatalError(Messages.rename_invalidated); } } } } catch (Exception e) { handleError(e, status); return new RefactoringStatus(); } return status; }
Source:
<code>public void check(OperationResult result) { HealthStateType type = HealthStateType.general(HealthStateScope.forPipeline(pipelineName)); <START> if (triggerMonitor.isAlreadyTriggered(pipelineName) || pipelineScheduleQueue.hasForcedBuildCause(new CaseInsensitiveString(pipelineName))) { <END> result.conflict("Failed to trigger pipeline: " + pipelineName, "Pipeline already triggered", HealthStateType.general(HealthStateScope.forPipeline(pipelineName))); } else { result.success(type); } }</code><technical_language>pass CaseInsensitiveString constructor of this class</technical_language>

Target:
public void check(OperationResult result) { String pipelineNameString = CaseInsensitiveString.str(pipelineName); HealthStateType type = HealthStateType.general(HealthStateScope.forPipeline(pipelineNameString)); if (triggerMonitor.isAlreadyTriggered(pipelineName) || pipelineScheduleQueue.hasForcedBuildCause(pipelineName)) { result.conflict("Failed to trigger pipeline: " + pipelineName, "Pipeline already triggered", HealthStateType.general(HealthStateScope.forPipeline(pipelineNameString))); } else { result.success(type); } }
Source:
<code>public void reportIssue(PomCheck check, int line, String message, List<Location> secondary) { AnalyzerMessage analyzerMessage = new AnalyzerMessage(check, getFile(), line, message, 0); for (Location location : secondary) { AnalyzerMessage secondaryLocation; if (location.onLine()) { <START> secondaryLocation = new AnalyzerMessage(check, getFile(), location.line, location.msg, 0); <END> } else { secondaryLocation = new AnalyzerMessage(check, getFile(), location.tree.startLocation().line(), location.msg, 0); } analyzerMessage.flows.add(Collections.singletonList(secondaryLocation)); } getMessages().add(analyzerMessage); }</code><technical_language>move logic of line Location Location class need duplicate constructor call</technical_language>

Target:
public void reportIssue(PomCheck check, int line, String message, List<Location> secondary) { AnalyzerMessage analyzerMessage = new AnalyzerMessage(check, getFile(), line, message, 0); for (Location location : secondary) { AnalyzerMessage secondaryLocation = new AnalyzerMessage(check, getFile(), location.startLine(), location.msg, 0); analyzerMessage.flows.add(Collections.singletonList(secondaryLocation)); } getMessages().add(analyzerMessage); }
Source:
<code>public FileDiff(final Repository repo, final RevCommit c, final DiffEntry entry) { repository = repo; diffEntry = entry; commit = c; base = null; <START> } <END></code><technical_language>Delegate new Constructor</technical_language>

Target:
public FileDiff(final Repository repo, final RevCommit c, final DiffEntry entry) { this(repo, c, null, entry); }
Source:
<code>public boolean isAcceptableReplacement(Part part, boolean refit) { Part newPart = getNewPart(); newPart.setUnit(unit); if(part instanceof EquipmentPart) { EquipmentPart eqpart = (EquipmentPart)part; EquipmentType et = eqpart.getType(); <START> return type.equals(et) && getTonnage() == part.getTonnage() && size == eqpart.getSize() <END> && part.getStickerPrice().equals(newPart.getStickerPrice()); } return false; }</code><technical_language>== comparisons bracketed? Asking part of coding style guide for return values</technical_language>

Target:
public boolean isAcceptableReplacement(Part part, boolean refit) { Part newPart = getNewPart(); newPart.setUnit(unit); if(part instanceof EquipmentPart) { EquipmentPart eqpart = (EquipmentPart)part; EquipmentType et = eqpart.getType(); return (type.equals(et) && getTonnage() == part.getTonnage()) && (size == eqpart.getSize()) && part.getStickerPrice().equals(newPart.getStickerPrice()); } return false; }
Source:
<code>public int getClusterSize(String clusterId, String zoneId) { Cluster cluster = Preconditions.checkNotNull( <START> getCluster(clusterId, zoneId), "Cluster " + clusterId + " was not found"); <END> return cluster.getServeNodes(); }</code><technical_language>Error message zoneId. I this for message prints a cluster..</technical_language>

Target:
public int getClusterSize(String clusterId, String zoneId) { String message = String.format("Cluster %s/%s was not found.", clusterId, zoneId); Cluster cluster = Preconditions.checkNotNull(getCluster(clusterId, zoneId), message); return cluster.getServeNodes(); }
Source:
<code>public static CharSeq of(char... characters) { Objects.requireNonNull(characters, "characters is null"); final char[] chrs = new char[characters.length]; System.arraycopy(characters, 0, chrs, 0, characters.length); <START> return characters.length == 0 ? empty() : new CharSeq(new String(chrs)); <END> }</code><technical_language>Simone! I this check final char[] chrs = ... avoid instantiate empty char[]</technical_language>

Target:
public static CharSeq of(char... characters) { Objects.requireNonNull(characters, "characters is null"); if (characters.length == 0) { return empty(); } else { final char[] chrs = new char[characters.length]; System.arraycopy(characters, 0, chrs, 0, characters.length); return new CharSeq(new String(chrs)); } }
Source:
<code>public AutoCompletionCandidates doAutoCompleteJobName(@AncestorInPath Item project, @QueryParameter String value) { if (!project.hasPermission(Item.CONFIGURE) && project.hasPermission(Item.EXTENDED_READ)) { return new AutoCompletionCandidates(); } <START> project.checkPermission(Item.CONFIGURE); <END> ItemGroup parent = project.getParent(); AutoCompletionCandidates candidates = new AutoCompletionCandidates(); List<AbstractProject> jobs = getAllProjects(); for (AbstractProject job: jobs) { if (job.getFullName().startsWith(value) || job.getRelativeNameFrom(parent).startsWith(value)) { if (job.hasPermission(Item.READ)) { candidates.add(job.getFullName()); } } } return candidates; }</code><technical_language>Simpler if (!project.hasPermission(Item.CONFIGURE)) { return new AutoCompletionCandidates(); }</technical_language>

Target:
public AutoCompletionCandidates doAutoCompleteJobName(@AncestorInPath Item project, @QueryParameter String value) { if (!project.hasPermission(Item.CONFIGURE)) { return new AutoCompletionCandidates(); } project.checkPermission(Item.CONFIGURE); ItemGroup parent = project.getParent(); AutoCompletionCandidates candidates = new AutoCompletionCandidates(); List<AbstractProject> jobs = Jenkins.getInstance().getAllItems(AbstractProject.class); for (AbstractProject job: jobs) { if (job.getFullName().contains(value)) { if (job.hasPermission(Item.READ)) { candidates.add(job.getFullName()); } } } return candidates; }
Source:
<code>public void write(StreamsDatum streamsDatum) { if(streamsDatum == null || streamsDatum.getDocument() == null) return; <START> LOGGER.debug("Update Document: {}", streamsDatum.getDocument()); <END> Map<String, Object> metadata = streamsDatum.getMetadata(); LOGGER.debug("Update Metadata: {}", metadata); String index = null; String type = null; String id = streamsDatum.getId(); if( metadata != null && metadata.containsKey("index")) index = (String) streamsDatum.getMetadata().get("index"); if( metadata != null && metadata.containsKey("type")) type = (String) streamsDatum.getMetadata().get("type"); if( id == null && metadata != null && metadata.containsKey("id")) id = (String) streamsDatum.getMetadata().get("id"); if(index == null || (config.getForceUseConfig() != null && config.getForceUseConfig())) { index = config.getIndex(); } if(type == null || (config.getForceUseConfig() != null && config.getForceUseConfig())) { type = config.getType(); } String json; try { json = OBJECT_MAPPER.writeValueAsString(streamsDatum.getDocument()); LOGGER.debug("Attempt Update: ({},{},{}) {}", index, type, id, json); update(index, type, id, json); } catch (Throwable e) { LOGGER.warn("Unable to Update Document in ElasticSearch: {}", e.getMessage()); } }</code><technical_language>this block of logic is in more place. Do abstracted elsewhere</technical_language>

Target:
public void write(StreamsDatum streamsDatum) { if(streamsDatum == null || streamsDatum.getDocument() == null) return; LOGGER.debug("Update Document: {}", streamsDatum.getDocument()); Map<String, Object> metadata = streamsDatum.getMetadata(); LOGGER.debug("Update Metadata: {}", metadata); String index = getIndex(metadata, config); String type = getType(metadata, config); String id = getId(streamsDatum); String json; try { json = OBJECT_MAPPER.writeValueAsString(streamsDatum.getDocument()); LOGGER.debug("Attempt Update: ({},{},{}) {}", index, type, id, json); update(index, type, id, json); } catch (Throwable e) { LOGGER.warn("Unable to Update Document in ElasticSearch: {}", e.getMessage()); } }
Source:
<code>public Iterable<ServerDetails> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<ServerDetails>() { @Override public boolean apply(ServerDetails server) { <START> return Iterables.contains(ids, server.getId()); <END> } }); }</code><technical_language>More statics</technical_language>

Target:
public Iterable<ServerDetails> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<ServerDetails>() { @Override public boolean apply(ServerDetails server) { return contains(ids, server.getId()); } }); }
Source:
<code>private void createShallowFile(ObjectId... shallowCommits) throws IOException { final File shallow = new File(rw.repository.getDirectory(), "shallow"); <START> final PrintWriter writer = new PrintWriter(shallow); <END> try { for (ObjectId commit : shallowCommits) writer.println(commit.getName()); } finally { writer.close(); } }</code><technical_language>PrintWriter is terrible errorhandling, avoid cost. JGItTestUtil.write for writing simple files</technical_language>

Target:
private void createShallowFile(ObjectId... shallowCommits) throws IOException { final StringBuilder builder = new StringBuilder(); for (ObjectId commit : shallowCommits) builder.append(commit.getName() + "\n"); JGitTestUtil.write(new File(rw.repository.getDirectory(), "shallow"), builder.toString()); }
Source:
<code><START> public Mapping buildMapping() { <END> return new Mapping() { public IdentifierGeneratorFactory getIdentifierGeneratorFactory() { return identifierGeneratorFactory; } public Type getIdentifierType(String entityName) throws MappingException { PersistentClass pc = classes.get( entityName ); if ( pc == null ) { throw new MappingException( "persistent class not known: " + entityName ); } return pc.getIdentifier().getType(); } public String getIdentifierPropertyName(String entityName) throws MappingException { final PersistentClass pc = classes.get( entityName ); if ( pc == null ) { throw new MappingException( "persistent class not known: " + entityName ); } if ( !pc.hasIdentifierProperty() ) { return null; } return pc.getIdentifierProperty().getName(); } public Type getReferencedPropertyType(String entityName, String propertyName) throws MappingException { final PersistentClass pc = classes.get( entityName ); if ( pc == null ) { throw new MappingException( "persistent class not known: " + entityName ); } Property prop = pc.getReferencedProperty( propertyName ); if ( prop == null ) { throw new MappingException( "property not known: " + entityName + '.' + propertyName ); } return prop.getType(); } }; }</code><technical_language>delegate of work super-class instead of copying code there? return a Mapping delegates methods instance returned super-class override</technical_language>

Target:
public Mapping buildMapping() { final Mapping delegate = super.buildMapping(); return new Mapping() { public IdentifierGeneratorFactory getIdentifierGeneratorFactory() { return identifierGeneratorFactory; } public Type getIdentifierType(String entityName) throws MappingException { return delegate.getIdentifierType( entityName ); } public String getIdentifierPropertyName(String entityName) throws MappingException { return delegate.getIdentifierPropertyName( entityName ); } public Type getReferencedPropertyType(String entityName, String propertyName) throws MappingException { return delegate.getReferencedPropertyType( entityName, propertyName ); } }; }
Source:
<code>public Object visitGetKeysInGroupCommand(final InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); if (!command.isGroupOwner()) { return invokeNextInterceptor(ctx, command); } final KeyFilter<Object> keyFilter = new CompositeKeyFilter<>(new GroupFilter<>(groupName, groupManager), new CollectionKeyFilter<>(ctx.getLookedUpEntries().keySet())); dataContainer.executeTask(keyFilter, <START> new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry<Object, Object>>() { <END> @Override public void apply(Object o, InternalCacheEntry<? super Object, ? super Object> internalCacheEntry) { synchronized (ctx) { entryFactory.wrapEntryForReading(ctx, o, internalCacheEntry).setSkipLookup(true); } } }); return invokeNextInterceptor(ctx, command); }</code><technical_language>IntelliJ this, signature of apply() method is in interface</technical_language>

Target:
public Object visitGetKeysInGroupCommand(final InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); if (!command.isGroupOwner()) { return invokeNextInterceptor(ctx, command); } final KeyFilter<Object> keyFilter = new CompositeKeyFilter<>(new GroupFilter<>(groupName, groupManager), new CollectionKeyFilter<>(ctx.getLookedUpEntries().keySet())); dataContainer.executeTask(keyFilter, new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry<Object, Object>>() { @Override public void apply(Object o, InternalCacheEntry<Object, Object> internalCacheEntry) { synchronized (ctx) { entryFactory.wrapEntryForReading(ctx, o, internalCacheEntry).setSkipLookup(true); } } }); return invokeNextInterceptor(ctx, command); }
Source:
<code>private C3Donut createDonut() { <START> String donutHoleTitle = displayerSettings.getDonutHoleTitle(); <END> return factory.c3Donut(donutHoleTitle); }</code><technical_language>@yesamer Hi. This is a sort of jump of faith - displayerSettings is null (I do direct reference in this class - wrong) "donutHoleTitle" is null too. Beside - if want/need customize C3Donut instantiation, he/she override buildConfiguration method invoke a "createDonut" (being private, createDonut overrided) general observation, though</technical_language>

Target:
protected C3Donut createDonut() { String donutHoleTitle = displayerSettings.getDonutHoleTitle(); return factory.c3Donut(donutHoleTitle); }
Source:
<code>StreamEdge(StreamSpec streamSpec, boolean isIntermediate, boolean isBroadcast, Config config) { this.streamSpec = streamSpec; this.isIntermediate = isIntermediate; this.isBroadcast = <START> isBroadcast || config.getBoolean(String.format("streams.%s.samza.broadcast", streamSpec.getId()), false);; <END> this.config = config; if (isBroadcast && isIntermediate) { partitions = 1; } this.name = StreamUtil.getNameFromSystemStream(getSystemStream()); }</code><technical_language>Please add this "streams.%s.samza.broadcast" in StreamConfig (similar bootstrap). Please a need in doc</technical_language>

Target:
StreamEdge(StreamSpec streamSpec, boolean isIntermediate, boolean isBroadcast, Config config) { this.streamSpec = streamSpec; this.isIntermediate = isIntermediate; this.isBroadcast = isBroadcast || (config == null) ? false : new StreamConfig(config).getBroadcastEnabled(streamSpec.toSystemStream()); this.config = config; if (isBroadcast && isIntermediate) { partitions = 1; } this.name = StreamUtil.getNameFromSystemStream(getSystemStream()); }
Source:
<code>private String createJaasFile(String kerberizedNimbusServiceName) { try { Path jaasFilePath = Files.createTempFile("jaas-", UUID.randomUUID().toString()); String filePath = jaasFilePath.toAbsolutePath().toString(); File jaasFile = new StormJaasCreator().create(filePath, kerberizedNimbusServiceName); return jaasFile.getAbsolutePath(); } catch (IOException e) { <START> throw new RuntimeException("Can't create JAAS file for connecting secured nimbus", e); <END> } }</code><technical_language>connect secure nimbus</technical_language>

Target:
private String createJaasFile(String kerberizedNimbusServiceName) { try { Path jaasFilePath = Files.createTempFile("jaas-", UUID.randomUUID().toString()); String filePath = jaasFilePath.toAbsolutePath().toString(); File jaasFile = new StormJaasCreator().create(filePath, kerberizedNimbusServiceName); return jaasFile.getAbsolutePath(); } catch (IOException e) { throw new RuntimeException("Can't create JAAS file to connect to secure nimbus", e); } }
Source:
<code>public void setOrigin(BigInteger shift) { <START> Preconditions.checkNotNull(shift, "shift"); <END> this.origin = shift; }</code><technical_language>do: this.origin = checkNotNull(shift, "shift"); Note I static imports for this. others static imports clear enough (same for Assert.assertTrue in tests)</technical_language>

Target:
public void setOrigin(BigInteger shift) { this.origin = Preconditions.checkNotNull(shift, "shift"); }
Source:
<code>public MetricDescriptor addLabel(String descriptorType, String newLabel) { String descriptorName = projectResourceName + "/metricDescriptors/" + descriptorType; MetricDescriptor descriptor; log.info("Adding label '{}' to stackdriver descriptor '{}'. This may lose existing metric data", newLabel, descriptorName); try { descriptor = service.projects().metricDescriptors() .get(descriptorName) .execute(); } catch (IOException ioex) { log.error("Could not fetch descriptor " + descriptorType + ": " + ioex); return null; } for (LabelDescriptor labelDescriptor : descriptor.getLabels()) { if (labelDescriptor.getKey().equals(newLabel)) { log.info("{} already added to descriptor", newLabel); return descriptor; } } LabelDescriptor labelDescriptor = new LabelDescriptor(); labelDescriptor.setKey(newLabel); labelDescriptor.setValueType("STRING"); descriptor.getLabels().add(labelDescriptor); try { log.info("Deleting existing stackdriver descriptor {}", descriptorName); service.projects().metricDescriptors().delete(descriptorName).execute(); } catch (IOException ioex) { log.info("Ignoring error " + ioex); } try { <START> log.info("Adding new definition for {}", descriptorName); <END> return service.projects().metricDescriptors() .create(projectResourceName, descriptor) .execute(); } catch (IOException ioex) { log.error("Failed to update the descriptor definition: " + ioex); return null; } }</code><technical_language>this read "adding new descriptor for {}"</technical_language>

Target:
public MetricDescriptor addLabel(String descriptorType, String newLabel) { String descriptorName = projectResourceName + "/metricDescriptors/" + descriptorType; MetricDescriptor descriptor; log.info("Adding label '{}' to stackdriver descriptor '{}'. This may lose existing metric data", newLabel, descriptorName); try { descriptor = service.projects().metricDescriptors() .get(descriptorName) .execute(); } catch (IOException ioex) { log.error("Could not fetch descriptor " + descriptorType + ": " + ioex); return null; } for (LabelDescriptor labelDescriptor : descriptor.getLabels()) { if (labelDescriptor.getKey().equals(newLabel)) { log.info("{} already added to descriptor", newLabel); return descriptor; } } LabelDescriptor labelDescriptor = new LabelDescriptor(); labelDescriptor.setKey(newLabel); labelDescriptor.setValueType("STRING"); descriptor.getLabels().add(labelDescriptor); try { log.info("Deleting existing stackdriver descriptor {}", descriptorName); service.projects().metricDescriptors().delete(descriptorName).execute(); } catch (IOException ioex) { log.info("Ignoring error " + ioex); } try { log.info("Adding new descriptor for {}", descriptorName); return service.projects().metricDescriptors() .create(projectResourceName, descriptor) .execute(); } catch (IOException ioex) { log.error("Failed to update the descriptor definition: " + ioex); return null; } }
Source:
<code>void subscribe(@Nonnull StreamListener streamListener, @Nonnull String namespace, @Nonnull List<TableSchema<K, V, M>> tablesOfInterest, long startAddress) { if (subscriptions.size() >= MAX_SUBSCRIBERS) { throw new StreamSubscriptionException( "subscribe: Max " + MAX_SUBSCRIBERS + " hit! Consider consolidating " + streamListener); } if (subscriptions.containsKey(streamListener)) { throw new StreamSubscriptionException( "StreamManager:subscriber already registered " + streamListener + ". Maybe call unregister first?"); } log.info("StreamManager::subscribe {}, startAddress {}, namespace {}, tables {}", streamListener, startAddress, namespace, tablesOfInterest.toString()); SubscriptionThread st = new SubscriptionThread(this, streamListener, namespace, tablesOfInterest, startAddress); subscriptions.put(streamListener, st); <START> st.start(); <END> }</code><technical_language>deamon threads, hang JVM exit</technical_language>

Target:
void subscribe(@Nonnull StreamListener streamListener, @Nonnull String namespace, @Nonnull List<TableSchema<K, V, M>> tablesOfInterest, long startAddress) { if (subscriptions.containsKey(streamListener)) { throw new StreamSubscriptionException( "StreamManager:subscriber already registered " + streamListener + ". Maybe call unregister first?"); } if (subscriptions.size() >= MAX_SUBSCRIBERS) { log.error("StreamManager::subscribe has too many subscribers", streamListener, MAX_SUBSCRIBERS); throw new StreamSubscriptionException( "StreamManager: too many (" + MAX_SUBSCRIBERS + ") subscriptions"); } log.info("StreamManager::subscribe {}, startAddress {}, namespace {}, tables {}", streamListener, startAddress, namespace, tablesOfInterest.toString()); SubscriberTask task = new SubscriberTask(this, streamListener, namespace, tablesOfInterest, startAddress); final ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay( task, 0, DEFAULT_SLEEP_MILLIS, TimeUnit.MILLISECONDS); subscriptions.put(streamListener, new StreamSubscriber(task, scheduledFuture)); }
Source:
<code>public void testGetKieText() { GAV gavEvaluation = new GAV("evaluation", "evaluation", "12.1.1-SNAPSHOT"); InputStream is = this.getClass().getResourceAsStream("evaluation-12.1.1.jar"); repo.deployArtifact(is, gavEvaluation, false); Collection<File> files = repo.listFiles(); for (File file : files) { String fileName = file.getName(); <START> if (fileName.startsWith("evaluation-12.1.1") && fileName.endsWith(".jar")) { <END> String path = file.getPath(); String jarPath = path.substring(repo.getM2RepositoryRootDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME).length()); String kieDeploymentDescriptorText = repo.getKieDeploymentDescriptorText(jarPath); assertNotNull(kieDeploymentDescriptorText); String kModuleText = repo.getKModuleText(jarPath); assertNotNull(kModuleText); break; } } }</code><technical_language>if file is in collection asserts evaluated test passes not</technical_language>

Target:
public void testGetKieText() { GAV gavEvaluation = new GAV("evaluation", "evaluation", "12.1.1-SNAPSHOT"); InputStream is = this.getClass().getResourceAsStream("evaluation-12.1.1.jar"); repo.deployArtifact(is, gavEvaluation, false); Optional<File> file = repo.listFiles("evaluation-12.1.1", singletonList("jar")).stream().findFirst(); assertTrue(file.isPresent()); String path = file.get().getPath(); String jarPath = path.substring(repo.getM2RepositoryRootDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME).length()); String kieDeploymentDescriptorText = repo.getKieDeploymentDescriptorText(jarPath); assertNotNull(kieDeploymentDescriptorText); String kModuleText = repo.getKModuleText(jarPath); assertNotNull(kModuleText); }
Source:
<code>protected void init(Set<String> allKeys, Set<String> usedKeys) { this.allKeys = new HashSet<String>(allKeys); this.usedKeys = new HashSet<String>(usedKeys); List<KeyValueLineModel> list = new ArrayList<KeyValueLineModel>(); <START> KeyValueLineModel lineModel; <END> disableEvent = true; for (String key : usedKeys) { lineModel = createNewLineModel(key); lineModel.getKeys().setSelectedItem(key); fillLineModel(lineModel, key); list.add(lineModel); } disableEvent = false; setItems(list); }</code><technical_language>reason for this of loop, inline createNewLineModel(key)</technical_language>

Target:
protected void init(Set<String> allKeys, Set<String> usedKeys) { this.allKeys = new HashSet<String>(allKeys); this.usedKeys = new HashSet<String>(usedKeys); List<KeyValueLineModel> list = new ArrayList<KeyValueLineModel>(); disableEvent = true; for (String key : usedKeys) { KeyValueLineModel lineModel = createNewLineModel(key); lineModel.getKeys().setSelectedItem(key); setValueByKey(lineModel, key); list.add(lineModel); } disableEvent = false; setItems(list); }
Source:
<code>public static List<Field> getDeclaredFields(Class<?> in) { return new Ordering<Field>() { @Override <START> public int compare(Field f1, Field f2) { <END> Column a1 = f1.getAnnotation(Column.class); Column a2 = f2.getAnnotation(Column.class); if (a1 == null && a2 == null) { return f1.getName().compareTo(f2.getName()); } if (a1 == null) { return 1; } if (a2 == null) { return -1; } return a1.id() - a2.id(); } }.sortedCopy(Arrays.asList(in.getDeclaredFields())); }</code><technical_language>trouble write a test</technical_language>

Target:
public static List<Field> getDeclaredFields(Class<?> in) { return sort(Arrays.asList(in.getDeclaredFields())); }
Source:
<code>private List<Contentlet> getRelatedChildren(final Contentlet contentlet, final Relationship rel, final User user, final boolean respectFrontendRoles) throws DotSecurityException, DotDataException { final List<Contentlet> result = new ArrayList<>(); final String relationshipName = rel.getRelationTypeValue().toLowerCase(); SearchResponse response = APILocator.getEsSearchAPI() .esSearchRelated(contentlet.getIdentifier(), relationshipName, false,false, user, respectFrontendRoles); if (response.getHits() == null) { return result; } for (SearchHit sh : response.getHits()) { try { Map<String, Object> sourceMap = sh.getSourceAsMap(); if (sourceMap.get(relationshipName) != null) { ((ArrayList<Map>) sourceMap.get(relationshipName)).stream().forEach(child -> { try { result.add(findContentletByIdentifierAnyLanguage( (String) child.get("identifier"))); } catch (Exception e) { throw new RuntimeException(e); } }); } } catch (Exception e) { <START> Logger.error(this, e.getMessage(), e); <END> } } return result; }</code><technical_language>Please log content's Identifier relationship name too</technical_language>

Target:
private List<Contentlet> getRelatedChildren(final Contentlet contentlet, final Relationship rel, final User user, final boolean respectFrontendRoles) throws DotSecurityException, DotDataException { if (getRelatedContentFromDB){ return FactoryLocator.getRelationshipFactory().dbRelatedContent(rel, contentlet, true); } else{ final List<Contentlet> result = new ArrayList<>(); final String relationshipName = rel.getRelationTypeValue().toLowerCase(); SearchResponse response = APILocator.getEsSearchAPI() .esSearchRelated(contentlet.getIdentifier(), relationshipName, false,false, user, respectFrontendRoles); if (response.getHits() == null) { return result; } for (SearchHit sh : response.getHits()) { Map<String, Object> sourceMap = sh.getSourceAsMap(); if (sourceMap.get(relationshipName) != null) { ((ArrayList<String>) sourceMap.get(relationshipName)).stream().forEach(child -> { try { result.add(findContentletByIdentifierAnyLanguage( child)); } catch (Exception e) { throw new RuntimeException(e); } }); } } return result; } }
Source:
<code>public CandlepinQuery<Owner> getOwnersByActiveProduct(Collection<String> productIds) { DetachedCriteria poolIdQuery = DetachedCriteria.forClass(Pool.class, "pool") .createAlias("pool.product", "products") <START> .createAlias("products.providedProducts", "providedProducts") <END> .add(CPRestrictions.in("providedProducts.id", productIds)) .setProjection(Property.forName("pool.id")); DetachedCriteria ownerIdQuery = DetachedCriteria.forClass(Entitlement.class, "e") .add(Subqueries.propertyIn("e.pool.id", poolIdQuery)) .createCriteria("pool").add(Restrictions.gt("endDate", new Date())) .setProjection(Property.forName("e.owner.id")); DetachedCriteria distinctQuery = DetachedCriteria.forClass(Owner.class, "o2") .add(Subqueries.propertyIn("o2.id", ownerIdQuery)) .setProjection(Projections.distinct(Projections.property("o2.key"))); DetachedCriteria criteria = DetachedCriteria.forClass(Owner.class, "o") .add(Subqueries.propertyIn("o.key", distinctQuery)); return this.cpQueryFactory.<Owner>buildQuery(this.currentSession(), criteria); }</code><technical_language>"products" singular here</technical_language>

Target:
public CandlepinQuery<Owner> getOwnersByActiveProduct(Collection<String> productIds) { DetachedCriteria poolIdQuery = DetachedCriteria.forClass(Pool.class, "pool") .createAlias("pool.product", "product") .createAlias("product.providedProducts", "providedProducts") .add(CPRestrictions.in("providedProducts.id", productIds)) .setProjection(Property.forName("pool.id")); DetachedCriteria ownerIdQuery = DetachedCriteria.forClass(Entitlement.class, "e") .add(Subqueries.propertyIn("e.pool.id", poolIdQuery)) .createCriteria("pool").add(Restrictions.gt("endDate", new Date())) .setProjection(Property.forName("e.owner.id")); DetachedCriteria distinctQuery = DetachedCriteria.forClass(Owner.class, "o2") .add(Subqueries.propertyIn("o2.id", ownerIdQuery)) .setProjection(Projections.distinct(Projections.property("o2.key"))); DetachedCriteria criteria = DetachedCriteria.forClass(Owner.class, "o") .add(Subqueries.propertyIn("o.key", distinctQuery)); return this.cpQueryFactory.<Owner>buildQuery(this.currentSession(), criteria); }
Source:
<code>private void waitForTimeout(TimeLimit timeout) { Duration waitPeriod = Duration.ofMillis(timeout.getTimeMillis()); currentTime = currentTime.plus(waitPeriod); reaperExecutor.tick(waitPeriod.toMillis(), TimeUnit.MILLISECONDS); <START> lockAcquirerExecutor.tick(waitPeriod.toMillis(), TimeUnit.MILLISECONDS); <END> }</code><technical_language>here, ticking _except_ for NanoTime, means related leases is valid here! calling this ETE test, nanotime ticking time. This is I leery of stubbed out time in a test this; ETE test means basically real thing; tests this chance of catching bugs in PR if stubbing stuff out; for catching incorrect assumptions testing code implements contract, really</technical_language>

Target:
private void waitForTimeout(TimeLimit timeout) { Stopwatch timer = Stopwatch.createStarted(); long buffer = 250L; while (timer.elapsed(TimeUnit.MILLISECONDS) < timeout.getTimeMillis() + buffer) { Uninterruptibles.sleepUninterruptibly(buffer, TimeUnit.MILLISECONDS); } }
Source:
<code>public MQTTDataGenerator connectToTopic(final String topic) { List<MQTTDataGenerator> dataGeneratorList = dataGeneratorListMap.get(topic); if (dataGeneratorList == null) { dataGeneratorList = new ArrayList<>(); dataGeneratorListMap.putIfAbsent(topic, dataGeneratorList); } final MQTTDataGenerator dataGenerator = new MQTTDataGenerator(this, topic); <START> dataGeneratorListMap.get(topic).add(dataGenerator); <END> return dataGenerator; }</code><technical_language>if dataGeneratorListMap.get(topic) returns null? (It null of unsubscribing)</technical_language>

Target:
public MQTTDataGenerator connectToTopic(final String topic) { Queue<MQTTDataGenerator> dataGeneratorList = dataGeneratorListMap.get(topic); if (dataGeneratorList == null) { dataGeneratorList = new ConcurrentLinkedQueue<>(); dataGeneratorListMap.put(topic, dataGeneratorList); } final MQTTDataGenerator dataGenerator = new MQTTDataGenerator(this, topic); dataGeneratorListMap.get(topic).add(dataGenerator); return dataGenerator; }
Source:
<code>public DatasetDTO getDataset(final Integer datasetId) { <START> final DatasetDTO datasetDTOS; <END> try { final ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.property("project.projectId"), "datasetId"); projectionList.add(Projections.sqlProjection("value as datasetTypeId", new String[] {"datasetTypeId"}, new Type[] {Hibernate.INTEGER}),"datasetTypeId"); projectionList.add(Projections.property("project.name"), "name"); projectionList.add(Projections.property("pr.objectProject.projectId"), "parentDatasetId"); final Criteria criteria = this.getSession().createCriteria(DmsProject.class, "project"); criteria.createAlias("project.relatedTos", "pr"); criteria.createAlias("project.properties", "pp", CriteriaSpecification.INNER_JOIN, Restrictions.eq("pp.variableId", TermId.DATASET_TYPE.getId())); criteria.add(Restrictions.eq("project.projectId", datasetId)); criteria.add(Restrictions.eq("pr.typeId", TermId.BELONGS_TO_STUDY.getId())); criteria.setProjection(projectionList); criteria.setResultTransformer(Transformers.aliasToBean(DatasetDTO.class)); datasetDTOS = (DatasetDTO) criteria.uniqueResult(); } catch (final HibernateException e) { throw new MiddlewareQueryException("Error getting getDataset for datasetId =" + datasetId + ":" + e.getMessage(), e); } return datasetDTOS; }</code><technical_language>@vmaletta Variable name singular</technical_language>

Target:
public DatasetDTO getDataset(final Integer datasetId) { final DatasetDTO datasetDTO; try { final ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.property("project.projectId"), "datasetId"); projectionList.add(Projections.sqlProjection("value as datasetTypeId", new String[] {"datasetTypeId"}, new Type[] {Hibernate.INTEGER}),"datasetTypeId"); projectionList.add(Projections.property("project.name"), "name"); projectionList.add(Projections.property("pr.objectProject.projectId"), "parentDatasetId"); final Criteria criteria = this.getSession().createCriteria(DmsProject.class, "project"); criteria.createAlias("project.relatedTos", "pr"); criteria.createAlias("project.properties", "pp", CriteriaSpecification.INNER_JOIN, Restrictions.eq("pp.variableId", TermId.DATASET_TYPE.getId())); criteria.add(Restrictions.eq("project.projectId", datasetId)); criteria.add(Restrictions.eq("pr.typeId", TermId.BELONGS_TO_STUDY.getId())); criteria.setProjection(projectionList); criteria.setResultTransformer(Transformers.aliasToBean(DatasetDTO.class)); datasetDTO = (DatasetDTO) criteria.uniqueResult(); } catch (final HibernateException e) { final String errorMessage = "Error getting getDataset for datasetId =" + datasetId + ":" + e.getMessage(); DmsProjectDao.LOG.error(errorMessage, e); throw new MiddlewareQueryException(errorMessage, e); } return datasetDTO; }
Source:
<code>public static Map<String, Object> jsonToMap(String jsonString) throws JsonParseException, JsonMappingException, <START> IOException { <END> final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); final Map<String, Object> data = mapper.readValue(jsonString, type); return data; }</code><technical_language>IOException is enough in mapToJson</technical_language>

Target:
public static Map<String, Object> jsonToMap(String jsonString) throws IOException { ObjectMapper mapper = new ObjectMapper(); MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); Map<String, Object> data = mapper.readValue(jsonString, type); return data; }
Source:
<code>public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("type", type.ordinal()); <START> mainObj.put("actionID", actionID); <END> } catch(Throwable t) { t.printStackTrace(); } return mainObj; }</code><technical_language>actionID actionId</technical_language>

Target:
public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("type", type.ordinal()); mainObj.put("actionId", actionID); } catch(Throwable t) { t.printStackTrace(); } return mainObj; }
Source:
<code>public void testFilterExpressionRewrite() { tester().assertThat(zeroRewriter).on(p -> <START> p.filter(new LongLiteral("1"), p.values())) <END> .matches( filter("0", PlanMatchPattern.values())); }</code><technical_language>static imports for PlanMatchPattern</technical_language>

Target:
public void testFilterExpressionRewrite() { tester().assertThat(zeroRewriter).on(p -> p.filter(new LongLiteral("1"), p.values())) .matches( filter("0", values())); }
Source:
<code>private static void allStylesForRendering( LayerGroupInfo group, List<StyleInfo> styles, boolean root) { switch (group.getMode()) { case EO: styles.add(group.getRootLayerStyle()); break; case CONTAINER: if (root) { throw new UnsupportedOperationException( "LayerGroup mode " + Mode.CONTAINER.getName() + " can not be rendered"); } default: int size = group.getLayers().size(); for (int i = 0; i < size; i++) { PublishedInfo p = group.getLayers().get(i); StyleInfo s = group.getStyles().get(i); <START> if (p instanceof LayerInfo) { <END> StyleInfo styleInfo = group.getStyles().get(i); if (((LayerInfo) p).getResource() instanceof WMSLayerInfo) { WMSLayerInfo wmsLayerInfo = (WMSLayerInfo) ((LayerInfo) p).getResource(); styleInfo = processWMSLayer(wmsLayerInfo, styleInfo); } styles.add(styleInfo); } else if (p instanceof LayerGroupInfo) { allStylesForRendering((LayerGroupInfo) p, styles, false); } else if (p == null && s != null) { expandStyleGroup( s, group.getBounds() == null ? null : group.getBounds().getCoordinateReferenceSystem(), null, styles); } } } }</code><technical_language>group.getStyles() contains correct style? a layer is added layer group a style is selected right? moment sense select right style for remote layers too</technical_language>

Target:
private static void allStylesForRendering( LayerGroupInfo group, List<StyleInfo> styles, boolean root) { switch (group.getMode()) { case EO: styles.add(group.getRootLayerStyle()); break; case CONTAINER: if (root) { throw new UnsupportedOperationException( "LayerGroup mode " + Mode.CONTAINER.getName() + " can not be rendered"); } default: int size = group.getLayers().size(); for (int i = 0; i < size; i++) { PublishedInfo p = group.getLayers().get(i); StyleInfo s = group.getStyles().get(i); if (p instanceof LayerInfo) { StyleInfo styleInfo = group.getStyles().get(i); if (((LayerInfo) p).getResource() instanceof WMSLayerInfo) { WMSLayerInfo wmsLayerInfo = (WMSLayerInfo) ((LayerInfo) p).getResource(); styleInfo = getRemoteWmsLayerStyle(wmsLayerInfo, styleInfo); } styles.add(styleInfo); } else if (p instanceof LayerGroupInfo) { allStylesForRendering((LayerGroupInfo) p, styles, false); } else if (p == null && s != null) { expandStyleGroup( s, group.getBounds() == null ? null : group.getBounds().getCoordinateReferenceSystem(), null, styles); } } } }