auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Vec3d getFogColor(World world, BlockPos pos, IBlockState state, Entity entity, Vec3d originalColor, float partialTicks) { if (getFluid() != null) { int color = getFluid().getColor(); int red = color >> 16 & 0xFF; int green = color >> 8 & 0xFF; int blue = color & 0xFF; return new Vec3d(red, green, blue); } else { return super.getFogColor(world, pos, state, entity, originalColor, partialTicks); } }

Target:
public Vec3d getFogColor(World world, BlockPos pos, IBlockState state, Entity entity, Vec3d originalColor, float partialTicks) { if (getFluid() != null) { int color = getFluid().getColor(); float red = (color >> 16 & 0xFF) / 255.0F; float green = (color >> 8 & 0xFF) / 255.0F; float blue = (color & 0xFF) / 255.0F; return new Vec3d(red, green, blue); } else { return super.getFogColor(world, pos, state, entity, originalColor, partialTicks); } }
Source:
private void initView(Context context, @Nullable AttributeSet attrs) { final boolean useLegacy = Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN || !EMDeviceUtil.isDeviceCTSCompliant(); if (useLegacy) { View.inflate(context, R.layout.exomedia_video_view_layout, this); } else { View.inflate(context, R.layout.exomedia_exo_view_layout, this); } shutterBottom = findViewById(R.id.exomedia_video_shutter_bottom); shutterTop = findViewById(R.id.exomedia_video_shutter_top); shutterLeft = findViewById(R.id.exomedia_video_shutter_left); shutterRight = findViewById(R.id.exomedia_video_shutter_right); previewImageView = (ImageView) findViewById(R.id.exomedia_video_preview_image); inflateVideoViewImpl(context, attrs, useLegacy); videoViewImpl = (VideoViewApi) findViewById(R.id.exomedia_video_view); muxNotifier = new MuxNotifier(); listenerMux = new EMListenerMux(muxNotifier); videoViewImpl.setListenerMux(listenerMux); videoViewImpl.setOnSizeChangedListener(muxNotifier); }

Target:
private void initView(Context context, @Nullable AttributeSet attrs) { View.inflate(context, R.layout.exomedia_video_view_layout, this); shutterBottom = findViewById(R.id.exomedia_video_shutter_bottom); shutterTop = findViewById(R.id.exomedia_video_shutter_top); shutterLeft = findViewById(R.id.exomedia_video_shutter_left); shutterRight = findViewById(R.id.exomedia_video_shutter_right); previewImageView = (ImageView) findViewById(R.id.exomedia_video_preview_image); inflateVideoViewImpl(context, attrs); videoViewImpl = (VideoViewApi) findViewById(R.id.exomedia_video_view); muxNotifier = new MuxNotifier(); listenerMux = new EMListenerMux(muxNotifier); videoViewImpl.setListenerMux(listenerMux); videoViewImpl.setOnSizeChangedListener(muxNotifier); }
Source:
public void init(FMLInitializationEvent event) { if(!ENABLE) return; BrewingRecipeRegistry.addRecipe(new ItemStack(Items.diamond_sword), new ItemStack(Items.rotten_flesh), new ItemStack(Items.diamond_hoe)); ItemStack output0 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.diamond_sword), new ItemStack(Items.rotten_flesh), null); if(output0.getItem() == Items.diamond_hoe) System.out.println("Recipe succefully registered and working. Diamond Hoe obtained."); BrewingRecipeRegistry.addRecipe(new ItemStack(Items.golden_sword), "gemDiamond", new ItemStack(Items.diamond_sword)); ItemStack output1 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.golden_sword), new ItemStack(Items.diamond), null); if(output1.getItem() == Items.diamond_sword) System.out.println("Recipe succefully registered and working. Diamond Sword obtained."); ItemStack output2 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.potionitem, 1, 0), new ItemStack(Items.nether_wart), null); if(output2 != null && output2.getItem() == Items.potionitem && output2.getItemDamage() == 16) System.out.println("Vanilla behaviour still in place. Brewed Water Bottle with Nether Wart and got Awkward Potion"); }

