auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void offer(Mutation mutation) throws IOException { if (activeMutationWorkers.get() == 0) { initializeAsyncMutators(); } long operationId; try { <START> operationId = heapSizeManager.registerOperationWithHeapSize(mutation.heapSize()); <END> } catch (InterruptedException e) { Thread.interrupted(); throw new IOException("Interrupted in buffered mutator while mutating row : '" + Bytes.toString(mutation.getRow()), e); } mutationsToBeSent.add(new MutationOperation(mutation, operationId)); }</code><technical_language>if need "operationId" of try{}, move "long operationId;" "mutationsToBeSent.add(new MutationOperation(mutation, operationId));" try {}</technical_language>

Target:
private void offer(Mutation mutation) throws IOException { if (activeMutationWorkers.get() == 0) { initializeAsyncMutators(); } try { long operationId = heapSizeManager.registerOperationWithHeapSize(mutation.heapSize()); mutationsToBeSent.add(new MutationOperation(mutation, operationId, false)); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException("Interrupted in buffered mutator while mutating row : '" + Bytes.toString(mutation.getRow()), e); } }
Source:
<code><START> public List<String> calculateDescriptorType() { <END> Set<DescriptorLanguage.FileType> set = this.getWorkflowVersions().stream().flatMap(tag -> tag.getSourceFiles().stream()).map(SourceFile::getType).collect( Collectors.toSet()); return Arrays.stream(DescriptorLanguage.values()).filter(lang -> set.contains(lang.getFileType())) .map(lang -> lang.toString().toUpperCase()).distinct().collect(Collectors.toList()); }</code><technical_language>worried this is fragile; time adds/modifies/deletes a sourcefile, call this method. "every time" is currently 2 places (unless missed :) ), worth overthinking this</technical_language>

Target:
public List<String> calculateDescriptorType() { Set<DescriptorLanguage.FileType> set = this.getWorkflowVersions().stream().flatMap(tag -> tag.getSourceFiles().stream()).map(SourceFile::getType).collect( Collectors.toSet()); return Arrays.stream(DescriptorLanguage.values()).filter(lang -> !(lang.toString().equals("cwl") || lang.toString().equals("wdl"))).filter(lang -> set.contains(lang.getFileType())) .map(lang -> lang.toString()).distinct().collect(Collectors.toList()); }
Source:
<code>public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) { <START> if (isClosed()) <END> throw log.cacheManagerClosed(); if (keyType == null) throw log.cannotBeNull("keyType"); if (valueType == null) throw log.cannotBeNull("valueType"); synchronized (caches) { Cache<K, V> cache = unchecked(caches.get(cacheName)); if (cache != null) { Configuration<?, ?> configuration = cache.getConfiguration(Configuration.class); Class<?> cfgKeyType = configuration.getKeyType(); if (verifyType(keyType, cfgKeyType)) { Class<?> cfgValueType = configuration.getValueType(); if (verifyType(valueType, cfgValueType)) return cache; throw log.incompatibleType(valueType, cfgValueType); } throw log.incompatibleType(keyType, cfgKeyType); } return null; } }</code><technical_language>this piece of code is copied 3 times. is worth create a checkNotClosed method</technical_language>

Target:
public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) { checkNotClosed().checkNull(keyType, "keyType").checkNull(valueType, "valueType"); synchronized (caches) { Cache<K, V> cache = unchecked(caches.get(cacheName)); if (cache != null) { Configuration<?, ?> configuration = cache.getConfiguration(Configuration.class); Class<?> cfgKeyType = configuration.getKeyType(); if (verifyType(keyType, cfgKeyType)) { Class<?> cfgValueType = configuration.getValueType(); if (verifyType(valueType, cfgValueType)) return cache; throw log.incompatibleType(valueType, cfgValueType); } throw log.incompatibleType(keyType, cfgKeyType); } return null; } }
Source:
<code>public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor) { this.camelContext = camelContext; this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; <START> systemSubjectBinder = new SystemSubjectBinder(); <END> setBlacklist(); }</code><technical_language>If setting this set ling 98</technical_language>

Target:
public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor) { this.camelContext = camelContext; this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; setBlacklist(); }
Source:
<code>public static boolean isSampleSlide(DetailedSample sample) { <START> return sample instanceof SampleSlide || sample.getSampleClass().getAlias().equals(SampleSlide.SUBCATEGORY_NAME); <END> }</code><technical_language>sample.getSampleClass().getAlias() -> sample.getSampleClass().getSampleSubcategory()</technical_language>

Target:
public static boolean isSampleSlide(DetailedSample sample) { return sample instanceof SampleSlide || SampleSlide.SUBCATEGORY_NAME.equals(sample.getSampleClass().getSampleSubcategory()); }
Source:
<code>protected void MoveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { <START> Map<Guid, Guid> imageDomainMap = getParameters().getImageMap(); <END> for (DiskImage disk : disks) { Guid destinationDomain = (imageDomainMap.get(disk.getId()) != null) ? imageDomainMap.get(disk.getId()) : getParameters().getStorageDomainId(); MoveOrCopyImageGroupParameters tempVar = new MoveOrCopyImageGroupParameters(containerID, disk .getimage_group_id().getValue(), disk.getId(), destinationDomain, getMoveOrCopyImageOperation()); tempVar.setParentCommand(getActionType()); tempVar.setEntityId(getParameters().getEntityId()); tempVar.setUseCopyCollapse(getParameters().getCopyCollapse()); tempVar.setCopyVolumeType(CopyVolumeType.LeafVol); tempVar.setPostZero(disk.getwipe_after_delete()); tempVar.setForceOverride(true); MoveOrCopyImageGroupParameters p = tempVar; if (getParameters().getDiskInfoList() != null && getParameters().getDiskInfoList().containsKey(disk.getinternal_drive_mapping())) { p.setVolumeType(getParameters().getDiskInfoList().get(disk.getinternal_drive_mapping()) .getvolume_type()); p.setVolumeFormat(getParameters().getDiskInfoList().get(disk.getinternal_drive_mapping()) .getvolume_format()); } p.setParentParemeters(getParameters()); VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.MoveOrCopyImageGroup, p); getParameters().getImagesParameters().add(p); getReturnValue().getTaskIdList().addAll(vdcRetValue.getInternalTaskIdList()); } }</code><technical_language>General question - define a field in class for this map, CTOR fill value? easier for reuse (not code getParameters().getImageMap() time)</technical_language>

