auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SimpleFeature next() throws IOException, IllegalArgumentException, NoSuchElementException { String fid = ""; try { if (!hasNext()) { throw new NoSuchElementException( "No more features in this reader, you should call " + "hasNext() to check for feature availability"); } SolrDocument doc = this.solrDocIterator.next(); fid = featureType.getTypeName() + "." + doc.getFieldValue(pkey.getName()); final int attributeCount = featureType.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { AttributeDescriptor type = featureType.getDescriptor(i); Object value = doc.getFieldValue(type.getLocalName()); if (value instanceof List<?>) { value = StringUtils.join(((List) value).toArray(), ";"); } if (type instanceof GeometryDescriptor) { GeometryDescriptor gatt = (GeometryDescriptor) type; if (value != null) { SolrSpatialStrategy spatialStrategy = SolrSpatialStrategy.createStrategy(gatt); <START> Geometry geometry = spatialStrategy.decode(value.toString()); <END> if (geometry != null && geometry.getUserData() == null) { geometry.setUserData(gatt.getCoordinateReferenceSystem()); } builder.add(geometry); } } else { builder.add(value); } } return builder.buildFeature(fid); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (this.solrDataStore.getLogger().isLoggable(Level.FINE)) { this.solrDataStore.getLogger().log(Level.FINE, "Created " + fid); } next = null; counter++; } }</code><technical_language>Wondering if creating strategy object feature read overhead.. created reader is instantiated instead</technical_language>

Target:
public SimpleFeature next() throws IOException, IllegalArgumentException, NoSuchElementException { String fid = ""; try { if (!hasNext()) { throw new NoSuchElementException( "No more features in this reader, you should call " + "hasNext() to check for feature availability"); } SolrDocument doc = this.solrDocIterator.next(); fid = featureType.getTypeName() + "." + doc.getFieldValue(pkey.getName()); final int attributeCount = featureType.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { AttributeDescriptor type = featureType.getDescriptor(i); Object value = doc.getFieldValue(type.getLocalName()); if (value instanceof List<?>) { value = StringUtils.join(((List) value).toArray(), ";"); } if (type instanceof GeometryDescriptor) { GeometryDescriptor gatt = (GeometryDescriptor) type; if (value != null) { SolrSpatialStrategy spatialStrategy = geometryReaders.get(gatt.getName()); if (spatialStrategy == null) { spatialStrategy = SolrSpatialStrategy.DEFAULT; } Geometry geometry = spatialStrategy.decode(value.toString()); if (geometry != null && geometry.getUserData() == null) { geometry.setUserData(gatt.getCoordinateReferenceSystem()); } builder.add(geometry); } } else { builder.add(value); } } return builder.buildFeature(fid); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (this.solrDataStore.getLogger().isLoggable(Level.FINE)) { this.solrDataStore.getLogger().log(Level.FINE, "Created " + fid); } next = null; counter++; } }
Source:
<code>private void _nextCustomizationEntry() throws Exception { try { if (_customizationShouldAbort) { _parser.cliAbort(); } else { <START> _customizationDialog[_customizationIndex++].call(); <END> } } catch (SoftError e) { log.errorFormat( "Soft error during host {0} customization dialog", _vds.gethost_name(), e ); _failException = e; _customizationShouldAbort = true; } }</code><technical_language>This check length of array of for presence of null element end. do prevent ArrayIndexOutOfBounds NullPointer</technical_language>

Target:
private void _nextCustomizationEntry() throws Exception { try { if (_customizationShouldAbort) { _parser.cliAbort(); } else { _customizationDialog[_customizationIndex++].call(); } } catch (ArrayIndexOutOfBoundsException e) { throw new RuntimeException("Protocol violation", e); } catch (SoftError e) { log.errorFormat( "Soft error during host {0} customization dialog", _vds.gethost_name(), e ); _failException = e; _customizationShouldAbort = true; } }
Source:
<code><START> public static Map<String, IAnalysisModuleHelper> getAnalysisModules() { <END> synchronized (fAnalysisModules) { if (fAnalysisModules.isEmpty()) { for (IAnalysisModuleSource source : fSources) { for (IAnalysisModuleHelper helper : source.getAnalysisModules()) { fAnalysisModules.put(helper.getId(), helper); } } } } return Collections.unmodifiableMap(fAnalysisModules); }</code><technical_language>This needs synchronized of fSources / registerModuleSource / initialize</technical_language>

Target:
public static synchronized Map<String, IAnalysisModuleHelper> getAnalysisModules() { if (fAnalysisModules.isEmpty()) { for (IAnalysisModuleSource source : fSources) { for (IAnalysisModuleHelper helper : source.getAnalysisModules()) { fAnalysisModules.put(helper.getId(), helper); } } } return Collections.unmodifiableMap(fAnalysisModules); }
Source:
<code>public CompletableFuture<Void> put(K key, V value) { assertRemoteCacheManagerIsStarted(); if (trace) { log.tracef("About to add (K,V): (%s, %s) lifespan:%d, maxIdle:%d", key, value, defaultLifespan, defaultMaxIdleTime); } K compatKey = hasCompatibility() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, true, estimateKeySize, estimateValueSize); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, false, estimateKeySize, estimateValueSize); PutKeyValueMultimapOperation<Void> op = operationsFactory.newPutKeyValueOperation(compatKey, <START> marshallKey, marshallValue, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); <END> return CompletableFuture.runAsync(() -> op.execute()); }</code><technical_language>I if want able supply Executor user run common thread pool</technical_language>

