auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArbitraryGranularitySpec that = (ArbitraryGranularitySpec) o; if (!intervals.equals(that.intervals)) { return false; } if (!rollup.equals(that.rollup)) { return false; } <START> if (!timezone.equals(that.timezone)) { <END> return false; } return !(queryGranularity != null ? !queryGranularity.equals(that.queryGranularity) : that.queryGranularity != null); }</code><technical_language>This some issues if timezone is null</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArbitraryGranularitySpec that = (ArbitraryGranularitySpec) o; if (!intervals.equals(that.intervals)) { return false; } if (!rollup.equals(that.rollup)) { return false; } if (timezone != null ? !timezone.equals(that.timezone): that.timezone != null) { return false; } return !(queryGranularity != null ? !queryGranularity.equals(that.queryGranularity) : that.queryGranularity != null); }
Source:
<code>protected AbstractBeanDefinition doParse(Element element, ParserContext parserContext, String channelName) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( "org.springframework.integration.redis.inbound.RedisInboundChannelAdapter"); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); builder.addPropertyReference("outputChannel", channelName); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "topics"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "error-channel"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "message-converter"); if (element.hasAttribute("serializer")) { String serializer = element.getAttribute("serializer"); if (StringUtils.hasText(serializer)) { builder.addPropertyReference("serializer", serializer); } else { <START> builder.addPropertyValue("serializer", null); <END> } } return builder.getBeanDefinition(); }</code><technical_language>I need a docbook and/or schema doc update "" means serializer (and String is default)</technical_language>

Target:
protected AbstractBeanDefinition doParse(Element element, ParserContext parserContext, String channelName) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisInboundChannelAdapter.class); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); builder.addPropertyReference("outputChannel", channelName); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "topics"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "error-channel"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "message-converter"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "serializer", true); return builder.getBeanDefinition(); }
Source:
<code>public ListenableFuture<Map<Cell, Value>> getAsync(TableReference tableRef, Map<Cell, Long> timestampByCell) { <START> try (CloseableTrace trace = startLocalTrace("getAsync({}, cells)", <END> LoggingArgs.safeTableOrPlaceholder(tableRef), timestampByCell.size())) { return delegate().getAsync(tableRef, timestampByCell); } }</code><technical_language>this'll weird, want AsyncTracer <LINK_0> require a dep bump though, spans meaningless</technical_language>

Target:
public ListenableFuture<Map<Cell, Value>> getAsync(TableReference tableRef, Map<Cell, Long> timestampByCell) { DetachedSpan detachedSpan = DetachedSpan.start(String.format("getAsync(%s, %s cells)", LoggingArgs.safeTableOrPlaceholder(tableRef), timestampByCell.size())); ListenableFuture<Map<Cell, Value>> future = delegate().getAsync(tableRef, timestampByCell); return attachDetachedSpanCompletion(detachedSpan, future, tracingExecutorService); }
Source:
<code>public static void initialize(Path logFileFolder) { String timestamp = TIMESTAMP_FORMAT.format(new Date()); loggingPath = logFileFolder.resolve(timestamp).normalize(); String pathString = loggingPath.toString(); System.setProperty(LOG_FILE_FOLDER, pathString); try { <START> deleteLogFiles(logFileFolder, ((int) Duration.ofDays(5).getSeconds())); <END> } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>deleteLogFiles a long parameter? This avoid need downcast reason</technical_language>

Target:
public static void initialize(Path logFileFolder) { String timestamp = TIMESTAMP_FORMAT.format(new Date()); loggingPath = logFileFolder.resolve(timestamp).normalize(); String pathString = loggingPath.toString(); System.setProperty(LOG_FILE_FOLDER, pathString); try { deleteLogFiles(logFileFolder, Duration.ofDays(5).getSeconds()); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); <START> for (Tracer tracer : tracers) { <END> local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }</code><technical_language>need support multiple tracer implementation. Refer - <LINK_0></technical_language>

Target:
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
Source:
<code>public static void register(TableFunctionModule module) { module.register(NAME, new BaseFunctionResolver( FuncParams.builder().withIndependentVarArgs(ANY_ARRAY).build()) { @Override public FunctionImplementation getForTypes(List<DataType> dataTypes) throws IllegalArgumentException { DataType returnType; if (dataTypes.size() == 1) { var dataType = dataTypes.get(0); if (isArray(dataType)) { returnType = ((ArrayType) dataType).innerType(); } else { <START> returnType = dataTypes.get(0); <END> } } else { returnType = ObjectType.untyped(); } return new ValuesTableFunctionImplementation( new FunctionInfo(new FunctionIdent(NAME, dataTypes), returnType, FunctionInfo.Type.TABLE)); } }); }</code><technical_language>I this case allowed</technical_language>

Target:
public static void register(TableFunctionModule module) { module.register(NAME, new BaseFunctionResolver( FuncParams.builder().withIndependentVarArgs(ANY_ARRAY).build()) { @Override public FunctionImplementation getForTypes(List<DataType> dataTypes) throws IllegalArgumentException { DataType returnType; if (dataTypes.size() == 1) { var dataType = dataTypes.get(0); if (isArray(dataType)) { returnType = ((ArrayType) dataType).innerType(); } else { throw new IllegalArgumentException( "Function argument must have an array data type, but was '" + dataType + "'"); } } else { returnType = ObjectType.untyped(); } return new ValuesTableFunctionImplementation( new FunctionInfo(new FunctionIdent(NAME, dataTypes), returnType, FunctionInfo.Type.TABLE)); } }); }
Source:
<code>private void addDiskMapping() { addStorageDomainMapForCopiedTemplateDisk(); <START> unregisteredDisksDao.removeUnregisteredDisk(getImage().getId(), getParameters().getStorageDomainId()); <END> setSucceeded(true); }</code><technical_language>operations needs performed in transaction</technical_language>

Target:
private void addDiskMapping() { executeInNewTransaction(() -> { addStorageDomainMapForCopiedTemplateDisk(); unregisteredDisksDao.removeUnregisteredDisk(getImage().getId(), getParameters().getStorageDomainId()); incrementDbGenerationForRelatedEntities(); return null; }); setSucceeded(true); }
Source:
<code>public HttpResponse doBuild(@QueryParameter TimeDuration delay) { checkPermission(BUILD); if (!isBuildable()) { <START> throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, new IOException(getFullName() + " cannot be indexed")); <END> } scheduleBuild2(delay == null ? 0 : delay.getTime(), new CauseAction(new Cause.UserIdCause())); return HttpResponses.forwardToPreviousPage(); }</code><technical_language>computed more coherent</technical_language>

Target:
public HttpResponse doBuild(@QueryParameter TimeDuration delay) { checkPermission(BUILD); if (!isBuildable()) { throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, new IOException(getFullName() + " cannot be recomputed")); } scheduleBuild2(delay == null ? 0 : delay.getTime(), new CauseAction(new Cause.UserIdCause())); return HttpResponses.forwardToPreviousPage(); }
Source:
<code>public static void copy(File src, File dst) throws IOException { if(src.isDirectory()){ String[] srcChildren = src.list(); <START> if (srcChildren == null) { <END> srcChildren = new String[0]; } for (String srcChildPathName : srcChildren) { File srcChild = new File(src, srcChildPathName); File dstChild = new File(dst, srcChildPathName); copy(srcChild, dstChild); } } else transferData(src, dst); }</code><technical_language>throw IOException here, source directory list content</technical_language>