Target:
public void init(FMLInitializationEvent event) { if(!ENABLE) return; BrewingRecipeRegistry.addRecipe(new ItemStack(Items.diamond_sword), new ItemStack(Items.rotten_flesh), new ItemStack(Items.diamond_hoe)); ItemStack output0 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.diamond_sword), new ItemStack(Items.rotten_flesh), null, null, null); if(output0.getItem() == Items.diamond_hoe) System.out.println("Recipe succefully registered and working. Diamond Hoe obtained."); BrewingRecipeRegistry.addRecipe(new ItemStack(Items.golden_sword), "gemDiamond", new ItemStack(Items.diamond_sword)); ItemStack output1 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.golden_sword), new ItemStack(Items.diamond), null, null, null); if(output1.getItem() == Items.diamond_sword) System.out.println("Recipe succefully registered and working. Diamond Sword obtained."); ItemStack output2 = BrewingRecipeRegistry.getOutput(new ItemStack(Items.potionitem, 1, 0), new ItemStack(Items.nether_wart), null, null, null); if(output2 != null && output2.getItem() == Items.potionitem && output2.getItemDamage() == 16) System.out.println("Vanilla behaviour still in place. Brewed Water Bottle with Nether Wart and got Awkward Potion"); }
Source:
public void testBlobIdFlag() throws Exception { boolean[] isEncrytpedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncrytpedValues) { BlobId blobId = new BlobId(BLOB_ID_V3, type, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, isEncrypted); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEcnrypted should match the original", isEncrypted, blobIdSerDed.isEncrypted()); } } } }

Target:
public void testBlobIdFlag() throws Exception { boolean[] isEncryptedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncryptedValues) { BlobId blobId = new BlobId(BLOB_ID_V3, type, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, isEncrypted); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEncrypted should match the original", isEncrypted, blobIdSerDed.isEncrypted()); } } } }
Source:
public void equals() { Assert.assertEquals(new Version(), new Version()); Assert.assertEquals(new Version(1, 2), new Version(1, 2)); Assert.assertEquals(new Version(1, 2), new Version("1.2")); Assert.assertEquals(new Version(1, 2, 3), new Version("1.2.3")); Assert.assertEquals(new Version(1, 2, 3, 4), new Version("1.2.3.4")); Assert.assertNotNull(new Version()); Assert.assertNotEquals("foo", new Version()); Assert.assertNotEquals(1.0d, new Version()); }

Target:
public void equals() { assertEquals(new Version(), new Version()); assertEquals(new Version(1, 2), new Version(1, 2)); assertEquals(new Version(1, 2), new Version("1.2")); assertEquals(new Version(1, 2, 3), new Version("1.2.3")); assertEquals(new Version(1, 2, 3, 4), new Version("1.2.3.4")); assertNotNull(new Version()); assertNotEquals("foo", new Version()); assertNotEquals(1.0d, new Version()); }
Source:
public static int getTransactionId(long operationId) { return (int) (operationId >>> LOG_ID_BITS); }

Target:
static int getTransactionId(long operationId) { return (int) (operationId >>> LOG_ID_BITS); }
Source:
protected void commonInitialize() { priorityUtil = new PriorityUtil(getModel()); virtioScsiUtil = new VirtioScsiUtil(getModel()); getModel().getVmId().setIsAvailable(false); getModel().getLease().setIsChangeable(false); getModel().getIsHighlyAvailable().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { boolean ha = getModel().getIsHighlyAvailable().getEntity(); getModel().getLease().setIsChangeable(vmLeasesSupported && ha); if (!ha) { getModel().getLease().setSelectedItem(null); } } }); getModel().getMigrationPolicies() .setItems(AsyncDataProvider.getInstance().getMigrationPolicies(Version.getLast())); }

Target:
protected void commonInitialize() { priorityUtil = new PriorityUtil(getModel()); virtioScsiUtil = new VirtioScsiUtil(getModel()); getModel().getVmId().setIsAvailable(false); getModel().getLease().setIsChangeable(false); getModel().getIsHighlyAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> { boolean ha = getModel().getIsHighlyAvailable().getEntity(); getModel().getLease().setIsChangeable(vmLeasesSupported && ha); if (!ha) { getModel().getLease().setSelectedItem(null); } }); getModel().getMigrationPolicies() .setItems(AsyncDataProvider.getInstance().getMigrationPolicies(Version.getLast())); }
Source:
private void setFetchThresholds() { KafkaConfig kafkaConfig = new KafkaConfig(config); Option<String> fetchThresholdOption = kafkaConfig.getConsumerFetchThreshold(systemName); long fetchThreshold = FETCH_THRESHOLD; if (fetchThresholdOption.isDefined()) { fetchThreshold = Long.valueOf(fetchThresholdOption.get()); LOG.info("fetchThresholdOption is configured. fetchThreshold=" + fetchThreshold); } Option<String> fetchThresholdBytesOption = kafkaConfig.getConsumerFetchThresholdBytes(systemName); long fetchThresholdBytes = FETCH_THRESHOLD_BYTES; if (fetchThresholdBytesOption.isDefined()) { fetchThresholdBytes = Long.valueOf(fetchThresholdBytesOption.get()); LOG.info("fetchThresholdBytesOption is configured. fetchThresholdBytes=" + fetchThresholdBytes); } int numTPs = topicPartitions2SSP.size(); assert (numTPs == topicPartitions2Offset.size()); LOG.info("fetchThresholdBytes = " + fetchThresholdBytes + "; fetchThreshold=" + fetchThreshold); LOG.info("number of topicPartitions " + numTPs); if (numTPs > 0) { perPartitionFetchThreshold = fetchThreshold / numTPs; LOG.info("perPartitionFetchThreshold=" + perPartitionFetchThreshold); if (fetchThresholdBytesEnabled) { perPartitionFetchThresholdBytes = (fetchThresholdBytes / 2) / numTPs; LOG.info("perPartitionFetchThresholdBytes is enabled. perPartitionFetchThresholdBytes=" + perPartitionFetchThresholdBytes); } } }

Target:
private void setFetchThresholds() { KafkaConfig kafkaConfig = new KafkaConfig(config); Option<String> fetchThresholdOption = kafkaConfig.getConsumerFetchThreshold(systemName); long fetchThreshold = FETCH_THRESHOLD; if (fetchThresholdOption.isDefined()) { fetchThreshold = Long.valueOf(fetchThresholdOption.get()); } Option<String> fetchThresholdBytesOption = kafkaConfig.getConsumerFetchThresholdBytes(systemName); long fetchThresholdBytes = FETCH_THRESHOLD_BYTES; if (fetchThresholdBytesOption.isDefined()) { fetchThresholdBytes = Long.valueOf(fetchThresholdBytesOption.get()); } int numPartitions = topicPartitionsToSSP.size(); if (numPartitions != topicPartitionsToOffset.size()) { throw new SamzaException("topicPartitionsToSSP.size() doesn't match topicPartitionsToOffset.size()"); } if (numPartitions > 0) { perPartitionFetchThreshold = fetchThreshold / numPartitions; if (fetchThresholdBytesEnabled) { perPartitionFetchThresholdBytes = (fetchThresholdBytes / 2) / numPartitions; } } LOG.info("{}: fetchThresholdBytes = {}; fetchThreshold={}; numPartitions={}, perPartitionFetchThreshold={}, perPartitionFetchThresholdBytes(0 if disabled)={}", this, fetchThresholdBytes, fetchThreshold, numPartitions, perPartitionFetchThreshold, perPartitionFetchThresholdBytes); }
Source:
public static ImmutableStorageProvider getStorageProvider(ImmutableStorageProviderFactory.AvailableImmutableStorages desiredProvider, AccountabilityConfigurationObject configuration) { if (Objects.isNull(storageProvider)) { switch (desiredProvider) { case SWARM: storageProvider = new SwarmProvider(configuration.getSwarm_gateway_url()); break; case TEST: default: storageProvider = new SwarmProvider("<LINK_0>"); break; } } return storageProvider; }