Target:
public CompletableFuture<Void> put(K key, V value) { if (trace) { log.tracef("About to add (K,V): (%s, %s) lifespan:%d, maxIdle:%d", key, value, defaultLifespan, defaultMaxIdleTime); } assertRemoteCacheManagerIsStarted(); K compatKey = hasCompatibility() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, true, estimateKeySize, estimateValueSize); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, false, estimateKeySize, estimateValueSize); PutKeyValueMultimapOperation<Void> op = operationsFactory.newPutKeyValueOperation(compatKey, marshallKey, marshallValue, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); return CompletableFuture.runAsync(() -> op.execute()); }
Source:
<code>public void testOtherAnnotation() { final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, <START> Opcodes.ACC_SYNTHETIC, "name", "()V", null, null); <END> m.visitInsn(Opcodes.RETURN); AnnotationNode a = new AnnotationNode("Lother/Annotation;"); m.invisibleAnnotations = Arrays.asList(a); filter.filter(m, this); assertNull(fromInclusive); assertNull(toInclusive); }</code><technical_language>@marchof synthetic access flag is unrelated this test, prefer remove</technical_language>

Target:
public void testOtherAnnotation() { final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, 0, "hashCode", "()I", null, null); m.visitAnnotation("Lother/Annotation;", false); m.visitInsn(Opcodes.ICONST_0); m.visitInsn(Opcodes.IRETURN); filter.filter(m, this); assertNull(fromInclusive); assertNull(toInclusive); }
Source:
<code>protected void openInformationDialogOnUiDesigner() { final String displayDialog = getPreferenceStore().getString(HIDE_UIDESIGNER_INFO_DIALOG); <START> if (!"true".equals(displayDialog)) { <END> MessageDialogWithPrompt .open( MessageDialog.INFORMATION, getShell(), Messages.openUiDesignerInformationWindowTitle, Messages.openUiDesignerInformationMessage, Messages.openUiDesignerInformationToggleMessage, false, getPreferenceStore(), HIDE_UIDESIGNER_INFO_DIALOG, SWT.NONE); } }</code><technical_language>String instead of a boolean ? getPreferenceStore().getBoolean(..)</technical_language>

Target:
protected void openInformationDialogOnUiDesigner() { if (!getEclipsePreferences().getBoolean(HIDE_UIDESIGNER_INFO_DIALOG, false)) { MessageDialogWithPrompt .open( MessageDialog.INFORMATION, getShell(), Messages.openUiDesignerInformationWindowTitle, Messages.openUiDesignerInformationMessage, Messages.openUiDesignerInformationToggleMessage, false, getPreferenceStore(), HIDE_UIDESIGNER_INFO_DIALOG, SWT.NONE); } }
Source:
<code>public ShaderEffectsDrawable(Bitmap bitmap) { this.bitmap = bitmap; bitmapPaint = new Paint(); <START> bitmapPaint.setAntiAlias(true); <END> int radius = bitmap.getWidth() / 2; RadialGradient vignette = new RadialGradient(radius, radius, radius, new int[] {0, 0, 0x7f000000}, new float[] {0.0f, 0.8f, 1.0f}, Shader.TileMode.CLAMP); Matrix oval = new Matrix(); oval.setScale(1.0f, 0.8f); vignette.setLocalMatrix(oval); bitmapPaint.setShader(new ComposeShader(new BitmapShader(this.bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP), vignette, PorterDuff.Mode.SRC_OVER)); ColorMatrix m1 = new ColorMatrix(); ColorMatrix m2 = new ColorMatrix(); m1.setSaturation(0.1f); m2.setScale(1f, 0.95f, 0.82f, 1.0f); m1.setConcat(m2, m1); bitmapPaint.setColorFilter(new ColorMatrixColorFilter(m1)); }</code><technical_language>This passed a flag constructor save a line</technical_language>

Target:
public ShaderEffectsDrawable(Bitmap bitmap) { this.bitmap = bitmap; if (bitmap == null) { throw new NullPointerException("Bitmap cannot be null."); } bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); int radius = bitmap.getWidth() / 2; RadialGradient vignette = new RadialGradient(radius, radius, radius, new int[]{0, 0, 0x7f000000}, new float[]{0.0f, 0.8f, 1.0f}, Shader.TileMode.CLAMP); Matrix oval = new Matrix(); oval.setScale(1.0f, 0.8f); vignette.setLocalMatrix(oval); bitmapPaint.setShader(new ComposeShader(new BitmapShader(this.bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP), vignette, PorterDuff.Mode.SRC_OVER)); ColorMatrix m1 = new ColorMatrix(); ColorMatrix m2 = new ColorMatrix(); m1.setSaturation(0.1f); m2.setScale(1f, 0.95f, 0.82f, 1.0f); m1.setConcat(m2, m1); bitmapPaint.setColorFilter(new ColorMatrixColorFilter(m1)); }
Source:
<code>protected @Nonnull String getSuccessfulDestination() { FolderComputation<I> computation = getComputation(); <START> if (computation != null) { <END> return computation.getSearchUrl() + "console"; } return super.getSuccessfulDestination(); }</code><technical_language>is a trickier Job/Run is a permanent identifier for run, included in URL, saved for perusal. FolderComputations simply overwritten currently (though is option save backup files disk)</technical_language>

Target:
protected @Nonnull String getSuccessfulDestination() { return computation.getSearchUrl() + "console"; }
Source:
<code>public void passesArgumentsToApp() throws Exception { <START> final String[] addArgs = {"works well!"}; <END> new MainRemote(MainRemoteTest.DemoAppArgs.class, addArgs).exec( new MainRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("works well")); } } ); }</code><technical_language>@HDouss args enough? <LINK_0></technical_language>