Target:
public static void copy(File src, File dst) throws IOException { if(src.isDirectory()){ String[] srcChildren = src.list(); if (srcChildren == null) { throw new IOException("Content from directory '" + src.getAbsolutePath() + "' can not be listed."); } for (String srcChildPathName : srcChildren) { File srcChild = new File(src, srcChildPathName); File dstChild = new File(dst, srcChildPathName); copy(srcChild, dstChild); } } else transferData(src, dst); }
Source:
<code>public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> remainders = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); for (int index = 0; index < remainders.size(); index++) { ItemStack itemStack = inv.getStackInSlot(index); if (!itemStack.isEmpty()) { Ingredient ingredient = input.get(index); <START> if (ingredient instanceof FluidIngredient) <END> { ItemStack container = itemStack.copy(); container.setCount(1); IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(container); if (fluidHandler != null) { FluidStack checking = fluidHandler.drain(((FluidIngredient)ingredient).getFluidStack(), true); if (checking == null) { fluidHandler.drain(Integer.MAX_VALUE, true); } itemStack = fluidHandler.getContainer(); } } else { itemStack = ForgeHooks.getContainerItem(itemStack); } remainders.set(index, itemStack); } } return remainders; }</code><technical_language>this interface fluid ingredients implement a callback for this logic? I this useful for RF battery ingredient a callback remove energy, other similar cases ingredient define special logic crafting</technical_language>

Target:
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> remainders = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); for (int index = 0; index < remainders.size(); index++) { ItemStack itemStack = inv.getStackInSlot(index); if (!itemStack.isEmpty()) { Ingredient ingredient = input.get(index); if (ingredient instanceof ICustomContainerCallback) { itemStack = ((ICustomContainerCallback)ingredient).getContainer(itemStack); } else { itemStack = ForgeHooks.getContainerItem(itemStack); } remainders.set(index, itemStack); } } return remainders; }
Source:
<code>private X509Certificate[] getCerts(SSLSessionInfo session) { try { Certificate[] javaCerts = session.getPeerCertificates(); if (javaCerts == null) { return null; } int x509Certs = 0; for (Certificate javaCert : javaCerts) { if (javaCert instanceof X509Certificate) { ++x509Certs; } } if (x509Certs == 0) { return null; } if (x509Certs == javaCerts.length) { return (X509Certificate[]) javaCerts; } X509Certificate[] results = new X509Certificate[x509Certs]; for (int i = 0; i < x509Certs; i++) { <START> results[i] = (X509Certificate) javaCerts[i]; <END> } return results; } catch (Exception e) { return null; } }</code><technical_language>certificate index i is instance of X509Certificate. loop instanceof check</technical_language>