Target:
protected void MoveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { for (DiskImage disk : disks) { Guid destinationDomain = (imageToDestinationDomainMap.get(disk.getId()) != null) ? imageToDestinationDomainMap.get(disk.getId()) : getParameters().getStorageDomainId(); MoveOrCopyImageGroupParameters tempVar = new MoveOrCopyImageGroupParameters(containerID, disk .getimage_group_id().getValue(), disk.getId(), destinationDomain, getMoveOrCopyImageOperation()); tempVar.setParentCommand(getActionType()); tempVar.setEntityId(getParameters().getEntityId()); tempVar.setUseCopyCollapse(getParameters().getCopyCollapse()); tempVar.setCopyVolumeType(CopyVolumeType.LeafVol); tempVar.setPostZero(disk.getwipe_after_delete()); tempVar.setForceOverride(true); MoveOrCopyImageGroupParameters p = tempVar; if (getParameters().getDiskInfoList() != null && getParameters().getDiskInfoList().containsKey(disk.getinternal_drive_mapping())) { p.setVolumeType(getParameters().getDiskInfoList().get(disk.getinternal_drive_mapping()) .getvolume_type()); p.setVolumeFormat(getParameters().getDiskInfoList().get(disk.getinternal_drive_mapping()) .getvolume_format()); } p.setParentParemeters(getParameters()); VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.MoveOrCopyImageGroup, p); getParameters().getImagesParameters().add(p); getReturnValue().getTaskIdList().addAll(vdcRetValue.getInternalTaskIdList()); } }
Source:
<code>public Map<String, List<String>> getHeaderFields() { <START> TreeMap<String, List<String>> ignoredCaseMap = new TreeMap<>( <END> String.CASE_INSENSITIVE_ORDER); for (Entry<String, List<String>> e : wrappedUrlConnection .getHeaderFields().entrySet()) { List<String> values = ignoredCaseMap.get(e.getKey()); if (values == null) { ignoredCaseMap.put(e.getKey(), e.getValue()); } else { LinkedList<String> newValues = new LinkedList<>(values); newValues.addAll(e.getValue()); ignoredCaseMap.put(e.getKey(), newValues); } } return Collections.unmodifiableMap(ignoredCaseMap); }</code><technical_language>caching list? AFAIK this method called multiple times connection</technical_language>

Target:
public Map<String, List<String>> getHeaderFields() { return wrappedUrlConnection.getHeaderFields(); }
Source:
<code>public void run() { while (true) { final TaskStatusEvent item = getNext(); if (item == null) { return; } final JobId jobId = item.getStatus().getJob().getId(); final String historyPath = Paths.historyJobHostEventsTimestamp( jobId, hostname, item.getTimestamp()); <START> log.debug("writing queued item to zookeeper {}", item.getStatus().getJob().getId(), <END> item.getTimestamp()); try { client.ensurePath(historyPath, true); client.createAndSetData(historyPath, item.getStatus().toJsonBytes()); final List<String> events = client.getChildren(Paths.historyJobHostEvents(jobId, hostname)); if (events.size() > MAX_NUMBER_STATUS_EVENTS_TO_RETAIN) { trimStatusEvents(events, jobId); } } catch (NodeExistsException e) { log.debug("item we wanted in is already there"); } catch (ConnectionLossException e) { log.warn("Connection lost while putting item into zookeeper, will retry"); putBack(item); break; } catch (KeeperException e) { log.error("Error putting item into zookeeper, will retry", e); putBack(item); break; } try { if (kafkaProducer.isPresent()) { Future<RecordMetadata> future = kafkaProducer.get().send( new ProducerRecord<String, TaskStatusEvent>(KAFKA_TOPIC, item)); RecordMetadata metadata = future.get(5, TimeUnit.SECONDS); log.debug("Sent an event to Kafka, meta: {}", metadata); } } catch (ExecutionException | InterruptedException | TimeoutException e) { log.error("Unable to send an event to Kafka", e); } } }</code><technical_language>move this log line try</technical_language>