Target:
public void passesArgumentsToApp() throws Exception { final String[] args = {"works well!"}; new MainRemote(MainRemoteTest.DemoAppArgs.class, args).exec( new MainRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("works well")); } } ); }
Source:
<code>private void runWindup(GraphContext context, File baseRuleDirectory, final List<Path> rulePaths, File input, File output) throws IOException { ProjectModel pm = context.getFramed().addVertex(null, ProjectModel.class); pm.setName("Project: " + input.getAbsolutePath()); FileModel inputPath = context.getFramed().addVertex(null, FileModel.class); inputPath.setFilePath(input.getCanonicalPath()); FileUtils.deleteDirectory(output); Files.createDirectories(output.toPath()); inputPath.setProjectModel(pm); pm.setRootFileModel(inputPath); WindupConfiguration windupConfiguration = new WindupConfiguration() .setGraphContext(context); windupConfiguration.setInputPath(Paths.get(inputPath.getFilePath())); windupConfiguration.setOutputDirectory(output.toPath()); windupConfiguration.addDefaultUserRulesDirectory(baseRuleDirectory.toPath()); final String baseRulesPathNormalized = baseRuleDirectory.toPath().normalize().toAbsolutePath().toString(); <START> System.out.println("baseRulesPathNormalized AAA " + baseRulesPathNormalized); <END> windupConfiguration.setRuleProviderFilter(new Predicate<RuleProvider>() { @Override public boolean accept(RuleProvider type) { if (type.getMetadata().getOrigin() == null) return true; if (!type.getMetadata().getOrigin().contains(baseRulesPathNormalized)) return true; for (Path acceptedRulePath : rulePaths) { if (type.getMetadata().getOrigin().contains(acceptedRulePath.toString())) return true; } return false; } }); processor.execute(windupConfiguration); }</code><technical_language>I fine this logged, format a better? :) this debugging code left in, I useful anyway</technical_language>

Target:
private void runWindup(GraphContext context, File baseRuleDirectory, final List<Path> rulePaths, File input, File output) throws IOException { ProjectModel pm = context.getFramed().addVertex(null, ProjectModel.class); pm.setName("Project: " + input.getAbsolutePath()); FileModel inputPath = context.getFramed().addVertex(null, FileModel.class); inputPath.setFilePath(input.getCanonicalPath()); FileUtils.deleteDirectory(output); Files.createDirectories(output.toPath()); inputPath.setProjectModel(pm); pm.setRootFileModel(inputPath); WindupConfiguration windupConfiguration = new WindupConfiguration() .setGraphContext(context); windupConfiguration.setInputPath(Paths.get(inputPath.getFilePath())); windupConfiguration.setOutputDirectory(output.toPath()); windupConfiguration.addDefaultUserRulesDirectory(baseRuleDirectory.toPath()); final String baseRulesPathNormalized = baseRuleDirectory.toPath().normalize().toAbsolutePath().toString(); LOG.info("Base path for rules is: " + baseRulesPathNormalized); windupConfiguration.setRuleProviderFilter(new Predicate<RuleProvider>() { @Override public boolean accept(RuleProvider type) { if (type.getMetadata().getOrigin() == null) return true; if (!type.getMetadata().getOrigin().contains(baseRulesPathNormalized)) return true; for (Path acceptedRulePath : rulePaths) { if (type.getMetadata().getOrigin().contains(acceptedRulePath.toString())) return true; } return false; } }); processor.execute(windupConfiguration); }
Source:
<code>public void theObjectlistShouldBeReturned(final Map<String, String> settings) throws Throwable { final GetAssociationLnObjectsAsyncRequest asyncRequest = AssociationLnObjectsRequestFactory .fromScenarioContext(); final GetAssociationLnObjectsResponse response = this.responseClient.getResponse(asyncRequest); assertEquals("Response should be OK", OsgpResultType.OK, response.getResult()); assertNotNull("Response should contain an AssociationLnList", response.getAssociationLnList()); assertNotNull("AssociationLnList shoudl have at least one entry", response.getAssociationLnList().getAssociationLnListElement().get(0)); final AssociationLnListElement element = response.getAssociationLnList().getAssociationLnListElement().get(0); <START> assertNotNull("AccessRights should be present", element.getAccessRights()); <END> assertNotNull("ClassId should be present", element.getClassId()); assertNotNull("LogicalName should be present", element.getLogicalName()); assertNotNull("Version should be present", element.getVersion()); }</code><technical_language>Check for AttributeId</technical_language>

Target:
public void theObjectlistShouldBeReturned(final Map<String, String> settings) throws Throwable { final GetAssociationLnObjectsAsyncRequest asyncRequest = AssociationLnObjectsRequestFactory .fromScenarioContext(); final GetAssociationLnObjectsResponse response = this.responseClient.getResponse(asyncRequest); assertEquals("Response should be OK", OsgpResultType.OK, response.getResult()); assertNotNull("Response should contain an AssociationLnList", response.getAssociationLnList()); assertNotNull("AssociationLnList shoudl have at least one entry", response.getAssociationLnList().getAssociationLnListElement().get(0)); final AssociationLnListElement element = response.getAssociationLnList().getAssociationLnListElement().get(0); assertNotNull("AccessRights should be present", element.getAccessRights()); assertNotNull("ClassId should be present", element.getClassId()); assertNotNull("LogicalName should be present", element.getLogicalName()); assertNotNull("Version should be present", element.getVersion()); assertNotNull("AttributeId should be present", element.getAccessRights().getAttributeAccess().getAttributeAccessItem().get(0).getAttributeId()); }
Source:
<code>public void optionalActivePublisherTest(long elements, PublisherTestRun<T> body) throws Throwable { if (elements > maxElementsFromPublisher()) { throw new SkipException(String.format("Unable to run this test, as required elements nr: %d is higher than supported by given producer: %d", elements, maxElementsFromPublisher())); } final Publisher<T> pub = createPublisher(elements); final String skipMessage = "Skipped because tested publisher does NOT implement this OPTIONAL requirement."; try { potentiallyPendingTest(pub, body); } catch (Exception ex) { notVerified(skipMessage); } catch (AssertionError ex) { <START> notVerified(skipMessage + " Reason for skipping was: " + ex.getMessage()); <END> } }</code><technical_language>good call</technical_language>