Target:
private X509Certificate[] getCerts(SSLSessionInfo session) { try { Certificate[] javaCerts = session.getPeerCertificates(); if (javaCerts == null) { return null; } int x509Certs = 0; for (Certificate javaCert : javaCerts) { if (javaCert instanceof X509Certificate) { ++x509Certs; } } if (x509Certs == 0) { return null; } int resultIndex = 0; X509Certificate[] results = new X509Certificate[x509Certs]; for (Certificate certificate : javaCerts) { if (certificate instanceof X509Certificate) { results[resultIndex++] = (X509Certificate) certificate; } } return results; } catch (Exception e) { return null; } }
Source:
<code>private boolean swiftUpload(final Connection conn, final SwiftTO swift, final String container, final String ldir, final String lfilename, final Boolean isISCSI, final int wait) { List<String> params = getSwiftParams(swift, container, ldir, lfilename, isISCSI); try { String result = hypervisorResource.callHostPluginAsync(conn, "swiftxenserver", "swift", wait, params.toArray(new String[params.size()])); <START> return "true".equals(result); <END> } catch (final Exception e) { s_logger.warn("swift upload failed due to " + e.toString(), e); } return false; }</code><technical_language>org.apache.commons.lang3.BooleanUtils.toBoolean(String) here</technical_language>

Target:
private boolean swiftUpload(final Connection conn, final SwiftTO swift, final String container, final String ldir, final String lfilename, final Boolean isISCSI, final int wait) { List<String> params = getSwiftParams(swift, container, ldir, lfilename, isISCSI); try { String result = hypervisorResource.callHostPluginAsync(conn, "swiftxenserver", "swift", wait, params.toArray(new String[params.size()])); return BooleanUtils.toBoolean(result); } catch (final Exception e) { s_logger.warn("swift upload failed due to " + e.toString(), e); } return false; }
Source:
<code>public SetPersistentViewCommand(TransactionalEditingDomain domain, View view) { <START> super(domain, "CreateStereotypePropertyView"); <END> this.view = view; }</code><technical_language>Create a constant</technical_language>

Target:
public SetPersistentViewCommand(TransactionalEditingDomain domain, View view) { super(domain, LABEL_COMMAND); this.view = view; }
Source:
<code>public void test() throws Exception { FileSystem fs = FileSystem.get(CachedConfiguration.getInstance()); <START> Path srcPath = new Path(System.getProperty("user.dir") + "/target/TestIterators-tests.jar"); <END> Path dstPath = new Path(CONTEXT_DIR + "/Test.jar"); fs.copyFromLocalFile(srcPath, dstPath); UtilWaitThread.sleep(5000); try { Connector c = getConnector(); c.instanceOperations().setProperty(CONTEXT_PROPERTY, CONTEXT_CLASSPATH); String tableName = getUniqueNames(1)[0]; c.tableOperations().create(tableName); BatchWriter bw = c.createBatchWriter(tableName, new BatchWriterConfig()); for (int i = 0; i < ITERATIONS; i++) { Mutation m = new Mutation("row" + i); m.put("cf", "col1", "Test"); bw.addMutation(m); } bw.close(); scanCheck(c, tableName, null, null, "Test"); batchCheck(c, tableName, null, null, "Test"); IteratorSetting cfg = new IteratorSetting(1, "reverse", "org.apache.accumulo.test.functional.ValueReversingIterator"); try { scanCheck(c, tableName, cfg, null, "tseT"); fail("This should have failed because context was not set"); } catch (Exception e) { } try { batchCheck(c, tableName, cfg, null, "tseT"); fail("This should have failed because context was not set"); } catch (Exception e) { } scanCheck(c, tableName, cfg, CONTEXT, "tseT"); batchCheck(c, tableName, cfg, CONTEXT, "tseT"); } finally { fs.delete(dstPath, true); } }</code><technical_language>Building this File Path (with implicitly/explicit file separators) nicer</technical_language>