Target:
public void run() { while (true) { final TaskStatusEvent item = getNext(); if (item == null) { return; } final JobId jobId = item.getStatus().getJob().getId(); final String historyPath = Paths.historyJobHostEventsTimestamp( jobId, hostname, item.getTimestamp()); try { log.debug("writing queued item to zookeeper {}", item.getStatus().getJob().getId(), item.getTimestamp()); client.ensurePath(historyPath, true); client.createAndSetData(historyPath, item.getStatus().toJsonBytes()); final List<String> events = client.getChildren(Paths.historyJobHostEvents(jobId, hostname)); if (events.size() > MAX_NUMBER_STATUS_EVENTS_TO_RETAIN) { trimStatusEvents(events, jobId); } } catch (NodeExistsException e) { log.debug("item we wanted in is already there"); } catch (ConnectionLossException e) { log.warn("Connection lost while putting item into zookeeper, will retry"); putBack(item); break; } catch (KeeperException e) { log.error("Error putting item into zookeeper, will retry", e); putBack(item); break; } try { if (kafkaProducer.isPresent()) { final Future<RecordMetadata> future = kafkaProducer.get().send( new ProducerRecord<String, TaskStatusEvent>(KAFKA_TOPIC, item)); final RecordMetadata metadata = future.get(5, TimeUnit.SECONDS); log.debug("Sent an event to Kafka, meta: {}", metadata); } } catch (ExecutionException | InterruptedException | TimeoutException e) { log.error("Unable to send an event to Kafka", e); } } }
Source:
<code>public void readPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setContainerName("AQAAAJ0fgTc="); createdUser.createPermission(permissionSettings, null).block(); Mono<CosmosPermissionResponse> readObservable = createdUser.getPermission(permissionSettings.getId()).read(null); CosmosResponseValidator<CosmosPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosPermissionResponse>() .withId(permissionSettings.getId()) .withPermissionMode(PermissionMode.READ) <START> .withPermissionContainerName("AQAAAJ0fgTc=") <END> .notNullEtag() .build(); validateSuccess(readObservable, validator); }</code><technical_language>this is called withPermissionContainerName in test . withPermissionContainerName("AQAAAJ0fgTc=") portion of selflink. is this container name a portion of selflink? ditto</technical_language>

Target:
public void readPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setContainerName("myContainer"); createdUser.createPermission(permissionSettings, null).block(); Mono<CosmosPermissionResponse> readObservable = createdUser.getPermission(permissionSettings.getId()).read(null); CosmosResponseValidator<CosmosPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosPermissionResponse>() .withId(permissionSettings.getId()) .withPermissionMode(PermissionMode.READ) .withPermissionContainerName("myContainer") .notNullEtag() .build(); validateSuccess(readObservable, validator); }
Source:
<code>public int getUserLimit(final String user) { <START> return specialUser.getOrDefault(user, count); <END> }</code><technical_language>I in this diff count = DEFAULT_COUNT. I assume else in is binding provided in properties file overwrite that</technical_language>

