text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;

namespace MagicOnion.Generator.Tests
{
    public class GenerateEnumFormatterTest
    {
        private readonly ITestOutputHelper _testOutputHelper;

        public GenerateEnumFormatterTest(ITestOutputHelper testOutputHelper)
        {
            _testOutputHelper = testOutputHelper;
        }

        [Fact]
        public async Task GenerateEnumFormatter_Return()
        {
            using var tempWorkspace = TemporaryProjectWorkarea.Create();
            tempWorkspace.AddFileToProject("IMyService.cs", @"
using System;
using MessagePack;
using MagicOnion;

namespace TempProject
{
    public interface IMyService : IService<IMyService>
    {
        UnaryResult<MyEnum> GetEnumAsync();
    }

    public enum MyEnum
    {
        A, B, C
    }
}
            ");

            var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None);
            await compiler.GenerateFileAsync(
                tempWorkspace.CsProjectPath,
                tempWorkspace.OutputDirectory,
                true,
                "TempProject.Generated",
                "",
                "MessagePack.Formatters"
            );

            var compilation = tempWorkspace.GetOutputCompilation();
            compilation.GetCompilationErrors().Should().BeEmpty();
            var symbols = compilation.GetNamedTypeSymbolsFromGenerated();
            symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter"));
        }

        [Fact]
        public async Task GenerateEnumFormatter_Return_Nullable()
        {
            using var tempWorkspace = TemporaryProjectWorkarea.Create();
            tempWorkspace.AddFileToProject("IMyService.cs", @"
using System;
using MessagePack;
using MagicOnion;

namespace TempProject
{
    public interface IMyService : IService<IMyService>
    {
        UnaryResult<MyEnum?> GetEnumAsync();
    }

    public enum MyEnum
    {
        A, B, C
    }
}
            ");

            var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None);
            await compiler.GenerateFileAsync(
                tempWorkspace.CsProjectPath,
                tempWorkspace.OutputDirectory,
                true,
                "TempProject.Generated",
                "",
                "MessagePack.Formatters"
            );

            var compilation = tempWorkspace.GetOutputCompilation();
            compilation.GetCompilationErrors().Should().BeEmpty();
            var symbols = compilation.GetNamedTypeSymbolsFromGenerated();
            symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter"));
        }

        [Fact]
        public async Task GenerateEnumFormatter_Parameter()
        {
            using var tempWorkspace = TemporaryProjectWorkarea.Create();
            tempWorkspace.AddFileToProject("IMyService.cs", @"
using System;
using MessagePack;
using MagicOnion;

namespace TempProject
{
    public interface IMyService : IService<IMyService>
    {
        UnaryResult<Nil> GetEnumAsync(MyEnum a);
    }

    public enum MyEnum
    {
        A, B, C
    }
}
            ");

            var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None);
            await compiler.GenerateFileAsync(
                tempWorkspace.CsProjectPath,
                tempWorkspace.OutputDirectory,
                true,
                "TempProject.Generated",
                "",
                "MessagePack.Formatters"
            );

            var compilation = tempWorkspace.GetOutputCompilation();
            compilation.GetCompilationErrors().Should().BeEmpty();
            var symbols = compilation.GetNamedTypeSymbolsFromGenerated();
            symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter"));
        }

        [Fact]
        public async Task GenerateEnumFormatter_Parameter_Nullable()
        {
            using var tempWorkspace = TemporaryProjectWorkarea.Create();
            tempWorkspace.AddFileToProject("IMyService.cs", @"
using System;
using MessagePack;
using MagicOnion;

namespace TempProject
{
    public interface IMyService : IService<IMyService>
    {
        UnaryResult<Nil> GetEnumAsync(MyEnum? a);
    }

    public enum MyEnum
    {
        A, B, C
    }
}
            ");

            var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None);
            await compiler.GenerateFileAsync(
                tempWorkspace.CsProjectPath,
                tempWorkspace.OutputDirectory,
                true,
                "TempProject.Generated",
                "",
                "MessagePack.Formatters"
            );

            var compilation = tempWorkspace.GetOutputCompilation();
            compilation.GetCompilationErrors().Should().BeEmpty();
            var symbols = compilation.GetNamedTypeSymbolsFromGenerated();
            symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter"));
        }
    }
}


text:
package com.flashmathdev.util;

import java.io.ByteArrayOutputStream;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;

public class ImageUtility {