Target:
public void optionalActivePublisherTest(long elements, PublisherTestRun<T> body) throws Throwable { if (elements > maxElementsFromPublisher()) { throw new SkipException( String.format("Unable to run this test, as required elements nr: %d is higher than supported by given producer: %d", elements, maxElementsFromPublisher())); } final Publisher<T> pub = createPublisher(elements); final String skipMessage = "Skipped because tested publisher does NOT implement this OPTIONAL requirement."; try { potentiallyPendingTest(pub, body); } catch (Exception ex) { notVerified(skipMessage); } catch (AssertionError ex) { notVerified(String.format("%s Reason for skipping was: %s", skipMessage, ex.getMessage())); } }
Source:
<code><START> protected static void printUsage(@Nonnull PrintStream printStream) { <END> CmdLineParser parser = new CmdLineParser(new Options()); printStream.append("Usage: java -jar jack.jar <options> <source files>\n" + "\n" + "Options:\n"); parser.printUsage(printStream); printStream.append("\n" + "@FILE : read command line from file\n"); }</code><technical_language>explicit new line char</technical_language>

Target:
protected static void printUsage(@Nonnull PrintStream printStream) { CmdLineParser parser = new CmdLineParser(new Options()); printStream.println("Usage: java -jar jack.jar <options> <source files>"); printStream.println(); printStream.println("Options:"); parser.printUsage(printStream); printStream.println(); printStream.println(" @FILE : read command line from file"); }
Source:
<code>public boolean shutdown(long timeout, TimeUnit timeUnit) { log.info("Shutdown WorkManager in " + timeUnit.toMillis(timeout) + " ms"); shutdownInProgress = true; try { boolean ret = streamProcessor.stop(Duration.ofMillis(timeUnit.toMillis(timeout))); <START> long shutDowndelay = Long.parseLong(Framework.getService(ConfigurationService.class) <END> .getProperty(SHUTDOWN_DELAY_MS_KEY, "0")); if (shutDowndelay > 0) { try { Thread.sleep(shutDowndelay); } catch (InterruptedException e) { log.error("Not able to wait for works to stop gracefully."); } } if (!ret) { log.error("Not able to stop worker pool within the timeout."); } return ret; } finally { shutdownInProgress = false; } }</code><technical_language>shutDowndelay shutdownDelay</technical_language>

Target:
public boolean shutdown(long timeout, TimeUnit timeUnit) { log.info("Shutdown WorkManager in " + timeUnit.toMillis(timeout) + " ms"); shutdownInProgress = true; try { long shutdownDelay = Long.parseLong(Framework.getService(ConfigurationService.class) .getProperty(SHUTDOWN_DELAY_MS_KEY, "0")); boolean ret = streamProcessor.stop(Duration.ofMillis(Math.max(timeUnit.toMillis(timeout), shutdownDelay))); if (!ret) { log.error("Not able to stop worker pool within the timeout."); } return ret; } finally { shutdownInProgress = false; } }
Source:
<code>List<AttributeStatement> createAttributeStatement(final List<Attribute> attributes) { final List<AttributeStatement> attributeStatements = new ArrayList<>(); <START> if (!attributes.isEmpty()) { <END> final AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); for (final Attribute attribute : attributes) { attributeStatement.getAttributes().add(attribute); } attributeStatements.add(attributeStatement); } return attributeStatements; }</code><technical_language>recommend CollectionUtil</technical_language>

Target:
List<AttributeStatement> createAttributeStatement(final List<Attribute> attributes) { final List<AttributeStatement> attributeStatements = new ArrayList<>(); if (CollectionUtils.isNotEmpty(attributes)) { final AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); for (final Attribute attribute : attributes) { attributeStatement.getAttributes().add(attribute); } attributeStatements.add(attributeStatement); } return attributeStatements; }
Source:
<code><START> boolean isFlaggedAsZipBomb() { <END> return flaggedAsZipBomb; }</code><technical_language>multithreading issues here? threads accessing root Archive object</technical_language>