Target:
public int getUserLimit(final String user) { return overrides.getOrDefault(user, count); }
Source:
<code>private static void loadAwards(){ <START> File dir = new File("data/awards/"); <END> File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); for(File file : files){ AwardSet awardSet = null; try { InputStream inputStream = new FileInputStream(file); JAXBContext jaxbContext = JAXBContext.newInstance(AwardSet.class, Award.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); awardSet = unmarshaller.unmarshal(new StreamSource(inputStream), AwardSet.class).getValue(); Map<String, Award> tempAwardMap = new HashMap<>(); String currentSetName = file.getName().replaceFirst("[.][^.]+$", ""); for (Award award : awardSet.getAwards()){ award.setSet(currentSetName); tempAwardMap.put(award.getName(), award); } awardsMap.put(currentSetName, tempAwardMap); } catch (JAXBException var4) { System.err.println("Error loading XML for awards: " + var4.getMessage()); var4.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }</code><technical_language>This a constant declared beginning of class easier find if needs change</technical_language>

Target:
private void loadAwards(){ File dir = new File(AWARDS_XML_ROOT_PATH); File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); for(File file : files){ AwardSet awardSet = null; try { InputStream inputStream = new FileInputStream(file); JAXBContext jaxbContext = JAXBContext.newInstance(AwardSet.class, Award.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); awardSet = unmarshaller.unmarshal(new StreamSource(inputStream), AwardSet.class).getValue(); Map<String, Award> tempAwardMap = new HashMap<>(); String currentSetName = file.getName().replaceFirst("[.][^.]+$", ""); for (Award award : awardSet.getAwards()){ award.setSet(currentSetName); tempAwardMap.put(award.getName(), award); } awardsMap.put(currentSetName, tempAwardMap); } catch (JAXBException var4) { System.err.println("Error loading XML for awards: " + var4.getMessage()); var4.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Source:
<code>private void validateTableConstraint(SqlTableConstraint constraint) { if (constraint.isUnique()) { <START> throw new ValidationException("UNIQUE constraint needs to implement"); <END> } if (constraint.isEnforced()) { throw new ValidationException("ENFORCED mode needs to implement," + " use [NOT ENFORCED] if possible"); } }</code><technical_language>Please throw UnsupportedException UNIQUE constraint is supported yet. message</technical_language>

Target:
private void validateTableConstraint(SqlTableConstraint constraint) { if (constraint.isUnique()) { throw new UnsupportedOperationException("UNIQUE constraint is not supported yet"); } if (constraint.isEnforced()) { throw new ValidationException("Flink doesn't support ENFORCED mode for " + "PRIMARY KEY constaint. ENFORCED/NOT ENFORCED controls if the constraint " + "checks are performed on the incoming/outgoing data. " + "Flink does not own the data therefore the only supported mode " + "is the NOT ENFORCED mode"); } }
Source:
<code>private Image createImage() { Rectangle bounds = m_widget.getBounds(); int width = bounds.width; int height = bounds.height; if (m_widget instanceof Shell) { Rectangle ca = ((Shell) m_widget).getClientArea(); width = ca.width; height = ca.height; } GC gcWidget = new GC(m_widget); Image image; try { image = new Image(m_widget.getDisplay(), width, height); gcWidget.copyArea(image, 0, 0); } finally { gcWidget.dispose(); } <START> <END> int frameWidth = 2; Image imageWithFrame = new Image(m_widget.getDisplay(), width + (2 * frameWidth), height + (2 * frameWidth)); GC gcResult = new GC(imageWithFrame); try { gcResult.setAdvanced(true); gcResult.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); gcResult.setLineWidth(frameWidth); gcResult.drawRectangle(imageWithFrame.getBounds()); gcResult.drawImage(image, 0, 0, width, height, frameWidth, frameWidth, width, height); } finally { image.dispose(); gcResult.dispose(); } return imageWithFrame; }</code><technical_language>please extract wrapping in a frame a new method. - sense protected</technical_language>

Target:
private Image createImage() { Rectangle bounds = m_widget.getBounds(); int width = bounds.width; int height = bounds.height; if (m_widget instanceof Shell) { Rectangle ca = ((Shell) m_widget).getClientArea(); width = ca.width; height = ca.height; } GC gcWidget = new GC(m_widget); Image image = new Image(m_widget.getDisplay(), width, height); Image imageWithFrame; try { gcWidget.copyArea(image, 0, 0); int frameWidth = 2; imageWithFrame = createImageWithFrame(image, frameWidth); } finally { gcWidget.dispose(); image.dispose(); } return imageWithFrame; }
Source:
<code>protected void setupExceptionOnFailure(boolean throwExceptionOnFailure) { <START> if (throwExceptionOnFailure || (devMode && logMissingProperties)) { <END> context.put(THROW_EXCEPTION_ON_FAILURE, true); } }</code><technical_language>I this is main reason devMode logMissingProperties continue "linked" (at in 2.5.x). users want check for missing properties in devMode (development) anyway. If logMissingProperties a "standalone flag", turn THROW_EXCEPTION_ON_FAILURE in a production configuration - greater repercussions intended. decoupled in 2.6 in a "safe way"</technical_language>

Target:
protected void setupExceptionOnFailure(boolean throwExceptionOnFailure) { if (throwExceptionOnFailure || logMissingProperties) { context.put(THROW_EXCEPTION_ON_FAILURE, true); } }
Source:
<code>public boolean validateEmployeeId(String employeeId) { <START> Person employee = buildPerson(employeeId); <END> boolean valid = ObjectUtils.isNotNull(employee); if (valid) { LOG.debug("validateEmployeeId, found a valid employee: " + employee.getName()); } else { LOG.error("validateEmployeeId, found a an invalid employee ID: " + employeeId); } return valid; }</code><technical_language>I forgot update this method name findPerson</technical_language>

Target:
public boolean validateEmployeeId(String employeeId) { Person employee = findPerson(employeeId); boolean valid = ObjectUtils.isNotNull(employee); if (valid) { LOG.debug("validateEmployeeId, found a valid employee: " + employee.getName()); } else { LOG.error("validateEmployeeId, found a an invalid employee ID: " + employeeId); } return valid; }
Source:
<code>private long getCollectionRecursiveSize(ContentCollection currentCollection, long maxIndividualFileSize, long zipMaxTotalSize, Set<String> zipSingleFileSizeExceeded) throws ZipMaxTotalSizeException { long total=0; List items = currentCollection.getMemberResources(); Iterator it = items.iterator(); while(it.hasNext()) { ContentEntity myElement = (ContentEntity) it.next(); if (myElement.isResource()) { long tempSize = ((ContentResource)myElement).getContentLength(); if (tempSize > maxIndividualFileSize) { String filePath = myElement.getId().replace("/group/" + ToolManager.getCurrentPlacement().getContext(), ""); zipSingleFileSizeExceeded.add(filePath); } <START> else {total=total+tempSize;} <END> } else if (myElement.isCollection()) { long tempSize = getCollectionRecursiveSize((ContentCollection)myElement, maxIndividualFileSize, zipMaxTotalSize, zipSingleFileSizeExceeded); if (tempSize > zipMaxTotalSize) { throw new ZipMaxTotalSizeException(); } else {total=total+tempSize;} } } return total; }</code><technical_language>Sakai splits this out multiple lines</technical_language>

Target:
private long getCollectionRecursiveSize(ContentCollection currentCollection, long maxIndividualFileSize, long zipMaxTotalSize, Set<String> zipSingleFileSizeExceeded) throws ZipMaxTotalSizeException { long total=0; List items = currentCollection.getMemberResources(); Iterator it = items.iterator(); while(it.hasNext()) { ContentEntity myElement = (ContentEntity) it.next(); if (myElement.isResource()) { long tempSize = ((ContentResource)myElement).getContentLength(); if (tempSize > maxIndividualFileSize) { String filePath = myElement.getId().replace("/group/" + ToolManager.getCurrentPlacement().getContext(), ""); zipSingleFileSizeExceeded.add(filePath); } else { total += tempSize; } } else if (myElement.isCollection()) { long tempSize = getCollectionRecursiveSize((ContentCollection)myElement, maxIndividualFileSize, zipMaxTotalSize, zipSingleFileSizeExceeded); if (tempSize > zipMaxTotalSize) { throw new ZipMaxTotalSizeException(); } else { total += tempSize; } } } return total; }
Source:
<code>private StringBuilder clustersListIntoTokenizedString() { StringBuilder attachedClustersStringBf = new StringBuilder(""); List<VDSGroup> attachedClustersList = <START> SchedulingManager.getInstance().getClustersByClusterPolicyId(getParameters().getClusterPolicyId()); <END> boolean isFirstCluster = true; for (VDSGroup vdsGroup : attachedClustersList) { if (isFirstCluster == false) attachedClustersStringBf.append(','); attachedClustersStringBf.append('\'').append(vdsGroup.getName()).append('\''); isFirstCluster = false; } return attachedClustersStringBf; }</code><technical_language>Please StringUtils.join() in order create comma separated list, instead of creating programmatically yourself</technical_language>

Target:
private String clustersListIntoTokenizedString() { List<VDSGroup> attachedClustersList = SchedulingManager.getInstance().getClustersByClusterPolicyId(getParameters().getClusterPolicyId()); List<String> clusterNamesList = new LinkedList<>(); for (VDSGroup vdsGroup : attachedClustersList) clusterNamesList.add(vdsGroup.getName()); return StringUtils.join(clusterNamesList, ','); }
Source:
<code>public void test_evaluate_array_numbers() { final AtomicIntegerArray atomicIntArray = new AtomicIntegerArray(3); atomicIntArray.set(0, -1); browser.addProgressListener(new ProgressListener() { @Override public void changed(ProgressEvent event) { } @Override public void completed(ProgressEvent event) { Object[] evalResult = (Object[]) browser.evaluate("return new Array(1,2,3)"); atomicIntArray.set(0, ((Double) evalResult[0]).intValue()); atomicIntArray.set(1, ((Double) evalResult[1]).intValue()); atomicIntArray.set(2, ((Double) evalResult[2]).intValue()); if (browser_debug) System.out.println("Node value: "+ evalResult); } }); browser.setText("<html><body><p id='myid'>HelloWorld</p></body></html>"); shell.open(); for (int i = 0; i < (loopMultipier * secondsToWaitTillFail); i++) { runLoopTimer(waitMS); if (atomicIntArray.get(0) != -1) { if (atomicIntArray.get(0) == 1 && atomicIntArray.get(1) == 2 && atomicIntArray.get(2) == 3) { return; } else { <START> System.err.println("ERROR: test_evaluate_array_numbers, resulting numbers not as expected"); <END> } } } fail(name.getMethodName() + " failed. Evaluation should have returned an array, but array not returned or values are not correct."); }</code><technical_language>fail message here</technical_language>

Target:
public void test_evaluate_array_numbers() { assumeFalse(webkit1SkipMsg(), isWebkit1); final AtomicIntegerArray atomicIntArray = new AtomicIntegerArray(3); atomicIntArray.set(0, -1); browser.addProgressListener(new ProgressListener() { @Override public void changed(ProgressEvent event) { } @Override public void completed(ProgressEvent event) { Object[] evalResult = (Object[]) browser.evaluate("return new Array(1,2,3)"); atomicIntArray.set(0, ((Double) evalResult[0]).intValue()); atomicIntArray.set(1, ((Double) evalResult[1]).intValue()); atomicIntArray.set(2, ((Double) evalResult[2]).intValue()); if (browser_debug) System.out.println("Node value: "+ evalResult); } }); browser.setText("<html><body><p id='myid'>HelloWorld</p></body></html>"); shell.open(); for (int i = 0; i < (loopMultipier * secondsToWaitTillFail); i++) { runLoopTimer(waitMS); if (atomicIntArray.get(0) != -1) { if (atomicIntArray.get(0) == 1 && atomicIntArray.get(1) == 2 && atomicIntArray.get(2) == 3) { return; } else { fail("Resulting numbers in the array are not as expected"); } } } fail("Evaluation should have returned an array, but array not returned or values are not correct."); }
Source:
<code>public int hashCode() { <START> return new HashCodeBuilder() <END> .append(elements) .append(exceptional) .toHashCode(); }</code><technical_language>replaced Objects.hashCode JDK</technical_language>

Target:
public int hashCode() { return Objects.hashCode(elements, exceptional); }
Source:
<code>protected Object handleClear(InvocationContext ctx, VisitableCommand command, Object ignored) { ComposedCompletionStage<Void> composedCompletionStage = null; List<InternalCacheEntry<Object, Object>> copyEntries = null; if (cacheNotifier.hasListener(CacheEntryRemoved.class)) { composedCompletionStage = CompletionStages.composedCompletionStage(); copyEntries = new ArrayList<>(dataContainer.entrySet()); <START> } <END> dataContainer.clear(); if (copyEntries != null) { for (InternalCacheEntry entry : copyEntries) { composedCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryRemoved(entry.getKey(), entry.getValue(), entry.getMetadata(), false, ctx, (ClearCommand) command)); } composedCompletionStage.freeze(); } return stageOrNullSyncValue(composedCompletionStage); }</code><technical_language>need do similar ISPN-8548 here, putting entries in a list OOMEs. For matter, list of CompletionStages a lot of memory. AFAIK CompletableFuture.thenCompose() creates a cycle graph released once, need some kind of batching</technical_language>

Target:
protected Object handleClear(InvocationContext ctx, VisitableCommand command, Object ignored) { AggregateCompletionStage<Void> aggregateCompletionStage = null; List<InternalCacheEntry<Object, Object>> copyEntries = null; if (cacheNotifier.hasListener(CacheEntryRemoved.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); copyEntries = new ArrayList<>(dataContainer.entrySet()); } dataContainer.clear(); if (copyEntries != null) { for (InternalCacheEntry entry : copyEntries) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryRemoved(entry.getKey(), entry.getValue(), entry.getMetadata(), false, ctx, (ClearCommand) command)); } } return delayedNull(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null); }
Source:
<code>public List<SleepInsight> getInsights( @Scope(OAuthScope.SLEEP_TIMELINE) final AccessToken accessToken) { LOGGER.debug("Returning list of insights for account id = {}", accessToken.accountId); <START> final Optional<Account> accountOptional = accountDAO.getById(accessToken.accountId); <END> if (!accountOptional.isPresent()) { throw new WebApplicationException(404); } return InsightProcessor.getInsights(accessToken.accountId); }</code><technical_language>need this. Authenticator fail if account exist. need query DB for user. Grab accountId token</technical_language>