	public static Uri getImageUri(Context inContext, Bitmap inImage) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
		String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
		return Uri.parse(path);
	}

	public static String getRealPathFromURI(Uri uri, Context context) {
	    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
	    cursor.moveToFirst();
	    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
	    return cursor.getString(idx);
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.mysql;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.mysql.cj.jdbc.JdbcStatement;
import io.airlift.json.JsonCodec;
import io.airlift.log.Logger;
import io.trino.plugin.base.aggregation.AggregateFunctionRewriter;
import io.trino.plugin.base.aggregation.AggregateFunctionRule;
import io.trino.plugin.base.expression.ConnectorExpressionRewriter;
import io.trino.plugin.jdbc.BaseJdbcClient;
import io.trino.plugin.jdbc.BaseJdbcConfig;
import io.trino.plugin.jdbc.ColumnMapping;
import io.trino.plugin.jdbc.ConnectionFactory;
import io.trino.plugin.jdbc.JdbcColumnHandle;
import io.trino.plugin.jdbc.JdbcExpression;
import io.trino.plugin.jdbc.JdbcJoinCondition;
import io.trino.plugin.jdbc.JdbcSortItem;
import io.trino.plugin.jdbc.JdbcStatisticsConfig;
import io.trino.plugin.jdbc.JdbcTableHandle;
import io.trino.plugin.jdbc.JdbcTypeHandle;
import io.trino.plugin.jdbc.PreparedQuery;
import io.trino.plugin.jdbc.QueryBuilder;
import io.trino.plugin.jdbc.RemoteTableName;
import io.trino.plugin.jdbc.WriteMapping;
import io.trino.plugin.jdbc.aggregation.ImplementAvgDecimal;
import io.trino.plugin.jdbc.aggregation.ImplementAvgFloatingPoint;
import io.trino.plugin.jdbc.aggregation.ImplementCount;
import io.trino.plugin.jdbc.aggregation.ImplementCountAll;
import io.trino.plugin.jdbc.aggregation.ImplementMinMax;
import io.trino.plugin.jdbc.aggregation.ImplementStddevPop;
import io.trino.plugin.jdbc.aggregation.ImplementStddevSamp;
import io.trino.plugin.jdbc.aggregation.ImplementSum;
import io.trino.plugin.jdbc.aggregation.ImplementVariancePop;
import io.trino.plugin.jdbc.aggregation.ImplementVarianceSamp;
import io.trino.plugin.jdbc.expression.JdbcConnectorExpressionRewriterBuilder;
import io.trino.plugin.jdbc.mapping.IdentifierMapping;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.AggregateFunction;
import io.trino.spi.connector.ColumnHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.JoinCondition;
import io.trino.spi.connector.JoinStatistics;
import io.trino.spi.connector.JoinType;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ColumnStatistics;
import io.trino.spi.statistics.Estimate;
import io.trino.spi.statistics.TableStatistics;
import io.trino.spi.type.CharType;
import io.trino.spi.type.DecimalType;
import io.trino.spi.type.Decimals;
import io.trino.spi.type.StandardTypes;
import io.trino.spi.type.TimeType;
import io.trino.spi.type.TimestampType;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeManager;
import io.trino.spi.type.TypeSignature;
import io.trino.spi.type.VarcharType;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.UnableToExecuteStatementException;

import javax.inject.Inject;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Types;
import java.util.AbstractMap.SimpleEntry;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Stream;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.base.Throwables.throwIfInstanceOf;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.mysql.cj.exceptions.MysqlErrorNumbers.ER_UNKNOWN_TABLE;
import static com.mysql.cj.exceptions.MysqlErrorNumbers.SQL_STATE_ER_TABLE_EXISTS_ERROR;
import static com.mysql.cj.exceptions.MysqlErrorNumbers.SQL_STATE_SYNTAX_ERROR;
import static io.airlift.json.JsonCodec.jsonCodec;
import static io.airlift.slice.Slices.utf8Slice;
import static io.trino.plugin.base.util.JsonTypeUtil.jsonParse;
import static io.trino.plugin.jdbc.DecimalConfig.DecimalMapping.ALLOW_OVERFLOW;
import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalDefaultScale;
import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRounding;
import static io.trino.plugin.jdbc.DecimalSessionSessionProperties.getDecimalRoundingMode;
import static io.trino.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
import static io.trino.plugin.jdbc.JdbcJoinPushdownUtil.implementJoinCostAware;
import static io.trino.plugin.jdbc.PredicatePushdownController.DISABLE_PUSHDOWN;
import static io.trino.plugin.jdbc.PredicatePushdownController.FULL_PUSHDOWN;
import static io.trino.plugin.jdbc.StandardColumnMappings.bigintColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.bigintWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.booleanColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.booleanWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.charWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.dateColumnMappingUsingLocalDate;
import static io.trino.plugin.jdbc.StandardColumnMappings.dateWriteFunctionUsingLocalDate;
import static io.trino.plugin.jdbc.StandardColumnMappings.decimalColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.defaultCharColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.defaultVarcharColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.doubleColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.doubleWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.integerColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.integerWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.longDecimalWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.longTimestampWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.realWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.shortDecimalWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.smallintColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.smallintWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.timeColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.timeWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.timestampColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.timestampWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintColumnMapping;
import static io.trino.plugin.jdbc.StandardColumnMappings.tinyintWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryReadFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.varbinaryWriteFunction;
import static io.trino.plugin.jdbc.StandardColumnMappings.varcharWriteFunction;
import static io.trino.plugin.jdbc.TypeHandlingJdbcSessionProperties.getUnsupportedTypeHandling;
import static io.trino.plugin.jdbc.UnsupportedTypeHandling.CONVERT_TO_VARCHAR;
import static io.trino.spi.StandardErrorCode.ALREADY_EXISTS;
import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DateType.DATE;
import static io.trino.spi.type.DecimalType.createDecimalType;
import static io.trino.spi.type.DoubleType.DOUBLE;
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.RealType.REAL;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TimeType.createTimeType;
import static io.trino.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static io.trino.spi.type.TimestampType.createTimestampType;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.TinyintType.TINYINT;
import static io.trino.spi.type.VarbinaryType.VARBINARY;
import static java.lang.Float.floatToRawIntBits;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.lang.String.join;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;

public class MySqlClient
        extends BaseJdbcClient
{
    private static final Logger log = Logger.get(MySqlClient.class);

    private static final int MAX_SUPPORTED_DATE_TIME_PRECISION = 6;
    // MySQL driver returns width of timestamp types instead of precision.
    // 19 characters are used for zero-precision timestamps while others
    // require 19 + precision + 1 characters with the additional character
    // required for the decimal separator.
    private static final int ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE = 19;
    // MySQL driver returns width of time types instead of precision, same as the above timestamp type.
    private static final int ZERO_PRECISION_TIME_COLUMN_SIZE = 8;

    // An empty character means that the table doesn't have a comment in MySQL
    private static final String NO_COMMENT = "";

    private static final JsonCodec<ColumnHistogram> HISTOGRAM_CODEC = jsonCodec(ColumnHistogram.class);

    // We don't know null fraction, but having no null fraction will make CBO useless. Assume some arbitrary value.
    private static final Estimate UNKNOWN_NULL_FRACTION_REPLACEMENT = Estimate.of(0.1);

    private final Type jsonType;
    private final boolean statisticsEnabled;
    private final ConnectorExpressionRewriter<String> connectorExpressionRewriter;
    private final AggregateFunctionRewriter<JdbcExpression, String> aggregateFunctionRewriter;

    @Inject
    public MySqlClient(
            BaseJdbcConfig config,
            JdbcStatisticsConfig statisticsConfig,
            ConnectionFactory connectionFactory,
            QueryBuilder queryBuilder,
            TypeManager typeManager,
            IdentifierMapping identifierMapping)
    {
        super(config, "`", connectionFactory, queryBuilder, identifierMapping);
        this.jsonType = typeManager.getType(new TypeSignature(StandardTypes.JSON));
        this.statisticsEnabled = statisticsConfig.isEnabled();

        this.connectorExpressionRewriter = JdbcConnectorExpressionRewriterBuilder.newBuilder()
                .addStandardRules(this::quoted)
                .build();

        JdbcTypeHandle bigintTypeHandle = new JdbcTypeHandle(Types.BIGINT, Optional.of("bigint"), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
        this.aggregateFunctionRewriter = new AggregateFunctionRewriter<>(
                this.connectorExpressionRewriter,
                ImmutableSet.<AggregateFunctionRule<JdbcExpression, String>>builder()
                        .add(new ImplementCountAll(bigintTypeHandle))
                        .add(new ImplementCount(bigintTypeHandle))
                        .add(new ImplementMinMax(false))
                        .add(new ImplementSum(MySqlClient::toTypeHandle))
                        .add(new ImplementAvgFloatingPoint())
                        .add(new ImplementAvgDecimal())
                        .add(new ImplementAvgBigint())
                        .add(new ImplementStddevSamp())
                        .add(new ImplementStddevPop())
                        .add(new ImplementVarianceSamp())
                        .add(new ImplementVariancePop())
                        .build());
    }

    @Override
    public Optional<JdbcExpression> implementAggregation(ConnectorSession session, AggregateFunction aggregate, Map<String, ColumnHandle> assignments)
    {
        // TODO support complex ConnectorExpressions
        return aggregateFunctionRewriter.rewrite(session, aggregate, assignments);
    }

    @Override
    public boolean supportsAggregationPushdown(ConnectorSession session, JdbcTableHandle table, List<AggregateFunction> aggregates, Map<String, ColumnHandle> assignments, List<List<ColumnHandle>> groupingSets)
    {
        // Remote database can be case insensitive.
        return preventTextualTypeAggregationPushdown(groupingSets);
    }

    private static Optional<JdbcTypeHandle> toTypeHandle(DecimalType decimalType)
    {
        return Optional.of(new JdbcTypeHandle(Types.NUMERIC, Optional.of("decimal"), Optional.of(decimalType.getPrecision()), Optional.of(decimalType.getScale()), Optional.empty(), Optional.empty()));
    }

    @Override
    public Collection<String> listSchemas(Connection connection)
    {
        // for MySQL, we need to list catalogs instead of schemas
        try (ResultSet resultSet = connection.getMetaData().getCatalogs()) {
            ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder();
            while (resultSet.next()) {
                String schemaName = resultSet.getString("TABLE_CAT");
                // skip internal schemas
                if (filterSchema(schemaName)) {
                    schemaNames.add(schemaName);
                }
            }
            return schemaNames.build();
        }
        catch (SQLException e) {
            throw new TrinoException(JDBC_ERROR, e);
        }
    }

    @Override
    protected boolean filterSchema(String schemaName)
    {
        if (schemaName.equalsIgnoreCase("mysql")
                || schemaName.equalsIgnoreCase("sys")) {
            return false;
        }
        return super.filterSchema(schemaName);
    }

    @Override
    public void abortReadConnection(Connection connection, ResultSet resultSet)
            throws SQLException
    {
        if (!resultSet.isAfterLast()) {
            // Abort connection before closing. Without this, the MySQL driver
            // attempts to drain the connection by reading all the results.
            connection.abort(directExecutor());
        }
    }

    @Override
    public PreparedStatement getPreparedStatement(Connection connection, String sql)
            throws SQLException
    {
        PreparedStatement statement = connection.prepareStatement(sql);
        if (statement.isWrapperFor(JdbcStatement.class)) {
            statement.unwrap(JdbcStatement.class).enableStreamingResults();
        }
        return statement;
    }

    @Override
    public ResultSet getTables(Connection connection, Optional<String> schemaName, Optional<String> tableName)
            throws SQLException
    {
        // MySQL maps their "database" to SQL catalogs and does not have schemas
        DatabaseMetaData metadata = connection.getMetaData();
        return metadata.getTables(
                schemaName.orElse(null),
                null,
                escapeNamePattern(tableName, metadata.getSearchStringEscape()).orElse(null),
                getTableTypes().map(types -> types.toArray(String[]::new)).orElse(null));
    }

    @Override
    public Optional<String> getTableComment(ResultSet resultSet)
            throws SQLException
    {
        // Empty remarks means that the table doesn't have a comment in MySQL
        return Optional.ofNullable(emptyToNull(resultSet.getString("REMARKS")));
    }

    @Override
    public void setTableComment(ConnectorSession session, JdbcTableHandle handle, Optional<String> comment)
    {
        String sql = format(
                "ALTER TABLE %s COMMENT = %s",
                quoted(handle.asPlainTable().getRemoteTableName()),
                mysqlVarcharLiteral(comment.orElse(NO_COMMENT))); // An empty character removes the existing comment in MySQL
        execute(session, sql);
    }

    @Override
    protected String getTableSchemaName(ResultSet resultSet)
            throws SQLException
    {
        // MySQL uses catalogs instead of schemas
        return resultSet.getString("TABLE_CAT");
    }

    @Override
    protected String createTableSql(RemoteTableName remoteTableName, List<String> columns, ConnectorTableMetadata tableMetadata)
    {
        checkArgument(tableMetadata.getProperties().isEmpty(), "Unsupported table properties: %s", tableMetadata.getProperties());
        return format("CREATE TABLE %s (%s) COMMENT %s", quoted(remoteTableName), join(", ", columns), mysqlVarcharLiteral(tableMetadata.getComment().orElse(NO_COMMENT)));
    }

    private static String mysqlVarcharLiteral(String value)
    {
        requireNonNull(value, "value is null");
        return "'" + value.replace("'", "''").replace("\\", "\\\\") + "'";
    }

    @Override
    public Optional<ColumnMapping> toColumnMapping(ConnectorSession session, Connection connection, JdbcTypeHandle typeHandle)
    {
        String jdbcTypeName = typeHandle.getJdbcTypeName()
                .orElseThrow(() -> new TrinoException(JDBC_ERROR, "Type name is missing: " + typeHandle));

        Optional<ColumnMapping> mapping = getForcedMappingToVarchar(typeHandle);
        if (mapping.isPresent()) {
            return mapping;
        }

        switch (jdbcTypeName.toLowerCase(ENGLISH)) {
            case "tinyint unsigned":
                return Optional.of(smallintColumnMapping());
            case "smallint unsigned":
                return Optional.of(integerColumnMapping());
            case "int unsigned":
                return Optional.of(bigintColumnMapping());
            case "bigint unsigned":
                return Optional.of(decimalColumnMapping(createDecimalType(20)));
            case "json":
                return Optional.of(jsonColumnMapping());
            case "enum":
                return Optional.of(defaultVarcharColumnMapping(typeHandle.getRequiredColumnSize(), false));
        }

        switch (typeHandle.getJdbcType()) {
            case Types.BIT:
                return Optional.of(booleanColumnMapping());

            case Types.TINYINT:
                return Optional.of(tinyintColumnMapping());

            case Types.SMALLINT:
                return Optional.of(smallintColumnMapping());

            case Types.INTEGER:
                return Optional.of(integerColumnMapping());

            case Types.BIGINT:
                return Optional.of(bigintColumnMapping());

            case Types.REAL:
                // Disable pushdown because floating-point values are approximate and not stored as exact values,
                // attempts to treat them as exact in comparisons may lead to problems
                return Optional.of(ColumnMapping.longMapping(
                        REAL,
                        (resultSet, columnIndex) -> floatToRawIntBits(resultSet.getFloat(columnIndex)),
                        realWriteFunction(),
                        DISABLE_PUSHDOWN));

            case Types.DOUBLE:
                return Optional.of(doubleColumnMapping());

            case Types.NUMERIC:
            case Types.DECIMAL:
                int decimalDigits = typeHandle.getDecimalDigits().orElseThrow(() -> new IllegalStateException("decimal digits not present"));
                int precision = typeHandle.getRequiredColumnSize();
                if (getDecimalRounding(session) == ALLOW_OVERFLOW && precision > Decimals.MAX_PRECISION) {
                    int scale = min(decimalDigits, getDecimalDefaultScale(session));
                    return Optional.of(decimalColumnMapping(createDecimalType(Decimals.MAX_PRECISION, scale), getDecimalRoundingMode(session)));
                }
                // TODO does mysql support negative scale?
                precision = precision + max(-decimalDigits, 0); // Map decimal(p, -s) (negative scale) to decimal(p+s, 0).
                if (precision > Decimals.MAX_PRECISION) {
                    break;
                }
                return Optional.of(decimalColumnMapping(createDecimalType(precision, max(decimalDigits, 0))));

            case Types.CHAR:
                return Optional.of(defaultCharColumnMapping(typeHandle.getRequiredColumnSize(), false));

            // TODO not all these type constants are necessarily used by the JDBC driver
            case Types.VARCHAR:
            case Types.NVARCHAR:
            case Types.LONGVARCHAR:
            case Types.LONGNVARCHAR:
                return Optional.of(defaultVarcharColumnMapping(typeHandle.getRequiredColumnSize(), false));

            case Types.BINARY:
            case Types.VARBINARY:
            case Types.LONGVARBINARY:
                return Optional.of(ColumnMapping.sliceMapping(VARBINARY, varbinaryReadFunction(), varbinaryWriteFunction(), FULL_PUSHDOWN));

            case Types.DATE:
                return Optional.of(dateColumnMappingUsingLocalDate());

            case Types.TIME:
                TimeType timeType = createTimeType(getTimePrecision(typeHandle.getRequiredColumnSize()));
                return Optional.of(timeColumnMapping(timeType));

            case Types.TIMESTAMP:
                TimestampType timestampType = createTimestampType(getTimestampPrecision(typeHandle.getRequiredColumnSize()));
                return Optional.of(timestampColumnMapping(timestampType));
        }

        if (getUnsupportedTypeHandling(session) == CONVERT_TO_VARCHAR) {
            return mapToUnboundedVarchar(typeHandle);
        }
        return Optional.empty();
    }

    private static int getTimestampPrecision(int timestampColumnSize)
    {
        if (timestampColumnSize == ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE) {
            return 0;
        }
        int timestampPrecision = timestampColumnSize - ZERO_PRECISION_TIMESTAMP_COLUMN_SIZE - 1;
        verify(1 <= timestampPrecision && timestampPrecision <= MAX_SUPPORTED_DATE_TIME_PRECISION, "Unexpected timestamp precision %s calculated from timestamp column size %s", timestampPrecision, timestampColumnSize);
        return timestampPrecision;
    }

    private static int getTimePrecision(int timeColumnSize)
    {
        if (timeColumnSize == ZERO_PRECISION_TIME_COLUMN_SIZE) {
            return 0;
        }
        int timePrecision = timeColumnSize - ZERO_PRECISION_TIME_COLUMN_SIZE - 1;
        verify(1 <= timePrecision && timePrecision <= MAX_SUPPORTED_DATE_TIME_PRECISION, "Unexpected time precision %s calculated from time column size %s", timePrecision, timeColumnSize);
        return timePrecision;
    }

    @Override
    public WriteMapping toWriteMapping(ConnectorSession session, Type type)
    {
        if (type == BOOLEAN) {
            return WriteMapping.booleanMapping("boolean", booleanWriteFunction());
        }
        if (type == TINYINT) {
            return WriteMapping.longMapping("tinyint", tinyintWriteFunction());
        }
        if (type == SMALLINT) {
            return WriteMapping.longMapping("smallint", smallintWriteFunction());
        }
        if (type == INTEGER) {
            return WriteMapping.longMapping("integer", integerWriteFunction());
        }
        if (type == BIGINT) {
            return WriteMapping.longMapping("bigint", bigintWriteFunction());
        }
        if (type == REAL) {
            return WriteMapping.longMapping("float", realWriteFunction());
        }
        if (type == DOUBLE) {
            return WriteMapping.doubleMapping("double precision", doubleWriteFunction());
        }

        if (type instanceof DecimalType decimalType) {
            String dataType = format("decimal(%s, %s)", decimalType.getPrecision(), decimalType.getScale());
            if (decimalType.isShort()) {
                return WriteMapping.longMapping(dataType, shortDecimalWriteFunction(decimalType));
            }
            return WriteMapping.objectMapping(dataType, longDecimalWriteFunction(decimalType));
        }

        if (type == DATE) {
            return WriteMapping.longMapping("date", dateWriteFunctionUsingLocalDate());
        }

        if (type instanceof TimeType timeType) {
            if (timeType.getPrecision() <= MAX_SUPPORTED_DATE_TIME_PRECISION) {
                return WriteMapping.longMapping(format("time(%s)", timeType.getPrecision()), timeWriteFunction(timeType.getPrecision()));
            }
            return WriteMapping.longMapping(format("time(%s)", MAX_SUPPORTED_DATE_TIME_PRECISION), timeWriteFunction(MAX_SUPPORTED_DATE_TIME_PRECISION));
        }

        if (TIME_WITH_TIME_ZONE.equals(type) || TIMESTAMP_TZ_MILLIS.equals(type)) {
            throw new TrinoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName());
        }

        if (type instanceof TimestampType timestampType) {
            if (timestampType.getPrecision() <= MAX_SUPPORTED_DATE_TIME_PRECISION) {
                verify(timestampType.getPrecision() <= TimestampType.MAX_SHORT_PRECISION);
                return WriteMapping.longMapping(format("datetime(%s)", timestampType.getPrecision()), timestampWriteFunction(timestampType));
            }
            return WriteMapping.objectMapping(format("datetime(%s)", MAX_SUPPORTED_DATE_TIME_PRECISION), longTimestampWriteFunction(timestampType, MAX_SUPPORTED_DATE_TIME_PRECISION));
        }

        if (VARBINARY.equals(type)) {
            return WriteMapping.sliceMapping("mediumblob", varbinaryWriteFunction());
        }

        if (type instanceof CharType charType) {
            return WriteMapping.sliceMapping("char(" + charType.getLength() + ")", charWriteFunction());
        }

        if (type instanceof VarcharType varcharType) {
            String dataType;
            if (varcharType.isUnbounded()) {
                dataType = "longtext";
            }
            else if (varcharType.getBoundedLength() <= 255) {
                dataType = "tinytext";
            }
            else if (varcharType.getBoundedLength() <= 65535) {
                dataType = "text";
            }
            else if (varcharType.getBoundedLength() <= 16777215) {
                dataType = "mediumtext";
            }
            else {
                dataType = "longtext";
            }
            return WriteMapping.sliceMapping(dataType, varcharWriteFunction());
        }

        if (type.equals(jsonType)) {
            return WriteMapping.sliceMapping("json", varcharWriteFunction());
        }

        throw new TrinoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName());
    }

    @Override
    public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata)
    {
        try {
            createTable(session, tableMetadata, tableMetadata.getTable().getTableName());
        }
        catch (SQLException e) {
            boolean exists = SQL_STATE_ER_TABLE_EXISTS_ERROR.equals(e.getSQLState());
            throw new TrinoException(exists ? ALREADY_EXISTS : JDBC_ERROR, e);
        }
    }

    @Override
    public void renameColumn(ConnectorSession session, JdbcTableHandle handle, JdbcColumnHandle jdbcColumn, String newColumnName)
    {
        try (Connection connection = connectionFactory.openConnection(session)) {
            String newRemoteColumnName = getIdentifierMapping().toRemoteColumnName(connection, newColumnName);
            RemoteTableName remoteTableName = handle.asPlainTable().getRemoteTableName();
            String sql = format(
                    "ALTER TABLE %s RENAME COLUMN %s TO %s",
                    quoted(remoteTableName.getCatalogName().orElse(null), remoteTableName.getSchemaName().orElse(null), remoteTableName.getTableName()),
                    quoted(jdbcColumn.getColumnName()),
                    quoted(newRemoteColumnName));
            execute(connection, sql);
        }
        catch (SQLException e) {
            // MySQL versions earlier than 8 do not support the above RENAME COLUMN syntax
            if (SQL_STATE_SYNTAX_ERROR.equals(e.getSQLState())) {
                throw new TrinoException(NOT_SUPPORTED, format("Rename column not supported in catalog: '%s'", handle.asPlainTable().getRemoteTableName().getCatalogName().orElse(null)), e);
            }
            throw new TrinoException(JDBC_ERROR, e);
        }
    }

    @Override
    public void renameSchema(ConnectorSession session, String schemaName, String newSchemaName)
    {
        throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming schemas");
    }

    @Override
    protected void copyTableSchema(Connection connection, String catalogName, String schemaName, String tableName, String newTableName, List<String> columnNames)
    {
        String tableCopyFormat = "CREATE TABLE %s AS SELECT * FROM %s WHERE 0 = 1";
        if (isGtidMode(connection)) {
            tableCopyFormat = "CREATE TABLE %s LIKE %s";
        }
        String sql = format(
                tableCopyFormat,
                quoted(catalogName, schemaName, newTableName),
                quoted(catalogName, schemaName, tableName));
        execute(connection, sql);
    }

    @Override
    public void renameTable(ConnectorSession session, JdbcTableHandle handle, SchemaTableName newTableName)
    {
        // MySQL doesn't support specifying the catalog name in a rename. By setting the
        // catalogName parameter to null, it will be omitted in the ALTER TABLE statement.
        RemoteTableName remoteTableName = handle.asPlainTable().getRemoteTableName();
        verify(remoteTableName.getSchemaName().isEmpty());
        renameTable(session, null, remoteTableName.getCatalogName().orElse(null), remoteTableName.getTableName(), newTableName);
    }

    @Override
    protected Optional<BiFunction<String, Long, String>> limitFunction()
    {
        return Optional.of((sql, limit) -> sql + " LIMIT " + limit);
    }

    @Override
    public boolean isLimitGuaranteed(ConnectorSession session)
    {
        return true;
    }

    @Override
    public boolean supportsTopN(ConnectorSession session, JdbcTableHandle handle, List<JdbcSortItem> sortOrder)
    {
        for (JdbcSortItem sortItem : sortOrder) {
            Type sortItemType = sortItem.getColumn().getColumnType();
            if (sortItemType instanceof CharType || sortItemType instanceof VarcharType) {
                // Remote database can be case insensitive.
                return false;
            }
        }
        return true;
    }

    @Override
    protected Optional<TopNFunction> topNFunction()
    {
        return Optional.of((query, sortItems, limit) -> {
            String orderBy = sortItems.stream()
                    .flatMap(sortItem -> {
                        String ordering = sortItem.getSortOrder().isAscending() ? "ASC" : "DESC";
                        String columnSorting = format("%s %s", quoted(sortItem.getColumn().getColumnName()), ordering);

                        switch (sortItem.getSortOrder()) {
                            case ASC_NULLS_FIRST:
                                // In MySQL ASC implies NULLS FIRST
                            case DESC_NULLS_LAST:
                                // In MySQL DESC implies NULLS LAST
                                return Stream.of(columnSorting);

                            case ASC_NULLS_LAST:
                                return Stream.of(
                                        format("ISNULL(%s) ASC", quoted(sortItem.getColumn().getColumnName())),
                                        columnSorting);
                            case DESC_NULLS_FIRST:
                                return Stream.of(
                                        format("ISNULL(%s) DESC", quoted(sortItem.getColumn().getColumnName())),
                                        columnSorting);
                        }
                        throw new UnsupportedOperationException("Unsupported sort order: " + sortItem.getSortOrder());
                    })
                    .collect(joining(", "));
            return format("%s ORDER BY %s LIMIT %s", query, orderBy, limit);
        });
    }

    @Override
    public boolean isTopNGuaranteed(ConnectorSession session)
    {
        return true;
    }

    @Override
    public Optional<PreparedQuery> implementJoin(
            ConnectorSession session,
            JoinType joinType,
            PreparedQuery leftSource,
            PreparedQuery rightSource,
            List<JdbcJoinCondition> joinConditions,
            Map<JdbcColumnHandle, String> rightAssignments,
            Map<JdbcColumnHandle, String> leftAssignments,
            JoinStatistics statistics)
    {
        if (joinType == JoinType.FULL_OUTER) {
            // Not supported in MySQL
            return Optional.empty();
        }
        return implementJoinCostAware(
                session,
                joinType,
                leftSource,
                rightSource,
                statistics,
                () -> super.implementJoin(session, joinType, leftSource, rightSource, joinConditions, rightAssignments, leftAssignments, statistics));
    }

    @Override
    protected boolean isSupportedJoinCondition(ConnectorSession session, JdbcJoinCondition joinCondition)
    {
        if (joinCondition.getOperator() == JoinCondition.Operator.IS_DISTINCT_FROM) {
            // Not supported in MySQL
            return false;
        }

        // Remote database can be case insensitive.
        return Stream.of(joinCondition.getLeftColumn(), joinCondition.getRightColumn())
                .map(JdbcColumnHandle::getColumnType)
                .noneMatch(type -> type instanceof CharType || type instanceof VarcharType);
    }

    @Override
    public TableStatistics getTableStatistics(ConnectorSession session, JdbcTableHandle handle)
    {
        if (!statisticsEnabled) {
            return TableStatistics.empty();
        }
        if (!handle.isNamedRelation()) {
            return TableStatistics.empty();
        }
        try {
            return readTableStatistics(session, handle);
        }
        catch (SQLException | RuntimeException e) {
            throwIfInstanceOf(e, TrinoException.class);
            throw new TrinoException(JDBC_ERROR, "Failed fetching statistics for table: " + handle, e);
        }
    }

    private TableStatistics readTableStatistics(ConnectorSession session, JdbcTableHandle table)
            throws SQLException
    {
        checkArgument(table.isNamedRelation(), "Relation is not a table: %s", table);

        log.debug("Reading statistics for %s", table);
        try (Connection connection = connectionFactory.openConnection(session);
                Handle handle = Jdbi.open(connection)) {
            StatisticsDao statisticsDao = new StatisticsDao(handle);

            Long rowCount = statisticsDao.getRowCount(table);
            log.debug("Estimated row count of table %s is %s", table, rowCount);

            if (rowCount == null) {
                // Table not found, or is a view.
                return TableStatistics.empty();
            }

            TableStatistics.Builder tableStatistics = TableStatistics.builder();
            tableStatistics.setRowCount(Estimate.of(rowCount));

            Map<String, String> columnHistograms = statisticsDao.getColumnHistograms(table);
            Map<String, ColumnIndexStatistics> columnStatisticsFromIndexes = statisticsDao.getColumnIndexStatistics(table);

            if (columnHistograms.isEmpty() && columnStatisticsFromIndexes.isEmpty()) {
                log.debug("No column histograms and index statistics read");
                // No more information to work on
                return tableStatistics.build();
            }

            for (JdbcColumnHandle column : this.getColumns(session, table)) {
                ColumnStatistics.Builder columnStatisticsBuilder = ColumnStatistics.builder();

                String columnName = column.getColumnName();
                Optional<ColumnHistogram> histogram = getColumnHistogram(columnHistograms, columnName);
                if (histogram.isPresent()) {
                    log.debug("Reading column statistics for %s, %s from histogram: %s", table, columnName, columnHistograms.get(columnName));
                    histogram.get().updateColumnStatistics(columnStatisticsBuilder);

                    // row count from INFORMATION_SCHEMA.TABLES is very inaccurate
                    rowCount = histogram.get().getUpdateRowCount(rowCount);
                }

                ColumnIndexStatistics columnIndexStatistics = columnStatisticsFromIndexes.get(columnName);
                if (columnIndexStatistics != null) {
                    log.debug("Reading column statistics for %s, %s from index statistics: %s", table, columnName, columnIndexStatistics);
                    updateColumnStatisticsFromIndexStatistics(table, columnName, columnStatisticsBuilder, columnIndexStatistics);

                    // row count from INFORMATION_SCHEMA.TABLES is very inaccurate
                    rowCount = max(rowCount, columnIndexStatistics.getCardinality());
                }

                ColumnStatistics columnStatistics = columnStatisticsBuilder.build();
                if (!columnStatistics.getDistinctValuesCount().isUnknown() && columnStatistics.getNullsFraction().isUnknown()) {
                    columnStatisticsBuilder.setNullsFraction(UNKNOWN_NULL_FRACTION_REPLACEMENT);
                    columnStatistics = columnStatisticsBuilder.build();
                }

                tableStatistics.setColumnStatistics(column, columnStatistics);
            }

            tableStatistics.setRowCount(Estimate.of(rowCount));
            return tableStatistics.build();
        }
    }

    private static Optional<ColumnHistogram> getColumnHistogram(Map<String, String> columnHistograms, String columnName)
    {
        return Optional.ofNullable(columnHistograms.get(columnName))
                .flatMap(histogramJson -> {
                    try {
                        return Optional.of(HISTOGRAM_CODEC.fromJson(histogramJson));
                    }
                    catch (RuntimeException e) {
                        log.warn(e, "Failed to parse column statistics histogram: %s", histogramJson);
                        return Optional.empty();
                    }
                });
    }

    private static void updateColumnStatisticsFromIndexStatistics(JdbcTableHandle table, String columnName, ColumnStatistics.Builder columnStatistics, ColumnIndexStatistics columnIndexStatistics)
    {
        // Prefer CARDINALITY from index statistics over NDV from a histogram.
        // Index column might be NULLABLE. Then CARDINALITY includes all
        columnStatistics.setDistinctValuesCount(Estimate.of(columnIndexStatistics.getCardinality()));

        if (!columnIndexStatistics.nullable) {
            double knownNullFraction = columnStatistics.build().getNullsFraction().getValue();
            if (knownNullFraction > 0) {
                log.warn("Inconsistent statistics, null fraction for a column %s, %s, that is not nullable according to index statistics: %s", table, columnName, knownNullFraction);
            }
            columnStatistics.setNullsFraction(Estimate.zero());
        }
    }

    private ColumnMapping jsonColumnMapping()
    {
        return ColumnMapping.sliceMapping(
                jsonType,
                (resultSet, columnIndex) -> jsonParse(utf8Slice(resultSet.getString(columnIndex))),
                varcharWriteFunction(),
                DISABLE_PUSHDOWN);
    }

    private static boolean isGtidMode(Connection connection)
    {
        try (java.sql.Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery("SHOW VARIABLES LIKE 'gtid_mode'")) {
            if (resultSet.next()) {
                return !resultSet.getString("Value").equalsIgnoreCase("OFF");
            }

            return false;
        }
        catch (SQLException e) {
            throw new TrinoException(JDBC_ERROR, e);
        }
    }

    private static class StatisticsDao
    {
        private final Handle handle;

        public StatisticsDao(Handle handle)
        {
            this.handle = requireNonNull(handle, "handle is null");
        }

        Long getRowCount(JdbcTableHandle table)
        {
            RemoteTableName remoteTableName = table.getRequiredNamedRelation().getRemoteTableName();
            return handle.createQuery("" +
                            "SELECT TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES " +
                            "WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table_name " +
                            "AND TABLE_TYPE = 'BASE TABLE' ")
                    .bind("schema", remoteTableName.getCatalogName().orElse(null))
                    .bind("table_name", remoteTableName.getTableName())
                    .mapTo(Long.class)
                    .findOne()
                    .orElse(null);
        }

        Map<String, ColumnIndexStatistics> getColumnIndexStatistics(JdbcTableHandle table)
        {
            RemoteTableName remoteTableName = table.getRequiredNamedRelation().getRemoteTableName();
            return handle.createQuery("" +
                            "SELECT " +
                            "  COLUMN_NAME, " +
                            "  MAX(NULLABLE) AS NULLABLE, " +
                            "  MAX(CARDINALITY) AS CARDINALITY " +
                            "FROM INFORMATION_SCHEMA.STATISTICS " +
                            "WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table_name " +
                            "AND SEQ_IN_INDEX = 1 " + // first column in the index
                            "AND SUB_PART IS NULL " + // ignore cases where only a column prefix is indexed
                            "AND CARDINALITY IS NOT NULL " + // CARDINALITY might be null (https://stackoverflow.com/a/42242729/65458)
                            "GROUP BY COLUMN_NAME") // there might be multiple indexes on a column
                    .bind("schema", remoteTableName.getCatalogName().orElse(null))
                    .bind("table_name", remoteTableName.getTableName())
                    .map((rs, ctx) -> {
                        String columnName = rs.getString("COLUMN_NAME");

                        boolean nullable = rs.getString("NULLABLE").equalsIgnoreCase("YES");
                        checkState(!rs.wasNull(), "NULLABLE is null");

                        long cardinality = rs.getLong("CARDINALITY");
                        checkState(!rs.wasNull(), "CARDINALITY is null");

                        return new SimpleEntry<>(columnName, new ColumnIndexStatistics(nullable, cardinality));
                    })
                    .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
        }

        Map<String, String> getColumnHistograms(JdbcTableHandle table)
        {
            try {
                handle.execute("SELECT 1 FROM INFORMATION_SCHEMA.COLUMN_STATISTICS WHERE 0=1");
            }
            catch (UnableToExecuteStatementException e) {
                if (e.getCause() instanceof SQLSyntaxErrorException && ((SQLSyntaxErrorException) e.getCause()).getErrorCode() == ER_UNKNOWN_TABLE) {
                    // The table is available since MySQL 8
                    log.debug("INFORMATION_SCHEMA.COLUMN_STATISTICS table is not available: %s", e);
                    return ImmutableMap.of();
                }
            }

            RemoteTableName remoteTableName = table.getRequiredNamedRelation().getRemoteTableName();
            return handle.createQuery("" +
                            "SELECT COLUMN_NAME, HISTOGRAM FROM INFORMATION_SCHEMA.COLUMN_STATISTICS " +
                            "WHERE SCHEMA_NAME = :schema AND TABLE_NAME = :table_name")
                    .bind("schema", remoteTableName.getCatalogName().orElse(null))
                    .bind("table_name", remoteTableName.getTableName())
                    .map((rs, ctx) -> new SimpleEntry<>(rs.getString("COLUMN_NAME"), rs.getString("HISTOGRAM")))
                    .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
        }
    }

    private static class ColumnIndexStatistics
    {
        private final boolean nullable;
        private final long cardinality;

        public ColumnIndexStatistics(boolean nullable, long cardinality)
        {
            this.cardinality = cardinality;
            this.nullable = nullable;
        }

        public long getCardinality()
        {
            return cardinality;
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("cardinality", getCardinality())
                    .add("nullable", nullable)
                    .toString();
        }
    }

    // See https://dev.mysql.com/doc/refman/8.0/en/optimizer-statistics.html
    public static class ColumnHistogram
    {
        private final Optional<Double> nullFraction;
        private final Optional<String> histogramType;
        private final Optional<List<List<Object>>> buckets;

        @JsonCreator
        public ColumnHistogram(
                @JsonProperty("null-values") Optional<Double> nullFraction,
                @JsonProperty("histogram-type") Optional<String> histogramType,
                @JsonProperty("buckets") Optional<List<List<Object>>> buckets)
        {
            this.nullFraction = nullFraction;
            this.histogramType = histogramType;
            this.buckets = buckets;
        }

        public void updateColumnStatistics(ColumnStatistics.Builder columnStatistics)
        {
            nullFraction.map(Estimate::of).ifPresent(columnStatistics::setNullsFraction);
            getDistinctValuesCount().map(Estimate::of).ifPresent(columnStatistics::setDistinctValuesCount);
        }

        private Optional<Long> getDistinctValuesCount()
        {
            if (histogramType.isPresent() && buckets.isPresent()) {
                switch (histogramType.get()) {
                    case "singleton":
                        return Optional.of((long) buckets.get().size());

                    case "equi-height":
                        long distinctValues = 0;
                        for (List<?> bucket : buckets.get()) {
                            distinctValues += ((Number) bucket.get(3)).longValue();
                        }
                        return Optional.of(distinctValues);

                    default:
                        log.debug("Unsupported histogram type: %s", histogramType.get());
                }
            }
            else {
                log.debug("Unsupported histogram: type: %s, bucket count: %s", histogramType, buckets.map(List::size));
            }
            return Optional.empty();
        }

        public long getUpdateRowCount(long rowCount)
        {
            return getDistinctValuesCount()
                    .map(distinctValuesCount -> max(rowCount, distinctValuesCount))
                    .orElse(rowCount);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>WebArgumentResolver (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.springframework.web.bind.support

Interface WebArgumentResolver

Functional Interface:

This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface
public interface WebArgumentResolver

SPI for resolving custom arguments for a specific handler method parameter.
 Typically implemented to detect special parameter types, resolving
 well-known argument values for them.

A typical implementation could look like as follows:

 public class MySpecialArgumentResolver implements WebArgumentResolver {

   public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
     if (methodParameter.getParameterType().equals(MySpecialArg.class)) {
       return new MySpecialArg("myValue");
     }
     return UNRESOLVED;
   }
 }

Since:

2.5.2

Author:

Juergen Hoeller

See Also:

RequestMappingHandlerAdapter.setCustomArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver>)

Field Summary

Fields

Modifier and Type
Field and Description

static Object
UNRESOLVED

Marker to be returned when the resolver does not know how to
 handle the given method parameter.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

Object
resolveArgument(MethodParameter methodParameter,
               NativeWebRequest webRequest)

Resolve an argument for the given handler method parameter within the given web request.

Field Detail

UNRESOLVED

static final Object UNRESOLVED

Marker to be returned when the resolver does not know how to
 handle the given method parameter.

Method Detail

resolveArgument

@Nullable
Object resolveArgument(MethodParameter methodParameter,
                                 NativeWebRequest webRequest)
                          throws Exception

Resolve an argument for the given handler method parameter within the given web request.

Parameters:

methodParameter - the handler method parameter to resolve

webRequest - the current web request, allowing access to the native request as well

Returns:

the argument value, or UNRESOLVED if not resolvable

Throws:

Exception - in case of resolution failure

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module Dhfex
  class Engine < ::Rails::Engine
    isolate_namespace Dhfex

    initializer 'dhfex.action_controller' do |app|
      ActiveSupport.on_load :action_controller do
        helper Dhfex::SharedHelper
      end
    end

  end
end


text:
{{> header}}

    <link href="/public/metronic-for-bolt/assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
    <link href="/public/metronic-for-bolt/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="/public/metronic-for-bolt/assets/pages/css/datatable_custom.css" rel="stylesheet" type="text/css" />
    <link href="/public/bolt-ui-sweetalert/dist/sweetalert.css" rel="stylesheet" type="text/css" />

{{> sub_header}}

{{> nav }}

 Avaliable Sessions

                    List of Avaliable Sessions

                              Add Session

                             Delete

                             Tools

                                     Print

                                     Copy

                                     PDF

                                     Excel

                                     CSV

                                     Reload

                                        <input type="checkbox" class="group-checkable" data-set="#sample_3 .checkboxes" />

                                 Session
                                 Start date
                                 End date
                                 Status
                                 Action

                            {{#each sessions}}

                                        <input type="checkbox" class="checkboxes" value="{{_id}}" />

                                 {{displayName}}
                                 {{begin}}
                                 {{end}}

                                    {{#if isCurrent}}
                                     Active
                                    {{else}}
                                     Inactive
                                    {{/if}}

                                          Edit

                            {{/each}}

{{> copyright }}

{{> sub_footer }}

{{> footer }}


text:
.splitpic .splitpic-images {
        position: relative;
        overflow: hidden;
}

.splitpic-image {
    overflow: hidden;
    margin-top: 0px;
}

.splitpic-left-image {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
}
.splitpic-right-image {
}
.splitpic-info {
    top: 45%;
    width: 100%;
    font-size: 200%;
    color: white;
    position: absolute;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.50);
}
.splitpic-bar {
    position: absolute;
    background-color: #113;
}
.splitpic-horizontal {
    cursor: ew-resize;
}
.splitpic-horizontal .splitpic-bar {
    top: 0;
    width: 5px;
    height: 100%;
}
.splitpic-vertical {
    cursor: ns-resize;
}
.splitpic-vertical .splitpic-bar {
    left: 0;
    width: 100%;
    height: 5px;
}


text:
namespace Dropbox.Api.TeamLog
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>Team linked app</para>
    /// </summary>
    /// <seealso cref="Global::Dropbox.Api.TeamLog.AppLogInfo" />
    public class TeamLinkedAppLogInfo : AppLogInfo
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<TeamLinkedAppLogInfo> Encoder = new TeamLinkedAppLogInfoEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<TeamLinkedAppLogInfo> Decoder = new TeamLinkedAppLogInfoDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="TeamLinkedAppLogInfo" />
        /// class.</para>
        /// </summary>
        /// <param name="appId">App unique ID.</param>
        /// <param name="displayName">App display name.</param>
        public TeamLinkedAppLogInfo(string appId = null,
                                    string displayName = null)
            : base(appId, displayName)
        {
        }

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="TeamLinkedAppLogInfo" />
        /// class.</para>
        /// </summary>
        /// <remarks>This is to construct an instance of the object when
        /// deserializing.</remarks>
        [sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
        public TeamLinkedAppLogInfo()
        {
        }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="TeamLinkedAppLogInfo" />.</para>
        /// </summary>
        private class TeamLinkedAppLogInfoEncoder : enc.StructEncoder<TeamLinkedAppLogInfo>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(TeamLinkedAppLogInfo value, enc.IJsonWriter writer)
            {
                if (value.AppId != null)
                {
                    WriteProperty("app_id", value.AppId, writer, enc.StringEncoder.Instance);
                }
                if (value.DisplayName != null)
                {
                    WriteProperty("display_name", value.DisplayName, writer, enc.StringEncoder.Instance);
                }
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="TeamLinkedAppLogInfo" />.</para>
        /// </summary>
        private class TeamLinkedAppLogInfoDecoder : enc.StructDecoder<TeamLinkedAppLogInfo>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="TeamLinkedAppLogInfo" />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override TeamLinkedAppLogInfo Create()
            {
                return new TeamLinkedAppLogInfo();
            }

            /// <summary>
            /// <para>Set given field.</para>
            /// </summary>
            /// <param name="value">The field value.</param>
            /// <param name="fieldName">The field name.</param>
            /// <param name="reader">The json reader.</param>
            protected override void SetField(TeamLinkedAppLogInfo value, string fieldName, enc.IJsonReader reader)
            {
                switch (fieldName)
                {
                    case "app_id":
                        value.AppId = enc.StringDecoder.Instance.Decode(reader);
                        break;
                    case "display_name":
                        value.DisplayName = enc.StringDecoder.Instance.Decode(reader);
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }
        }

        #endregion
    }
}


text:
/* */
var $export = require('./$.export'),
    $task = require('./$.task');
$export($export.G + $export.B, {
  setImmediate: $task.set,
  clearImmediate: $task.clear
});


text:
package com.netflix.ndbench.plugin.dynamodb.operations.dynamodb.dataplane;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.model.ConsumedCapacity;
import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.ndbench.api.plugin.DataGenerator;
import com.netflix.ndbench.plugin.dynamodb.operations.dynamodb.AbstractDynamoDBOperation;

import java.util.List;

/**
 * @author Alexander Patrikalakis
 */
public class AbstractDynamoDBDataPlaneOperation extends AbstractDynamoDBOperation {
    protected final DataGenerator dataGenerator;
    protected final AtomicDouble consumed = new AtomicDouble(0.0);
    protected final ReturnConsumedCapacity returnConsumedCapacity;

    protected AbstractDynamoDBDataPlaneOperation(AmazonDynamoDB dynamoDB, String tableName, String partitionKeyName,
                                                 DataGenerator dataGenerator,
                                                 ReturnConsumedCapacity returnConsumedCapacity) {
        super(dynamoDB, tableName, partitionKeyName);
        this.dataGenerator = dataGenerator;
        this.returnConsumedCapacity = returnConsumedCapacity;
    }

    protected double getConsumedCapacityForTable(List<ConsumedCapacity> consumedCapacities) {
        Preconditions.checkNotNull(consumedCapacities);
        return consumedCapacities.stream()
                .filter(c -> tableName.equals(c.getTableName()))
                .map(ConsumedCapacity::getCapacityUnits)
                .findFirst()
                .orElse(0.0);
    }

    public double getAndResetConsumed() {
        return consumed.getAndSet(0.0);
    }
}


text:
module Unboxed
  module Capistrano
    module Recipes
      VERSION = "0.0.4"
    end
  end
end


text:
<?
namespace frontend\assets;

use yii\web\AssetBundle;
use yii\web\View;

class MainAsset extends  AssetBundle{

    public $basePath = '@webroot';
    public $baseUrl = '@web';

    public $css = [
        'source/style.css',
        'source/owl-carousel/owl.carousel.css',
        'source/owl-carousel/owl.theme.css',
        'source/slitslider/css/style.css',
        'source/slitslider/css/custom.css'
    ];

    public $js = [
        'source/script.js',
        'source/owl-carousel/owl.carousel.js',
        'source/slitslider/js/modernizr.custom.79639.js',
        'source/slitslider/js/jquery.ba-cond.min.js',
        'source/slitslider/js/jquery.slitslider.js',
        'source/js/google_analytics_auto.js'
    ];

    public $depends = [
        'yii\web\YiiAsset', // yii.js, jquery.js
        'yii\bootstrap\BootstrapAsset', // bootstrap.css
        'yii\bootstrap\BootstrapPluginAsset' // bootstrap.js
    ];

    public $jsOptions = [
      'position' =>  View::POS_END,
    ];

}


text:
package src_test

import (

	"strings"
	. "StringCalculatorKataGo/src"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("StringCalculator", func() {
    var cal StringCalculator

    BeforeEach(func() {
        cal = StringCalculator{
        }
    })

    Describe("Add method", func() {
        Context("with empty string imput", func() {
            It("should return zero", func() {
				Expect(cal.Add("")).To(Equal(0))
            })
        })

        Context("With only one number", func() {
            It("should be the same number", func() {
				Expect(cal.Add("3")).To(Equal(3))
            })
        })
		Context("With two numbers", func() {
            It("should be the add of numbers", func() {
				Expect(cal.Add("3,3")).To(Equal(6))
            })
        })
		Context("With more numbers", func() {
            It("should be the add of numbers", func() {
				Expect(cal.Add("3,3,3")).To(Equal(9))
            })
        })
		Context("With new lines between numbers", func() {
            It("should be the add of numbers", func() {
				Expect(cal.Add("1/n3,3,3")).To(Equal(10))
            })
        })
		Context("With different delimiter starting by //[delimiter]", func() {
            It("should be the add of numbers", func() {
				Expect(cal.Add("//[;]1/n3;3;3")).To(Equal(10))
            })
        })
		Context("With numbers bigger than 1000", func() {
            It("should throw an error", func() {
				_ , err := cal.Add("3,-3")
				Expect(err).To(HaveOccurred())
            })
            It("should throw an error with only one number", func() {
				_ , err := cal.Add("-3")
				Expect(err).To(HaveOccurred())
            })
            It("should throw show in the error message negative numbers", func() {
				_ , err := cal.Add("-3,4,-5")
				Expect(strings.Contains(err.Error(),"-3")).To(Equal(true))
				Expect(strings.Contains(err.Error(),"-5")).To(Equal(true))
            })
        })
	})

})


text:
/**
 * Dimensions.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.dfa.axis.v1_19;

public class Dimensions  implements java.io.Serializable {
    private int height;

    private int width;

    public Dimensions() {
    }

    public Dimensions(
           int height,
           int width) {
           this.height = height;
           this.width = width;
    }

    /**
     * Gets the height value for this Dimensions.
     *
     * @return height
     */
    public int getHeight() {
        return height;
    }

    /**
     * Sets the height value for this Dimensions.
     *
     * @param height
     */
    public void setHeight(int height) {
        this.height = height;
    }

    /**
     * Gets the width value for this Dimensions.
     *
     * @return width
     */
    public int getWidth() {
        return width;
    }

    /**
     * Sets the width value for this Dimensions.
     *
     * @param width
     */
    public void setWidth(int width) {
        this.width = width;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof Dimensions)) return false;
        Dimensions other = (Dimensions) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            this.height == other.getHeight() &&
            this.width == other.getWidth();
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        _hashCode += getHeight();
        _hashCode += getWidth();
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(Dimensions.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.19", "Dimensions"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("height");
        elemField.setXmlName(new javax.xml.namespace.QName("", "height"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("width");
        elemField.setXmlName(new javax.xml.namespace.QName("", "width"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
from matplotlib import style

style.use('ggplot')
stocks = ['ORCL', 'IBM', 'C', 'GOOGL', 'MSFT', 'AAPL']
start = datetime.datetime(2008, 1, 1)
end = datetime.datetime(2010, 1, 1)
df = web.DataReader(stocks, 'yahoo', start, end)
#print(df.head())
df['Adj Close'].plot()
plt.show()


text:
<!DOCTYPE html>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="style.css" rel="stylesheet" media="screen" type="text/css">
    <link href="bootstrap/css/material.css" rel="stylesheet" media="screen" type="text/css">
    <link href="bootstrap/icons/icons-material-design.css" rel="stylesheet" media="screen" type="text/css">

        TweetyLink

Hi

          Thanks for downloading TweetyLink!

          To get started, just click the button below...

          <button type="button" class="btn btn-lg" id="btn-sign-in">SIGN IN WITH TWITTER</button>

8m

@FarPixel

Check out this awesome website! http://josh.farrant.me

10m

@KevinBox

Trying out a new design for my site http://www.kevinbox.co.uk/classic.html

15m

@charlesrchance

http://www.sipcentric.com

15m

@DavidMaitland

http://www.davidmaitland.me


text:
void get_runtime_config_paths_from_app(const pal::string_t& app, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(app);
    auto path = get_directory(app);

    get_runtime_config_paths(path, name, cfg, dev_cfg);
}

void get_runtime_config_paths_from_arg(const pal::string_t& arg, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(arg);

    auto json_name = name + _X(".json");
    auto dev_json_name = name + _X(".dev.json");

    auto json_path = get_directory(arg);
    auto dev_json_path = json_path;

    append_path(&json_path, json_name.c_str());
    append_path(&dev_json_path, dev_json_name.c_str());

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());

    dev_cfg->assign(dev_json_path);
    cfg->assign(json_path);
}

void get_runtime_config_paths(const pal::string_t& path, const pal::string_t& name, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto json_path = path;
    auto json_name = name + _X(".runtimeconfig.json");
    append_path(&json_path, json_name.c_str());
    cfg->assign(json_path);

    auto dev_json_path = path;
    auto dev_json_name = name + _X(".runtimeconfig.dev.json");
    append_path(&dev_json_path, dev_json_name.c_str());
    dev_cfg->assign(dev_json_path);

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());
}

host_mode_t detect_operating_mode(const host_startup_info_t& host_info)
{
    if (coreclr_exists_in_dir(host_info.dotnet_root))
    {
        // Detect between standalone apphost or legacy split mode (specifying --depsfile and --runtimeconfig)

        pal::string_t deps_in_dotnet_root = host_info.dotnet_root;
        pal::string_t deps_filename = host_info.get_app_name() + _X(".deps.json");
        append_path(&deps_in_dotnet_root, deps_filename.c_str());
        bool deps_exists = pal::file_exists(deps_in_dotnet_root);

        trace::info(_X("Detecting mode... CoreCLR present in dotnet root [%d] and checking if [%s] file present=[%d]"),
            host_info.dotnet_root.c_str(), deps_filename.c_str(), deps_exists);

        // Name of runtimeconfig file; since no path is included here the check is in the current working directory
        pal::string_t config_in_cwd = host_info.get_app_name() + _X(".runtimeconfig.json");

        return (deps_exists || !pal::file_exists(config_in_cwd)) && pal::file_exists(host_info.app_path) ? host_mode_t::apphost : host_mode_t::split_fx;
    }

    if (pal::file_exists(host_info.app_path))
    {
        // Framework-dependent apphost
        return host_mode_t::apphost;
    }

    return host_mode_t::muxer;
}

void try_patch_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading patch roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_star = start_ver.patch_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering patch roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, true))
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Patch roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}

void try_prerelease_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading prerelease roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_pat_star = start_ver.prerelease_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_pat_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering prerelease roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, false)
            && ver.is_prerelease()) // Pre-release can roll forward to only pre-release
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Prerelease roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}


text:
#import "ConcurrentOp.h"

#import "TiledImageBuilder.h"

@implementation ConcurrentOp
{
	NSMutableData *data;
}

- (uint32_t)milliSeconds
{
	return _imageBuilder.milliSeconds;
}

- (NSMutableURLRequest *)setup
{
	data = [NSMutableData dataWithCapacity:10000];
	self.imageBuilder = [[TiledImageBuilder alloc] initForNetworkDownloadWithDecoder:_decoder size:CGSizeMake(320, 320) orientation:_orientation];
	return [super setup];
}

- (void)setWebData:(NSData *)webData
{
	super.webData = webData;

#ifdef LIBJPEG
	if(_decoder == libjpegIncremental) {
		// Since the SesslonDelegate is trying to be sophisticated, and use the chained dispatch_data obhects,
		// our consumer is just consuming chunks at its own pace. So we'll always keep the webData at 0 byes,
		// and use our own internal mutable object to transfer bytes. Its the best compromise we can use.
		if([webData length]) {
			[data appendData:webData];
			BOOL consumed = [_imageBuilder jpegAdvance:data];
			if(consumed) {
				// This use to be hidden in the imagebuilder class, really was hard to spot
				[data setLength:0];
			}
			dispatch_queue_t q	= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
			super.webData = (NSData *)dispatch_data_create(NULL, 0, q, ^{});
			super.currentReceiveSize = 0;
		}
	}
#endif
}

- (void)completed
{

#ifdef LIBJPEG
	if(_decoder == libjpegIncremental) {
		if(_imageBuilder.failed) {
			NSLog(@"FAILED!");
			self.imageBuilder = nil;
		}
	} else
#endif
	{
		[_imageBuilder writeToImageFile:self.webData];
		[_imageBuilder dataFinished];
	}

	[super completed];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.kie</groupId>
    <artifactId>kie-api-parent</artifactId>
    <version>6.2.0.Final</version>
  </parent>

  <artifactId>kie-internal</artifactId>
  <packaging>bundle</packaging><!-- bundle = jar + OSGi metadata -->

  <name>KIE Internal</name>
  <description>The Drools and jBPM internal API which is NOT backwards compatible between releases.</description>

  <build>
    <resources>
      <resource>
        <filtering>false</filtering>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <filtering>true</filtering>
        <directory>src/main/filtered-resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <configuration>
          <instructions>
            <Bundle-SymbolicName>org.kie.internalapi</Bundle-SymbolicName>
            <Import-Package>
              com.sun.tools.xjc;resolution:=optional,
              com.thoughtworks.xstream;resolution:=optional,
              javax.enterprise.*;resolution:=optional,
              javax.inject.*;resolution:=optional,
              javax.xml.bind;resolution:=optional,
              javax.xml.bind.annotation;resolution:=optional,
              javax.xml.bind.annotation.adapters;resolution:=optional,
              org.drools.compiler.builder.impl,
              org.drools.core.builder.conf.impl;resolution:=optional,
              org.drools.core.command.impl,
              org.drools.core.concurrent,
              org.drools.core.impl,
              org.drools.core.io.impl,
              org.drools.core.marshalling.impl;resolution:=optional,
              org.drools.decisiontable;resolution:=optional,
              org.drools.persistence.jpa;resolution:=optional,
              org.jbpm.bpmn2;resolution:=optional,
              org.jbpm.marshalling.impl;resolution:=optional,
              org.jbpm.process.builder;resolution:=optional,
              org.jbpm.runtime.manager.impl;resolution:=optional,
              org.jbpm.services.task.persistence;resolution:=optional,
              org.kie.api,
              org.kie.api.builder,
              org.kie.api.builder.model,
              org.kie.api.command,
              org.kie.api.concurrent,
              org.kie.api.conf,
              org.kie.api.definition,
              org.kie.api.definition.process,
              org.kie.api.definition.rule,
              org.kie.api.definition.type,
              org.kie.api.event,
              org.kie.api.io,
              org.kie.api.logger,
              org.kie.api.marshalling,
              org.kie.api.persistence.jpa,
              org.kie.api.runtime,
              org.kie.api.runtime.conf,
              org.kie.api.runtime.manager,
              org.kie.api.runtime.manager.audit,
              org.kie.api.runtime.process,
              org.kie.api.runtime.rule,
              org.kie.api.task,
              org.kie.api.task.model,
              =org.kie.scanner.*;resolution:=optional,
              org.mvel2,
              org.slf4j
            </Import-Package>
            <Export-Package>
              org.kie.internal.*
            </Export-Package>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
    </dependency>
    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <scope>provided</scope><!-- HACK for OSGi: should be <optional>true</optional> instead -->
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-xjc</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <scope>provided</scope>
    </dependency>
      <dependency>
          <groupId>org.mvel</groupId>
          <artifactId>mvel2</artifactId>
      </dependency>
  </dependencies>
</project>


text:
#ifndef __NAVIPACK_SESSION_LAYER_H__
#define __NAVIPACK_SESSION_LAYER_H__
/** @addtogroup Session_Layer
* @{
*/

#include "navipack_type.h"
#include "navipack_transport_layer.h"

#define CHASSIS_PLATFORM
#include "navipack_protocol.h"

#define REG_ID_STATUS   1
#define REG_ID_COTROL   2
#define REG_ID_CONFIG   3
#define REG_ID_USER     4
#define REG_ID_UID      5

typedef struct
{
    // 需要初始化
    u8 *rxBuffer;   ///< 接收 Buffer 指针
    u8 *txBuffer;   ///< 发送 Buffer 指针
    u16 rxSize;     ///< 接收 Buffer 尺寸
    u16 txSize;     ///< 发送 Buffer 尺寸

    u16 rxDataLen;
    u16 txDataLen;
    TransportFrame_Type rxFrame;
    TransportFrame_Type txFrame;

    NaviPack_CtrlType control;  ///< 控制寄存器
    NaviPack_StatusType status; ///< 状态寄存器
    NaviPack_ConfigType config; ///< 参数寄存器
    u32 FirmwareRespond;
}NavipackComm_Type;

bool NaviPack_SessionRxProcessor(NavipackComm_Type *comm, u8 data);
bool RegisterWrite(NaviPack_HeadType *head, u8 *reg, u32 size, u8 reg_id);
bool RegisterRead(NavipackComm_Type *comm, NaviPack_HeadType *head, u8 err_id, u8 *reg, u32 reg_size, u8 reg_id);
bool Navipack_TransportUnpacking(NavipackComm_Type *comm, u8 data);
bool Navipack_TransportPacking(NavipackComm_Type *comm, u8 *in_buf, u16 len, u8 pack_flag);

bool Navipack_TxCallback(u8* pbuf, u16 len);
bool Navipack_RxCallback(NavipackComm_Type *comm, NaviPack_HeadType *head);

/**
* @}
*/
#endif


text:
import Ember from "ember";
import AjaxPromise from './../../utils/ajax-promise';
import addressDetails from './address_details';
import { translationMacro as t } from "ember-i18n";
const { getOwner } = Ember;

export default addressDetails.extend({
  deliveryController: Ember.inject.controller('delivery'),

  selectedDate: null,
  selectedTime: null,
  speakEnglish: false,
  borrowTrolley: false,
  porterage: false,
  longerGoods: false,
  longGoodSelection: "half",

  datePrompt: t("gogovan.book_van.date"),
  timePrompt: t("gogovan.book_van.time"),
  i18n: Ember.inject.service(),

  isSelectedVan: Ember.computed("selectedGogovanOption", function() {
    return this.get("selectedGogovanOption") === "1";
  }),

  offer: Ember.computed("deliveryController", {
    get() {
      return this.get("deliveryController.model.offer");
    },
    set(key, value) {
      return value;
    }
  }),

  available_dates: Ember.computed('available_dates.[]', {
    get: function() {
      new AjaxPromise("/available_dates", "GET", this.get('session.authToken'), { schedule_days: 120 })
        .then(data => this.set("available_dates", data));
    },
    set: function(key, value) {
      return value;
    }
  }),

  gogovanOptions: Ember.computed(function() {
    var allOptions = this.store.peekAll('gogovan_transport');
    return allOptions.rejectBy('disabled', true).sortBy('id');
  }),

  selectedGogovanOption: Ember.computed('gogovanOptions', 'offer', function() {
    return this.get("offer.gogovanTransport.id") || this.get('gogovanOptions.firstObject.id');
  }),

  timeSlots: Ember.computed(function() {
    var options = [];
    var slots = {
      "600": "10:00",
      "630": "10:30",
      "660": "11:00",
      "690": "11:30",
      "720": "12:00",
      "750": "12:30",
      "780": "1:00",
      "810": "1:30",
      "840": "2:00",
      "870": "2:30",
      "900": "3:00"
    };
    for (var minutes in slots) {
      var period = parseInt(minutes, 10) >= 720 ? this.locale("gogovan.book_van.pm") : this.locale("gogovan.book_van.am");
      options.push({ id: minutes, name: slots[minutes] + " " + period });
    }
    return options;
  }),

  locale: function(str) {
    return this.get("i18n").t(str);
  },

  actions: {
    bookVan() {
      var controller = this;
      var loadingView = getOwner(controller).lookup('component:loading').append();
      var selectedDate = controller.get('selectedDate');
      var deliveryId = controller.get('deliveryController.model.id');
      var delivery = controller.store.peekRecord('delivery', deliveryId);
      var gogovanOptionId = controller.get('selectedGogovanOption');

      selectedDate.setMinutes(selectedDate.getMinutes() + parseInt(controller.get('selectedTime.id'), 10));

      var requestProperties = {};
      requestProperties.pickupTime = selectedDate;
      requestProperties.slot = this.get('selectedTime.name');
      requestProperties.districtId = controller.get('selectedDistrict.id');
      requestProperties.territoryId = controller.get('selectedTerritory.id');
      requestProperties.needEnglish = controller.get("speakEnglish");
      requestProperties.needCart = controller.get("borrowTrolley");
      requestProperties.needCarry = controller.get("porterage");
      requestProperties.offerId = delivery.get('offer.id');
      requestProperties.gogovanOptionId = gogovanOptionId;

      if (this.get("isSelectedVan")) {
        requestProperties.needOver6ft = this.get("longerGoods");
        requestProperties.removeNet = this.get("longGoodSelection");
      }

      var order = controller.store.createRecord('gogovan_order', requestProperties);
      order.set('delivery', delivery);
      new AjaxPromise("/gogovan_orders/calculate_price", "POST", controller.get('session.authToken'), requestProperties).then(function(data) {
        var coupon = data.breakdown.coupon_discount;
        if (coupon) {
          var discount = coupon.value.toString();
          order.set("isDiscountAvailable", true);
          order.set("couponDiscount", discount.slice(0, 1) + "$" + discount.slice(1));
        } else {
          order.set("isDiscountAvailable", false);
        }
        order.set('baseFee', data.base);
        order.set('total', data.total);
        order.set('needEnglishFee', data.breakdown.speak_english && data.breakdown.speak_english.value);
        order.set('needCartFee', (data.breakdown.borrow_carts && data.breakdown.borrow_carts.value) || (data.breakdown.borrow_forklift_pcs && data.breakdown.borrow_forklift_pcs.value));
        order.set('removeNetFee', data.breakdown.remove_net && data.breakdown.remove_net.value);
        loadingView.destroy();
        controller.transitionToRoute('delivery.confirm_van', { queryParams: { placeOrder: true } });
      });
    }
  }
});


text: Visualization of 2013 Overweight Prevalence


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.3.5.3_A2_T5;
 * @section: 15.3.5.3, 11.8.6;
 * @assertion: Assume F is a Function object. When the [[HasInstance]] method of
 *             F is called with value V and V is an object, the following steps
 *             are taken: i) Call the [[Get]] method of F with property name
 *             "prototype". ii) Let O be Result(i). iii) O is not an object,
 *             throw a TypeError exception;
 * @description: F.prototype is void 0, and V is new F;
 */