Target:
public static ImmutableStorageProvider getStorageProvider(ImmutableStorageProviderFactory.AvailableImmutableStorages desiredProvider, AccountabilityConfigurationObject configuration) { if (Objects.isNull(storageProvider)) { switch (desiredProvider) { case SWARM: storageProvider = new SwarmProvider(configuration.getSwarmGatewayUrl()); break; case TEST: default: storageProvider = new SwarmProvider("<LINK_0>"); break; } } return storageProvider; }
Source:
public static int getArchivedFormsValidityInDays(CommCareApp app) { int daysForReview = -1; String daysToPurge = app.getAppPreferences().getString("cc-days-form-retain", "-1"); try { daysForReview = Integer.parseInt(daysToPurge); } catch (NumberFormatException nfe) { Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "Invalid days to purge: " + daysToPurge); } return daysForReview; }

Target:
public static int getArchivedFormsValidityInDays(CommCareApp app) { int daysForReview = -1; String daysToPurge = app.getAppPreferences().getString(DAYS_TO_RETAIN_SAVED_FORMS_KEY, "-1"); try { daysForReview = Integer.parseInt(daysToPurge); } catch (NumberFormatException nfe) { Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "Invalid days to purge: " + daysToPurge); } return daysForReview; }
Source:
private void checkArgument(ExpressionTree arg, String name, String message) { LiteralTree literal = null; int sign = 1; if (arg.is(Tree.Kind.INT_LITERAL)) { literal = (LiteralTree) arg; } else if (arg.is(Tree.Kind.UNARY_MINUS) && ((UnaryExpressionTree) arg).expression().is(Tree.Kind.INT_LITERAL)) { sign = -1; literal = (LiteralTree) ((UnaryExpressionTree) arg).expression(); } if (literal != null) { int argValue = Integer.parseInt(literal.value()) * sign; if (argValue > Threshold.getThreshold(name) || argValue < 0) { addIssue(arg, MessageFormat.format(message, argValue, name)); } } }

Target:
private void checkArgument(ExpressionTree arg, String name, String message) { LiteralTree literal = null; int sign = 1; if (arg.is(Tree.Kind.INT_LITERAL)) { literal = (LiteralTree) arg; } else if (arg.is(Tree.Kind.UNARY_MINUS, Tree.Kind.UNARY_PLUS) && ((UnaryExpressionTree) arg).expression().is(Tree.Kind.INT_LITERAL)) { if(arg.is(Tree.Kind.UNARY_MINUS)) { sign = -1; } literal = (LiteralTree) ((UnaryExpressionTree) arg).expression(); } if (literal != null) { int argValue = Integer.parseInt(literal.value()) * sign; if (argValue > Threshold.getThreshold(name) || argValue < 0) { addIssue(arg, MessageFormat.format(message, argValue, name)); } } }
Source:
public YobitRateSource() { api = RestProxyFactory.createProxy(IBity.class, "<LINK_0>"); }

Target:
public YobitRateSource() { api = RestProxyFactory.createProxy(IYobitAPI.class, "<LINK_0>"); }
Source:
public SecureFamily(Family family) { if (family == null) { throw new UnsupportedOperationException(); } this.family = family; }

Target:
public SecureFamily(Family family) { if (family == null) { throw new IllegalArgumentException(); } this.family = family; }
Source:
public void sendResponse(Response response, ChannelHandlerContext ctx) { ByteBuf outBuf = PooledByteBufAllocator.DEFAULT.buffer(); outBuf.writeByte(API.PROTO_CORFU_MSG_MARK); outBuf.writeBytes(response.toByteArray()); ctx.writeAndFlush(outBuf); }

Target:
public void sendResponse(Response response, ChannelHandlerContext ctx) { ByteBuf outBuf = PooledByteBufAllocator.DEFAULT.buffer(); ByteBufOutputStream responseOutputStream = new ByteBufOutputStream(outBuf); try { responseOutputStream.writeByte(API.PROTO_CORFU_MSG_MARK); response.writeTo(responseOutputStream); ctx.writeAndFlush(outBuf); } catch(IOException e) { log.warn("sendResponse[{}]: Exception occurred when sending response {}, caused by {}", response.getHeader().getRequestId(), response.getHeader(), e.getCause(), e); } finally { IOUtils.closeQuietly(responseOutputStream); outBuf.release(); } }
Source:
FluxComponent getFluxComponent(StreamlineComponent streamlineComponent) { ProxyUtil<FluxComponent> proxyUtil = new ProxyUtil<>(FluxComponent.class); try { FluxComponent fluxComponent = proxyUtil.loadClassFromLibsDirectory(extraJarsLocation, streamlineComponent.getTransformationClass()); return fluxComponent; } catch (ClassNotFoundException | MalformedURLException | InstantiationException | IllegalAccessException e) { LOG.error("Error while creating flux component", e); throw new RuntimeException(e); } }