Target:
public void test() throws Exception { Path baseDir = new Path(System.getProperty("user.dir")); Path targetDir = new Path(baseDir, "target"); Path jarPath = new Path(targetDir, "TestIterators-tests.jar"); Path dstPath = new Path(CONTEXT_DIR + "/Test.jar"); fs.copyFromLocalFile(jarPath, dstPath); UtilWaitThread.sleep(WAIT); try { Connector c = getConnector(); c.instanceOperations().setProperty(CONTEXT_PROPERTY, CONTEXT_CLASSPATH); String tableName = getUniqueNames(1)[0]; c.tableOperations().create(tableName); BatchWriter bw = c.createBatchWriter(tableName, new BatchWriterConfig()); for (int i = 0; i < ITERATIONS; i++) { Mutation m = new Mutation("row" + i); m.put("cf", "col1", "Test"); bw.addMutation(m); } bw.close(); scanCheck(c, tableName, null, null, "Test"); batchCheck(c, tableName, null, null, "Test"); IteratorSetting cfg = new IteratorSetting(21, "reverse", "org.apache.accumulo.test.functional.ValueReversingIterator"); try { scanCheck(c, tableName, cfg, null, "tseT"); fail("This should have failed because context was not set"); } catch (Exception e) { } try { batchCheck(c, tableName, cfg, null, "tseT"); fail("This should have failed because context was not set"); } catch (Exception e) { } scanCheck(c, tableName, cfg, CONTEXT, "tseT"); batchCheck(c, tableName, cfg, CONTEXT, "tseT"); } finally { fs.delete(dstPath, true); } }
Source:
<code>private DataloadProcess postProcess(DataloadProcess process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } Object processToSend; HttpMethod method = HttpMethod.POST; if (tempFile.length() > MAX_MULTIPART_SIZE) { try { process.setPath(dataStoreService.getUri(tempFile.getName()).getPath()); dataStoreService.upload(tempFile.getName(), new FileInputStream(tempFile)); processToSend = process; if (DataloadProcess.TEMPLATE.matches(postUri.toString())) { method = HttpMethod.PUT; } } catch (FileNotFoundException e) { <START> throw new GoodDataException("Unable to access zipped process data", e); <END> } } else { final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); processToSend = parts; } try { return restTemplate.exchange(postUri, method, new HttpEntity<>(processToSend), DataloadProcess.class).getBody(); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to post dataload process.", e); } finally { deleteTempFile(tempFile); } }</code><technical_language>add path</technical_language>

Target:
private DataloadProcess postProcess(DataloadProcess process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } Object processToSend; HttpMethod method = HttpMethod.POST; if (tempFile.length() > MAX_MULTIPART_SIZE) { try { process.setPath(dataStoreService.getUri(tempFile.getName()).getPath()); dataStoreService.upload(tempFile.getName(), new FileInputStream(tempFile)); processToSend = process; if (DataloadProcess.TEMPLATE.matches(postUri.toString())) { method = HttpMethod.PUT; } } catch (FileNotFoundException e) { throw new GoodDataException("Unable to access zipped process data at " + tempFile.getAbsolutePath(), e); } } else { final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); processToSend = parts; } try { return restTemplate.exchange(postUri, method, new HttpEntity<>(processToSend), DataloadProcess.class).getBody(); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to post dataload process.", e); } finally { deleteTempFile(tempFile); } }
Source:
<code>public void close() { <START> } <END></code><technical_language>factory close cursor (which is closeable)</technical_language>

Target:
public void close() { cursor.close(); }
Source:
<code>public void run(final IProgressMonitor monitor) throws CoreException { List<URI> externalResourcesURI = resourceManager.getExternalResources(); List<Resource> resourcesToRemove = new ArrayList<Resource>(externalResourcesURI.size()); for (URI uri : externalResourcesURI) { Resource resource = modelSet.getResource(uri, false); if (null != resource) { try { if (modelSet.shouldSave(resource)) { resource.save(null); } resourcesToRemove.add(resource); } catch (IOException e) { Activator.log.error("There was an error during save.", e); } } } <START> modelSet.getResources().removeAll(resourcesToRemove); <END> resourceManager.clear(); }</code><technical_language>remove resources resource set unloaded, I expect adapters attached contents (such UML CacheAdapter) leak memory. references objects in resources resources removed changed proxies unloading. I unload() calls</technical_language>

Target:
public void run(final IProgressMonitor monitor) throws CoreException { List<URI> externalResourcesURI = resourceManager.getExternalResources(); List<Resource> resourcesToRemove = new ArrayList<Resource>(externalResourcesURI.size()); MultiStatus saveStatus = null; for (URI uri : externalResourcesURI) { Resource resource = modelSet.getResource(uri, false); if (null != resource) { try { if (modelSet.shouldSave(resource)) { resource.save(null); } } catch (IOException e) { if (null == saveStatus) { saveStatus = new MultiStatus(Activator.PLUGIN_ID, SWT.ERROR, "Some resources could not be saved", null); } saveStatus.add(new Status(SWT.ERROR, Activator.PLUGIN_ID, "The resource " + uri.toString() + " could not be saved", e)); } finally { resource.unload(); resourcesToRemove.add(resource); } } } modelSet.getResources().removeAll(resourcesToRemove); resourceManager.clear(); if (null != saveStatus) { throw new CoreException(saveStatus); } }
Source:
<code>@Override protected void beforeTest() throws Exception { startGridsMultiThreaded(GRID_CNT - 2); <START> client = true; <END> Ignite grid = startClientGrid(GRID_CNT - 2); grid.createNearCache(DEFAULT_CACHE_NAME, new NearCacheConfiguration()); grid = startClientGrid(GRID_CNT - 1); grid.cache(DEFAULT_CACHE_NAME); }</code><technical_language>If I correct, remove 'client', field is once, change condition in 'getConfiguration' method from: if (!client) { to: if (!c.isClientMode()) {</technical_language>

Target:
@Override protected void beforeTest() throws Exception { startGridsMultiThreaded(GRID_CNT - 2); Ignite grid = startClientGrid(GRID_CNT - 2); grid.createNearCache(DEFAULT_CACHE_NAME, new NearCacheConfiguration()); grid = startClientGrid(GRID_CNT - 1); grid.cache(DEFAULT_CACHE_NAME); }
Source:
<code>public Collection<Prefab> listPrefabs(Class<? extends Component> comp) { Collection<Prefab> prefabs = Sets.newHashSet(); <START> prefabs.addAll(assetManager.getLoadedAssets(Prefab.class).stream().filter(p -> p.getComponent(comp) != null).collect(Collectors.toList())); <END> return prefabs; }</code><technical_language>This converted a Set. Personally, I try get lines shorter 120 chars line is visible in GitHub, a matter of taste</technical_language>

Target:
public Collection<Prefab> listPrefabs(Class<? extends Component> comp) { return assetManager.getLoadedAssets(Prefab.class).stream().filter(p -> p.getComponent(comp) != null) .collect(Collectors.toCollection(HashSet::new)); }
Source:
<code>public static FullTextExpression index(@NonNull String name) { <START> <END> if(name == null) { throw new IllegalArgumentException("name is null"); } return new FullTextExpression(name); }</code><technical_language>Please remove extra empty line</technical_language>

Target:
public static FullTextExpression index(@NonNull String name) { if (name == null) { throw new IllegalArgumentException("name is null."); } return new FullTextExpression(name); }
Source:
<code>public void removeBlock(long sessionId, long blockId, BlockStoreLocation location) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { LOG.debug("removeBlock: sessionId={}, blockId={}, location={}", sessionId, blockId, location); long lockId = mLockManager.tryLockBlock(sessionId, blockId, BlockLockType.WRITE, REMOVE_BLOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (lockId == BlockLockManager.INVALID_LOCK_ID) { <START> throw new IOException(String.format("Can not acquire lock for block %d", blockId)); <END> } BlockMeta blockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { if (mMetaManager.hasTempBlockMeta(blockId)) { throw new InvalidWorkerStateException(ExceptionMessage.REMOVE_UNCOMMITTED_BLOCK, blockId); } blockMeta = mMetaManager.getBlockMeta(blockId); if (!blockMeta.getBlockLocation().belongsTo(location)) { throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_NOT_FOUND_AT_LOCATION, blockId, location); } } catch (Exception e) { mLockManager.unlockBlock(lockId); throw e; } try (LockResource r = new LockResource(mMetadataWriteLock)) { removeBlockInternal(blockMeta); } finally { mLockManager.unlockBlock(lockId); } for (BlockStoreEventListener listener : mBlockStoreEventListeners) { synchronized (listener) { listener.onRemoveBlockByClient(sessionId, blockId); listener.onRemoveBlock(sessionId, blockId, blockMeta.getBlockLocation()); } } }</code><technical_language>a question: meet this exception, need more information happened, who(sessionId) hold this block write lock, long held this session? If user wrong session client, is a user/admin clear specific session's locks? that, wait session timeout</technical_language>

Target:
public void removeBlock(long sessionId, long blockId, BlockStoreLocation location) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { LOG.debug("removeBlock: sessionId={}, blockId={}, location={}", sessionId, blockId, location); long lockId = mLockManager.tryLockBlock(sessionId, blockId, BlockLockType.WRITE, REMOVE_BLOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (lockId == BlockLockManager.INVALID_LOCK_ID) { throw new IOException( String.format("Can not acquire lock to remove block %d for session %d after %d ms", blockId, sessionId, REMOVE_BLOCK_TIMEOUT_MS)); } BlockMeta blockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { if (mMetaManager.hasTempBlockMeta(blockId)) { throw new InvalidWorkerStateException(ExceptionMessage.REMOVE_UNCOMMITTED_BLOCK, blockId); } blockMeta = mMetaManager.getBlockMeta(blockId); if (!blockMeta.getBlockLocation().belongsTo(location)) { throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_NOT_FOUND_AT_LOCATION, blockId, location); } } catch (Exception e) { mLockManager.unlockBlock(lockId); throw e; } try (LockResource r = new LockResource(mMetadataWriteLock)) { removeBlockInternal(blockMeta); } finally { mLockManager.unlockBlock(lockId); } for (BlockStoreEventListener listener : mBlockStoreEventListeners) { synchronized (listener) { listener.onRemoveBlockByClient(sessionId, blockId); listener.onRemoveBlock(sessionId, blockId, blockMeta.getBlockLocation()); } } }
Source:
<code>protected void configure(StateMachineExecutor executor) { executor.register(PutCommand.class, this::put); <START> executor.register(GetQuery.class, this::get); <END> executor.register(DeleteCommand.class, this::delete); }</code><technical_language>name GetCommand consistent</technical_language>

Target:
protected void configure(StateMachineExecutor executor) { executor.register(PutCommand.class, this::put); executor.register(GetCommand.class, this::get); executor.register(DeleteCommand.class, this::delete); }
Source:
<code>public void committed(long epoch, Layout layout, boolean force) throws WrongEpochException { CompletableFuture<Boolean>[] commitList = layout.getLayoutServers().stream() .map(x -> { CompletableFuture<Boolean> cf = new CompletableFuture<>(); try { if (force) { cf = getRuntimeLayout(layout).getLayoutClient(x).force(layout); } else { cf = getRuntimeLayout(layout).getLayoutClient(x).committed(epoch, layout); } } catch (NetworkException e) { cf.completeExceptionally(e); } return cf; }) .toArray(CompletableFuture[]::new); int timeouts = 0; int responses = 0; <START> <END> for (CompletableFuture cf : commitList) { try { CFUtils.getUninterruptibly(cf, WrongEpochException.class, TimeoutException.class, NetworkException.class); responses++; } catch (WrongEpochException e) { if (!force) { throw e; } log.warn("committed: Error while force committing", e); } catch (TimeoutException | NetworkException e) { log.warn("committed: Error while committing", e); timeouts++; } } log.info("committed: Successful requests={}, responses={}, timeouts={}", commitList.length, responses, timeouts); }</code><technical_language>I failing bug. iterating while (responses < commitList.length). CompletableFuture.anyOf() invoked for CF do execute exceptionally</technical_language>

Target:
public void committed(long epoch, Layout layout, boolean force) throws WrongEpochException { CompletableFuture<Boolean>[] commitList = layout.getLayoutServers().stream() .map(x -> { CompletableFuture<Boolean> cf = new CompletableFuture<>(); try { if (force) { cf = getRuntimeLayout(layout).getLayoutClient(x).force(layout); } else { cf = getRuntimeLayout(layout).getLayoutClient(x).committed(epoch, layout); } } catch (NetworkException e) { cf.completeExceptionally(e); } return cf; }) .toArray(CompletableFuture[]::new); int responses = 0; for (CompletableFuture cf : commitList) { try { CFUtils.getUninterruptibly(cf, WrongEpochException.class, TimeoutException.class, NetworkException.class, NoBootstrapException.class); responses++; } catch (WrongEpochException e) { if (!force) { throw e; } log.warn("committed: encountered exception", e); } catch (NoBootstrapException | TimeoutException | NetworkException e) { log.warn("committed: encountered exception", e); } } log.debug("committed: Successful requests={}, responses={}", commitList.length, responses); }
Source:
<code>public boolean releaseDomainSpecificVirtualRanges(final long domainId) { final List<DomainVlanMapVO> maps = _domainVlanMapDao.listDomainVlanMapsByDomain(domainId); <START> if (maps != null && !maps.isEmpty()) { <END> try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(final TransactionStatus status) { for (DomainVlanMapVO map : maps) { if (!releasePublicIpRange(map.getVlanDbId(), _accountMgr.getSystemUser().getId(), _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM))) { throw new CloudRuntimeException("Failed to release domain specific virtual ip ranges for domain id=" + domainId); } } } }); } catch (final CloudRuntimeException e) { s_logger.error(e); return false; } } else { s_logger.trace("Domain id=" + domainId + " has no domain specific virtual ip ranges, nothing to release"); } return true; }</code><technical_language>@ustcweizhou Thanks for changes, code is ok, more thing. please change condition (**maps != null && !maps.isEmpty()**) for (**MapUtils.isEmpty(maps)**) more details (<LINK_0> Thanks</technical_language>

Target:
public boolean releaseDomainSpecificVirtualRanges(final long domainId) { final List<DomainVlanMapVO> maps = _domainVlanMapDao.listDomainVlanMapsByDomain(domainId); if (CollectionUtils.isNotEmpty(maps)) { try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(final TransactionStatus status) { for (DomainVlanMapVO map : maps) { if (!releasePublicIpRange(map.getVlanDbId(), _accountMgr.getSystemUser().getId(), _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM))) { throw new CloudRuntimeException("Failed to release domain specific virtual ip ranges for domain id=" + domainId); } } } }); } catch (final CloudRuntimeException e) { s_logger.error(e); return false; } } else { s_logger.trace("Domain id=" + domainId + " has no domain specific virtual ip ranges, nothing to release"); } return true; }
Source:
<code>private InetSocketAddress resolve(InetSocketAddress address) { try { String curHostString = address.getHostString(); List<InetAddress> resolvedAddresses = new ArrayList<>(Arrays.asList(this.resolver.getAllByName(curHostString))); if (resolvedAddresses.isEmpty()) { return address; } Collections.shuffle(resolvedAddresses); return new InetSocketAddress(resolvedAddresses.get(0), address.getPort()); <START> } catch (UnknownHostException e) { <END> return address; } }</code><technical_language>log exception here. caller handle unknown address correctly</technical_language>