Target:
synchronized boolean isFlaggedAsZipBomb() { return flaggedAsZipBomb; }
Source:
<code><START> public void testGetKeysForContainer() throws Exception { <END> Response response = containerKeyService.getKeysForContainer(1L); Collection<KeyMetadata> keyMetadataList = (Collection<KeyMetadata>) response.getEntity(); assertTrue(keyMetadataList.size() == 2); Iterator<KeyMetadata> iterator = keyMetadataList.iterator(); KeyMetadata keyMetadata = iterator.next(); assertTrue(keyMetadata.getKey().equals("key_one")); assertTrue(keyMetadata.getVersions().size() == 1); assertTrue(keyMetadata.getBlockIds().size() == 1); Map<Long, List<KeyMetadata.ContainerBlockMetadata>> blockIds = keyMetadata.getBlockIds(); assertTrue(blockIds.get(0L).iterator().next().getLocalID() == 101); keyMetadata = iterator.next(); assertTrue(keyMetadata.getKey().equals("key_two")); assertTrue(keyMetadata.getVersions().size() == 2); assertTrue(keyMetadata.getVersions().contains(0L) && keyMetadata .getVersions().contains(1L)); assertTrue(keyMetadata.getBlockIds().size() == 2); blockIds = keyMetadata.getBlockIds(); assertTrue(blockIds.get(0L).iterator().next().getLocalID() == 103); assertTrue(blockIds.get(1L).iterator().next().getLocalID() == 104); response = containerKeyService.getKeysForContainer(3L); keyMetadataList = (Collection<KeyMetadata>) response.getEntity(); assertTrue(keyMetadataList.isEmpty()); }</code><technical_language>need throws Exception here, throw exception this method. Exception 'java.lang.Exception' is thrown in method less... (F1) Inspection info: Reports exceptions declared in a method's signature thrown method implementations/derivatives</technical_language>

Target:
public void testGetKeysForContainer() { Response response = containerKeyService.getKeysForContainer(1L); Collection<KeyMetadata> keyMetadataList = (Collection<KeyMetadata>) response.getEntity(); assertTrue(keyMetadataList.size() == 2); Iterator<KeyMetadata> iterator = keyMetadataList.iterator(); KeyMetadata keyMetadata = iterator.next(); assertTrue(keyMetadata.getKey().equals("key_one")); assertTrue(keyMetadata.getVersions().size() == 1); assertTrue(keyMetadata.getBlockIds().size() == 1); Map<Long, List<KeyMetadata.ContainerBlockMetadata>> blockIds = keyMetadata.getBlockIds(); assertTrue(blockIds.get(0L).iterator().next().getLocalID() == 101); keyMetadata = iterator.next(); assertTrue(keyMetadata.getKey().equals("key_two")); assertTrue(keyMetadata.getVersions().size() == 2); assertTrue(keyMetadata.getVersions().contains(0L) && keyMetadata .getVersions().contains(1L)); assertTrue(keyMetadata.getBlockIds().size() == 2); blockIds = keyMetadata.getBlockIds(); assertTrue(blockIds.get(0L).iterator().next().getLocalID() == 103); assertTrue(blockIds.get(1L).iterator().next().getLocalID() == 104); response = containerKeyService.getKeysForContainer(3L); keyMetadataList = (Collection<KeyMetadata>) response.getEntity(); assertTrue(keyMetadataList.isEmpty()); }
Source:
<code>public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockRayTraceResult hit) { <START> FluidUtil.interactWithFluidHandler(playerIn, hand, worldIn, pos, hit.getFace()); <END> ItemStack stack = playerIn.getHeldItem(hand); if (!stack.isEmpty() && FluidLib.getFluidItemCap(stack).isPresent()) { BloodContainerTileEntity bloodContainer = (BloodContainerTileEntity) worldIn.getTileEntity(pos); IFluidHandler source = bloodContainer.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY).orElseThrow(() -> new IllegalStateException("Cannot get IFluidHandler from bloodContainer")); if (playerIn.isSneaking()) { FluidActionResult result = FluidUtil.tryFillContainer(stack, source, Integer.MAX_VALUE, playerIn, true); if (result.isSuccess()) { playerIn.setHeldItem(hand, result.getResult()); } } else { FluidActionResult result = tryEmptyContainer(stack, source, Integer.MAX_VALUE, playerIn, true); if (result.isSuccess()) { playerIn.setHeldItem(hand, result.getResult()); } } return true; } return true; }</code><technical_language>this line similar remaining part</technical_language>

Target:
public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockRayTraceResult hit) { if (!FluidUtil.interactWithFluidHandler(playerIn, hand, worldIn, pos, hit.getFace()) && playerIn.getHeldItem(hand).getItem().equals(Items.GLASS_BOTTLE) && VampirismConfig.SERVER.autoConvertGlassBottles.get()) { FluidUtil.getFluidHandler(worldIn, pos, hit.getFace()).ifPresent((fluidHandler -> { if (fluidHandler.getFluidInTank(0).getFluid().equals(ModFluids.blood)) { ItemStack glass = playerIn.getHeldItem(hand); ItemStack bloodBottle = new ItemStack(ModItems.blood_bottle, 1); playerIn.setHeldItem(hand, bloodBottle); bloodBottle = FluidUtil.tryFillContainer(bloodBottle, fluidHandler, Integer.MAX_VALUE, playerIn, true).getResult(); if (glass.getCount() > 1) { glass.shrink(1); playerIn.setHeldItem(hand, glass); playerIn.addItemStackToInventory(bloodBottle); } else { playerIn.setHeldItem(hand, bloodBottle); } } })); } return true; }
Source:
<code>public void canFetchRelease() throws Exception { final Repo repo = RtReleasesITCase.repo(); try { final Releases releases = repo.releases(); final String tag = "v1.0"; final Release release = releases.create(tag); MatcherAssert.assertThat( releases.get(release.number()).number(), Matchers.equalTo(release.number()) ); MatcherAssert.assertThat( <START> releases.get(release.number()).json().getString("tag_name"), <END> Matchers.equalTo(tag) ); releases.remove(release.number()); } finally { RtReleasesITCase.remove(repo); } }</code><technical_language>Smart.tag instead of json().getString("tag_name")</technical_language>