Target:
public List<SleepInsight> getInsights( @Scope(OAuthScope.SLEEP_TIMELINE) final AccessToken accessToken) { LOGGER.debug("Returning list of insights for account id = {}", accessToken.accountId); return InsightProcessor.getInsights(accessToken.accountId); }
Source:
<code>public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + <START> debugInfoForIndex(index)); <END> for (int j = i; j < widgetTable.length; j++) { if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }</code><technical_language>debugInforForIndex (line 4966) does: this i? index is number of items in result</technical_language>

Target:
public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + debugInfoForIndex(i)); for (int j = i; j < widgetTable.length; j++) { if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }
Source:
<code>private void downloadRuntime(String name) { JBossRuntimeDetection prefPage = new JBossRuntimeDetection(); prefPage.open(); DownloadRuntimesWizard runtimeWiz = prefPage.downloadRuntime(); runtimeWiz.selectRuntime(name); runtimeWiz.next(); new PushButton("Add...").click(); new DefaultText(0).setText("aqtwrdnr"); new DefaultText(1).setText("aqtwrdnr"); new PushButton("OK").click(); runtimeWiz.next(); new WaitUntil(new ShellWithTextIsAvailable("Download Runtimes"), TimePeriod.getCustom(5)); <START> AbstractWait.sleep(TimePeriod.getCustom(2)); <END> new RadioButton(0).toggle(true); runtimeWiz.next(); runtimeWiz.setInstallFolder(getPath() + "target/temp_install"); runtimeWiz.setDownloadFolder(getPath() + "target/temp"); runtimeWiz.finish(name); new WaitWhile(new ShellWithTextIsAvailable("Download 'JBoss Fuse 6.3.0'"), TimePeriod.getCustom(900)); prefPage.ok(); }</code><technical_language>Do need wait for 2 seconds? Please consider some wait condition</technical_language>