Target:
private InetSocketAddress resolve(InetSocketAddress address) { try { String curHostString = address.getHostString(); List<InetAddress> resolvedAddresses = new ArrayList<>(Arrays.asList(this.resolver.getAllByName(curHostString))); if (resolvedAddresses.isEmpty()) { return address; } Collections.shuffle(resolvedAddresses); return new InetSocketAddress(resolvedAddresses.get(0), address.getPort()); } catch (UnknownHostException e) { LOG.error("Unable to resolve address: {}", address.toString(), e); return address; } }
Source:
<code>public void hasSameValues_checkingAgainstSameInstanceOfAllergy_shouldInterpretAsSameValues() { Allergy allergy = allergy(); <START> allergy.hasSameValues(allergy()); <END> }</code><technical_language>this line AssertTrue(allergy.hasSameValues(allergy()));</technical_language>

Target:
public void hasSameValues_checkingAgainstSameInstanceOfAllergy_shouldInterpretAsSameValues() { Allergy allergy = allergy(); assertThat(allergy.hasSameValues(allergy()),is(true)); }
Source:
<code>public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { <START> childAt.playSoundEffect(SoundEffectConstants.CLICK); <END> return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } childView.playSoundEffect(SoundEffectConstants.CLICK); final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(childView, object)) { mRecyclerViewClickListener.execute(childView, object); return true; } if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }</code><technical_language>this sound..</technical_language>