Target:
FluxComponent getFluxComponent(StreamlineComponent streamlineComponent) { ProxyUtil<FluxComponent> proxyUtil = new ProxyUtil<>(FluxComponent.class); try { FluxComponent fluxComponent = proxyUtil.loadClassFromLibDirectory(extraJarsLocation, streamlineComponent.getTransformationClass()); return fluxComponent; } catch (ClassNotFoundException | MalformedURLException | InstantiationException | IllegalAccessException e) { LOG.error("Error while creating flux component", e); throw new RuntimeException(e); } }
Source:
public void testChangeBrickField() throws InterpretationException { cloneBrickFormula.setRoot(new FormulaElement(FormulaElement.ElementType.NUMBER, CLONE_BRICK_FORMULA_VALUE, null)); assertNotSame(brickFormula.interpretInteger(sprite), cloneBrickFormula.interpretInteger(sprite)); }

Target:
public void testChangeBrickField() throws InterpretationException { cloneBrickFormula.setRoot(new FormulaElement(FormulaElement.ElementType.NUMBER, CLONE_BRICK_FORMULA_VALUE, null)); assertNotEquals(brickFormula.interpretInteger(sprite), cloneBrickFormula.interpretInteger(sprite)); }
Source:
private List<String> recursiveFolderDownload(ChannelSftp channelSftp, String sftpRemoteRelativePath, String sftpLocalRelativePath) throws SftpException, IOException { List<String> filesRelativePathName = new ArrayList<>(); List<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(sftpRemoteRelativePath); if (isRemoteFile(fileAndFolderList)) { String localFilePath = Paths.get(sftpLocalRelativePath, fileAndFolderList.get(0).getFilename()).toString(); filesRelativePathName.add(downloadSingleFile(channelSftp, sftpRemoteRelativePath, localFilePath)); if (sftpExtractArchive && sftpRemoteRelativePath.endsWith(".zip")) { getOut().println("Decompressing archive: " + localFilePath); ZipUtil.unpack(new File(localFilePath), new File(sftpLocalRelativePath)); getOut().println("Archive decompressed successfully at: " + sftpLocalRelativePath); } return filesRelativePathName; } for (ChannelSftp.LsEntry item : fileAndFolderList) { String remoteFilePath = Paths.get(sftpRemoteRelativePath, item.getFilename()).toString(); String localFilePath = Paths.get(sftpLocalRelativePath, item.getFilename()).toString(); File localFile = new File(localFilePath); if (!item.getAttrs().isDir()) { filesRelativePathName.add(downloadSingleFile(channelSftp, remoteFilePath, localFilePath)); } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { localFile.mkdirs(); filesRelativePathName.addAll(recursiveFolderDownload(channelSftp, remoteFilePath, localFilePath)); } } return filesRelativePathName; }

Target:
private List<String> recursiveFolderDownload(ChannelSftp channelSftp, String sftpRemoteRelativePath, String sftpLocalRelativePath) throws SftpException, IOException { List<String> filesRelativePathName = new ArrayList<>(); List<ChannelSftp.LsEntry> fileAndFolderList = null; try { fileAndFolderList = channelSftp.ls(sftpRemoteRelativePath); } catch (SftpException e) { throw new SftpException(e.id, "File not found or permission denied at " + sftpRemoteRelativePath, e.getCause()); } if (isRemoteFile(fileAndFolderList)) { String localFilePath = Paths.get(sftpLocalRelativePath, fileAndFolderList.get(0).getFilename()).toString(); filesRelativePathName.add(downloadSingleFile(channelSftp, sftpRemoteRelativePath, localFilePath)); if (sftpExtractArchive && sftpRemoteRelativePath.endsWith(".zip")) { extractArchive(localFilePath, sftpLocalRelativePath); } return filesRelativePathName; } for (ChannelSftp.LsEntry item : fileAndFolderList) { String remoteFilePath = Paths.get(sftpRemoteRelativePath, item.getFilename()).toString(); String localFilePath = Paths.get(sftpLocalRelativePath, item.getFilename()).toString(); File localFile = new File(localFilePath); if (!item.getAttrs().isDir()) { filesRelativePathName.add(downloadSingleFile(channelSftp, remoteFilePath, localFilePath)); } else if (!(CURRENT_FOLDER.equals(item.getFilename()) || PARENT_FOLDER.equals(item.getFilename()))) { localFile.mkdirs(); filesRelativePathName.addAll(recursiveFolderDownload(channelSftp, remoteFilePath, localFilePath)); } } return filesRelativePathName; }
Source:
public void compile(ICompilationUnit[] sourceUnits, boolean lastRound) { this.stats.startTime = System.currentTimeMillis(); try { reportProgress(Messages.compilation_beginningToCompile); if (this.annotationProcessorManager == null) { beginToCompile(sourceUnits); } else { ICompilationUnit[] originalUnits = sourceUnits.clone(); try { beginToCompile(sourceUnits); if (!lastRound) { processAnnotations(); } if (!this.options.generateClassFiles) { return; } } catch (SourceTypeCollisionException e) { backupAptProblems(); reset(); int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits, e.isLastRound); return; } } restoreAptProblems(); processCompiledUnits(0, lastRound); } catch (AbortCompilation e) { this.handleInternalException(e, null); } if (this.options.verbose) { if (this.totalUnits > 1) { this.out.println( Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits))); } else { this.out.println( Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits))); } } }