Target:
private void downloadRuntime(String name) { JBossRuntimeDetection prefPage = new JBossRuntimeDetection(); prefPage.open(); DownloadRuntimesWizard runtimeWiz = prefPage.downloadRuntime(); runtimeWiz.selectRuntime(name); runtimeWiz.next(); new PushButton("Add...").click(); new LabeledTextExt("Username:").setText("aqtwrdnr"); new LabeledTextExt("Password:").setText("aqtwrdnr"); new PushButton("OK").click(); runtimeWiz.next(); new WaitUntil(new ShellWithTextIsAvailable("Download Runtimes")); new WaitUntil(new RadioButtonIsAvailable("I accept the terms of the license agreement")); runtimeWiz.next(); runtimeWiz.setInstallFolder(getPath() + "target/temp_install"); runtimeWiz.setDownloadFolder(getPath() + "target/temp"); runtimeWiz.finish(name); new WaitWhile(new ShellWithTextIsAvailable("Download 'JBoss Fuse 6.3.0'"), TimePeriod.getCustom(900)); prefPage.ok(); }
Source:
<code>public void simpleWhileLoop() { <START> final CFG cfg = buildCFG("void fun() {int i = 0; while(i < 10) {i++; System.out.println(i); } }"); <END> Map<Tree, CFGLoop> loops = CFGLoop.getCFGLoops(cfg); assertThat(loops).hasSize(1); CFGLoop loop = loops.values().iterator().next(); List<Block> blocks = CFGLoop.sorted(cfg.blocks()); assertThat(loop.startingBlock()).isSameAs(blocks.get(2)); assertThat(loop.blocks()).containsOnly(blocks.get(1)); assertThat(loop.hasNoWayOut()).isTrue(); }</code><technical_language>Please a dedicated file for code samples. Easy code snippets easy read, impossible for complicated one</technical_language>

Target:
public void simpleWhileLoop() { String methodName = "simpleWhileLoop"; final CFG cfg = buildCFG(methodName); Map<Tree, CFGLoop> loops = CFGLoop.getCFGLoops(cfg); assertThat(loops).hasSize(1); CFGLoop loop = loops.values().iterator().next(); List<Block> blocks = sorted(cfg.blocks()); assertThat(loop.startingBlock()).isSameAs(blocks.get(2)); assertThat(loop.blocks()).containsOnly(blocks.get(1)); assertThat(loop.hasNoWayOut()).isTrue(); }
Source:
<code>public void visitNode(Tree tree) { MethodTree method = (MethodTree) tree; <START> JavaFileScannerContext.CognitiveComplexity result = context.cognitiveComplexity(method); <END> int total = result.complexity; if (total > max) { reportIssue(method.simpleName(), "Refactor this method to reduce its Cognitive Complexity from " + total + " to the " + max + " allowed.", result.locations, total - max); } }</code><technical_language>CognitiveComplexityVisitor.methodComplexity directly, method JavaScannerContext removed</technical_language>