Target:
public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(childView, object)) { mRecyclerViewClickListener.execute(childView, object); return true; } if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }
Source:
<code>protected void executeQueryCommand() { Map<String, Object> response = findDirectoryUserById(); if (!response.containsKey("result")) { getQueryReturnValue().setSucceeded(false); } else { Collection<DirectoryUser> users = DirectoryUtils.mapPrincipalRecordsToDirectoryUsers( getParameters().getDomain(), (List<ExtMap>) response.get("result")); if (!users.isEmpty()) { <START> getQueryReturnValue().setReturnValue(new ArrayList<>(users).get(0)); <END> } } }</code><technical_language>user iterator().next() instead of creating ArrayList Collection? getQueryReturnValue().setReturnValue(users.iterator().next());</technical_language>

Target:
protected void executeQueryCommand() { Map<String, Object> response = findDirectoryUserById(); if (!response.containsKey("result")) { getQueryReturnValue().setSucceeded(false); } else { Collection<DirectoryUser> users = DirectoryUtils.mapPrincipalRecordsToDirectoryUsers( getParameters().getDomain(), (List<ExtMap>) response.get("result")); if (!users.isEmpty()) { getQueryReturnValue().setReturnValue(users.iterator().next()); } } }
Source:
<code>public GetSearchResultsResponse getSearchResults(JsonRpcPeer peer, JSONObject params) { final GetSearchResultsRequest request = mObjectMapper.convertValue( params, GetSearchResultsRequest.class); <START> final List<Integer> results = mSearchResults.get(request.searchId).subList(request.fromIndex, request.toIndex); <END> final GetSearchResultsResponse response = new GetSearchResultsResponse(); response.nodeIds = results; return response; }</code><technical_language>trust searchId client is valid. If mSearchResults.get() return null crash NPE. check return get() it. If returns null ... I guess return null? test returning null this method making Chrome crash do weird (I doubt will, good double-check)</technical_language>