Target:
private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) { this.stats.startTime = System.currentTimeMillis(); try { reportProgress(Messages.compilation_beginningToCompile); if (this.annotationProcessorManager == null) { beginToCompile(sourceUnits); } else { ICompilationUnit[] originalUnits = sourceUnits.clone(); try { beginToCompile(sourceUnits); if (!lastRound) { processAnnotations(); } if (!this.options.generateClassFiles) { return; } } catch (SourceTypeCollisionException e) { backupAptProblems(); reset(); int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits, e.isLastRound); return; } } restoreAptProblems(); processCompiledUnits(0, lastRound); } catch (AbortCompilation e) { this.handleInternalException(e, null); } if (this.options.verbose) { if (this.totalUnits > 1) { this.out.println( Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits))); } else { this.out.println( Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits))); } } }
Source:
private void notifyAboutPendingChangesIfNotInTransaction() { if (changesBus != null && numberOfRunningTransactions.get() == 0) { for (final Changes changes : pendingChanges) { pendingChanges.remove(changes); changesBus.onNext(changes); } } }

Target:
private void notifyAboutPendingChangesIfNotInTransaction() { if (changesBus != null && numberOfRunningTransactions.get() == 0) { final Set<Changes> changes = pendingChanges .getAndSet(newSetFromMap(new ConcurrentHashMap<Changes, Boolean>())); for (final Changes next : changes) { changesBus.onNext(next); } } }
Source:
public String getLocalPath(IJavaBreakpoint bp) throws CoreException { if (bp.getMarker() != null && bp.getMarker().getResource() != null && bp.getMarker().getResource().getType() == IResource.FILE) { String type = bp.getTypeName(); if (type != null) { String pkg = (type.lastIndexOf('.') >= 0 ? (type.substring(0, type.lastIndexOf('.')) + "/") : "").replace('.', '/'); return pkg + bp.getMarker().getResource().getName(); } } return null; }

Target:
private String getLocalPath(IJavaBreakpoint bp) throws CoreException { if (bp.getMarker() != null && bp.getMarker().getResource() != null && bp.getMarker().getResource().getType() == IResource.FILE) { String type = bp.getTypeName(); if (type != null) { String pkg = (type.lastIndexOf('.') >= 0 ? (type.substring(0, type.lastIndexOf('.')) + "/") : "").replace('.', '/'); return pkg + bp.getMarker().getResource().getName(); } } return null; }
Source:
private void seekInternal() throws IOException { if (pos == nextPos) { return; } if (nextPos > pos) { long skipped = wrappedStream.skip(nextPos - pos); pos = pos + skipped; } if (nextPos < pos) { wrappedStream.close(); try { wrappedStream = channel.get(path.toUri().getPath()); pos = wrappedStream.skip(nextPos); } catch (SftpException e) { throw new UncheckedIOException(new IOException(e)); } } }

Target:
private void seekInternal() throws IOException { if (pos == nextPos) { return; } if (nextPos > pos) { long skipped = wrappedStream.skip(nextPos - pos); pos = pos + skipped; } if (nextPos < pos) { wrappedStream.close(); try { wrappedStream = channel.get(path.toUri().getPath()); pos = wrappedStream.skip(nextPos); } catch (SftpException e) { throw new IOException(e); } } }
Source:
private ArrayList getList(Group group) throws TranslatorException { ArrayList<Object> outputList = new ArrayList(); int fieldCount = group.getType().getFieldCount(); for (int field = 0; field < fieldCount; field++) { int valueCount = group.getFieldRepetitionCount(field); for (int index = 0; index < valueCount; index++) { Group listGroup = group.getGroup(field, index); Type fieldType = listGroup.getType().getType(0); if(!fieldType.isPrimitive()) { throw new TranslatorException("We don't support any logical types in a list."); } PrimitiveType.PrimitiveTypeName type = fieldType.asPrimitiveType().getPrimitiveTypeName(); outputList.add(getPrimitiveTypeObject(type, 0, 0, listGroup, fieldType)); } } return outputList; }

Target:
private ArrayImpl getList(Group group) throws TranslatorException { ArrayList<Object> outputList = new ArrayList<Object>(); int fieldCount = group.getType().getFieldCount(); for (int field = 0; field < fieldCount; field++) { int valueCount = group.getFieldRepetitionCount(field); for (int index = 0; index < valueCount; index++) { Group listGroup = group.getGroup(field, index); Type fieldType = listGroup.getType().getType(0); if(!fieldType.isPrimitive()) { throw new TranslatorException("We don't support any logical types in a list."); } PrimitiveType.PrimitiveTypeName type = fieldType.asPrimitiveType().getPrimitiveTypeName(); outputList.add(getPrimitiveTypeObject(type, 0, 0, listGroup, fieldType)); } } return new ArrayImpl(outputList.toArray()); }
Source:
void setData(List<List<String>> listOfGroups) { this.listOfGroups.clear(); this.listOfGroups = listOfGroups; notifyDataSetChanged(); delegate.setNoGroup(); }

Target:
void setData(List<List<String>> listOfGroups) { this.listOfGroups.clear(); this.listOfGroups.addAll(listOfGroups); notifyDataSetChanged(); }
Source:
private void writeMessageToPartition(final int partition) throws InterruptedException, ExecutionException { final KafkaProducer<String, String> producer = kafkaHelper.createProducer(); final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TEST_TOPIC, partition, "blah_key", "blah_value"); producer.send(producerRecord).get(); }

Target:
private void writeMessageToPartition(final int partition) throws InterruptedException, ExecutionException { final KafkaProducer<String, String> producer = kafkaHelper.createProducer(); final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TEST_TOPIC, partition, "blahKey", "blahValue"); producer.send(producerRecord).get(); }
Source:
public boolean canPushMerges() { return projectControl.controlForRef(getRefName()).canPerform( Permission.PUSH_MERGE) && canWrite(); }

Target:
public boolean canPushMerges() { if (projectControl.controlForRef(getRefName()).canPerform( Permission.PUSH_MERGE) && canWrite()) { return true; } else if (projectControl.controlForRef( MagicBranch.NEW_CHANGE + getRefName()) .canPerform(Permission.PUSH_MERGE) && canWrite()) { return true; } return false; }
Source:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!timeout.isNegative() || timeout.isZero()) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }

