auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected TestHivePushdownFilterQueries() { super(() -> createQueryRunner()); }

Target:
protected TestHivePushdownFilterQueries() { super(TestHivePushdownFilterQueries::createQueryRunner); }
Source:
public static Optional<HashComputation> computeHash(Iterable<VariableReferenceExpression> fields, FunctionManager functionManager) { requireNonNull(fields, "fields is null"); List<VariableReferenceExpression> variables = ImmutableList.copyOf(fields); if (variables.isEmpty()) { return Optional.empty(); } return Optional.of(new HashComputation(fields, functionManager)); }

Target:
private static Optional<HashComputation> computeHash(Iterable<VariableReferenceExpression> fields, FunctionManager functionManager) { requireNonNull(fields, "fields is null"); List<VariableReferenceExpression> variables = ImmutableList.copyOf(fields); if (variables.isEmpty()) { return Optional.empty(); } return Optional.of(new HashComputation(fields, functionManager)); }
Source:
private void assertInvalidPath(String path) { SubfieldTokenizer tokenizer = new SubfieldTokenizer(path); try { ImmutableList<PathElement> pathElements = Streams.stream(tokenizer).collect(toImmutableList()); fail("Expected failure"); } catch (PrestoException e) { // this is expected assertTrue(e.getMessage().startsWith("Invalid subfield path: ")); } }

Target:
private void assertInvalidPath(String path) { SubfieldTokenizer tokenizer = new SubfieldTokenizer(path); try { Streams.stream(tokenizer).collect(toImmutableList()); fail("Expected failure"); } catch (PrestoException e) { // this is expected assertTrue(e.getMessage().startsWith("Invalid subfield path: ")); } }
Source:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; }

Target:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; }
Source:
long adjustValue(int offsetIndex, long value) { if (inDictionaryStream != null) { return inDictionaryFlags[offsetIndex] ? dictionary[(int) value] : value; } return dictionary[(int) value]; }

Target:
private long adjustValue(int offsetIndex, long value) { if (inDictionaryStream != null) { return inDictionaryFlags[offsetIndex] ? dictionary[(int) value] : value; } return dictionary[(int) value]; }
Source:
int adjustValue(long value, int offsetIndex) { if (inDictionaryStream != null && !inDictionaryFlags[offsetIndex]) { return toIntExact(value + stripeDictionarySize); } return toIntExact(value); }

Target:
private int adjustValue(long value, int offsetIndex) { if (inDictionaryStream != null && !inDictionaryFlags[offsetIndex]) { return toIntExact(value + stripeDictionarySize); } return toIntExact(value); }
Source:
public void testLength() { double length = 4350866.6362; // Empty linestring returns null assertLength("LINESTRING EMPTY", null); // Linestring with one point has length 0 assertLength("LINESTRING (0 0)", 0.0); // Linestring with only one distinct point has length 0 assertLength("LINESTRING (0 0, 0 0, 0 0)", 0.0); // ST_Length is equivalent to sums of ST_DISTANCE between points in the LineString assertLength("LINESTRING (-71.05 42.36, -87.62 41.87, -122.41 37.77)", length); // Linestring has same length as its reverse assertLength("LINESTRING (-122.41 37.77, -87.62 41.87, -71.05 42.36)", length); // Path north pole -> south pole -> north pole should be roughly the circumference of the Earth assertLength("LINESTRING (0.0 90.0, 0.0 -90.0, 0.0 90.0)", 4.003e7); // Empty multi-linestring returns null assertLength("MULTILINESTRING (EMPTY)", null); // Multi-linestring with one path is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77))", length); // Multi-linestring with two disjoint paths has length equal to sum of lengths of lines assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77), (-73.05 42.36, -89.62 41.87, -124.41 37.77))", 2 * length); // Multi-linestring with adjacent paths is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87), (-87.62 41.87, -122.41 37.77))", length); }

Target:
public void testLength() { // Empty linestring returns null assertLength("LINESTRING EMPTY", null); // Linestring with one point has length 0 assertLength("LINESTRING (0 0)", 0.0); // Linestring with only one distinct point has length 0 assertLength("LINESTRING (0 0, 0 0, 0 0)", 0.0); double length = 4350866.6362; // ST_Length is equivalent to sums of ST_DISTANCE between points in the LineString assertLength("LINESTRING (-71.05 42.36, -87.62 41.87, -122.41 37.77)", length); // Linestring has same length as its reverse assertLength("LINESTRING (-122.41 37.77, -87.62 41.87, -71.05 42.36)", length); // Path north pole -> south pole -> north pole should be roughly the circumference of the Earth assertLength("LINESTRING (0.0 90.0, 0.0 -90.0, 0.0 90.0)", 4.003e7); // Empty multi-linestring returns null assertLength("MULTILINESTRING (EMPTY)", null); // Multi-linestring with one path is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77))", length); // Multi-linestring with two disjoint paths has length equal to sum of lengths of lines assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77), (-73.05 42.36, -89.62 41.87, -124.41 37.77))", 2 * length); // Multi-linestring with adjacent paths is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87), (-87.62 41.87, -122.41 37.77))", length); }
Source:
public FunctionHandle lookupFunction(QualifiedName name, List<TypeSignatureProvider> parameterTypes) { return staticFunctionNamespace.resolveFunction(name, parameterTypes); }

Target:
public FunctionHandle lookupFunction(QualifiedName name, List<TypeSignatureProvider> parameterTypes) { return staticFunctionNamespace.lookupFunction(name, parameterTypes); }
Source:
public void testCastOperatorsExistForCoercions() { Set<Type> types = getStandardPrimitiveTypes(); for (Type sourceType : types) { for (Type resultType : types) { if (typeRegistry.canCoerce(sourceType, resultType) && sourceType != UNKNOWN && resultType != UNKNOWN) { try { functionManager.lookupCast(CastType.CAST, sourceType.getTypeSignature(), resultType.getTypeSignature()); } catch (OperatorNotFoundException e) { fail(format("'%s' -> '%s' coercion exists but there is no cast operator", sourceType, resultType)); } } } } }

Target:
public void testCastOperatorsExistForCoercions() { Set<Type> types = getStandardPrimitiveTypes(); for (Type sourceType : types) { for (Type resultType : types) { if (typeRegistry.canCoerce(sourceType, resultType) && sourceType != UNKNOWN && resultType != UNKNOWN) { try { functionManager.lookupCast(CAST, sourceType.getTypeSignature(), resultType.getTypeSignature()); } catch (OperatorNotFoundException e) { fail(format("'%s' -> '%s' coercion exists but there is no cast operator", sourceType, resultType)); } } } } }
Source:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { // analyze statement Analysis analysis = analyze(session, statement, parameters, warningCollector); // plan statement LogicalPlanner logicalPlanner = new LogicalPlanner(session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }

Target:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { // analyze statement Analysis analysis = analyze(session, statement, parameters, warningCollector); // plan statement LogicalPlanner logicalPlanner = new LogicalPlanner(true, session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }
Source:
public void setNoMorePagesForLifespan(Lifespan lifespan) { noMorePagesForLifespan.add(requireNonNull(lifespan, "lifespan is null")); }

Target:
public void setNoMorePagesForLifespan(Lifespan lifespan) { requireNonNull(lifespan, "lifespan is null"); noMorePagesForLifespan.add(lifespan); }
Source:
private LocationHandle createLocationHandle(HdfsContext context, ConnectorSession session, Path targetPath, boolean isExistingTable) { if (shouldUseTemporaryDirectory(session, context, targetPath)) { Path writePath = createTemporaryPath(session, context, hdfsEnvironment, targetPath); return new LocationHandle(targetPath, writePath, isExistingTable, STAGE_AND_MOVE_TO_TARGET_DIRECTORY); } else { return new LocationHandle(targetPath, targetPath, isExistingTable, isExistingTable ? DIRECT_TO_TARGET_EXISTING_DIRECTORY : DIRECT_TO_TARGET_NEW_DIRECTORY); } }

Target:
private LocationHandle createLocationHandle(HdfsContext context, ConnectorSession session, Path targetPath, boolean isExistingTable) { if (shouldUseTemporaryDirectory(session, context, targetPath)) { Path writePath = createTemporaryPath(session, context, hdfsEnvironment, targetPath); return new LocationHandle(targetPath, writePath, isExistingTable, STAGE_AND_MOVE_TO_TARGET_DIRECTORY); } if (isExistingTable) { return new LocationHandle(targetPath, targetPath, true, DIRECT_TO_TARGET_EXISTING_DIRECTORY); } return new LocationHandle(targetPath, targetPath, false, DIRECT_TO_TARGET_NEW_DIRECTORY); }
Source:
private static void assertTimestampCorrect(String timestampString) { Timestamp timestamp = Timestamp.valueOf(timestampString); NanoTime nanoTime = NanoTimeUtils.getNanoTime(timestamp, false); ByteBuffer buffer = ByteBuffer.wrap(nanoTime.toBinary().getBytes()); long decodedTimestampMillis = getTimestampMillis(Binary.fromConstantByteBuffer(buffer)); assertEquals(decodedTimestampMillis, timestamp.getTime()); }

Target:
private static void assertTimestampCorrect(String timestampString) { Timestamp timestamp = Timestamp.valueOf(timestampString); NanoTime nanoTime = getNanoTime(timestamp, false); ByteBuffer buffer = ByteBuffer.wrap(nanoTime.toBinary().getBytes()); long decodedTimestampMillis = getTimestampMillis(fromConstantByteBuffer(buffer)); assertEquals(decodedTimestampMillis, timestamp.getTime()); }
Source:
ObjectMetadata getS3ObjectMetadata(Path path) throws IOException { String bucketName = getBucketName(uri); String key = keyFromPath(path); ObjectMetadata s3ObjectMetadata = getS3ObjectMetadata(path, bucketName, key); if (s3ObjectMetadata == null && !key.isEmpty()) { // check if key is not a "directory" verify(!key.endsWith(PATH_SEPARATOR), "Expected key to not end with %s", PATH_SEPARATOR); return getS3ObjectMetadata(path, bucketName, key + PATH_SEPARATOR); } return s3ObjectMetadata; }

Target:
ObjectMetadata getS3ObjectMetadata(Path path) throws IOException { String bucketName = getBucketName(uri); String key = keyFromPath(path); ObjectMetadata s3ObjectMetadata = getS3ObjectMetadata(path, bucketName, key); if (s3ObjectMetadata == null && !key.isEmpty()) { return getS3ObjectMetadata(path, bucketName, key + PATH_SEPARATOR); } return s3ObjectMetadata; }
Source:
public Builder setBaseDataDir(Optional<Path> baseDataDir) { requireNonNull(baseDataDir, "baseDataDir is null"); this.baseDataDir = baseDataDir; return this; }

Target:
public Builder setBaseDataDir(Optional<Path> baseDataDir) { this.baseDataDir = requireNonNull(baseDataDir, "baseDataDir is null"); return this; }
Source:
private RetryDriver retry() { return RetryDriver.retry() .exponentialBackoff( this.minBackoffDelay, this.maxBackoffDelay, this.maxRetryTime, this.scaleFactor) .maxAttempts(this.maxRetries + 1) .exceptionMapper(exceptionMapper) .stopOn(PrestoException.class); }

Target:
private RetryDriver retry() { return RetryDriver.retry() .exponentialBackoff( minBackoffDelay, maxBackoffDelay, maxRetryTime, scaleFactor) .maxAttempts(maxRetries + 1) .exceptionMapper(exceptionMapper) .stopOn(PrestoException.class); }
Source:
public void tearDown() { try (Closer closer = Closer.create()) { // Closer is documented to mimic try-with-resource, which implies close will happen in reverse order. // first close the cients, then clear the map closer.register(clients::clear); for (Entry<String, TransportClient> entry : clients.entrySet()) { closer.register(entry.getValue()); } closer.register(() -> executor.shutdown()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
public void tearDown() { // Closer closes the resources in reverse order. // Therefore, we first clear the clients map, then close each client. try (Closer closer = Closer.create()) { closer.register(clients::clear); for (Entry<String, TransportClient> entry : clients.entrySet()) { closer.register(entry.getValue()); } closer.register(executor::shutdown); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public Result apply(SemiJoinNode semiJoinNode, Captures captures, Context context) { JoinDistributionType joinDistributionType = getJoinDistributionType(context.getSession()); switch (joinDistributionType) { case AUTOMATIC: return Result.ofPlanNode(getCostBasedDistributionType(semiJoinNode, context)); case PARTITIONED: return Result.ofPlanNode(semiJoinNode.withDistributionType(PARTITIONED)); case BROADCAST: return Result.ofPlanNode(semiJoinNode.withDistributionType(REPLICATED)); default: throw new UnsupportedOperationException("Unknown join_distribution_type: " + joinDistributionType); } }

Target:
public Result apply(SemiJoinNode semiJoinNode, Captures captures, Context context) { JoinDistributionType joinDistributionType = getJoinDistributionType(context.getSession()); switch (joinDistributionType) { case AUTOMATIC: return Result.ofPlanNode(getCostBasedDistributionType(semiJoinNode, context)); case PARTITIONED: return Result.ofPlanNode(semiJoinNode.withDistributionType(PARTITIONED)); case BROADCAST: return Result.ofPlanNode(semiJoinNode.withDistributionType(REPLICATED)); default: throw new IllegalArgumentException("Unknown join_distribution_type: " + joinDistributionType); } }
Source:
public void add(Block block, int position) { requireNonNull(block, "block must not be null"); checkArgument(position >= 0, "position must be >= 0"); if (block.isNull(position)) { if (!containsNullElement) { containsNullElement = true; } } // null is added to both elementBlock and the blockPositionByHash hash table only once. // Adding it to elementBlock makes getBlock() being able to be called multiple times. // Adding it to hash table avoids changes in rehash() int hashPosition = getHashPositionOfElement(block, position); if (blockPositionByHash.get(hashPosition) == EMPTY_SLOT) { addNewElement(hashPosition, block, position); } }

Target:
public void add(Block block, int position) { requireNonNull(block, "block must not be null"); checkArgument(position >= 0, "position must be >= 0"); // containsNullElement flag is maintained so contains() method can have shortcut for null value if (block.isNull(position)) { containsNullElement = true; } int hashPosition = getHashPositionOfElement(block, position); if (blockPositionByHash.get(hashPosition) == EMPTY_SLOT) { addNewElement(hashPosition, block, position); } }
Source:
private void addNewElement(int hashPosition, Block block, int position) { elementType.appendTo(block, position, elementBlock); if (elementBlock.getSizeInBytes() - initialElementBlockSizeInBytes > FOUR_MEGABYTES) { throw new PrestoException( EXCEEDED_FUNCTION_MEMORY_LIMIT, format("The input to %s is too large. More than %s of memory is needed to hold the intermediate hash set.\n", functionName, MAX_FUNCTION_MEMORY)); } blockPositionByHash.set(hashPosition, elementBlock.getPositionCount() - 1); // increase capacity, if necessary if (++size >= maxFill) { rehash(); } }

Target:
private void addNewElement(int hashPosition, Block block, int position) { elementType.appendTo(block, position, elementBlock); if (elementBlock.getSizeInBytes() - initialElementBlockSizeInBytes > FOUR_MEGABYTES) { throw new PrestoException( EXCEEDED_FUNCTION_MEMORY_LIMIT, format("The input to %s is too large. More than %s of memory is needed to hold the intermediate hash set.\n", functionName, MAX_FUNCTION_MEMORY)); } blockPositionByHash.set(hashPosition, elementBlock.getPositionCount() - 1); // increase capacity, if necessary size++; if (size >= maxFill) { rehash(); } }
Source:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { try { return getCompressionCodec((TextInputFormat) inputFormat, path) .map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec)) .orElse(true); } catch (IllegalAccessException e) { LOG.error(e, "Failed to find compressionCodec for inputFormat: %s", inputFormat.getClass().getName()); return false; } } return false; }

Target:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { return getCompressionCodec((TextInputFormat) inputFormat, path) .map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec)) .orElse(true); } return false; }
Source:
public static int computeTruncatedLength(Slice slice, int offset, int length, int maxCodePointCount, boolean isCharType) { int truncatedLength = length; if (isCharType) { // truncate the characters and then remove the trailing white spaces truncatedLength = byteCountWithoutTrailingSpace(slice, offset, length, maxCodePointCount); } else if (maxCodePointCount >= 0 && length > maxCodePointCount) { truncatedLength = byteCount(slice, offset, length, maxCodePointCount); } return truncatedLength; }

Target:
public static int computeTruncatedLength(Slice slice, int offset, int length, int maxCodePointCount, boolean isCharType) { if (isCharType) { // truncate the characters and then remove the trailing white spaces return byteCountWithoutTrailingSpace(slice, offset, length, maxCodePointCount); } if (maxCodePointCount >= 0 && length > maxCodePointCount) { return byteCount(slice, offset, length, maxCodePointCount); } return length; }
Source:
public static void main(String[] args) throws Throwable { // assure the benchmarks are valid before running BenchmarkData data = new BenchmarkData(); data.setup(); new BenchmarkDictionaryBlockGetSizeInBytes().getSizeInBytes(data); Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .warmupMode(WarmupMode.INDI) .include(".*" + BenchmarkDictionaryBlockGetSizeInBytes.class.getSimpleName() + ".*") .build(); new Runner(options).run(); }

Target:
public static void main(String[] args) throws Throwable { // assure the benchmarks are valid before running BenchmarkData data = new BenchmarkData(); data.setup(); new BenchmarkDictionaryBlockGetSizeInBytes().getSizeInBytes(data); Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .include(".*" + BenchmarkDictionaryBlockGetSizeInBytes.class.getSimpleName() + ".*") .build(); new Runner(options).run(); }
Source:
public PolymorphicScalarFunctionChoice build() { if (argumentProperties == null || argumentProperties.isEmpty()) { argumentProperties = nCopies(signature.getArgumentTypes().size(), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)); } return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups.build()); }

Target:
public PolymorphicScalarFunctionChoice build() { return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups.build()); }
Source:
public ConnectorBucketNodeMap getBucketNodeMap(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { Set<Node> nodes = nodeManager.getRequiredWorkerNodes(); checkState(!nodes.isEmpty(), "No TPCH nodes available"); // Split the data using split and skew by the number of nodes available. return createBucketNodeMap(toIntExact((long)nodes.size() * splitsPerNode)); }

Target:
public ConnectorBucketNodeMap getBucketNodeMap(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { Set<Node> nodes = nodeManager.getRequiredWorkerNodes(); // Split the data using split and skew by the number of nodes available. return createBucketNodeMap(toIntExact((long) nodes.size() * splitsPerNode)); }
Source:
public ConnectorBucketNodeMap getBucketNodeMap(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { // create one bucket per node return createBucketNodeMap( nodeManager.getRequiredWorkerNodes().size(), value -> { throw new PrestoException(NOT_SUPPORTED, "Black hole connector does not supported distributed reads"); }); }

Target:
public ConnectorBucketNodeMap getBucketNodeMap(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { // create one bucket per node return createBucketNodeMap(nodeManager.getRequiredWorkerNodes().size()); }
Source:
public QuantileDigestAggregationFunction(TypeSignature... typeSignatures) { super(NAME, ImmutableList.of(comparableTypeParameter("V")), ImmutableList.of(), parseTypeSignature("qdigest(V)"), ImmutableList.copyOf(typeSignatures)); }

Target:
private QuantileDigestAggregationFunction(TypeSignature... typeSignatures) { super( NAME, ImmutableList.of(comparableTypeParameter("V")), ImmutableList.of(), parseTypeSignature("qdigest(V)"), ImmutableList.copyOf(typeSignatures)); }
Source:
List<Page> generateTestData() { List<Type> typesArray = new ArrayList<>(); int currentPartitionIdentifier = 1; typesArray.add(BIGINT); typesArray.add(BIGINT); typesArray.add(BIGINT); typesArray.add(BIGINT); RowPagesBuilder pagesBuilder = buildPages(currentPartitionIdentifier, typesArray); return pagesBuilder.build(); }

Target:
private List<Page> generateTestData() { List<Type> typesArray = new ArrayList<>(); int currentPartitionIdentifier = 1; typesArray.add(BIGINT); typesArray.add(BIGINT); typesArray.add(BIGINT); typesArray.add(BIGINT); RowPagesBuilder pagesBuilder = buildPages(currentPartitionIdentifier, typesArray); return pagesBuilder.build(); }
Source:
public void abort() { // rollback and close try (Connection connection = this.connection; PreparedStatement statement = this.statement) { connection.rollback(); } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } finally { try { jdbcClient.rollbackCreateTable(handle); } catch (Exception e) { log.warn(e, format("Failed to cleanup temporary table: %s", handle.getTemporaryTableName())); } } }

Target:
public void abort() { // rollback and close try (Connection connection = this.connection; PreparedStatement statement = this.statement) { connection.rollback(); } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }
Source:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { JdbcOutputTableHandle handle = jdbcClient.beginCreateTable(tableMetadata, ignoreExisting); finishCreateTable(session, handle, emptyList(), emptyList()); }

Target:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { jdbcClient.createTable(tableMetadata); }
Source:
public PlanNodeStatsEstimate( @JsonProperty("outputRowCount") double outputRowCount, @JsonProperty("symbolStatistics") Map<Symbol, SymbolStatsEstimate> symbolStatistics) { checkArgument(isNaN(outputRowCount) || outputRowCount >= 0, "outputRowCount cannot be negative"); this.outputRowCount = outputRowCount; this.symbolStatistics = HashTreePMap.from(requireNonNull(symbolStatistics, "symbolStatistics is null")); }

Target:
public PlanNodeStatsEstimate( @JsonProperty("outputRowCount") double outputRowCount, @JsonProperty("symbolStatistics") Map<Symbol, SymbolStatsEstimate> symbolStatistics) { this(outputRowCount, HashTreePMap.from(requireNonNull(symbolStatistics, "symbolStatistics is null"))); }
Source:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate localCosts = costCalculator.calculateCost(node, statsProvider, session, types); PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); PlanNodeCostEstimate cumulativeCost = costCalculator.calculateCost(node, statsProvider, session, types).add(sourcesCost); return cumulativeCost; }

Target:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); return costCalculator.calculateCost(node, statsProvider, session, types).add(sourcesCost); }
Source:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); PlanNodeCostEstimate cumulativeCost = costCalculator.calculateCost(node, statsProvider, noLookup(), session, types).add(sourcesCost); return cumulativeCost; }

Target:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); return costCalculator.calculateCost(node, statsProvider, session, types).add(sourcesCost); }
Source:
public void testDefaultAcl() throws Exception { Configuration config = new Configuration(); try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) { MockAmazonS3 s3 = new MockAmazonS3(); String expectedBucketName = "test-bucket"; fs.initialize(new URI("s3n://" + expectedBucketName + "/"), config); fs.setS3Client(s3); FSDataOutputStream stream = fs.create(new Path("s3n://test-bucket/test")); stream.close(); assertEquals(CannedAccessControlList.Private, s3.getAcl()); } }

Target:
public void testDefaultAcl() throws Exception { Configuration config = new Configuration(); try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) { MockAmazonS3 s3 = new MockAmazonS3(); String expectedBucketName = "test-bucket"; fs.initialize(new URI("s3n://" + expectedBucketName + "/"), config); fs.setS3Client(s3); try (FSDataOutputStream stream = fs.create(new Path("s3n://test-bucket/test"))) { // initiate an upload by creating a stream & closing it immediately } assertEquals(CannedAccessControlList.Private, s3.getAcl()); } }
Source:
private String randomTwoChoices() { // Randomly pick 2 different candidates and select the less loaded one int randomPosition = ThreadLocalRandom.current().nextInt(activeNodes.size()); int randomOffset = ThreadLocalRandom.current().nextInt(1, activeNodes.size()); String candidate1 = activeNodes.get(randomPosition); String candidate2 = activeNodes.get((randomPosition + randomOffset) % activeNodes.size()); if (nodeBucketCounts.get(candidate2) < nodeBucketCounts.get(candidate1)) { candidate1 = candidate2; } return candidate1; }

Target:
private String randomTwoChoices() { // Purely random choices can overload unlucky node while selecting the least loaded one based on stale // local information can overload the previous idle node. Here we randomly pick 2 nodes and select the // less loaded one. This prevents those issues and renders good enough load balance. int randomPosition = ThreadLocalRandom.current().nextInt(activeNodes.size()); int randomOffset = ThreadLocalRandom.current().nextInt(1, activeNodes.size()); String candidate1 = activeNodes.get(randomPosition); String candidate2 = activeNodes.get((randomPosition + randomOffset) % activeNodes.size()); return (nodeBucketCounts.get(candidate1) <= nodeBucketCounts.get(candidate2)) ? candidate1 : candidate2; }
Source:
YieldingIterator(WorkProcessor<T> processor) { this.processor = requireNonNull(processor, "processorParameter is null"); }

Target:
private YieldingIterator(WorkProcessor<T> processor) { this.processor = requireNonNull(processor, "processorParameter is null"); }
Source:
public SingleMultimapAggregationState(Type keyType, Type valueType) { this.keyType = requireNonNull(keyType); this.valueType = requireNonNull(valueType); keyBlockBuilder = this.keyType.createBlockBuilder(null, EXPECTED_ENTRIES, expectedValueSize(keyType, EXPECTED_ENTRY_SIZE)); valueBlockBuilder = this.valueType.createBlockBuilder(null, EXPECTED_ENTRIES, expectedValueSize(valueType, EXPECTED_ENTRY_SIZE)); }

Target:
public SingleMultimapAggregationState(Type keyType, Type valueType) { this.keyType = requireNonNull(keyType); this.valueType = requireNonNull(valueType); keyBlockBuilder = keyType.createBlockBuilder(null, EXPECTED_ENTRIES, expectedValueSize(keyType, EXPECTED_ENTRY_SIZE)); valueBlockBuilder = valueType.createBlockBuilder(null, EXPECTED_ENTRIES, expectedValueSize(valueType, EXPECTED_ENTRY_SIZE)); }
Source:
public BlockBuilder nextColumn() { int currentChannel = channel; channel++; return pageBuilder.getBlockBuilder(currentChannel); }

Target:
private BlockBuilder nextColumn() { int currentChannel = channel; channel++; return pageBuilder.getBlockBuilder(currentChannel); }
Source:
private static long getGeometryMemorySize(OGCGeometry geometry) { if (geometry == null) { return 0; } else if (geometry.isEmpty()) { return OGC_GEOMETRY_BASE_INSTANCE_SIZE; } else { return geometry.estimateMemorySize(); } }

Target:
private static long getGeometryMemorySize(OGCGeometry geometry) { if (geometry == null) { return 0; } // Due to the following issue: // https://github.com/Esri/geometry-api-java/issues/192 // We must check if the geometry is empty before calculating its size. Once the issue is resolved // and we bring the fix into our codebase, we can remove this check. if (geometry.isEmpty()) { return OGC_GEOMETRY_BASE_INSTANCE_SIZE; } return geometry.estimateMemorySize(); }
Source:
public boolean isEnabled(Session session) { // we run this for cost-based reordering also for cases when some of the tables do not have statistics FeaturesConfig.JoinReorderingStrategy joinReorderingStrategy = getJoinReorderingStrategy(session); return joinReorderingStrategy == ELIMINATE_CROSS_JOINS || joinReorderingStrategy == COST_BASED; }

Target:
public boolean isEnabled(Session session) { // we run this for cost-based reordering also for cases when some of the tables do not have statistics JoinReorderingStrategy joinReorderingStrategy = getJoinReorderingStrategy(session); return joinReorderingStrategy == ELIMINATE_CROSS_JOINS || joinReorderingStrategy == COST_BASED; }
Source:
private static boolean isDeterminateConstant(RowExpression expression, MethodHandle isIndeterminateFunction) { if (!(expression instanceof ConstantExpression)) { return false; } ConstantExpression constantExpression = (ConstantExpression) expression; Object value = constantExpression.getValue(); boolean isNull = value == null; if (isNull) { return false; } try { return !(boolean) isIndeterminateFunction.invoke(value, isNull); } catch (Throwable t) { throwIfUnchecked(t); throw new RuntimeException(t); } }

Target:
private static boolean isDeterminateConstant(RowExpression expression, MethodHandle isIndeterminateFunction) { if (!(expression instanceof ConstantExpression)) { return false; } ConstantExpression constantExpression = (ConstantExpression) expression; Object value = constantExpression.getValue(); boolean isNull = value == null; if (isNull) { return false; } try { return !(boolean) isIndeterminateFunction.invoke(value, false); } catch (Throwable t) { throwIfUnchecked(t); throw new RuntimeException(t); } }
Source:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { return getSourceTable(tableName) .map(t -> (RaptorTableHandle) getTableHandle(t)) .map(handle -> new ColumnRangesSystemTable(handle, dbi)); }

Target:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { return getSourceTable(tableName) .map(this::getTableHandle) .map(handle -> new ColumnRangesSystemTable(handle, dbi)); }
Source:
public PathElement(Optional<NodeLocation> location, Optional<Identifier> catalog, Identifier schema) { super(location); this.catalog = requireNonNull(catalog, "catalog is null"); this.schema = requireNonNull(schema, "schema is null"); }

Target:
private PathElement(Optional<NodeLocation> location, Optional<Identifier> catalog, Identifier schema) { super(location); this.catalog = requireNonNull(catalog, "catalog is null"); this.schema = requireNonNull(schema, "schema is null"); }
Source:
public static List<SqlScalarFunction> parseFunctionDefinitions(Class<?> clazz) { ImmutableList.Builder<SqlScalarFunction> builder = ImmutableList.builder(); for (ScalarHeaderAndMethods methods : findScalarsInFunctionSetClass(clazz)) { // Non-static function only makes sense in classes annotated @ScalarFunction. builder.add(parseParametricScalar(methods, ImmutableMap.of())); } return builder.build(); }

Target:
public static List<SqlScalarFunction> parseFunctionDefinitions(Class<?> clazz) { ImmutableList.Builder<SqlScalarFunction> builder = ImmutableList.builder(); for (ScalarHeaderAndMethods methods : findScalarsInFunctionSetClass(clazz)) { // Non-static function only makes sense in classes annotated @ScalarFunction. builder.add(parseParametricScalar(methods, Optional.empty())); } return builder.build(); }
Source:
public static long stNumPoints(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return GeometryUtils.getPointCount(deserialize(input)); }

Target:
public static long stNumPoints(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return getPointCount(deserialize(input)); }
Source:
public ConnectorTableHandle beginDelete(ConnectorSession session, ConnectorTableHandle tableHandle) { KuduTableHandle kuduTableHandle = fromConnectorTableHandle(session, tableHandle); return kuduTableHandle; }

Target:
public ConnectorTableHandle beginDelete(ConnectorSession session, ConnectorTableHandle tableHandle) { return tableHandle; }
Source:
public boolean isFinished() { if (finished) { return true; } boolean finished = finishing && probe == null && pageBuilder.isEmpty() && outputPage == null; // if finished drop references so memory is freed early if (finished) { close(); } return finished; }

Target:
public boolean isFinished() { boolean finished = this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null; // if finished drop references so memory is freed early if (finished) { close(); } return finished; }
Source:
public static void main(String[] args) throws IOException, RunnerException { BenchmarkData data = new BenchmarkData(); data.setup(); data.validate(); Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .include(".*" + BenchmarkSTIntersects.class.getSimpleName() + ".*") .build(); new Runner(options).run(); }

Target:
public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .include(".*" + BenchmarkSTIntersects.class.getSimpleName() + ".*") .build(); new Runner(options).run(); }
Source:
public static void combine(HistogramState state, HistogramState otherState) { // NOTE: state = current merged state; otherState = scratchState (new data to be added) // since we have a single instance of a histogram, it will never be non-null. Even asking for a histogram that does not exist returns the histogram object. It doesn't // "exist" until we call add() on it,though requireNonNull(state.get() != null, "this.typedHistogram should always be non-null"); requireNonNull(otherState.get() != null, "scratch state should always be non-null"); TypedHistogram typedHistogram = state.get(); long startSize = typedHistogram.getEstimatedSize(); typedHistogram.addAll(otherState.get()); state.addMemoryUsage(typedHistogram.getEstimatedSize() - startSize); }

Target:
public static void combine(HistogramState state, HistogramState otherState) { // NOTE: state = current merged state; otherState = scratchState (new data to be added) // for grouped histograms and single histograms, we have a single histogram object. In neither case, can otherState.get() return null. // Semantically, a histogram object will be returned even if the group is empty. // In that case, the histogram object will represent an empty histogram until we call add() on // it. requireNonNull(otherState.get() != null, "scratch state should always be non-null"); TypedHistogram typedHistogram = state.get(); long startSize = typedHistogram.getEstimatedSize(); typedHistogram.addAll(otherState.get()); state.addMemoryUsage(typedHistogram.getEstimatedSize() - startSize); }
Source:
public void testShowTablesLikeWithEscape() { //Cassandra connector currently does not support create table, so here override MaterializedResult withEscape = computeActual("SHOW TABLES LIKE '%$_%' ESCAPE '$'"); assertThat(withEscape.getOnlyColumnAsSet()).allMatch(tableName -> ((String) tableName).contains("_")); }

Target:
public void testShowTablesLikeWithEscape() { // Cassandra connector currently does not support create table }
Source:
public void testShowTablesLikeWithEscape() { assertQueryFails("SHOW TABLES IN a LIKE '%$_%' ESCAPE", "line 1:36: no viable alternative at input '<EOF>'"); assertQueryFails("SHOW TABLES LIKE 't$_%' ESCAPE ''", "Escape string must be a single character"); assertQueryFails("SHOW TABLES LIKE 't$_%' ESCAPE '$$'", "Escape string must be a single character"); try { assertUpdate("CREATE TABLE test_escape_1 (a bigint)"); assertUpdate("CREATE TABLE test_escape11 (a bigint)"); } catch (RuntimeException e) { assertTrue(ImmutableSet.of("This connector does not support creating tables", "Unsupported statement type CreateTable") .contains(e.getMessage())); return; } assertQuery("SHOW TABLES LIKE 'test_escape_%'", "VALUES 'test_escape_1', 'test_escape11'"); assertQuery("SHOW TABLES LIKE 'test_escape\\_%' ESCAPE '\\'", "VALUES 'test_escape_1'"); assertUpdate("DROP TABLE test_escape_1"); assertUpdate("DROP TABLE test_escape11"); }

Target:
public void testShowTablesLikeWithEscape() { assertQueryFails("SHOW TABLES IN a LIKE '%$_%' ESCAPE", "line 1:36: no viable alternative at input '<EOF>'"); assertQueryFails("SHOW TABLES LIKE 't$_%' ESCAPE ''", "Escape string must be a single character"); assertQueryFails("SHOW TABLES LIKE 't$_%' ESCAPE '$$'", "Escape string must be a single character"); assertUpdate("CREATE TABLE test_escape_1 (a bigint)"); assertUpdate("CREATE TABLE test_escape11 (a bigint)"); assertQuery("SHOW TABLES LIKE 'test_escape_%'", "VALUES 'test_escape_1', 'test_escape11'"); assertQuery("SHOW TABLES LIKE 'test_escape\\_%' ESCAPE '\\'", "VALUES 'test_escape_1'"); assertUpdate("DROP TABLE test_escape_1"); assertUpdate("DROP TABLE test_escape11"); }
Source:
protected String getWarningMessage(PrestoWarning warning) { // If this is a real terminal color the warnings yellow return REAL_TERMINAL ? format("%sWARNING: %s%s", WARNING_BEGIN, warning.getMessage(), WARNING_END) : format("WARNING: %s", warning.getMessage()); }

Target:
private String getWarningMessage(PrestoWarning warning) { // If this is a real terminal color the warnings yellow if (REAL_TERMINAL) { return format("%sWARNING: %s%s", WARNING_BEGIN, warning.getMessage(), WARNING_END); } return format("WARNING: %s", warning.getMessage()); }
Source:
private static void assertStartsWithExpectedWarnings(SQLWarning warning, SQLWarning expected) { // Warnings generated with the testing warning collector may have more warnings than expected // due to getWarnings being called multiple times in the StatementClient implementation if (warning == null) { assertNull(expected); return; } assertNotNull(expected); while (true) { assertWarningsEqual(warning, expected); warning = warning.getNextWarning(); expected = expected.getNextWarning(); if (expected == null) { return; } else { assertNotNull(warning); } } }

Target:
private static void assertStartsWithExpectedWarnings(SQLWarning warning, SQLWarning expected) { assertNotNull(expected); assertNotNull(warning); while (true) { assertWarningsEqual(warning, expected); warning = warning.getNextWarning(); expected = expected.getNextWarning(); if (expected == null) { return; } assertNotNull(warning); } }
Source:
public void start() { DateTime now = DateTime.now(); executionStartTime.compareAndSet(null, now); startNanos.compareAndSet(0, System.nanoTime()); startFullGcCount.compareAndSet(0, gcMonitor.getMajorGcCount()); startFullGcTimeNanos.compareAndSet(0, gcMonitor.getMajorGcTime().roundTo(NANOSECONDS)); // always update last execution start time lastExecutionStartTime.set(now); }

Target:
public void start() { DateTime now = DateTime.now(); executionStartTime.compareAndSet(null, now); startNanos.compareAndSet(0, System.nanoTime()); startFullGcCount.compareAndSet(-1, gcMonitor.getMajorGcCount()); startFullGcTimeNanos.compareAndSet(-1, gcMonitor.getMajorGcTime().roundTo(NANOSECONDS)); // always update last execution start time lastExecutionStartTime.set(now); }
Source:
public void testValues() { assertQuery("VALUES 1, 2, 3, 4"); assertQuery("VALUES 1, 3, 2, 4 ORDER BY 1", "SELECT * FROM (VALUES 1, 3, 2, 4) ORDER BY 1"); assertQuery("VALUES (1.1, 2, 'foo'), (sin(3.3), 2+2, 'bar')"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) ORDER BY 1", "VALUES (sin(3.3), 2+2), (1.1, 2)"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) LIMIT 1", "VALUES (1.1, 2)"); assertQuery("SELECT * FROM (VALUES (1.1, 2), (sin(3.3), 2+2))"); assertQuery( "SELECT * FROM (VALUES (1.1, 2), (sin(3.3), 2+2)) x (a, b) LEFT JOIN (VALUES (1.1, 2), (1.1, 2+2)) y (a, b) USING (a)", "VALUES (1.1, 2, 4), (1.1, 2, 2), (sin(3.3), 4, NULL)"); assertQuery("SELECT 1.1 in (VALUES (1.1), (2.2))", "VALUES (TRUE)"); assertQuery("" + "WITH a AS (VALUES (1.1, 2), (sin(3.3), 2+2)) " + "SELECT * FROM a", "VALUES (1.1, 2), (sin(3.3), 2+2)"); // implicity coersions assertQuery("VALUES 1, 2.2, 3, 4.4"); assertQuery("VALUES (1, 2), (3.3, 4.4)"); assertQuery("VALUES true, 1.0 in (1, 2, 3)"); }

Target:
public void testValues() { assertQuery("VALUES 1, 2, 3, 4"); assertQuery("VALUES 1, 3, 2, 4 ORDER BY 1", "SELECT * FROM (VALUES 1, 3, 2, 4) ORDER BY 1"); assertQuery("VALUES (1.1, 2, 'foo'), (sin(3.3), 2+2, 'bar')"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) ORDER BY 1", "VALUES (sin(3.3), 2+2), (1.1, 2)"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) LIMIT 1", "VALUES (1.1, 2)"); assertQuery("SELECT * FROM (VALUES (1.1, 2), (sin(3.3), 2+2))"); assertQuery("SELECT 1.1 in (VALUES (1.1), (2.2))", "VALUES (TRUE)"); assertQuery("" + "WITH a AS (VALUES (1.1, 2), (sin(3.3), 2+2)) " + "SELECT * FROM a", "VALUES (1.1, 2), (sin(3.3), 2+2)"); // implicity coersions assertQuery("VALUES 1, 2.2, 3, 4.4"); assertQuery("VALUES (1, 2), (3.3, 4.4)"); assertQuery("VALUES true, 1.0 in (1, 2, 3)"); }
Source:
public StreamProperties visitSort(SortNode node, List<StreamProperties> inputProperties) { StreamProperties sourceProperties = Iterables.getOnlyElement(inputProperties); if (sourceProperties.isSingleStream()) { // stream is only sorted if sort operator is executed without parallelism return StreamProperties.ordered(); } else { return sourceProperties; } }

Target:
public StreamProperties visitSort(SortNode node, List<StreamProperties> inputProperties) { StreamProperties sourceProperties = Iterables.getOnlyElement(inputProperties); if (sourceProperties.isSingleStream()) { // stream is only sorted if sort operator is executed without parallelism return StreamProperties.ordered(); } return sourceProperties; }
Source:
public boolean isFinished() { boolean finished = (this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null) || isLookupSourceEmpty(); // if finished drop references so memory is freed early if (finished) { close(); } return finished; }

Target:
public boolean isFinished() { boolean finished = this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null; // if finished drop references so memory is freed early if (finished) { close(); } return finished; }
Source:
public Work<?> addPage(Page page) { // Just add the page to the pending work, which will be processed later. Work<?> work = hash.addPage(page); return work; }

Target:
public Work<?> addPage(Page page) { // Just add the page to the pending work, which will be processed later. return hash.addPage(page); }
Source:
public boolean needsInput() { // Since SetBuilderOperator doesn't produce any output, the getOutput() // method may never be called. We need to handle any unfinished work // before addInput() can be called again. if (unfinishedWork.isPresent() && !processUnfinishedWork()) { return false; } return !finished; }

Target:
public boolean needsInput() { // Since SetBuilderOperator doesn't produce any output, the getOutput() // method may never be called. We need to handle any unfinished work // before addInput() can be called again. return !finished && (unfinishedWork == null || processUnfinishedWork()); }
Source:
protected static ReadMapping dateReadMapping() { return longReadMapping(DATE, (resultSet, columnIndex) -> { // JDBC returns a date using a timestamp at midnight in the JVM timezone long localMillis = resultSet.getDate(columnIndex).getTime(); // Convert it to a midnight in UTC long utcMillis = ISOChronology.getInstance().getZone().getMillisKeepLocal(UTC, localMillis); // convert to days return MILLISECONDS.toDays(utcMillis); }); }

Target:
public static ReadMapping dateReadMapping() { return longReadMapping(DATE, (resultSet, columnIndex) -> { // JDBC returns a date using a timestamp at midnight in the JVM timezone long localMillis = resultSet.getDate(columnIndex).getTime(); // Convert it to a midnight in UTC long utcMillis = ISOChronology.getInstance().getZone().getMillisKeepLocal(UTC, localMillis); // convert to days return MILLISECONDS.toDays(utcMillis); }); }
Source:
public synchronized ListenableFuture<?> updateUserMemory(long delta) { if (delta >= 0) { if (queryMemoryContext.getUserMemory() + delta > maxMemory) { throw exceededLocalLimit(succinctBytes(maxMemory)); } return memoryPool.reserve(queryId, delta); } memoryPool.free(queryId, -delta); return NOT_BLOCKED; }

Target:
private synchronized ListenableFuture<?> updateUserMemory(long delta) { if (delta >= 0) { if (queryMemoryContext.getUserMemory() + delta > maxMemory) { throw exceededLocalLimit(succinctBytes(maxMemory)); } return memoryPool.reserve(queryId, delta); } memoryPool.free(queryId, -delta); return NOT_BLOCKED; }
Source:
public static Slice succinctDuration(@SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.VARCHAR) Slice unit) { try { Duration duration = Duration.succinctDuration(value, valueOfTimeUnit(unit.toStringUtf8())); return utf8Slice(duration.toString()); } catch (IllegalArgumentException e) { // When value is negative, NaN, etc. throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } }

Target:
public static Slice succinctDuration(@SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.VARCHAR) Slice unit) { Duration duration; try { duration = Duration.succinctDuration(value, valueOfTimeUnit(unit.toStringUtf8())); } catch (IllegalArgumentException e) { // When value is negative, NaN, etc. throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } return utf8Slice(duration.toString()); }
Source:
public void initialize() { if (initialized.compareAndSet(false, true)) { taskStateMachine.addStateChangeListener(newState -> { if (newState.isDone()) { executionEndTime.set(DateTime.now()); endNanos.set(System.nanoTime()); } }); } }

Target:
private void initialize() { taskStateMachine.addStateChangeListener(newState -> { if (newState.isDone()) { executionEndTime.set(DateTime.now()); endNanos.set(System.nanoTime()); } }); }