Target:
public GetSearchResultsResponse getSearchResults(JsonRpcPeer peer, JSONObject params) { final GetSearchResultsRequest request = mObjectMapper.convertValue( params, GetSearchResultsRequest.class); final List<Integer> results = mSearchResults.get(request.searchId); if (results == null) { LogUtil.w("\"" + request.searchId + "\" is not a valid reference to a search result"); return null; } final List<Integer> resultsRange = results.subList(request.fromIndex, request.toIndex); final GetSearchResultsResponse response = new GetSearchResultsResponse(); response.nodeIds = resultsRange; return response; }
Source:
<code>public static Collection<NumberArrayFactory> data() throws IOException { <START> fixture = prepareDirectoryAndPageCache( IntArrayTest.class ); <END> PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = autoWithPageCacheFallback( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); return Arrays.asList( HEAP, OFF_HEAP, autoWithPageCacheFallback, pageCacheArrayFactory ); }</code><technical_language>wondering fixture</technical_language>

Target:
public static Collection<NumberArrayFactory> data() throws IOException { fixture = prepareDirectoryAndPageCache( IntArrayTest.class ); PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = auto( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); return Arrays.asList( HEAP, OFF_HEAP, autoWithPageCacheFallback, pageCacheArrayFactory ); }
Source:
<code><START> protected synchronized void updateBytes(long bytes) <END> { if (parentMemoryContext != null) { parentMemoryContext.updateBytes(bytes); } long oldLocalUsedBytes = this.usedBytes; usedBytes += bytes; if (notificationListener != null) { notificationListener.memoryUsageUpdated(oldLocalUsedBytes, usedBytes); } }</code><technical_language>package-private instead instead of protected</technical_language>

Target:
synchronized ListenableFuture<?> updateBytes(long bytes) { ListenableFuture<?> future = NOT_BLOCKED; if (parentMemoryContext != null) { future = parentMemoryContext.updateBytes(bytes); usedBytes += bytes; return future; } if (reservationHandler != null) { future = reservationHandler.reserveMemory(bytes); } usedBytes += bytes; if (guaranteedMemory.isPresent() && usedBytes < guaranteedMemory.getAsLong()) { future = NOT_BLOCKED; } return future; }
Source:
<code>private static boolean createLockFile(byte[] lockValue, FileObject lockObject, String fullPath) throws FileSystemException { lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); <START> stream.close(); <END> } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + maskURLPassword(fullPath), e); return false; } finally { lockObject.close(); } return true; }</code><technical_language>close stream finally block? Otherwise, this lead a resource leak exception occurring write() flush method</technical_language>