FACTORY = Function("this.prop=1;");

FACTORY.prototype.name = "fairy";

instance = new FACTORY;

FACTORY.prototype = void 0;

// CHECK#1
try {
  instance instanceof FACTORY;
  $FAIL('#1: O is not an object, throw a TypeError exception');
} catch (e) {
  if (!(e instanceof TypeError)) {
    $ERROR('#1.1: O is not an object, throw a TypeError exception');
  }
}

// CHECK#2
if ((instance.constructor !== FACTORY) || (instance.name !== "fairy")) {
  $ERROR('#2: instance.constructor === FACTORY');
}


text:
package gumi.builders.url;

import static gumi.builders.url.Rfc3986Util.*;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Percent-encoding according to the URI and URL standards.
 */
public class Encoder {

    protected static final boolean IS_PATH = true;

    protected static final boolean IS_NOT_PATH = false;

    protected static final boolean IS_FRAGMENT = true;

    protected static final boolean IS_NOT_FRAGMENT = false;

    protected static final boolean IS_USERINFO = true;

    protected static final boolean IS_NOT_USERINFO = false;

    protected final Charset outputEncoding;

    public Encoder(final Charset outputEncoding) {
        this.outputEncoding = outputEncoding;
    }

    public String encodeUserInfo(String input) {
        if (null == input || input.isEmpty()) {
            return "";
        }
        return urlEncode(input, IS_NOT_PATH, IS_NOT_FRAGMENT, IS_USERINFO);
    }