Target:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!(timeout.isNegative() || timeout.isZero())) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }
Source:
public Set<String> getInvalidActiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { if (startTs == null || endTs == null) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Require start_ts & end_ts").build()); } final Jedis jedis = jedisPool.getResource(); final Set<String> allSeenSenses = new HashSet<>(); final Set<String> allValidSeenSenses = new HashSet<>(); try { allSeenSenses.addAll(jedis.zrangeByScore(ActiveDevicesTrackerConfiguration.ALL_DEVICES_SEEN_SET_KEY, startTs, endTs)); allValidSeenSenses.addAll(jedis.zrangeByScore(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs)); } catch (Exception e) { LOGGER.error("Failed retrieving fw history for device.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } allSeenSenses.removeAll(allValidSeenSenses); return allSeenSenses; }

Target:
public Set<String> getInvalidActiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { if (startTs == null || endTs == null) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Require start_ts & end_ts").build()); } final Jedis jedis = jedisPool.getResource(); final Set<String> allSeenSenses = new HashSet<>(); final Set<String> allValidSeenSenses = new HashSet<>(); try { final Pipeline pipe = jedis.pipelined(); final redis.clients.jedis.Response<Set<String>> allDevs = pipe.zrangeByScore(ActiveDevicesTrackerConfiguration.ALL_DEVICES_SEEN_SET_KEY, startTs, endTs); final redis.clients.jedis.Response<Set<String>> allValid = pipe.zrangeByScore(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs); pipe.sync(); allSeenSenses.addAll(allDevs.get()); allValidSeenSenses.addAll(allValid.get()); } catch (Exception e) { LOGGER.error("Failed retrieving invalid active senses.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } allSeenSenses.removeAll(allValidSeenSenses); return allSeenSenses; }
Source:
public SWTGridDescription getGridDescription(SWTGridDescription gridDescription) { if (rendererGridDescription == null) { rendererGridDescription = GridDescriptionFactory.INSTANCE.createSimpleGrid(1, 2, this); final SWTGridCell label = rendererGridDescription.getGrid().get(0); label.setHorizontalGrab(false); label.setVerticalGrab(false); label.setVerticalFill(false); final Optional<Integer> labelWidth = getLabelWidth(); if (labelWidth.isPresent()) { label.setPreferredSize(labelWidth.get(), SWT.DEFAULT); } final SWTGridCell controls = rendererGridDescription.getGrid().get(1); controls.setVerticalGrab(false); controls.setVerticalFill(false); } return rendererGridDescription; }

Target:
public SWTGridDescription getGridDescription(SWTGridDescription gridDescription) { if (rendererGridDescription == null) { rendererGridDescription = GridDescriptionFactory.INSTANCE.createSimpleGrid(1, 2, this); final SWTGridCell label = rendererGridDescription.getGrid().get(0); label.setHorizontalGrab(false); label.setVerticalGrab(false); label.setVerticalFill(false); final Optional<Integer> labelWidth = getLabelWidth(); if (labelWidth.isPresent()) { label.setPreferredSize( labelWidth.get(), label.getPreferredSize() == null ? SWT.DEFAULT : label.getPreferredSize().y); } final SWTGridCell controls = rendererGridDescription.getGrid().get(1); controls.setVerticalGrab(false); controls.setVerticalFill(false); } return rendererGridDescription; }
Source:
public List<String> findAll() { return encodings; }

Target:
public List<Encoding> findAll() { return encodings; }
Source:
public void testGenerateMapGeneratorPresent() { when(applicationContext.getBean(GenerateMapTask.class)).thenReturn(generateMapTask); instance.generateMap(testMapNameGenerator).join(); verify(taskService).submitTask(generateMapTask); verify(generateMapTask).setVersion(versionGeneratorPresent); verify(generateMapTask).setSeed(seed); verify(generateMapTask).setGeneratorExecutableFile(fafDataDirectory.getRoot().toPath().resolve(MapGeneratorService.GENERATOR_EXECUTABLE_SUB_DIRECTORY).resolve(String.format(MapGeneratorService.getGENERATOR_EXECUTABLE_FILENAME(), versionGeneratorPresent)).toFile()); verify(generateMapTask).setMapFilename(testMapNameGenerator); verifyNoMoreInteractions(taskService); }

Target:
public void testGenerateMapGeneratorPresent() throws Exception { when(applicationContext.getBean(GenerateMapTask.class)).thenReturn(generateMapTask); String mapName = instance.generateMap(testMapNameGenerator).get(); assertThat(mapName, equalTo(testMapNameGenerator)); verify(taskService).submitTask(generateMapTask); verify(generateMapTask).setVersion(versionGeneratorPresent); verify(generateMapTask).setSeed(seed); verify(generateMapTask).setMapFilename(testMapNameGenerator); String generatorExecutableName = String.format(MapGeneratorService.getGENERATOR_EXECUTABLE_FILENAME(), versionGeneratorPresent); verify(generateMapTask).setGeneratorExecutableFile(fafDataDirectory.getRoot().toPath().resolve(MapGeneratorService.GENERATOR_EXECUTABLE_SUB_DIRECTORY).resolve(generatorExecutableName).toFile()); verifyNoMoreInteractions(taskService); }
Source:
void shutdown(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); cleanupTask(task); if (clean) { try { task.closeClean(); } catch (final TaskMigratedException e) { task.closeDirty(); } catch (final RuntimeException e) { firstException.compareAndSet(null, e); task.closeDirty(); } } else { task.closeDirty(); } if (task.isActive()) { try { activeTaskCreator.closeAndRemoveTaskProducerIfNeeded(task.id()); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing task producer.", e); } } } iterator.remove(); } try { activeTaskCreator.closeThreadProducerIfNeeded(); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing thread producer.", e); } } final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw new RuntimeException("Unexpected exception while closing task", fatalException); } }