Target:
private static boolean createLockFile(byte[] lockValue, FileObject lockObject, String fullPath) throws FileSystemException { lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + maskURLPassword(fullPath), e); return false; } finally { try { stream.close(); } catch (IOException e) { log.debug("Error closing stream", e); } lockObject.close(); } return true; }
Source:
<code>private DashboardSetupStatus initDashboard(final String hostAddress, final int port) { <START> final boolean isValidHostAddr = !hostAddress.equals(AsyncDolphinLauncher.INVALID_HOST_ADDRESS); <END> if (!isValidHostAddr) { LOG.log(Level.INFO, "Dashboard is not in use"); return DashboardSetupStatus.getFailedStatus(); } else { final String dashboardURL = "http://" + hostAddress + ":" + port + "/"; try { final PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor()); connectionManager.setMaxTotal(Integer.MAX_VALUE); final CloseableHttpAsyncClient reusableHttpClient = HttpAsyncClients.custom().setConnectionManager(connectionManager).build(); reusableHttpClient.start(); runMetricsSenderThread(); return DashboardSetupStatus.getSucceededSatus(dashboardURL, reusableHttpClient); } catch (IOReactorException e) { LOG.log(Level.WARNING, "Dashboard: Fail on initializing IOReactor.", e); return DashboardSetupStatus.getFailedStatus(); } } }</code><technical_language>negations: in (isValidHostAddr is true hostAddress is **NOT** equal constant), other in L147 (if isValidHostAddr is **NOT** true first). Readers need inverse logic twice, is a bit difficult. simpler follows? final boolean invalidHostAddress = hostAddress.equals(AsyncDolphinLauncher.INVALID_HOST_ADDRESS); if (invalidHostAddress) { .. } else { .. }</technical_language>

Target:
private DashboardSetupStatus initDashboard(final String hostAddress, final int port) { final boolean invalidHostAddr = hostAddress.equals(AsyncDolphinLauncher.INVALID_HOST_ADDRESS); if (invalidHostAddr) { LOG.log(Level.INFO, "Dashboard is not in use"); return DashboardSetupStatus.getFailed(); } else { final String dashboardURL = "http://" + hostAddress + ":" + port + "/"; try { final PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor()); connectionManager.setMaxTotal(Integer.MAX_VALUE); final CloseableHttpAsyncClient reusableHttpClient = HttpAsyncClients.custom().setConnectionManager(connectionManager).build(); reusableHttpClient.start(); runMetricsSenderThread(); return DashboardSetupStatus.getSuccessful(dashboardURL, reusableHttpClient); } catch (IOReactorException e) { LOG.log(Level.WARNING, "Dashboard: Fail on initializing IOReactor.", e); return DashboardSetupStatus.getFailed(); } } }
Source:
<code>static String isProcedureValidForScope(TaskScope scope, Procedure procedure, boolean restrictProcedureByScope) { if (scope != TaskScope.PARTITIONS && procedure.getSinglepartition() && procedure.getPartitionparameter() == -1) { return String.format( "Procedure %s is a directed procedure and must be run on PARTITIONS. Cannot be scheduled on %s.", procedure.getTypeName(), scope.name().toLowerCase()); } if (!restrictProcedureByScope) { return null; } switch (scope) { case DATABASE: if (procedure.getSinglepartition()) { return String.format( <START> "Procedrue %s is a single partition procedure. Cannot be scheduled on the database", <END> procedure.getTypeName()); } break; case HOSTS: if (procedure.getTransactional()) { return String.format("Procedure %s is a transactional procedure. Cannot be scheduled on a host.", procedure.getTypeName()); } break; case PARTITIONS: if (!procedure.getSinglepartition()) { return String.format("Procedure %s is not a partitioned procedure. Cannot be scheduled on a partition.", procedure.getTypeName()); } if (procedure.getPartitionparameter() != -1) { return String.format( "Procedure %s must be a directed procedure which is not partitioned on a table. " + "Cannot be scheduled on a partition.", procedure.getTypeName()); } break; default: throw new IllegalArgumentException("Unknown scope: " + scope); } return null; }</code><technical_language>I suggest ", be"</technical_language>

Target:
static String isProcedureValidForScope(TaskScope scope, Procedure procedure, boolean restrictProcedureByScope) { if (scope != TaskScope.PARTITIONS && procedure.getSinglepartition() && procedure.getPartitionparameter() == -1) { return String.format("Procedure %s is a directed procedure and must be run on PARTITIONS only.", procedure.getTypeName()); } if (!restrictProcedureByScope) { return null; } switch (scope) { case DATABASE: if (procedure.getSinglepartition()) { return String.format( "Procedure %s is a single partition procedure, which cannot be scheduled on the database", procedure.getTypeName()); } break; case HOSTS: if (procedure.getTransactional()) { return String.format("Procedure %s is a transactional procedure, which cannot be scheduled on a host.", procedure.getTypeName()); } break; case PARTITIONS: if (!procedure.getSinglepartition() && procedure.getPartitionparameter() != -1) { return String.format( "Procedure %s must be a directed procedure, which cannot be scheduled on a partition.", procedure.getTypeName()); } break; default: throw new IllegalArgumentException("Unknown scope: " + scope); } return null; }
Source:
<code>public MemoryConfigurationBuilder storageType(StorageType storageType) { StorageType config = storageType == StorageType.OBJECT ? StorageType.HEAP : storageType; if (config == StorageType.BINARY) { <START> encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); <END> } attributes.attribute(MemoryConfiguration.STORAGE).set(config); memoryStorageConfigurationBuilder.storageType(config); return this; }</code><technical_language>Hrmm, this correct me. signify is a byte array (protostream is more specific)</technical_language>

Target:
public MemoryConfigurationBuilder storageType(StorageType storageType) { memoryStorageConfigurationBuilder.storageType(storageType); return this; }