Target:
public void canFetchRelease() throws Exception { final Repo repo = RtReleasesITCase.repo(); try { final Releases releases = repo.releases(); final String tag = "v1.0"; final Release release = releases.create(tag); MatcherAssert.assertThat( releases.get(release.number()).number(), Matchers.equalTo(release.number()) ); MatcherAssert.assertThat( new Release.Smart(releases.get(release.number())).tag(), Matchers.equalTo(tag) ); releases.remove(release.number()); } finally { RtReleasesITCase.remove(repo); } }
Source:
<code>public void cancel() { stmts.forEach(stmt -> { try { if (stmt != null && !stmt.isClosed()) { stmt.cancel(); } } catch (SQLException e) { throw new IllegalStateException(e); <START> } <END> }); }</code><technical_language>above, close connection well</technical_language>

Target:
public void cancel() { stmts.forEach(stmt -> cancelSoftly(stmt)); }
Source:
<code>public static void main(String[] args) throws Exception { <START> File persistenceFile = new File("/Users/akrai/persistence-local.yml"); <END> if (!persistenceFile.exists()) { System.err.println("Missing file:" + persistenceFile); System.exit(1); } RunAdhocDatabaseQueriesTool dq = new RunAdhocDatabaseQueriesTool(persistenceFile); dq.disableAllActiveDetections(Collections.singleton(160640739L)); LOG.info("DONE"); }</code><technical_language>hide user name here</technical_language>

Target:
public static void main(String[] args) throws Exception { File persistenceFile = new File("/path/to/persistence.yml"); if (!persistenceFile.exists()) { System.err.println("Missing file:" + persistenceFile); System.exit(1); } RunAdhocDatabaseQueriesTool dq = new RunAdhocDatabaseQueriesTool(persistenceFile); dq.disableAllActiveDetections(Collections.singleton(160640739L)); LOG.info("DONE"); }
Source:
<code><START> private String getInvalidTypeNameFromTypeArgument(DetailAST typeArgumentToken) { <END> if (typeArgumentToken == null) { return null; } final DetailAST identToken = typeArgumentToken.findFirstToken(TokenTypes.IDENT); if (identToken != null) { final String typeName = identToken.getText(); if (classPathMap.containsKey(typeName) && !isValidLibrary(classPathMap.get(typeName))) { return typeName; } } return null; }</code><technical_language>This method's logic is limited typeArgumentTokens, reuse this method call in other places in code reduce duplication of checkstyle logic</technical_language>

Target:
private String getInvalidTypeNameFromTypeArgument(DetailAST typeArgumentToken) { final DetailAST identToken = typeArgumentToken.findFirstToken(TokenTypes.IDENT); if (identToken == null) { return null; } final String typeName = identToken.getText(); return isValidClassDependency(typeName) ? null : typeName; }
Source:
<code>public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { <START> return repository.findByNameIn(resourceNames).stream() <END> .map(dbServer -> dbServer.getResourceCrn().toString()).collect(Collectors.toList()); }</code><technical_language>get crns database</technical_language>

Target:
public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { return repository.findResourceCrnsByNames(resourceNames) .stream().map(Crn::toString).collect(Collectors.toList()); }
Source:
<code><START> public static boolean validateURL(String targetURL) { <END> return targetURL.contains("http"); }</code><technical_language>I a method called validateURL if checks http prefix if a validateHostname method in DatadogUtilities</technical_language>

Target:
public static boolean validateURL(String targetURL) { return StringUtils.isNotBlank(targetURL) && targetURL.contains("http"); }
Source:
<code>protected void init(Repository repository, String gitDir) { Charset outputEncoding = UTF_8; if (repository != null) { String encoding = <START> repository.getConfig().getString("i18n", <END> null, "logOutputEncoding"); if (encoding != null) { try { outputEncoding = Charset.forName(encoding); } catch (IllegalArgumentException e) { throw die(CLIText.get().cannotCreateOutputStream); } } } if (ins == null) ins = new FileInputStream(FileDescriptor.in); if (outs == null) outs = new FileOutputStream(FileDescriptor.out); if (errs == null) errs = new FileOutputStream(FileDescriptor.err); outw = new ThrowingPrintWriter(new BufferedWriter( new OutputStreamWriter(outs, outputEncoding))); errw = new ThrowingPrintWriter(new BufferedWriter( new OutputStreamWriter(errs, outputEncoding))); if (repository != null && repository.getDirectory() != null) { db = repository; gitdir = repository.getDirectory().getAbsolutePath(); } else { db = repository; gitdir = gitDir; } }</code><technical_language>if getString() returns null line 202 throw a NPE</technical_language>

Target:
protected void init(Repository repository, String gitDir) { Charset charset = UTF_8; if (repository != null) { String logOutputEncoding = repository.getConfig().getString("i18n", null, "logOutputEncoding"); if (logOutputEncoding != null) { try { charset = Charset.forName(logOutputEncoding); } catch (IllegalArgumentException e) { throw die(CLIText.get().cannotCreateOutputStream); } } } if (ins == null) ins = new FileInputStream(FileDescriptor.in); if (outs == null) outs = new FileOutputStream(FileDescriptor.out); if (errs == null) errs = new FileOutputStream(FileDescriptor.err); outw = new ThrowingPrintWriter(new BufferedWriter( new OutputStreamWriter(outs, charset))); errw = new ThrowingPrintWriter(new BufferedWriter( new OutputStreamWriter(errs, charset))); if (repository != null && repository.getDirectory() != null) { db = repository; gitdir = repository.getDirectory().getAbsolutePath(); } else { db = repository; gitdir = gitDir; } }
Source:
<code>private View getPortView(Port port) { View portView = null; Iterator<?> iterator = hostView.getChildren().iterator(); while (iterator.hasNext() <START> && null == portView) { <END> Object child = iterator.next(); if ((child instanceof Node) && ((Node) child).getElement().equals(port)) { portView = (Node) child; } } return portView; }</code><technical_language>break-condition continue-condition</technical_language>