Target:
public void visitNode(Tree tree) { MethodTree method = (MethodTree) tree; CognitiveComplexityVisitor.Result result = CognitiveComplexityVisitor.methodComplexity(method); int total = result.complexity; if (total > max) { reportIssue(method.simpleName(), "Refactor this method to reduce its Cognitive Complexity from " + total + " to the " + max + " allowed.", result.locations, total - max); } }
Source:
<code>private void setUpUiClient(WebView container) { container.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage cm) { if(!DEBUG) { return super.onConsoleMessage(cm); } trace(this, "onConsoleMessage() :: %s:%s | %s", cm.sourceId(), cm.lineNumber(), cm.message()); return true; } @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){ if(DEBUG) trace(this, "onShowFileChooser() :: %s,%s,%s", webView, filePathCallback, fileChooserParams); boolean capture = fileChooserParams.isCaptureEnabled(); trace(this, "onShowFileChooser() capture :: %s", capture); String[] acceptTypes = fileChooserParams.getAcceptTypes(); trace(this, "onShowFileChooser() acceptTypes :: %s", Arrays.toString(acceptTypes)); if(!photoGrabber.canHandle(acceptTypes, capture)) { warn(this, "openFileChooser() :: No file chooser is currently implemented for \"accept\" value: %s", Arrays.toString(acceptTypes)); return false; } trace(this, "onShowFileChooser() opening chooser"); photoGrabber.chooser(filePathCallback, capture); return true; } @Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) { <START> trace(this, "onGeolocationPermissionsShowPrompt() :: origin=%s, callback=%s", origin, callback); <END> callback.invoke(origin, true, true); } }); }</code><technical_language>callback a nice toString end a memory reference helpful. remove trace logs more readable</technical_language>

Target:
private void setUpUiClient(WebView container) { container.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage cm) { if(!DEBUG) { return super.onConsoleMessage(cm); } trace(this, "onConsoleMessage() :: %s:%s | %s", cm.sourceId(), cm.lineNumber(), cm.message()); return true; } @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){ if(DEBUG) trace(this, "onShowFileChooser() :: %s,%s,%s", webView, filePathCallback, fileChooserParams); boolean capture = fileChooserParams.isCaptureEnabled(); trace(this, "onShowFileChooser() capture :: %s", capture); String[] acceptTypes = fileChooserParams.getAcceptTypes(); trace(this, "onShowFileChooser() acceptTypes :: %s", Arrays.toString(acceptTypes)); if(!photoGrabber.canHandle(acceptTypes, capture)) { warn(this, "openFileChooser() :: No file chooser is currently implemented for \"accept\" value: %s", Arrays.toString(acceptTypes)); return false; } trace(this, "onShowFileChooser() opening chooser"); photoGrabber.chooser(filePathCallback, capture); return true; } @Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) { callback.invoke(origin, true, true); } }); }
Source:
<code>private String getFingerprint(String hostName) { connect(hostName); <START> String fingerprint = "Unknown"; <END> try { PublicKey serverKey = this.client.getServerKey(); if (serverKey == null) { log.error("Unable to get host key"); } else { String tmpFingerprint = OpenSSHUtils.getKeyFingerprintString(serverKey); if (tmpFingerprint == null) { log.error("Unable to get host fingerprint"); } else { fingerprint = tmpFingerprint; } } } catch (Throwable e) { log.errorFormat("Could not fetch fingerprint of server {0} with message: {1}", hostName, ExceptionUtils.getMessage(e)); } return fingerprint; }</code><technical_language>I fingerprint initialized null. Client understand if fingerprint is null, means error fetch it</technical_language>

Target:
protected String getFingerprint(String hostName) { connect(hostName); String fingerprint = null; PublicKey serverKey = this.client.getServerKey(); if (serverKey == null) { log.error("Unable to get host key"); } else { fingerprint = OpenSSHUtils.getKeyFingerprintString(serverKey); } return fingerprint; }
Source:
<code>public Azure withDefaultSubscription() { if (profile.subscriptionId() == null) { List<Subscription> subscriptions = new ArrayList<>(); this.subscriptions().list().forEach(subscription -> { subscriptions.add(subscription); }); if (subscriptions.size() == 0) { throw logger.logExceptionAsError( <START> new RuntimeException("Please create a subscription before you start resource management. " <END> + "To learn more, see: <LINK_0>")); } else if (subscriptions.size() > 1) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("More than one subscription found in your tenant. " + "Please specify which one below is desired for resource management."); subscriptions.forEach(subscription -> { stringBuilder.append("\n" + subscription.displayName() + " : " + subscription.subscriptionId()); }); throw logger.logExceptionAsError(new RuntimeException(stringBuilder.toString())); } else { profile.withSubscriptionId(subscriptions.get(0).subscriptionId()); } } return new Azure(httpPipeline, profile, this); }</code><technical_language>Is find a more specific exception type? RuntimeException is generally viewed abstract base class. IllegalStateException, InvalidArgumentException (if defaultSubscription works for 1 subscription)</technical_language>

Target:
public Azure withDefaultSubscription() { if (profile.subscriptionId() == null) { profile.withSubscriptionId(Utils.defaultSubscription(this.subscriptions().list())); } return new Azure(httpPipeline, profile, this); }
Source:
<code>public Trace getTrace(String tenantId, String id) { Span span = getSpan(tenantId, id); <START> if (span == null || (span != null && span.serverSpan())) { <END> String clientId = SpanUniqueIdGenerator.getClientId(id); if (getSpan(tenantId, clientId) != null) { id = clientId; } } Trace trace = getTraceFragment(tenantId, id); if (trace != null) { processConnectedFragment(tenantId, trace); } return trace; }</code><technical_language>(span == null || (span != null && span.serverSpan())) is (span == null || span.serverSpan())</technical_language>