Target:
void shutdown(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); cleanupTask(task); if (clean) { try { task.closeClean(); } catch (final TaskMigratedException e) { task.closeDirty(); } catch (final RuntimeException e) { firstException.compareAndSet(null, e); task.closeDirty(); } } else { task.closeDirty(); } if (task.isActive()) { try { activeTaskCreator.closeAndRemoveTaskProducerIfNeeded(task.id()); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing task " + task.id() + " producer.", e); } } } iterator.remove(); } try { activeTaskCreator.closeThreadProducerIfNeeded(); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing thread producer.", e); } } final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw new RuntimeException("Unexpected exception while closing task", fatalException); } }
Source:
private static FileOutputStream updateCertEntry(final String oldAlias, final String newAlias, Certificate certificate, final String storeLoc, final String passkey, KeyStore tstore) throws CertificateManagerException, IOException { FileOutputStream os = null; try { tstore.deleteEntry(oldAlias); os = new FileOutputStream(storeLoc); tstore.setCertificateEntry(newAlias, certificate); tstore.store(os, passkey.toCharArray()); } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { LOG.error("Unable to update the Certifiate: ", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getMessage(), ex); } finally { IOUtils.closeQuietly(os); } return os; }

Target:
private static void updateCertEntry(final String oldAlias, final String newAlias, Certificate certificate, final String storeLoc, final String passkey, KeyStore tstore) throws CertificateManagerException { try (FileOutputStream os = new FileOutputStream(storeLoc)) { tstore.deleteEntry(oldAlias); tstore.setCertificateEntry(newAlias, certificate); tstore.store(os, passkey.toCharArray()); } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { LOG.error("Unable to update the Certifiate: ", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getMessage(), ex); } }
Source:
public void setup() { SWTBotUtils.openView(getViewID()); fViewBot = fBot.viewById(getViewID()); fViewBot.show(); Matcher<Chart> widgetOfType = WidgetOfType.widgetOfType(Chart.class); fChart = fViewBot.bot().widget(widgetOfType); fTrace = getTestTrace(); File file = new File(fTrace.getPath()); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), fTrace.getTraceTypeId()); String analysisId = getAnalysisId(); if (analysisId != null) { IAnalysisModule module = fTrace.getAnalysisModule(analysisId); assertNotNull(module); module.schedule(); assertTrue(module.waitForCompletion()); } SWTBotUtils.activateEditor(fBot, fTrace.getName()); }

Target:
public void setup() { SWTBotUtils.openView(getViewID()); fViewBot = fBot.viewById(getViewID()); fViewBot.show(); Matcher<Chart> widgetOfType = WidgetOfType.widgetOfType(Chart.class); fChart = fViewBot.bot().widget(widgetOfType); fTrace = getTestTrace(); File file = new File(fTrace.getPath()); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), fTrace.getTraceTypeId()); String analysisId = getAnalysisId(); if (analysisId != null) { Set<@NonNull ITmfTrace> traces = TmfTraceManager.getInstance().getOpenedTraces(); ITmfTrace trace = Iterables.find(traces, t -> t.getName().equals(fTrace.getName())); IAnalysisModule module = trace.getAnalysisModule(analysisId); assertNotNull(module); module.schedule(); assertTrue(module.waitForCompletion()); } SWTBotUtils.activateEditor(fBot, fTrace.getName()); }
Source:
protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { Map<KeyExtent,List<Range>> tablets = binnedRanges.computeIfAbsent(location, k -> new HashMap<>()); List<Range> tabletsRanges = tablets.computeIfAbsent(ke, k -> new ArrayList<>()); tabletsRanges.add(range); }

Target:
protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { binnedRanges.computeIfAbsent(location, k -> new HashMap<>()) .computeIfAbsent(ke, k -> new ArrayList<>()).add(range); }
Source:
private static Slice codePointsToSliceUtf8(List<Integer> codePoints) { int length = codePoints.stream() .mapToInt(SliceUtf8::lengthOfCodePoint) .sum(); byte[] result = new byte[length]; int offset = 0; for (int codePoint : codePoints) { byte[] codePointUtf8 = SliceUtf8.codePointToUtf8(codePoint).getBytes(); System.arraycopy(codePointUtf8, 0, result, offset, codePointUtf8.length); offset += codePointUtf8.length; } return Slices.wrappedBuffer(result); }

Target:
private static Slice codePointsToSliceUtf8(List<Integer> codePoints) { int length = codePoints.stream() .mapToInt(SliceUtf8::lengthOfCodePoint) .sum(); Slice result = Slices.wrappedBuffer(new byte[length]); int offset = 0; for (int codePoint : codePoints) { setCodePointAt(codePoint, result, offset); offset += lengthOfCodePoint(codePoint); } return result; }
Source:
static zipkin.Span convert(Span span, Host host) { Builder zipkinSpan = new zipkin.Span.Builder(); Endpoint ep = Endpoint.create(host.getServiceName(), host.getIpv4(), host.getPort().shortValue()); if (span.logs().isEmpty() && span.tags().isEmpty()) { addLocalComponentAnnotation(span, zipkinSpan, ep); } else { ZipkinMessageListener.addZipkinAnnotations(zipkinSpan, span, ep); ZipkinMessageListener.addZipkinBinaryAnnotations(zipkinSpan, span, ep); } if (!spanContainsAnyZipkinConstant(span)) { addLocalComponentAnnotation(span, zipkinSpan, ep); } else if (spanContainsAnyZipkinClientConstantAndSaIsNotSet(span)) { addServerAddressAnnotation(zipkinSpan, ep); } zipkinSpan.timestamp(span.getBegin() * 1000); zipkinSpan.duration(span.getAccumulatedMillis() * 1000); zipkinSpan.traceId(span.getTraceId()); if (span.getParents().size() > 0) { if (span.getParents().size() > 1) { SamplingZipkinSpanIterator.log .debug("zipkin doesn't support spans with multiple parents. Omitting " + "other parents for " + span); } zipkinSpan.parentId(span.getParents().get(0)); } zipkinSpan.id(span.getSpanId()); if (StringUtils.hasText(span.getName())) { zipkinSpan.name(span.getName()); } return zipkinSpan.build(); }