Target:
private View getPortView(Port port) { View portView = null; Iterator<?> iterator = hostView.getChildren().iterator(); while (null == portView && iterator.hasNext()) { Object child = iterator.next(); if ((child instanceof Node) && ((Node) child).getElement().equals(port)) { portView = (Node) child; } } return portView; }
Source:
<code>private List<Sample> adjustTimeSeries (final List<Sample> samples, final String sensor, final String senseId) { <START> if (sensor.toUpperCase().equals(Sensor.PARTICULATES.name()) && this.hasDustSmoothEnabled(senseId)) { <END> return SmoothSample.convert(samples); } return samples; }</code><technical_language>Sensor.Particulates.name().equals(blah)</technical_language>

Target:
private List<Sample> adjustTimeSeries (final List<Sample> samples, final String sensor, final String senseId) { if (Sensor.PARTICULATES.name().equalsIgnoreCase(sensor) && this.hasDustSmoothEnabled(senseId)) { return SmoothSample.convert(samples); } return samples; }
Source:
<code>public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); context.record( <START> TransformLineageRecorderUtils.oneToOneIn(new ArrayList<>(decryptFields), <END> "decrypt", "Decrypt the requested fields.")); }</code><technical_language>decryptFields null, get config. Also, this transform emit fields input schema. If field is in decryptFields, decrypt it; is identity transform. generate operations descriptions</technical_language>

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); decryptFields = conf.getDecryptFields(); if (context.getInputSchema() == null || context.getInputSchema().getFields() == null) { return; } List<String> decryptedFields = TransformLineageRecorderUtils.getFields(context.getInputSchema()).stream() .filter(decryptFields::contains) .collect(Collectors.toList()); List<String> identityFields = TransformLineageRecorderUtils.getFields(context.getInputSchema()); identityFields.removeAll(decryptedFields); List<FieldOperation> output = new ArrayList<>(); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(decryptedFields, "decrypt", "Decrypted the requested fields.")); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(identityFields, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); context.record(output); }
Source:
<code>public long deleteHorizonMs() { if (isDeleteHorizonSet()) { return firstTimestamp(); <START> } <END> return RecordBatch.NO_TIMESTAMP; }</code><technical_language>need for for single line statement</technical_language>

Target:
public long deleteHorizonMs() { if (deleteHorizonSet()) return firstTimestamp(); return RecordBatch.NO_TIMESTAMP; }
Source:
<code>void onServerClose(final String reason) { executor.executeIncoming(new Runnable() { @Override public String toString() { return "Server Closed EOF. " + MockedClientConnection.this; } @Override public void run() { MockedClientConnection.this.close(reason, new TargetDisconnectedException("Mocked Remote socket closed")); } }); executor.shutdownOutgoing(); <START> System.out.println("<<<< <<<<"); <END> }</code><technical_language>Leftover</technical_language>

Target:
void onServerClose(final String reason) { executor.executeIncoming(new Runnable() { @Override public String toString() { return "Server Closed EOF. " + MockedClientConnection.this; } @Override public void run() { MockedClientConnection.this.close(reason, new TargetDisconnectedException("Mocked Remote socket closed")); } }); executor.shutdownOutgoing(); }
Source:
<code><START> private void loadPerspectiveAndCheckLoadingTime(String perspectiveID, boolean headerIncluded) { <END> String standalonePerspectiveURL = getStandalonePerspectiveURL(perspectiveID, headerIncluded); driver.get(standalonePerspectiveURL); BusyPopup.waitForDisappearance(); ApplicationLoadingPopup.waitForDisappearance(PERSPECTIVE_LOADING_TIMEOUT); }</code><technical_language>chance this test @Parameterized? test 35 perspectives test case evil. Alternatively (as sniffing potential problems annotation Arquillian.), looped code function put some logging it, test failed? Of course, a method for of perspectives - "cleanest" solution in this situation. I sort of overkill</technical_language>

Target:
private void loadPerspectiveAndCheckLoadingTime(String perspectiveID, boolean headerIncluded) { String standalonePerspectiveURL = getStandalonePerspectiveURL(perspectiveID, headerIncluded); driver.get(standalonePerspectiveURL); ApplicationLoadingPopup.waitForDisappearance(PERSPECTIVE_LOADING_TIMEOUT); BusyPopup.waitForDisappearance(); }
Source:
<code>private void statusToAll(String status, String text) { JSONObject controlMessage = new JSONObject(); JSONObject controlBody = new JSONObject(); controlBody.put("status", status); controlBody.put("text", text); controlMessage.put("control", controlBody); trace.log(TraceLevel.INFO,"statusToAll() : " + controlMessage.toString()); <START> sendToAll(controlMessage.toString()); <END> }</code><technical_language>Is toString() explicit serialization call?, I.e. serialize()</technical_language>