Target:
public Trace getTrace(String tenantId, String id) { Span span = getSpan(tenantId, id); if (span == null || span.serverSpan()) { String clientId = SpanUniqueIdGenerator.getClientId(id); if (getSpan(tenantId, clientId) != null) { id = clientId; } } Trace trace = getTraceFragment(tenantId, id); if (trace != null) { processConnectedFragment(tenantId, trace); } return trace; }
Source:
<code>private static boolean hasOnlyStaticMembers(ClassTree classTree) { List<Tree> members = classTree.members(); <START> if (members.isEmpty() || noStaticMember(members)) { <END> return false; } for (Tree member : members) { if (!isConstructor(member) && !isStatic(member) && !member.is(Tree.Kind.EMPTY_STATEMENT)) { return false; } } return true; }</code><technical_language>members.isEmpty() is redundant here, noStaticMember true members empty. method replaced if logic is cleaned up. need test is member, is constructor empty statement, of static. private static boolean hasOnlyStaticMembers(ClassTree classTree) { List<Tree> members = classTree.members().stream() .filter(m -> !m.is(Tree.Kind.CONSTRUCTOR, Tree.Kind.EMPTY_STATEMENT)) .collect(Collectors.toList()); return !members.isEmpty() && members.stream().allMatch(UtilityClassWithPublicConstructorCheck::isStatic); }</technical_language>

Target:
private static boolean hasOnlyStaticMembers(ClassTree classTree) { List<Tree> members = classTree.members(); if (noStaticMember(members)) { return false; } return members.stream().allMatch(member -> isConstructor(member) || isStatic(member) || member.is(Tree.Kind.EMPTY_STATEMENT)); }
Source:
<code>DirListingMetadata getDirListingMetadataFromDirMetaAndList(Path path, List<PathMetadata> metas, DDBPathMetadata dirPathMeta) { boolean isAuthoritative = false; if(dirPathMeta != null) { isAuthoritative = dirPathMeta.isAuthoritativeDir(); } LOG.trace("Listing table in region for returning {}", tableName, region, path, metas); if (!metas.isEmpty() && dirPathMeta == null) { LOG.warn("Directory marker is deleted, but the list of the directory " <START> + "elements is not empty: {}. This case is handled as the directory" <END> + " was deleted.", metas); return null; } if(metas.isEmpty() && dirPathMeta == null) { return null; } return new DirListingMetadata(path, metas, isAuthoritative, dirPathMeta.getLastUpdated()); }</code><technical_language>"is handled if"</technical_language>

Target:
DirListingMetadata getDirListingMetadataFromDirMetaAndList(Path path, List<PathMetadata> metas, DDBPathMetadata dirPathMeta) { boolean isAuthoritative = false; if (dirPathMeta != null) { isAuthoritative = dirPathMeta.isAuthoritativeDir(); } LOG.trace("Listing table in region for returning {}", tableName, region, path, metas); if (!metas.isEmpty() && dirPathMeta == null) { LOG.warn("Directory marker is deleted, but the list of the directory " + "elements is not empty: {}. This case is handled as if the " + "directory was deleted.", metas); return null; } if(metas.isEmpty() && dirPathMeta == null) { return null; } return new DirListingMetadata(path, metas, isAuthoritative, dirPathMeta.getLastUpdated()); }
Source:
<code>public void testCorrelatedSubqueries() { assertPlan( "SELECT orderkey FROM orders WHERE 3 = (SELECT orderkey)", LogicalPlanner.Stage.OPTIMIZED, anyTree( filter("BIGINT '3' = X", lateral( ImmutableList.of("X"), tableScan("orders", ImmutableMap.of("X", "orderkey")), node(EnforceSingleRowNode.class, project( node(ValuesNode.class)))))), MorePredicates.<PlanOptimizer>isInstanceOfAny(AddLocalExchanges.class, CheckSubqueryNodesAreRewritten.class).negate()); <START> } <END></code><technical_language>please put argument in separate line like: method( arg1, arg2, ..., lastArg);</technical_language>

Target:
public void testCorrelatedSubqueries() { assertPlan( "SELECT orderkey FROM orders WHERE 3 = (SELECT orderkey)", LogicalPlanner.Stage.OPTIMIZED, any( filter( "X = BIGINT '3'", tableScan("orders", ImmutableMap.of("X", "orderkey"))))); }
Source:
<code>public boolean actionShouldBeSuppressed(final long lastAllowedPresentationTime, final UUID actionUUID) { <START> Long lastPresentation = suppressionTimeStore.get(actionUUID.toString()); <END> boolean value = lastPresentation != null && lastPresentation >= lastAllowedPresentationTime; if (!value) { synchronized (lock) { suppressionTimeStore.put(actionUUID.toString(), clock.now()); } saveAllData(); runloop.add(runloop.obtainMessage(MSG_SAVE_SUPPRESSION_STORE)); } return value; }</code><technical_language>accessing suppressionTimeStore synchronized too? beaconActions, beaconScans, etc? Especially plain HashMap, synchronized one</technical_language>

Target:
public boolean actionShouldBeSuppressed(final long lastAllowedPresentationTime, final UUID actionUUID) { Long lastPresentation; synchronized (lock) { lastPresentation = suppressionTimeStore.get(actionUUID.toString()); } boolean value = lastPresentation != null && lastPresentation >= lastAllowedPresentationTime; if (!value) { synchronized (lock) { suppressionTimeStore.put(actionUUID.toString(), clock.now()); } saveAllData(); runloop.add(runloop.obtainMessage(MSG_SAVE_SUPPRESSION_STORE)); } return value; }