Target:
static zipkin.Span convert(Span span, Host host) { Builder zipkinSpan = new zipkin.Span.Builder(); Endpoint ep = Endpoint.create(host.getServiceName(), host.getIpv4(), host.getPort().shortValue()); if (notClientOrServer(span)) { ensureLocalComponent(span, zipkinSpan, ep); } ZipkinMessageListener.addZipkinAnnotations(zipkinSpan, span, ep); ZipkinMessageListener.addZipkinBinaryAnnotations(zipkinSpan, span, ep); if (hasClientSend(span)) { ensureServerAddr(span, zipkinSpan, ep); } zipkinSpan.timestamp(span.getBegin() * 1000); zipkinSpan.duration(span.getAccumulatedMillis() * 1000); zipkinSpan.traceId(span.getTraceId()); if (span.getParents().size() > 0) { if (span.getParents().size() > 1) { SamplingZipkinSpanIterator.log .debug("zipkin doesn't support spans with multiple parents. Omitting " + "other parents for " + span); } zipkinSpan.parentId(span.getParents().get(0)); } zipkinSpan.id(span.getSpanId()); if (StringUtils.hasText(span.getName())) { zipkinSpan.name(span.getName()); } return zipkinSpan.build(); }
Source:
public void run () throws Exception { LOG.info("Periodically making an OTP2 Raptor TransitLayer from the TimetableSnapshot at intervals of seconds.", updateIntervalSeconds); while (true) { try { Thread.sleep(1000 * updateIntervalSeconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } if (graph.timetableSnapshotSource != null) { final TimetableSnapshot timetableSnapshot = graph.timetableSnapshotSource.getTimetableSnapshot(); if (timetableSnapshot.hashCode() != lastSnapshotHashCode) { lastSnapshotHashCode = timetableSnapshot.hashCode(); final TransitLayer realtimeTransitLayer = TransitLayerMapper.map(graph); updaterManager.execute(g -> g.realtimeTransitLayer = realtimeTransitLayer); } } } }

Target:
public void run () { LOG.info("Periodically making an OTP2 Raptor TransitLayer from the TimetableSnapshot at intervals of seconds.", updateIntervalSeconds); while (true) { try { Thread.sleep(1000 * updateIntervalSeconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } final TimetableSnapshot timetableSnapshot = graph.getTimetableSnapshot(); if (timetableSnapshot != null) { if (timetableSnapshot.hashCode() != lastSnapshotHashCode) { lastSnapshotHashCode = timetableSnapshot.hashCode(); final TransitLayer realtimeTransitLayer = TransitLayerMapper.map(graph); updaterManager.execute(g -> g.realtimeTransitLayer = realtimeTransitLayer); } } } }
Source:
public static Metric<Double> distinctValuesCount(String columnName) { return new Metric<Double>() { @Override public Optional<Double> getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getDistinctValuesCount()); } @Override public Optional<Double> getValueFromAggregationQueryResult(Object value) { return Optional.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "count(distinct " + columnName + ")"; } @Override public String getName() { return "DISTINCT_VALUES_COUNT(" + columnName + ")"; } }; }

Target:
public static Metric distinctValuesCount(String columnName) { return new Metric() { @Override public OptionalDouble getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getDistinctValuesCount()); } @Override public OptionalDouble getValueFromAggregationQueryResult(Object value) { return OptionalDouble.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "count(distinct " + columnName + ")"; } @Override public String toString() { return "DISTINCT_VALUES_COUNT(" + columnName + ")"; } }; }
Source:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); AssetRequestHandler handler = new AssetRequestHandler(context); List<RequestHandler> handlers = new ArrayList<RequestHandler>(Arrays.asList(handler)); Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }

Target:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); RequestHandler handler = new AssetRequestHandler(context); List<RequestHandler> handlers = Arrays.asList(handler); Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }
Source:
private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Function<E, S> classifier, Consumer<S> onLowerWatermarkCrossed, Consumer<S> onUpperWatermarkCrossed) { assert lowerWatermark >= 0 && lowerWatermark < upperWatermark; this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = classifier; this.onLowerWatermarkCrossed = onLowerWatermarkCrossed; this.onUpperWatermarkCrossed = onUpperWatermarkCrossed; final Map<S, StreamTracker> trackerMap = new ConcurrentHashMap<>(); this.trackerSupplier = key -> trackerMap.computeIfAbsent(key, StreamTracker::new); }

Target:
private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Function<E, S> classifier, Consumer<S> onLowerWatermarkCrossed, Consumer<S> onUpperWatermarkCrossed) { this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = classifier; this.onLowerWatermarkCrossed = onLowerWatermarkCrossed; this.onUpperWatermarkCrossed = onUpperWatermarkCrossed; final Map<S, StreamTracker> trackerMap = new ConcurrentHashMap<>(); this.trackerSupplier = key -> trackerMap.computeIfAbsent(key, StreamTracker::new); }