    public String encodePath(final String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }
        final StringBuilder sb = new StringBuilder();
        final StringTokenizer st = new StringTokenizer(input, "/", true);
        while (st.hasMoreElements()) {
            final String element = st.nextToken();
            if ("/".equals(element)) {
                sb.append(element);
            } else if (!element.isEmpty()) {
                sb.append(urlEncode(element, IS_PATH, IS_NOT_FRAGMENT, IS_NOT_USERINFO));
            }
        }
        return sb.toString();
    }

    public String encodeQueryParameters(final UrlParameterMultimap queryParametersMultimap) {
        if (queryParametersMultimap == null)
            throw new IllegalArgumentException("queryParametersMultimap is required to not be null.");
        final StringBuilder sb = new StringBuilder();
        for (final Map.Entry<String, String> e : queryParametersMultimap.flatEntryList()) {
            sb.append(encodeQueryElement(e.getKey()));
            if (e.getValue() != null) {
                sb.append('=');
                sb.append(encodeQueryElement(e.getValue()));
            }
            sb.append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    protected String encodeQueryElement(final String input) {
        return urlEncode(input, IS_NOT_PATH, IS_NOT_FRAGMENT, IS_NOT_USERINFO);
    }

    public String encodeFragment(final String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return urlEncode(input, IS_NOT_PATH, IS_FRAGMENT, IS_NOT_USERINFO);
    }

    protected String urlEncode(final String input, final boolean isPath,
            final boolean isFragment, final boolean isUserInfo)
    {
        final StringBuilder sb = new StringBuilder();
        final char[] inputChars = input.toCharArray();
        for (int i = 0; i < Character.codePointCount(inputChars, 0, inputChars.length); i++) {
            final CharBuffer cb;
            final int codePoint = Character.codePointAt(inputChars, i);
            if (Character.isBmpCodePoint(codePoint)) {
                final char c = Character.toChars(codePoint)[0];
                if ((isPath && isPChar(c) && c != '+')
                        || isFragment && isFragmentSafe(c)
                        || isUserInfo && c == ':'
                        || isUnreserved(c))
                {
                    sb.append(c);
                    continue;
                } else {
                    cb = CharBuffer.allocate(1);
                    cb.append(c);
                }
            } else {
                cb = CharBuffer.allocate(2);
                cb.append(Character.highSurrogate(codePoint));
                cb.append(Character.lowSurrogate(codePoint));
            }
            cb.rewind();
            final ByteBuffer bb = outputEncoding.encode(cb);
            for (int j = 0; j < bb.limit(); j++) {
                // Until someone has a real problem with the performance of this bit,
                // I will leave this less optimal, but much simpler implementation in place
                sb.append('%');
                sb.append(String.format("%1$02X", bb.get(j)));
            }
        }
        return sb.toString();
    }

}


text:
"""
Providing iterator functions that are not in all version of Python we support.
Where possible, we try to use the system-native version and only fall back to
these implementations if necessary.
"""

import itertools

# Fallback for Python 2.4, Python 2.5
def product(*args, **kwds):
    """
    Taken from http://docs.python.org/library/itertools.html#itertools.product
    """
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

if hasattr(itertools, 'product'):
    product = itertools.product

def is_iterable(x):
    "A implementation independent way of checking for iterables"
    try:
        iter(x)
    except TypeError:
        return False
    else:
        return True

def all(iterable):
    for item in iterable:
        if not item:
            return False
    return True

def any(iterable):
    for item in iterable:
        if item:
            return True
    return False


text:
package com.github.dozermapper.core.vo;

public class CustomDoubleObject extends BaseTestObject implements CustomDoubleObjectIF {
    private double theDouble;
    private String name;

    public double getTheDouble() {
        return theDouble;
    }

    public void setTheDouble(double theDouble) {
        this.theDouble = theDouble;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}