Target:
private void statusToAll(String status, String text) { JSONObject controlMessage = new JSONObject(); JSONObject controlBody = new JSONObject(); controlBody.put("status", status); controlBody.put("value", text); controlMessage.put("control", controlBody); sendToAll(controlMessage); }
Source:
<code>public void testDefaultLogEvent() { String logmsg = "simple log message"; this.loggerLogback.info(logmsg); verify(this.mockAppender).doAppend(this.captorLoggingEvent.capture()); final LoggingEvent loggingEvent = this.captorLoggingEvent.getValue(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); <START> assertFalse("formatted log message must not be empty.", layoutMessage.isEmpty()); <END> assertTrue("formatted log message must contain the original message.", layoutMessage.contains(logmsg)); }</code><technical_language>extra messages nice in real world for empty equals this is overkill default messages sufficient</technical_language>

Target:
public void testDefaultLogEvent() { String logmsg = "simple log message"; LOG.info(logmsg); final LoggingEvent loggingEvent = getLastLogEvent(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); assertThat(layoutMessage.isEmpty()).as("formatted log message is empty.").isFalse(); assertThat(layoutMessage.contains(logmsg)).as("formatted log message contains original message.").isTrue(); }
Source:
<code>public EncryptedBlobClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Map<String, String> connectionStringPieces = Utility.parseConnectionString(connectionString); <START> String accountName = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_NAME_NAME); <END> String accountKey = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_KEY_NAME); if (ImplUtils.isNullOrEmpty(accountName) || ImplUtils.isNullOrEmpty(accountKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' must contain 'AccountName' and 'AccountKey'.")); } String endpointProtocol = connectionStringPieces.get(Constants.ConnectionStringConstants.DEFAULT_ENDPOINTS_PROTOCOL_NAME); String endpointSuffix = connectionStringPieces.get(Constants.ConnectionStringConstants.ENDPOINT_SUFFIX_NAME); if (!ImplUtils.isNullOrEmpty(endpointProtocol) && !ImplUtils.isNullOrEmpty(endpointSuffix)) { endpoint(String.format("%s://%s.blob.%s", endpointProtocol, accountName, endpointSuffix.replaceFirst("^\\.", ""))); } this.accountName = accountName; return credential(new StorageSharedKeyCredential(accountName, accountKey)); }</code><technical_language>ACCOUNT_NAME_NAME sounds a weird, need some doc</technical_language>

Target:
public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw logger .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; }
Source:
<code>private void createImageForVmMetaData() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePool.getId(), storageDomainId, vmConfImageGroupId, MemoryUtils.METADATA_SIZE_IN_BYTES, VolumeType.Sparse, <START> VolumeFormat.RAW, <END> vmConfVolumeId, "")); if (!retVal.getSucceeded()) { throw new EngineException(EngineError.VolumeCreationError, "Failed to create image for vm configuration!"); } Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_VM_TASK_KEY); Guid guid = enclosingCommand.createTask( taskId, retVal.getCreationInfo(), enclosingCommand.getActionType()); enclosingCommand.getTaskIdList().add(guid); }</code><technical_language>is a raw-sparse volume block storage</technical_language>

Target:
private void createImageForVmMetaData() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePool.getId(), storageDomainId, vmConfImageGroupId, MemoryUtils.METADATA_SIZE_IN_BYTES, getVolumeTypeForDomain(), VolumeFormat.RAW, vmConfVolumeId, "")); if (!retVal.getSucceeded()) { throw new EngineException(EngineError.VolumeCreationError, "Failed to create image for vm configuration!"); } Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_VM_TASK_KEY); Guid guid = enclosingCommand.createTask( taskId, retVal.getCreationInfo(), enclosingCommand.getActionType()); enclosingCommand.getTaskIdList().add(guid); }
Source:
<code>private void parseIndexing(final XMLExtendedStreamReader reader, final ConfigurationBuilderHolder holder) throws XMLStreamException { ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = replaceProperties(reader.getAttributeValue(i)); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case INDEX: Index index = Index.valueOf(value); builder.indexing().index(index); break; case AUTO_CONFIG: builder.indexing().autoConfig(Boolean.valueOf(value)); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } Properties indexingProperties = new Properties(); while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) { Element element = Element.forName(reader.getLocalName()); switch (element) { <START> case INDEXED_ENTITY: { <END> if (reader.getAttributeCount() > 0) { throw ParseUtils.unexpectedAttribute(reader, 0); } String className = reader.getElementText(); Class<?> indexedEntity = Util.loadClass(className, holder.getClassLoader()); builder.indexing().addIndexedEntity(indexedEntity); break; } case PROPERTY: { parseProperty(reader, indexingProperties); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } builder.indexing().withProperties(indexingProperties); }</code><technical_language>hate here, a <indexed-entities><indexed-entity>*</indexed-entities> form..</technical_language>

Target:
private void parseIndexing(final XMLExtendedStreamReader reader, final ConfigurationBuilderHolder holder) throws XMLStreamException { ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = replaceProperties(reader.getAttributeValue(i)); Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case INDEX: Index index = Index.valueOf(value); builder.indexing().index(index); break; case AUTO_CONFIG: builder.indexing().autoConfig(Boolean.valueOf(value)); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } Properties indexingProperties = new Properties(); while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) { Element element = Element.forName(reader.getLocalName()); switch (element) { case INDEXED_ENTITIES: { parseIndexedEntities(reader, holder, builder); break; } case PROPERTY: { parseProperty(reader, indexingProperties); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } builder.indexing().withProperties(indexingProperties); }
Source:
<code>public static boolean isWikimediaHost(String host) { <START> if (host.length() > MAX_ADDRESS_LENGTH) return false; <END> return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }</code><technical_language>convert host lowercase, i catch before</technical_language>

Target:
public static boolean isWikimediaHost(String host) { host = host.toLowerCase(); if (host.length() > MAX_ADDRESS_LENGTH) return false; return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }