text:
package com.hazelcast.jet.sql;

import com.hazelcast.jet.sql.impl.connector.test.TestBatchSqlConnector;
import com.hazelcast.jet.sql.impl.connector.test.TestStreamSqlConnector;
import com.hazelcast.sql.HazelcastSqlException;
import com.hazelcast.sql.SqlService;
import com.hazelcast.sql.impl.type.QueryDataType;
import org.junit.BeforeClass;
import org.junit.Test;

import java.math.BigDecimal;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class SqlAggregateTest extends SqlTestSupport {

    private static SqlService sqlService;

    @BeforeClass
    public static void setUpClass() {
        initialize(2, null);
        sqlService = instance().getSql();
    }

    @Test
    public void test_groupBy() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{null, "1"},
                new String[]{"Alice", "1"},
                new String[]{null, "1"}
        );

        assertRowsAnyOrder(
                "SELECT name FROM " + name + " GROUP BY 1", // field ordinal
                asList(
                        new Row("Alice"),
                        new Row("Bob"),
                        new Row((String) null)
                )
        );
        assertRowsAnyOrder(
                "SELECT distance, name FROM " + name + " GROUP BY distance, name",
                asList(
                        new Row(1, "Alice"),
                        new Row(2, "Alice"),
                        new Row(1, "Bob"),
                        new Row(1, null)
                )
        );
    }

    @Test
    public void test_groupByEmpty() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT name FROM " + name + " GROUP BY name",
                emptyList()
        );
    }

    @Test
    public void test_groupByNotSelectedField() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "4"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name FROM " + name + " GROUP BY name, distance",
                asList(
                        new Row("Alice"),
                        new Row("Alice"),
                        new Row("Bob"),
                        new Row("Joey")
                )
        );
    }

    @Test
    public void test_groupByExpression() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, (distance * 2) d FROM " + name + " GROUP BY name, distance * 2",
                asList(
                        new Row("Alice", 2L),
                        new Row("Alice", 4L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_groupByHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, distance FROM " + name + " GROUP BY name, distance HAVING distance < 2",
                asList(
                        new Row("Alice", 1),
                        new Row("Bob", 1)
                )
        );
    }

    @Test
    public void test_groupByExpressionHavingExpression() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "4"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, (distance * 2) d FROM " + name + " GROUP BY name, d HAVING d > 2",
                asList(
                        new Row("Alice", 4L),
                        new Row("Alice", 8L),
                        new Row("Joey", 4L)
                )
        );
    }

    @Test
    public void test_distinct() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "4"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "2"}
        );

        assertRowsAnyOrder(
                "SELECT DISTINCT name FROM " + name,
                asList(
                        new Row("Alice"),
                        new Row("Bob"),
                        new Row("Joey")
                )
        );
    }

    @Test
    public void test_all() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "4"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "2"}
        );

        assertRowsAnyOrder(
                "SELECT ALL name FROM " + name,
                asList(
                        new Row("Alice"),
                        new Row("Alice"),
                        new Row("Alice"),
                        new Row("Bob"),
                        new Row("Joey")
                )
        );
    }

    @Test
    public void test_count() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{null, "1"}
        );

        assertRowsAnyOrder(
                "SELECT COUNT(name) FROM " + name,
                singletonList(new Row(2L))
        );
        assertRowsAnyOrder(
                "SELECT COUNT(*) FROM " + name,
                singletonList(new Row(3L))
        );
    }

    @Test
    public void test_emptyCount() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT COUNT(*) FROM " + name,
                singletonList(new Row(0L))
        );
    }

    @Test
    public void test_emptyCountGroupBy() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT COUNT(*) FROM " + name + " GROUP BY name",
                emptyList()
        );
    }

    @Test
    public void test_distinctCount() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT COUNT(DISTINCT distance) FROM " + name,
                singletonList(new Row(2L))
        );
    }

    @Test
    public void test_groupCount() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, COUNT(*) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 3L),
                        new Row("Bob", 1L)
                )
        );
    }

    @Test
    public void test_groupDistinctCount() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, COUNT(DISTINCT distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 2L),
                        new Row("Bob", 1L)
                )
        );
    }

    @Test
    public void test_groupExpressionCount() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"},
                new String[]{"Joey", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, (distance * 2) d, COUNT(*) FROM " + name + " GROUP BY name, d",
                asList(
                        new Row("Alice", 2L, 2L),
                        new Row("Alice", 4L, 1L),
                        new Row("Bob", 2L, 1L),
                        new Row("Joey", 2L, 1L)
                )
        );
    }

    @Test
    public void test_groupCountExpression() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"},
                new String[]{"Joey", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, 2 * COUNT(*) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 6L),
                        new Row("Bob", 2L),
                        new Row("Joey", 2L)
                )
        );
    }

    @Test
    public void test_groupCountHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, COUNT(*) c FROM " + name + " GROUP BY name, distance HAVING c < 2",
                asList(
                        new Row("Alice", 1L),
                        new Row("Bob", 1L)
                )
        );
    }

    @Test
    public void test_groupCountHavingAggregation() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, COUNT(*) FROM " + name + " GROUP BY name, distance HAVING COUNT(*) < 2",
                asList(
                        new Row("Alice", 1L),
                        new Row("Bob", 1L)
                )
        );
    }

    @Test
    public void test_groupExpressionCountHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, (distance * 2) d, COUNT(*) c FROM " + name + " GROUP BY name, d HAVING c < 2",
                asList(
                        new Row("Alice", 4L, 1L),
                        new Row("Bob", 2L, 1L)
                )
        );
    }

    @Test
    public void test_min() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT MIN(name), MIN(distance) FROM " + name,
                singletonList(new Row("Alice", 1))
        );
    }

    @Test
    public void test_emptyMin() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT MIN(name), MIN(distance) FROM " + name,
                singletonList(new Row(null, null))
        );
    }

    @Test
    public void test_groupMin() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, MIN(distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 1),
                        new Row("Bob", 2)
                )
        );
    }

    @Test
    public void test_distinctMin() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT MIN(DISTINCT name) FROM " + name,
                singletonList(new Row("Alice"))
        );
    }

    @Test
    public void test_groupExpressionMin() {
        String name = createTable(
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, MIN(distance * 2) m FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 2L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_groupMinHaving() {
        String name = createTable(
                new String[]{"Joey", "3"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, MIN(distance) m FROM " + name + " GROUP BY name HAVING m > 1",
                asList(
                        new Row("Bob", 2),
                        new Row("Joey", 3)
                )
        );
    }

    @Test
    public void test_groupExpressionMinHaving() {
        String name = createTable(
                new String[]{"Joey", "3"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, MIN(distance * 2) m FROM " + name + " GROUP BY name HAVING m < 5",
                asList(
                        new Row("Alice", 2L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_max() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT MAX(name), MAX(distance) FROM " + name,
                singletonList(new Row("Joey", 2))
        );
    }

    @Test
    public void test_emptyMax() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT MAX(name), MAX(distance) FROM " + name,
                singletonList(new Row(null, null))
        );
    }

    @Test
    public void test_groupMax() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, MAX(distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 2),
                        new Row("Bob", 2)
                )
        );
    }

    @Test
    public void test_distinctMax() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT MAX(DISTINCT name) FROM " + name,
                singletonList(new Row("Joey"))
        );
    }

    @Test
    public void test_groupExpressionMax() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, MAX(distance * 2) m FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 4L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_groupMaxHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, MAX(distance) m FROM " + name + " GROUP BY name HAVING m > 1",
                asList(
                        new Row("Alice", 2),
                        new Row("Joey", 3)
                )
        );
    }

    @Test
    public void test_groupExpressionMaxHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, MAX(distance * 2) m FROM " + name + " GROUP BY name HAVING m < 5",
                asList(
                        new Row("Alice", 4L),
                        new Row("Bob", 4L)
                )
        );
    }

    @Test
    public void test_sum() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT SUM(distance) FROM " + name,
                singletonList(new Row(3L))
        );
    }

    @Test
    public void test_emptySum() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT SUM(distance) FROM " + name,
                singletonList(new Row((Object) null))
        );
    }

    @Test
    public void test_almostEmptySum() {
        String name = createTable(
                new String[]{"Alice", null}
        );

        assertRowsAnyOrder(
                "SELECT SUM(distance) FROM " + name,
                singletonList(new Row((Object) null))
        );
    }

    @Test
    public void test_distinctSum() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT SUM(DISTINCT distance) FROM " + name,
                singletonList(new Row(3L))
        );
    }

    @Test
    public void test_groupSum() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, SUM(distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 3L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_groupDistinctSum() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, SUM(DISTINCT distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 3L),
                        new Row("Bob", 1L)
                )
        );
    }

    @Test
    public void test_groupExpressionSum() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, SUM(distance * 2) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", 6L),
                        new Row("Bob", 2L)
                )
        );
    }

    @Test
    public void test_groupSumHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, SUM(distance) s FROM " + name + " GROUP BY name HAVING s > 2",
                asList(
                        new Row("Alice", 3L),
                        new Row("Joey", 3L)
                )
        );
    }

    @Test
    public void test_groupExpressionSumHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, SUM(distance * 2) s FROM " + name + " GROUP BY name HAVING s > 4",
                asList(
                        new Row("Alice", 6L),
                        new Row("Joey", 6L)
                )
        );
    }

    @Test
    public void test_avg() {
        String name = createTable(
                new String[]{"Alice", "4"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", null}
        );

        assertRowsAnyOrder(
                "SELECT AVG(distance) FROM " + name,
                singletonList(new Row(new BigDecimal("3")))
        );
    }

    @Test
    public void test_emptyAvg() {
        String name = createTable();

        assertRowsAnyOrder(
                "SELECT AVG(distance) FROM " + name,
                singletonList(new Row((Object) null))
        );
    }

    @Test
    public void test_distinctAvg() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT AVG(DISTINCT distance) FROM " + name,
                singletonList(new Row(new BigDecimal("1.5")))
        );
    }

    @Test
    public void test_groupAvg() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, AVG(distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", new BigDecimal("1.5")),
                        new Row("Bob", new BigDecimal("2"))
                )
        );
    }

    @Test
    public void test_groupDistinctAvg() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "1"}
        );

        assertRowsAnyOrder(
                "SELECT name, AVG(DISTINCT distance) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", new BigDecimal("1.5")),
                        new Row("Bob", new BigDecimal("1"))
                )
        );
    }

    @Test
    public void test_groupExpressionAvg() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "1"},
                new String[]{"Alice", "2"}
        );

        assertRowsAnyOrder(
                "SELECT name, AVG(distance * 2) FROM " + name + " GROUP BY name",
                asList(
                        new Row("Alice", new BigDecimal("3")),
                        new Row("Bob", new BigDecimal("2"))
                )
        );
    }

    @Test
    public void test_groupAvgHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "3"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, AVG(distance) s FROM " + name + " GROUP BY name HAVING s > 2",
                asList(
                        new Row("Bob", new BigDecimal("2.5")),
                        new Row("Joey", new BigDecimal("3"))
                )
        );
    }

    @Test
    public void test_groupExpressionAvgHaving() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "3"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT name, AVG(distance * 2) s FROM " + name + " GROUP BY name HAVING s > 4",
                asList(
                        new Row("Bob", new BigDecimal("5")),
                        new Row("Joey", new BigDecimal("6"))
                )
        );
    }

    @Test
    public void test_multipleAggregateFunctions() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT COUNT(*), MIN(distance), MAX(distance), SUM(distance), AVG(distance) FROM " + name,
                singletonList(new Row(3L, 1, 3, 6L, new BigDecimal("2")))
        );
    }

    @Test
    public void test_expressionFromAggregates() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT COUNT(*) * SUM(distance) FROM " + name,
                singletonList(new Row(18L))
        );
    }

    @Test
    public void test_nestedAggregation() {
        String name = createTable(
                new String[]{"Alice", "1"},
                new String[]{"Bob", "2"},
                new String[]{"Alice", "2"},
                new String[]{"Bob", "3"},
                new String[]{"Joey", "3"}
        );

        assertRowsAnyOrder(
                "SELECT MAX(avg_dist) " +
                        "FROM (SELECT name, AVG(distance) avg_dist FROM " + name + " GROUP BY name)",
                singletonList(
                        new Row(new BigDecimal("3"))
                )
        );
    }

    @Test
    public void test_aggregatingStreamingSource() {
        String name = randomName();
        sqlService.execute("CREATE MAPPING " + name + " TYPE " + TestStreamSqlConnector.TYPE_NAME);

        assertThatThrownBy(() -> sqlService.execute("SELECT COUNT(*) FROM " + name))
                .isInstanceOf(HazelcastSqlException.class)
                .hasMessageContaining("not supported");
    }

    @Test
    public void test_distinctStreamingSource() {
        String name = randomName();
        sqlService.execute("CREATE MAPPING " + name + " TYPE " + TestStreamSqlConnector.TYPE_NAME);

        assertThatThrownBy(() -> sqlService.execute("SELECT DISTINCT v FROM " + name))
                .isInstanceOf(HazelcastSqlException.class)
                .hasMessageContaining("not supported");
    }

    @Test
    public void test_rollup() {
        String name = createTable();
        assertThatThrownBy(
                () -> sqlService.execute("SELECT COUNT(*) FROM " + name + " GROUP BY ROLLUP(name, distance)"))
                .isInstanceOf(HazelcastSqlException.class)
                .hasMessageContaining("ROLLUP not supported");
    }

    @Test
    public void test_cube() {
        String name = createTable();
        assertThatThrownBy(
                () -> sqlService.execute("SELECT COUNT(*) FROM " + name + " GROUP BY CUBE(name, distance)"))
                .isInstanceOf(HazelcastSqlException.class)
                .hasMessageContaining("CUBE not supported");
    }

    @Test
    public void test_groupingSet() {
        String name = createTable();
        assertThatThrownBy(
                () -> sqlService.execute("SELECT COUNT(*) FROM " + name + " GROUP BY GROUPING SETS ((name), (distance))"))
                .isInstanceOf(HazelcastSqlException.class)
                .hasMessageContaining("GROUPING SETS not supported");
    }

    private static String createTable(String[]... values) {
        String name = randomName();
        TestBatchSqlConnector.create(
                sqlService,
                name,
                asList("name", "distance"),
                asList(QueryDataType.VARCHAR, QueryDataType.INT),
                asList(values)
        );
        return name;
    }
}


text:
using HAbp.Domain.Repositories;
using HAbp.Runtime.Session;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;

namespace HAbp.Dependency
{
    /// <summary>
    /// 所有内置注册方法,统一放在这里
    /// </summary>
    internal class AbpCoreInstaller
    {
        IServiceCollection services = null;
        public AbpCoreInstaller(IServiceCollection services)
        {
            this.services = services;
        }
        public void Install()
        {
            //尝试注册日志组件
            services.AddLogging();

            ////注册ABP自身语言本地化
            //serviceCollection.Add(ServiceDescriptor.Singleton<IStringLocalizer<AbpResource>>(sc => null));
            ////serviceCollection.AddLocalization(localizationOptions => {
            ////    if (localizationOptions.ResourcesPath == String.Empty)
            ////    {

            ////    }
            ////});

            services.TryAddSingleton<IRepositoryFactory, RepositoryFactory>();
            services.TryAddTransient(typeof(IRepository<,>), typeof(Repository<,>));
            services.TryAddTransient(typeof(IRepository<>), typeof(Repository<>));

            services.TryAddScoped<IAbpSession, NullAbpSession>();

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.commons.lang3.tuple;

/**
 *
A mutable pair consisting of two {@code Object} elements.

 *
 *
Not #ThreadSafe#

 *
 * @param <L> the left element type
 * @param <R> the right element type
 *
 * @since Lang 3.0
 * @version $Id: MutablePair.java 1436770 2013-01-22 07:09:45Z ggregory $
 */
public class MutablePair<L, R> extends Pair<L, R> {

    /** Serialization version */
    private static final long serialVersionUID = 4954918890077093841L;

    /** Left object */
    public L left;
    /** Right object */
    public R right;

    /**
     *
Obtains an immutable pair of from two objects inferring the generic types.

     *
     *
This factory allows the pair to be created using inference to
     * obtain the generic types.

     *
     * @param <L> the left element type
     * @param <R> the right element type
     * @param left  the left element, may be null
     * @param right  the right element, may be null
     * @return a pair formed from the two parameters, not null
     */
    public static <L, R> MutablePair<L, R> of(final L left, final R right) {
        return new MutablePair<L, R>(left, right);
    }

    /**
     * Create a new pair instance of two nulls.
     */
    public MutablePair() {
        super();
    }

    /**
     * Create a new pair instance.
     *
     * @param left  the left value, may be null
     * @param right  the right value, may be null
     */
    public MutablePair(final L left, final R right) {
        super();
        this.left = left;
        this.right = right;
    }

    //-----------------------------------------------------------------------
    /**
     * {@inheritDoc}
     */
    @Override
    public L getLeft() {
        return left;
    }

    /**
     * Sets the left element of the pair.
     *
     * @param left  the new value of the left element, may be null
     */
    public void setLeft(final L left) {
        this.left = left;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public R getRight() {
        return right;
    }

    /**
     * Sets the right element of the pair.
     *
     * @param right  the new value of the right element, may be null
     */
    public void setRight(final R right) {
        this.right = right;
    }

    /**
     * Sets the {@code Map.Entry} value.
     * This sets the right element of the pair.
     *
     * @param value  the right value to set, not null
     * @return the old value for the right element
     */
    @Override
    public R setValue(final R value) {
        final R result = getRight();
        setRight(value);
        return result;
    }

}


text:
require 'spec_helper'
require 'bike_model_factory'

describe BikeModelFactory do
  it "should take a hash of arguments with specified scope" do
    args = {
      :model_id => '1',
      :brand_scope=>BikeBrand,
      :model_scope=>BikeModel
    }
    factory = BikeModelFactory.new(args)
    expect(factory).to_not be_nil
  end

  context "constructed with nil params" do
    let(:params){h={:model_id => nil,
        :model_name =>nil,
        :brand_id =>nil,
        :brand_name => nil,
      :param_prefix => :bike}}
    subject(:factory){BikeModelFactory.new(params)}
    it "is not nil" do
      expect(factory).to_not be_nil
    end
  end

  context "constructed with model name and brand name" do
    let(:params){h={:model_id => nil,
        :model_name =>'mymodelname',
        :brand_id =>nil,
        :brand_name => 'mybrandname',
      :param_prefix => :bike}}
    subject(:factory){BikeModelFactory.new(params)}
    it "is not nil" do
      expect(factory).to_not be_nil
    end
  end
end

class ModelFactoryAsserter

  def initialize(base, model=nil)
    @base = base
    @model = model || BikeModel.all.first
    @brand = @model.brand if @model
  end

  #
  # @params Array given_params used to generate the factory params
  # @params (:sym, [:sym, :sym]) expected as model_case or [model_case, brand_case]
  def run(given_params, expected)
    params = generate_params(given_params)
    params.merge!({:param_prefix => :bike})

    brand_case = 0 # initialize to not nil
    model_case = 0 # initialize to not nil

    if expected.respond_to?(:to_sym)
      model_case = expected
    elsif expected.respond_to?('to_a')
      model_case = expected.to_a[0]
      brand_case = expected.to_a[1]
    end

    if model_case == :found
      factory = BikeModelFactory.new(params)
      @base.expect(factory.model).to_not @base.be_nil
      @base.expect(factory.model).to @base.eq @model

      if brand_case == :found
        @base.expect(factory.model.brand).to @base.eq @brand
      elsif brand_case.nil?
        @base.expect(factory.model.brand).to @base.be_nil
      end

    elsif model_case == :new
      factory = BikeModelFactory.new(params)

      @base.expect(factory.model).to_not @base.be_nil
      @base.expect(factory.model).to @base.be_valid

      if brand_case == :found
        @base.expect{ factory.model.save }.
          to @base.change{BikeModel.count + BikeBrand.count}.by(1)
        @base.expect(factory.model.brand).to_not @base.be_nil
      elsif brand_case == :new
        @base.expect{ factory.model.save }.
          to @base.change{BikeModel.count + BikeBrand.count}.by(2)
        @base.expect(factory.model.brand).to_not @base.be_nil
      elsif brand_case == nil
        @base.expect{ factory.model.save }.
          to @base.change{BikeModel.count + BikeBrand.count}.by(1)
        @base.expect(factory.model.brand).to @base.be_nil
      end
    elsif model_case.nil?
      factory = BikeModelFactory.new(params)
      @base.expect(factory.model).to @base.be_nil
    elsif model_case == :exception
      e_thrown = false
      begin
        factory = BikeModelFactory.new(params)
      rescue Exception
        e_thrown = true
      end
      @base.expect(e_thrown).to @base.be_truthy
    end
  end

  private

  #
  # given paramaters in form of
  # [model_id, model_name, brand_id, brand_name]
  def generate_params(given)
    given ||= []
    {:model_id => generate_id(@model, given[0]),
      :model_name => generate_name(@model, given[1]),
      :brand_id => generate_id(@brand, given[2]),
      :brand_name => generate_name(@brand, given[3])}
  end

  # @params (nil, :found, :missing) sym id param case
  def generate_id(scope, sym)
    return nil if scope.nil?
    id = case sym
         when :found then scope.id
         when :missing then 0
         else nil
         end
    return id
  end

  # @params (nil, :found, :new) sym name param case
  def generate_name(scope, sym)
    return nil if scope.nil?
    id = case sym
         when :found then scope.name
         when :new then scope.name.to_s + " new#{scope.class.count+1}"
           else nil
         end
    return id
  end

end # class ModelFactoryAsserter

describe 'BikeModelFactory#model' do
  before :all do
    model_with_brand = BikeModel.where{ bike_brand_id != nil}.first
    expect(model_with_brand).to_not be_nil
    @a = ModelFactoryAsserter.new(self, model_with_brand)

    model_without_brand = BikeModel.where{bike_brand_id == nil}.first
    expect(model_without_brand).to_not be_nil
    @b = ModelFactoryAsserter.new(self, model_without_brand)

    model_without_name = BikeModel.where{ name == '' }.first
    expect(model_without_name).to_not be_nil
    @c = ModelFactoryAsserter.new(self, model_without_name)

    unknown_model_with_brand = BikeModel.where{ (name == '') & (bike_brand_id != nil)}.first
    expect(unknown_model_with_brand).to_not be_nil
    @d = ModelFactoryAsserter.new(self, unknown_model_with_brand)
  end

  should = "should be nil"
  it should do @a.run(nil , nil) end
  it should do @a.run([0,0,0,0] , nil) end
  it should do @a.run([:missing,0,0,0] , nil) end

  should = "should be found"
  context "with brand" do
    it should do @a.run([:found, 0, 0, 0],:found) end
    it should do @a.run([0, :found, 0, :found],:found) end
    it should do @a.run([0, :found, :found, 0],[:found, :found]) end
  end
  context "without brand" do
    it should do @b.run([0, :found, 0, 0], [:found, nil]) end
  end
  context "model without name" do
    it should do @c.run([0, :found, :found, 0], :found) end
    it should do @c.run([0, :found, 0, :found], :found) end
    it should do @c.run([0, 0, :found, 0], [:found, :found]) end
    it should do @c.run([0, 0, 0, :found], [:found, :found]) end
  end

  should = "should be new with nil brand"
  it should do @a.run([0, :new, 0, 0], [:new, nil]) end

  should = "should be new with found brand"
  it should do @a.run([0, :new, :found, 0], [:new, :found]) end
  it should do @a.run([0, :new, 0, :found], [:new, :found]) end

  should = "should be found with found brand"
  it should do @d.run([0, 0, :found, 0], [:found, :found]) end
  it should do @d.run([0, 0, 0, :found], [:found, :found]) end

  should = "should be new with new brand"
  it should do @a.run([0, :new, 0, :new], [:new, :new]) end
  it should do @a.run([0, 0, 0, :new], [:new, :new]) end

  should = "should be new with new brand"
  it should do @d.run([0, 0, 0, :new], [:new, :new]) end

  should = "should raise exception"
  it should do @a.run([0, 0, :found, :found], :exception) end
  it should do @a.run([0, :found, :found, :found], :exception) end

  it should do @a.run([:found, 0, 0, :found], :exception) end
  it should do @a.run([:found, 0, :found, 0], :exception) end
  it should do @a.run([:found, 0, :found, :found], :exception) end
  it should do @a.run([:found, :found, 0, 0], :exception) end
  it should do @a.run([:found, :found, 0, :found], :exception) end
  it should do @a.run([:found, :found, :found, 0], :exception) end
  it should do @a.run([:found, :found, :found, :found], :exception) end

end # describe BikeModelFactory#model


text:
%%
%% This is file `accsupp-example1.tex',
%% generated with the docstrip utility.
%%
%% The original source files were:
%%
%% accsupp.dtx  (with options: `example1')
%%
%% This is a generated file.
%%
%% Project: accsupp
%% Version: 2010/01/16 v0.3
%%
%% Copyright (C) 2007, 2010 by
%%    Heiko Oberdiek <heiko.oberdiek at googlemail.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either
%% version 1.3c of this license or (at your option) any later
%% version. This version of this license is in
%%    http://www.latex-project.org/lppl/lppl-1-3c.txt
%% and the latest version of this license is in
%%    http://www.latex-project.org/lppl.txt
%% and version 1.3 or later is part of all distributions of
%% LaTeX version 2005/12/01 or later.
%%
%% This work has the LPPL maintenance status "maintained".
%%
%% This Current Maintainer of this work is Heiko Oberdiek.
%%
%% This work consists of the main source file accsupp.dtx
%% and the derived files
%%    accsupp.sty, accsupp.pdf, accsupp.ins, accsupp.drv,
%%    accsupp-pdftex.def, accsupp-dvipdfm.def, accsupp-dvips.def,
%%    accsupp-example1.tex, accsupp-example2.tex,
%%    accsupp-test1.tex.
%%
\documentclass{article}
\usepackage{accsupp}[2007/11/14]
\usepackage{centernot}
% U+2226 NOT PARALLEL
% \mathrel{...} prevents page break in between
\newcommand*{\notparallel}{%
  \ensuremath{%
    \mathrel{%
      \BeginAccSupp{method=hex,unicode,ActualText=2226}%
      \centernot{\parallel}%
      \EndAccSupp{}%
    }%
  }%
}
\begin{document}
\begin{equation}
A\notparallel B
\end{equation}
\end{document}
\endinput
%%
%% End of file `accsupp-example1.tex'.


text:
define([
    'jquery',
    'bluebird',
    'kb_lib/html',
    'kb_lib/htmlBootstrapBuilders',
    '../utils',
    './assemblySummary',
    './assemblyContigs'
], ($, Promise, html, BS, utils, AssemblySummary, AssemblyContigs) => {
    const t = html.tag,
        div = t('div');

    function factory(config) {
        let hostNode,
            container;
        const runtime = config.runtime;

        const widgets = [
            {
                module: AssemblySummary,
                id: 'summary'
            },
            {
                module: AssemblyContigs,
                id: 'contigs'
            }
        ];
        widgets.forEach((widget) => {
            widget.instance = widget.module.make({
                runtime
            });
        });

        // VIEW

        function layout() {
            return div([
                BS.buildPanel({
                    type: 'default',
                    title: 'Summary',
                    body: div({
                        dataElement: 'summary'
                    })
                }),
                BS.buildPanel({
                    type: 'default',
                    title: 'Contigs',
                    body: div({
                        dataElement: 'contigs'
                    })
                })
            ]);
        }

        // WIDGET API

        function attach(node) {
            hostNode = node;
            container = hostNode.appendChild(document.createElement('div'));
            // safe
            container.innerHTML = layout();
            return Promise.all(
                widgets.map((widget) => {
                    return widget.instance.attach(container.querySelector(`[data-element="${  widget.id  }"]`));
                })
            );
        }

        function start(params) {
            // get the assembly reference
            const assemblyRef = utils.getRef(params);

            return Promise.all(
                widgets.map((widget) => {
                    return widget.instance.start({
                        objectRef: assemblyRef
                    });
                })
            );
        }

        function stop() {
            return Promise.all(
                widgets.map((widget) => {
                    return widget.instance.stop();
                })
            );
        }

        function detach() {
            return Promise.all(
                widgets.map((widget) => {
                    return widget.instance.detach();
                })
            ).then(() => {
                if (hostNode && container) {
                    // safe
                    container.innerHTML = '';
                    hostNode.removeChild(container);
                }
            });
        }

        return Object.freeze({
            attach,
            start,
            stop,
            detach
        });
    }

    return {
        make(config) {
            return factory(config);
        }
    };
});


text:
"""Functional test for moving_averages.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.python.platform

from six.moves import xrange  # pylint: disable=redefined-builtin
from tensorflow.python.framework import test_util
from tensorflow.python.framework import types
from tensorflow.python.ops import constant_op
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.training import moving_averages

class MovingAveragesTest(test_util.TensorFlowTestCase):

  def testAssignMovingAverage(self):
    with self.test_session():
      var = variables.Variable([10.0, 11.0])
      val = constant_op.constant([1.0, 2.0], types.float32)
      decay = 0.25
      assign = moving_averages.assign_moving_average(var, val, decay)
      variables.initialize_all_variables().run()
      self.assertAllClose([10.0, 11.0], var.eval())
      assign.op.run()
      self.assertAllClose([10.0 * 0.25 + 1.0 * (1.0 - 0.25),
                           11.0 * 0.25 + 2.0 * (1.0 - 0.25)],
                          var.eval())

def _Repeat(value, dim):
  if dim == 1:
    return value
  return [value for _ in xrange(dim)]

class ExponentialMovingAverageTest(test_util.TensorFlowTestCase):

  def _CheckDecay(self, ema, actual_decay, dim):
    tens = _Repeat(10.0, dim)
    thirties = _Repeat(30.0, dim)
    var0 = variables.Variable(tens, name="v0")
    var1 = variables.Variable(thirties, name="v1")
    variables.initialize_all_variables().run()
    # Note that tensor2 is not a Variable but just a plain Tensor resulting
    # from the sum operation.
    tensor2 = var0 + var1
    update = ema.apply([var0, var1, tensor2])
    avg0 = ema.average(var0)
    avg1 = ema.average(var1)
    avg2 = ema.average(tensor2)

    self.assertFalse(avg0 in variables.trainable_variables())
    self.assertFalse(avg1 in variables.trainable_variables())
    self.assertFalse(avg2 in variables.trainable_variables())
    variables.initialize_all_variables().run()

    self.assertEqual("v0/ExponentialMovingAverage:0", avg0.name)
    self.assertEqual("v1/ExponentialMovingAverage:0", avg1.name)
    self.assertEqual("add/ExponentialMovingAverage:0", avg2.name)

    # Check initial values.
    self.assertAllClose(tens, var0.eval())
    self.assertAllClose(thirties, var1.eval())
    self.assertAllClose(_Repeat(10.0 + 30.0, dim), tensor2.eval())

    # Check that averages are initialized correctly.
    self.assertAllClose(tens, avg0.eval())
    self.assertAllClose(thirties, avg1.eval())
    # Note that averages of Tensor's initialize to zeros_like since no value
    # of the Tensor is known because the Op has not been run (yet).
    self.assertAllClose(_Repeat(0.0, dim), avg2.eval())

    # Update the averages and check.
    update.run()
    dk = actual_decay

    expected = _Repeat(10.0 * dk + 10.0 * (1 - dk), dim)
    self.assertAllClose(expected, avg0.eval())
    expected = _Repeat(30.0 * dk + 30.0 * (1 - dk), dim)
    self.assertAllClose(expected, avg1.eval())
    expected = _Repeat(0.0 * dk + (10.0 + 30.0) * (1 - dk), dim)
    self.assertAllClose(expected, avg2.eval())

    # Again, update the averages and check.
    update.run()
    expected = _Repeat((10.0 * dk + 10.0 * (1 - dk)) * dk + 10.0 * (1 - dk),
                       dim)
    self.assertAllClose(expected, avg0.eval())
    expected = _Repeat((30.0 * dk + 30.0 * (1 - dk)) * dk + 30.0 * (1 - dk),
                       dim)
    self.assertAllClose(expected, avg1.eval())
    expected = _Repeat(((0.0 * dk + (10.0 + 30.0) * (1 - dk)) * dk +
                        (10.0 + 30.0) * (1 - dk)),
                       dim)
    self.assertAllClose(expected, avg2.eval())

  def testAverageVariablesNoNumUpdates_Scalar(self):
    with self.test_session():
      ema = moving_averages.ExponentialMovingAverage(0.25)
      self._CheckDecay(ema, actual_decay=0.25, dim=1)

  def testAverageVariablesNoNumUpdates_Vector(self):
    with self.test_session():
      ema = moving_averages.ExponentialMovingAverage(0.25)
      self._CheckDecay(ema, actual_decay=0.25, dim=5)

  def testAverageVariablesNumUpdates_Scalar(self):
    with self.test_session():
      # With num_updates 1, the decay applied is 0.1818
      ema = moving_averages.ExponentialMovingAverage(0.25, num_updates=1)
      self._CheckDecay(ema, actual_decay=0.181818, dim=1)

  def testAverageVariablesNumUpdates_Vector(self):
    with self.test_session():
      # With num_updates 1, the decay applied is 0.1818
      ema = moving_averages.ExponentialMovingAverage(0.25, num_updates=1)
      self._CheckDecay(ema, actual_decay=0.181818, dim=5)

  def testAverageVariablesNames(self):
    v0 = variables.Variable(10.0, name="v0")
    v1 = variables.Variable(30.0, name="v1")
    tensor2 = v0 + v1
    ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
    self.assertEqual("v0/foo_avg", ema.average_name(v0))
    self.assertEqual("v1/foo_avg", ema.average_name(v1))
    self.assertEqual("add/foo_avg", ema.average_name(tensor2))
    ema.apply([v0, v1, tensor2])
    self.assertEqual(ema.average_name(v0), ema.average(v0).op.name)
    self.assertEqual(ema.average_name(v1), ema.average(v1).op.name)
    self.assertEqual(ema.average_name(tensor2), ema.average(tensor2).op.name)

if __name__ == "__main__":
  googletest.main()


text:
import React from 'react';
import { NativeModules, UIManager, ViewPropTypes, requireNativeComponent } from 'react-native';
// To make the transition from React Native's `requireNativeComponent` to Expo's
// `requireNativeViewManager` as easy as possible, `requireNativeViewManager` is a drop-in
// replacement for `requireNativeComponent`.
//
// For each view manager, we create a wrapper component that accepts all of the props available to
// the author of the universal module. This wrapper component splits the props into two sets: props
// passed to React Native's View (ex: style, testID) and custom view props, which are passed to the
// adapter view component in a prop called `proxiedProperties`.
// NOTE: React Native is moving away from runtime PropTypes and may remove ViewPropTypes, in which
// case we will need another way to separate standard React Native view props from other props,
// which we proxy through the adapter
const ViewPropTypesKeys = Object.keys(ViewPropTypes);
/**
 * A drop-in replacement for `requireNativeComponent`.
 */
export function requireNativeViewManager(viewName) {
    if (__DEV__) {
        const { NativeUnimoduleProxy } = NativeModules;
        if (!NativeUnimoduleProxy.viewManagersNames.includes(viewName)) {
            const exportedViewManagerNames = NativeUnimoduleProxy.viewManagersNames.join(', ');
            console.warn(`The native view manager required by name (${viewName}) from NativeViewManagerAdapter isn't exported by expo-modules-core. Views of this type may not render correctly. Exported view managers: [${exportedViewManagerNames}].`);
        }
    }
    // Set up the React Native native component, which is an adapter to the universal module's view
    // manager
    const reactNativeViewName = `ViewManagerAdapter_${viewName}`;
    const ReactNativeComponent = requireNativeComponent(reactNativeViewName);
    const reactNativeUIConfiguration = (UIManager.getViewManagerConfig
        ? UIManager.getViewManagerConfig(reactNativeViewName)
        : UIManager[reactNativeViewName]) || {
        NativeProps: {},
        directEventTypes: {},
    };
    const reactNativeComponentPropNames = [
        'children',
        ...ViewPropTypesKeys,
        ...Object.keys(reactNativeUIConfiguration.NativeProps),
        ...Object.keys(reactNativeUIConfiguration.directEventTypes),
    ];
    // Define a component for universal-module authors to access their native view manager
    function NativeComponentAdapter(props, ref) {
        const nativeProps = pick(props, reactNativeComponentPropNames);
        const proxiedProps = omit(props, reactNativeComponentPropNames);
        return React.createElement(ReactNativeComponent, { ...nativeProps, proxiedProperties: proxiedProps, ref: ref });
    }
    NativeComponentAdapter.displayName = `Adapter<${viewName}>`;
    return React.forwardRef(NativeComponentAdapter);
}
function omit(props, propNames) {
    const copied = { ...props };
    for (const propName of propNames) {
        delete copied[propName];
    }
    return copied;
}
function pick(props, propNames) {
    return propNames.reduce((prev, curr) => {
        if (curr in props) {
            prev[curr] = props[curr];
        }
        return prev;
    }, {});
}
//# sourceMappingURL=NativeViewManagerAdapter.native.js.map


text:
function loadText()
    {
    var txtLang = document.getElementsByName("txtLang");
    txtLang[0].innerHTML = "Farvepalette";
    txtLang[1].innerHTML = "Farvens navn";
    txtLang[2].innerHTML = "216 websikre farver";
    txtLang[3].innerHTML = "Ny";
    txtLang[4].innerHTML = "Aktuel";
    txtLang[5].innerHTML = "Egne farver";

    document.getElementById("btnAddToCustom").value = "Tilf\u00F8j til egne farver";
    document.getElementById("btnCancel").value = " Annuller ";
    document.getElementById("btnRemove").value = " Fjern farve ";
    document.getElementById("btnApply").value = " Opdater ";
    document.getElementById("btnOk").value = " Ok ";
    }
function writeTitle()
    {
    document.write("<title>Farve</title>")
    }


text:
/** @jsxRuntime classic */
/** @jsx jsx */
import { jsx } from '@emotion/react';

import { Type } from '../../../components/primitives/Type';
import { DocsPage } from '../../../components/Page';
import { Well } from '../../../components/primitives/Well';
import { useMediaQuery } from '../../../lib/media';
import { InlineCode } from '../../../components/primitives/Code';

export function QuickStart() {
  const mq = useMediaQuery();
  return (

        <Well heading="Keystone Quick Start" href="/docs/getting-started">
          Take a tour of Keystone in minutes with our CLI starter project
        </Well>

  );
}

export function Foundations() {
  const mq = useMediaQuery();
  return (

        <Well
          grad="grad2"
          heading="Lesson 1: Installing Keystone "
          href="/docs/walkthroughs/lesson-1"
        >
          Get Keystone up and running with your first content type
        </Well>
        <Well grad="grad2" heading="Lesson 2: Relating things" href="/docs/walkthroughs/lesson-2">
          Connect two content types and learn how to configure the appearance of field inputs
        </Well>
        <Well
          grad="grad2"
          heading="Lesson 3: Publishing workflows"
          href="/docs/walkthroughs/lesson-3"
        >
          Support publishing needs with Keystone's <InlineCode>select</InlineCode> and{' '}
          <InlineCode>timestamp</InlineCode> fields
        </Well>
        <Well grad="grad2" heading="Lesson 4: Auth & Sessions" href="/docs/walkthroughs/lesson-4">
          Add sessions, password protection, and a sign-in screen to your Keystone app
        </Well>
        <Well grad="grad2" heading="Lesson 5: Rich Text" href="/docs/walkthroughs/lesson-5">
          Add a powerful <InlineCode>document</InlineCode> field to your app and learn how to
          configure it to meet your needs
        </Well>

  );
}

export default function Docs() {
  return (
    <DocsPage
      noRightNav
      noProse
      title={'Walkthroughs'}
      description={
        'Explore tutorials with step-by-step instruction on building solutions with Keystone.'
      }
      isIndexPage
      editPath="docs/walkthroughs/index.tsx"
    >
      <Type as="h1" look="heading64">
        Walkthroughs
      </Type>

      <Type as="p" look="body18" margin="1.25rem 0 1.5rem 0">
        Step-by-step tutorials for building with Keystone.
      </Type>

      <Type as="h2" look="heading30" margin="2rem 0 1rem 0">
        Getting started
      </Type>

      <Type as="p" look="body18" margin=".25rem 0 1.5rem 0">
        If you're new to Keystone begin here. These walkthroughs introduce the system, key concepts,
        and show you how to get up and running with schema-driven development the Keystone way.
      </Type>

      <QuickStart />

      <Type as="h3" look="heading24" margin="2rem 0 1rem 0" id="learn-keystone">
        Learn Keystone
      </Type>

      <Type as="p" look="body18" margin=".25rem 0 1.5rem 0">
        Learn how to build a functioning blog backend with relationships, auth, and session data
        from an empty folder, and gain insights into Keystone's core concepts along the way.
      </Type>

      <Foundations />
    </DocsPage>
  );
}


text:
class SpreadsheetConsumerClientServiceImpl
  require "google/api_client"
  require "google_drive"
  DEFAULT_SCOPE = ["https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds/"]
  CLASS_OPTIONS = %i[google_client_id google_client_secret spreadsheet_name oauth_redirect_url max_wl min_wl cache_time_in_seconds]
  INSTANCE_OPTIONS = %i[client last_fetch_at]

  class Configuration
    attr_accessor *CLASS_OPTIONS
  end

  def self.configure
    yield configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  attr_accessor *INSTANCE_OPTIONS

  def initialize(options={})
    @client = Google::APIClient.new
    client.authorization.client_id = self.class.configuration.google_client_id
    client.authorization.client_secret = self.class.configuration.google_client_secret
    client.authorization.scope = DEFAULT_SCOPE
    client.authorization.redirect_uri = self.class.configuration.oauth_redirect_url
  end

  def authorization_uri
    client.authorization.authorization_uri
  end

  def authorized?
    ret = true
    session = GoogleDrive.login_with_oauth(@access_token)
    session.spreadsheets
  rescue Google::APIClient::AuthorizationError
    ret = false
  ensure
    return ret
  end

  def authorize!(code)
    client.authorization.code = code
    client.authorization.fetch_access_token!
    @access_token = client.authorization.access_token
  end

  def authorize_from_access_token!(token)
    client.authorization.access_token = token
    @access_token = token
  end

  def access_token
    @access_token
  end

  def players
    if @players.nil? || is_cache_invalid?
      fetch_players!
    end
    @players
  end

  private

  def is_cache_invalid?
    last_fetch_at.nil? || (Time.now - self.class.configuration.cache_time_in_seconds).cover?(last_fetch_at) == false
  end

  def fetch_players!
    @last_fetch_at = Time.now
    trailing_30_days = (Date.today - 30).to_time .. Time.now
    session = GoogleDrive.login_with_oauth(@access_token)
    ss = session.files.select{|f| f.title == self.class.configuration.spreadsheet_name}.first
    ws = ss.worksheets.first
    data = ws.rows[1..-1].select{|row| trailing_30_days.cover?(Date.strptime(row[0], '%m/%d/%Y').to_time)}
    player_names = data.map{|row| [row[3],row[4]]}.flatten.uniq
    players = player_names.map do |name|
      games = data.select{|row| (row[3] == name || row[4] == name)}
      total = games.count
      wins = data.select{|row| (row[5] == name)}.count
      {
        name: name,
        total: total,
        wins: wins,
        losses: total - wins,
        ratio: wins.fdiv(total - wins).round(2),
        power: 0,
        games: games
      }
    end

    #Power ranking calculation
    players.each do |player|
      player_power_base = player[:ratio]
      player_power_base = self.class.configuration.max_wl if player_power_base > self.class.configuration.max_wl
      player_power_base
      player[:power] = player_power_base + player[:games].map do |row|
        if row[5] == player[:name]
          opponent_name = [row[3],row[4]].reject{|name| name == player[:name]}.first
          opponent_ratio = players.select{|p| p[:name] == opponent_name}.first[:ratio]
          opponent_ratio = self.class.configuration.max_wl if opponent_ratio > self.class.configuration.max_wl
          opponent_ratio = self.class.configuration.min_wl if opponent_ratio < self.class.configuration.min_wl
          (row[1].to_i - row[2].to_i).abs * opponent_ratio
        else
          0
        end
      end.inject(&:+)
      player[:power] = (player[:power] * 100.0 / 110.0 * 10.0).round(0)
      player[:power] = -1 if player[:total] < 3
    end

    #Player average margin
    players.each do |player|
      player[:avg_spread] = player[:games].map do |row|
        if row[5] == player[:name]
          (row[1].to_i - row[2].to_i).abs
        else
          0
        end
      end.compact.inject(&:+).fdiv(player[:total]).round(2)
    end
    @players = players.sort_by{|p| p[:power]}.reverse
  end
end


text:
import sys,re,collections,nltk
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize

# patterns that used to find or/and replace particular chars or words
# to find chars that are not a letter, a blank or a quotation
pat_letter = re.compile(r'[^a-zA-Z \']+')
# to find the 's following the pronouns. re.I is refers to ignore case
pat_is = re.compile("(it|he|she|that|this|there|here)(\'s)", re.I)
# to find the 's following the letters
pat_s = re.compile("(?<=[a-zA-Z])\'s")
# to find the ' following the words ending by s
pat_s2 = re.compile("(?<=s)\'s?")
# to find the abbreviation of not
pat_not = re.compile("(?<=[a-zA-Z])n\'t")
# to find the abbreviation of would
pat_would = re.compile("(?<=[a-zA-Z])\'d")
# to find the abbreviation of will
pat_will = re.compile("(?<=[a-zA-Z])\'ll")
# to find the abbreviation of am
pat_am = re.compile("(?<=[I|i])\'m")
# to find the abbreviation of are
pat_are = re.compile("(?<=[a-zA-Z])\'re")
# to find the abbreviation of have
pat_ve = re.compile("(?<=[a-zA-Z])\'ve")

lmtzr = WordNetLemmatizer()

def get_words(file):
    with open (file) as f:
        words_box=[]
        pat = re.compile(r'[^a-zA-Z \']+')
        for line in f:
            #if re.match(r'[a-zA-Z]*',line):
            #    words_box.extend(line.strip().strip('\'\"\.,').lower().split())
            # words_box.extend(pat.sub(' ', line).strip().lower().split())
            words_box.extend(merge(replace_abbreviations(line).split()))
    return collections.Counter(words_box)

def merge(words):
    new_words = []
    for word in words:
        if word:
            tag = nltk.pos_tag(word_tokenize(word)) # tag is like [('bigger', 'JJR')]
            pos = get_wordnet_pos(tag[0][1])
            if pos:
                lemmatized_word = lmtzr.lemmatize(word, pos)
                new_words.append(lemmatized_word)
            else:
                new_words.append(word)
    return new_words

def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return nltk.corpus.wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return nltk.corpus.wordnet.VERB
    elif treebank_tag.startswith('N'):
        return nltk.corpus.wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return nltk.corpus.wordnet.ADV
    else:
        return ''

def replace_abbreviations(text):
    new_text = text
    new_text = pat_letter.sub(' ', text).strip().lower()
    new_text = pat_is.sub(r"\1 is", new_text)
    new_text = pat_s.sub("", new_text)
    new_text = pat_s2.sub("", new_text)
    new_text = pat_not.sub(" not", new_text)
    new_text = pat_would.sub(" would", new_text)
    new_text = pat_will.sub(" will", new_text)
    new_text = pat_am.sub(" am", new_text)
    new_text = pat_are.sub(" are", new_text)
    new_text = pat_ve.sub(" have", new_text)
    new_text = new_text.replace('\'', ' ')
    return new_text

def append_ext(words):
    new_words = []
    for item in words:
        word, count = item
        tag = nltk.pos_tag(word_tokenize(word))[0][1] # tag is like [('bigger', 'JJR')]
        new_words.append((word, count, tag))
    return new_words

def write_to_file(words, file='results.txt'):
    f = open(file, 'w')
    for item in words:
        for field in item:
            f.write(str(field)+',')
        f.write('\n')

if __name__=='__main__':
    book = sys.argv[1]
    print "counting..."
    words = get_words(book)
    print "writing file..."
    write_to_file(append_ext(words.most_common()))


text:
Netclock is a very simple command line tool for querying ntp and comparing the result with the system time.

Uses pool.ntp.org as a time server.

## Usage

```
$ npm install netclock

$ netclock
   ____________________________________________________

   System time  : Wed Sep 09 2015 17:51:15 GMT+0100 (IST)
   Network time : Wed Sep 09 2015 17:51:33 GMT+0100 (IST)

   ____________________________________________________

```

## License

MIT License (MIT)


text:
package com.redhat.samples.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import org.apache.log4j.Logger;

@WebService
public class GreetingService {
  private static final Logger LOGGER = Logger.getLogger(GreetingService.class);

  @WebMethod
  public String hello(@WebParam(name = "name") String name) {
    String message = String.format("Hello, %s!", name);
    LOGGER.info(message);
    return message;
  }

  @WebMethod
  public String goodbye(@WebParam(name = "name") String name) {
    String message = String.format("Goodbye, %s!", name);
    LOGGER.info(message);
    return message;
  }

}


text:
package com.amazonaws.services.waf.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.waf.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * RuleSummaryMarshaller
 */
public class RuleSummaryJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a JSONWriter
     */
    public void marshall(RuleSummary ruleSummary, JSONWriter jsonWriter) {
        if (ruleSummary == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonWriter.object();

            if (ruleSummary.getRuleId() != null) {
                jsonWriter.key("RuleId").value(ruleSummary.getRuleId());
            }

            if (ruleSummary.getName() != null) {
                jsonWriter.key("Name").value(ruleSummary.getName());
            }

            jsonWriter.endObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static RuleSummaryJsonMarshaller instance;

    public static RuleSummaryJsonMarshaller getInstance() {
        if (instance == null)
            instance = new RuleSummaryJsonMarshaller();
        return instance;
    }

}


text:
<?php
namespace Concrete\Core\File\Component\Chooser\Option;

use Concrete\Core\File\Component\Chooser\ChooserOptionInterface;
use Concrete\Core\File\Component\Chooser\OptionSerializableTrait;

class SavedSearchOption implements ChooserOptionInterface
{

    use OptionSerializableTrait;

    public function getComponentKey(): string
    {
        return 'saved-search';
    }

    public function getTitle(): string
    {
        return t('Saved Searches');
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>JS.PlayerFramework</title>

    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />

    <link href="/css/default.css" rel="stylesheet" />

    <link href="/Microsoft.PlayerFramework.Js/css/Default-base.css" rel="stylesheet">
    <link href="/Microsoft.PlayerFramework.Js/css/Default-dark.css" rel="stylesheet">

    <link href="/Microsoft.PlayerFramework.Js.Advertising/css/Advertising.css" rel="stylesheet">


text:
/*==============================================================================================================================
| Author        Jeremy Caney (Jeremy@Caney.net)
| Client        Skepti-Forum Project
| Project       Forum Archive
\=============================================================================================================================*/
using System.Web.Mvc;
using SkeptiForum.Archive;
using SkeptiForum.Archive.Models;
using System.Threading.Tasks;

namespace SkeptiForum.Archive.Controllers {

  /*============================================================================================================================
  | CLASS: SITEMAP CONTROLLER
  \---------------------------------------------------------------------------------------------------------------------------*/
  /// <summary>
  ///   Used to provide access to a sitemap.org sitemap for use by search engines.
  /// </summary>
  [RoutePrefix("Sitemap")]
  public class SitemapController : Controller {

    /*==========================================================================================================================
    | GET: /SITEMAP
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Generates an index of sitemaps available on this site, each corresponding to a Facebook group.
    /// </summary>
    /// <returns>An index of sitemaps.</returns>
    [Route()]
    public ActionResult Index() {
      Response.ContentType = "application/xml";
      return View(ArchiveManager.Groups);
    }

    /*==========================================================================================================================
    | GET: /GROUPS/KEY/SITEMAP/
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Generates a sitemap of posts associated with an individual group based on JSON files discovered on disk based on the
    ///   friendly group key name.
    /// </summary>
    /// <param name="id">The identifier of the Facebook Group.</param>
    /// <returns>An index of posts associated with the specified group.</returns>
    [Route("~/Groups/{groupKey:alpha}/Sitemap")]
    public async Task<ActionResult> Group(string groupKey) {
      var group = ArchiveManager.Groups[groupKey];
      return await GetSitemapView(group.Id);
    }

    /*==========================================================================================================================
    | GET: /GROUPS/4/SITEMAP/
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Generates a sitemap of posts associated with an individual group based on JSON files discovered on disk.
    /// </summary>
    /// <param name="id">The identifier of the Facebook Group.</param>
    /// <returns>An index of posts associated with the specified group.</returns>
    [Route("~/Groups/{groupId:long}/Sitemap")]
    public async Task<ActionResult> Group(long groupId = -1) {
      return await GetSitemapView(groupId);
    }

    /*==========================================================================================================================
    | METHOD: GET SITEMAP VIEW (HELPER)
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Generates a sitemap of posts associated with an individual group based on JSON files discovered on disk.
    /// </summary>
    /// <param name="id">The identifier of the Facebook Group.</param>
    /// <returns>An index of posts associated with the specified group.</returns>
    private async Task<ActionResult> GetSitemapView(long groupId = -1) {

      /*------------------------------------------------------------------------------------------------------------------------
      | Validate group identifier
      \-----------------------------------------------------------------------------------------------------------------------*/
      if (groupId < 1 || !ArchiveManager.Groups.Contains(groupId)) {
        return HttpNotFound("A group with the ID '" + groupId + "' does not exist.");
      }

      /*------------------------------------------------------------------------------------------------------------------------
      | Set Content Type to XML
      \-----------------------------------------------------------------------------------------------------------------------*/
      Response.ContentType = "application/xml";

      /*------------------------------------------------------------------------------------------------------------------------
      | Assemble view model
      \-----------------------------------------------------------------------------------------------------------------------*/
      var viewModel = new SitemapGroupViewModel(
        ArchiveManager.Groups[groupId],
        await ArchiveManager.StorageProvider.GetPostsAsync(groupId)
      );

      /*------------------------------------------------------------------------------------------------------------------------
      | Return data to view
      \-----------------------------------------------------------------------------------------------------------------------*/
      return View(viewModel);

    }

  } //Class
} //Namespace


text:
#ifndef PAGMO_ALGORITHM_CSTRS_SELF_ADAPTIVE_H
#define PAGMO_ALGORITHM_CSTRS_SELF_ADAPTIVE_H

#include <string>

#include "../config.h"
#include "../population.h"
#include "../serialization.h"
#include "base.h"
#include "jde.h"

namespace pagmo { namespace algorithm {

/// Self-Adaptive Fitness constraints handling meta-algorithm
/**
 *
 * Seld-Adaptive Fitness constraints handling is a meta-algorithm that allows
 * to solve constrained optimization problems. The key idea of this constraint
 * handling technique is to represent the constraint violation by a single
 * infeasibility measure, and to adapt dynamically the penalization of infeasible solutions.
 *
 * This meta-algorithm is based on the problem self-adaptive.
 *
 * Note: This constraints handling technique can only be used for <b>MINIMIZATION</b> problems
 *
 * @see Farmani, R., & Wright, J. A. (2003). Self-adaptive fitness formulation for constrained optimization.
 * Evolutionary Computation, IEEE Transactions on, 7(5), 445-455 for the paper introducing the method.
 *
 * @author Jeremie Labroquere (jeremie.labroquere@gmail.com)
 */

class __PAGMO_VISIBLE cstrs_self_adaptive: public base
{
public:
	cstrs_self_adaptive(const base & = jde(), int gen = 1,
						double = 1e-15, double = 1e-15);
    cstrs_self_adaptive(const cstrs_self_adaptive &);
	base_ptr clone() const;

public:
	void evolve(population &) const;
	std::string get_name() const;
	base_ptr get_algorithm() const;
	void set_algorithm(const base &);

protected:
	std::string human_readable_extra() const;

private:

	friend class boost::serialization::access;
	template <class Archive>
	void serialize(Archive &ar, const unsigned int)
	{
		ar & boost::serialization::base_object<base>(*this);
		ar & m_original_algo;
		ar & const_cast<int &>(m_gen);
		ar & const_cast<double &>(m_ftol);
		ar & const_cast<double &>(m_xtol);
	}
	base_ptr m_original_algo;
	//Number of generations
	const int m_gen;

	// tolerance
	const double m_ftol;
	const double m_xtol;
};

}} //namespaces

BOOST_CLASS_EXPORT_KEY(pagmo::algorithm::cstrs_self_adaptive)

#endif // PAGMO_ALGORITHM_cstrs_self_adaptive_H


text:
<?php

namespace Acme\PortfolioBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class HomeController extends Controller
{
    public function indexAction()
    {
        //return new Response('
Home
');
        return $this->render(
            'AcmePortfolioBundle:Home:index.html.twig'
        );

    }

    public function aboutAction()
    {
        //return new Response('
Home
');
        return $this->render(
            'AcmePortfolioBundle:Home:about.html.twig'
        );

    }
}


text:
package com.google.errorprone.refaster.testdata.template;

import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.Placeholder;
import java.util.Collection;

/** Template to verify that block placeholders get inlined with the correct lambda body type. */
abstract class InferLambdaBodyType<E> {
  @Placeholder
  abstract void doSomething(E function);

  @BeforeTemplate
  void before(Collection<E> collection) {
    for (E e : collection) {
      doSomething(e);
    }
  }

  @AfterTemplate
  void after(Collection<E> collection) {
    collection.forEach((E e) -> doSomething(e));
  }
}


text:
<?php

class Model_Resposta extends \Orm\Model
{
	protected static $_properties = array(
		'id',
		'conteudo',
		'created_at',
		'user_id',
		'inscricao_id'
	);

	protected static $_belongs_to = array(
		'user',
		'inscricao' => array(
			'model_to'       => 'Model_Inscricao',
            'cascade_delete' => true
		)
	);

	protected static $_observers = array(
	    '\Orm\Observer_CreatedAt' => array(
	        'events' => array('before_insert'),
	    ),
	);
}


text:
<extend name="Public/base"/>

<block name="body">

{$info['id']?'编辑':'新增'}配置

	<form action="{:U()}" method="post" class="form-horizontal">

			配置标识(用于C函数调用,只能使用英文且不能重复)

				<input type="text" class="text input-large" name="name" value="{$info.name|default=''}">

			配置标题(用于后台显示的配置标题)

				<input type="text" class="text input-large" name="title" value="{$info.title|default=''}">

			排序(用于分组显示的顺序)

				<input type="text" class="text input-small" name="sort" value="{$info.sort|default=0}">

			配置类型(系统会根据不同类型解析配置值)

				<select name="type">
					<volist name="Think.config.CONFIG_TYPE_LIST" id="type">
						<option value="{$key}">{$type}</option>
					</volist>
				</select>

			配置分组(配置分组 用于批量设置 不分组则不会显示在系统设置中)

				<select name="group">
					<option value="0">不分组</option>
					<volist name="Think.config.CONFIG_GROUP_LIST" id="group">
						<option value="{$key}">{$group}</option>
					</volist>
				</select>

			配置值(配置值)

					<textarea name="value">{$info.value|default=''}</textarea>

			配置项(如果是枚举型 需要配置该项)

					<textarea name="extra">{$info.extra|default=''}</textarea>

			说明(配置详细说明)

					<textarea name="remark">{$info.remark|default=''}</textarea>

			<input type="hidden" name="id" value="{$info.id|default=''}">
			<button class="btn submit-btn ajax-post" id="submit" type="submit" target-form="form-horizontal">确 定</button>
			<button class="btn btn-return" onclick="javascript:history.back(-1);return false;">返 回</button>

	</form>
</block>

<block name="script">

</block>


text:
require 'rubygems'
require 'sinatra/base'
require 'test/unit'
require 'rack/test'
require 'active_record'
require 'sinatra/simple-authentication'
require 'nokogiri'

module Sinatra
  class Base
    set :environment, :test
    ::ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => "#{Dir.pwd}/test.db")
    register Sinatra::SimpleAuthentication
  end
end

class TcActiveRecord < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def teardown
    Sinatra::SimpleAuthentication::Controllers::Session.model_class.delete_all
  end

  def test_signup_page
    get '/signup'
    assert last_response.ok?

    html = Nokogiri::HTML(last_response.body)
    assert html.css('[name="email"]')
    assert html.css('[name="password"]')
    assert html.css('[name="password_confirmation"]')
  end

  def test_login_page
    get '/login'
    assert last_response.ok?

    html = Nokogiri::HTML(last_response.body)
    assert html.css('[name="email"]')
    assert html.css('[name="password"]')
  end

  def test_user_validations
    taken_email = "Email has already been taken."
    missing_email = "Email can't be blank."
    invalid_email = "Invalid email format."
    missing_password = "Password can't be blank."
    short_password = "Password is too short, must be between 4 and 16 characters long."
    long_password = "Password is too long, must be between 4 and 16 characters long."

    #Empty user
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new

    assert !user.save
    assert user.errors[:email].include?(missing_email)
    assert user.errors[:password].include?(missing_password)
    assert user.errors[:password].include?(short_password)

    #Short password
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new
    user.password = "X" * 3

    assert !user.save
    assert user.errors[:email].include?(missing_email)
    assert user.errors[:password].include?(short_password)

    #Long password
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new
    user.password = "X" * 17

    assert !user.save
    assert user.errors[:email].include?(missing_email)
    assert user.errors[:password].include?(long_password)

    #Wrong format email
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new
    user.email = "InvaidEmailFormat"

    assert !user.save
    assert user.errors[:email].include?(invalid_email)
    assert user.errors[:password].include?(missing_password)
    assert user.errors[:password].include?(short_password)

    #Valid user
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new
    user.email = "test@mail.com"
    user.password = "PASSWORD"
    assert user.save

    #user_class duplicated email
    user = Sinatra::SimpleAuthentication::Controllers::Session.model_class.new
    user.email = "test@mail.com"
    user.password = "PASSWORD"

    assert !user.save
    assert user.errors[:email].include?(taken_email)
  end
end


text:
/*
 * ColorBasedROIExtractorRGB.cpp
 *
 *  Created on: Dec 2, 2011
 *      Author: Pinaki Sunil Banerjee
 */

#include "ColorBasedROIExtractorRGB.h"
#include "brics_3d/core/ColoredPoint3D.h"
#include "brics_3d/core/Logger.h"

namespace brics_3d {

ColorBasedROIExtractorRGB::ColorBasedROIExtractorRGB() {

	this->red = 0;
	this->green = 0;
	this->blue = 0;
	this->distanceThresholdMinimum = 0.0;
	this->distanceThresholdMaximum = 0.0;
}

ColorBasedROIExtractorRGB::~ColorBasedROIExtractorRGB() {
	// TODO Auto-generated destructor stub
}

void ColorBasedROIExtractorRGB::filter(PointCloud3D *originalPointCloud, PointCloud3D *resultPointCloud) {

	if(this->red == 0 && this->green == 0 && this->blue == 0 ) {
		LOG(WARNING) << "[WARNING] Using limits: R=0, G=0, B=0 for RGB based ROI Extraction!!!";
	}

	unsigned int cloudSize = originalPointCloud->getSize();
	int tempR, tempG, tempB;
	uint8_t tempChar;
	bool passed;
	brics_3d::Point3D tempPoint3D;
	resultPointCloud->getPointCloud()->clear();

	for (unsigned int i = 0; i < cloudSize; i++) {
		passed = false;

		if( (*originalPointCloud->getPointCloud())[i].asColoredPoint3D() == 0) {
			continue; //this point does not contain color information so skip it
		}

		//Getting the HSV values for the RGB points
		tempChar = (*originalPointCloud->getPointCloud())[i].asColoredPoint3D()->getR();
		tempR = tempChar << 0;
		tempR = abs(tempR);

		tempChar = (*originalPointCloud->getPointCloud())[i].asColoredPoint3D()->getG();
		tempG = tempChar << 0;
		tempG = abs(tempG);

		tempChar = (*originalPointCloud->getPointCloud())[i].asColoredPoint3D()->getB();
		tempB = tempChar << 0;
		tempB = abs(tempB);

//		printf("[INFO] Current R=%d, G=%d, B=%d, \n", tempR, tempG, tempB);

		double redDistance = (double)(tempR-this->red);
		double greenDistance = (double)(tempG-this->green);
		double blueDistance = (double)(tempB-this->blue);

		double currentDistance = (redDistance*redDistance) + (greenDistance*greenDistance) +
									(blueDistance*blueDistance);
		currentDistance = std::sqrt(currentDistance);

		if (currentDistance <= distanceThresholdMaximum && currentDistance >= distanceThresholdMinimum) passed=true;

		if(passed){
//			brics_3d::Point3D *tempPoint3D =  new brics_3d::Point3D(originalPointCloud->getPointCloud()->data()[i].getX(),
//					originalPointCloud->getPointCloud()->data()[i].getY(),
//					originalPointCloud->getPointCloud()->data()[i].getZ());
//
//			brics_3d::ColoredPoint3D *tempColoredPoint3D = new brics_3d::ColoredPoint3D(tempPoint3D,
//					originalPointCloud->getPointCloud()->data()[i].red,
//					originalPointCloud->getPointCloud()->data()[i].green,
//					originalPointCloud->getPointCloud()->data()[i].blue);
//
//			out_cloud->addPoint(tempColoredPoint3D);
			resultPointCloud->addPointPtr((*originalPointCloud->getPointCloud())[i].clone());
//			delete tempPoint3D;
//			delete tempColoredPoint3D;
		}

	}

}

}


text:
from django.conf.urls import url

from partner.views import (
    OrganizationProfileAPIView,
    PartnerProfileAPIView,
    PartnerProfileSummaryAPIView,
    PartnersListAPIView,
    PartnerShortListAPIView,
    PartnerIdentificationAPIView,
    PartnerContactInformationAPIView,
    PartnerMandateMissionAPIView,
    PartnerFundingAPIView,
    PartnerCollaborationAPIView,
    PartnerProjectImplementationAPIView,
    PartnerOtherInfoAPIView,
    PartnerCountryProfileAPIView,
    PartnersMemberListAPIView,
)

urlpatterns = [
    url(r'^$', PartnersListAPIView.as_view(), name="partners"),
    url(r'^(?P<pk>\d+)/$', PartnerProfileAPIView.as_view(), name="partner-profile"),
    url(r'^(?P<pk>\d+)/country-profile/$', PartnerCountryProfileAPIView.as_view(), name="country-profile"),
    url(r'^(?P<pk>\d+)/org-profile/$', OrganizationProfileAPIView.as_view(), name="org-profile"),
    url(r'^(?P<pk>\d+)/summary/$', PartnerProfileSummaryAPIView.as_view(), name="partner-profile-summary"),
    url(r'^(?P<pk>\d+)/identification/$', PartnerIdentificationAPIView.as_view(), name="identification"),
    url(r'^(?P<pk>\d+)/contact-information/$', PartnerContactInformationAPIView.as_view(), name="contact-information"),
    url(r'^(?P<pk>\d+)/mandate-mission/$', PartnerMandateMissionAPIView.as_view(), name="mandate-mission"),
    url(r'^(?P<pk>\d+)/funding/$', PartnerFundingAPIView.as_view(), name="funding"),
    url(r'^(?P<pk>\d+)/collaboration/$', PartnerCollaborationAPIView.as_view(), name="collaboration"),
    url(
        r'^(?P<pk>\d+)/project-implementation/$',
        PartnerProjectImplementationAPIView.as_view(),
        name="project-implementation"
    ),
    url(r'^(?P<pk>\d+)/other-info/$', PartnerOtherInfoAPIView.as_view(), name="other-info"),
    url(r'^short/$', PartnerShortListAPIView.as_view(), name="partners-short"),
    url(r'^(?P<pk>\d+)/members/', PartnersMemberListAPIView.as_view(), name="members"),
]


text:
package com.dglapps.simuloc.domain.player;

import com.dglapps.simuloc.domain.player.listener.TripPlayerListener;
import com.dglapps.simuloc.domain.stepcalculator.StandstillStepCalculator;
import com.dglapps.simuloc.domain.stepcalculator.StepCalculatorFactory;
import com.dglapps.simuloc.domain.stepcalculator.StraightStepCalculator;
import com.dglapps.simuloc.domain.trip.Position;
import com.dglapps.simuloc.domain.trip.Trip;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.time.Clock;
import java.time.OffsetDateTime;
import java.util.concurrent.CompletableFuture;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class TripPlayerTest {

  private Clock clock;
  private TripPlayer tripPlayer;

  @BeforeEach
  public void setup() {
    this.clock = Clock.systemUTC();
    this.tripPlayer = new TripPlayer(
        new StepCalculatorFactory(),
        position -> CompletableFuture.completedFuture(null)
    );
  }

  @Test
  public void givenTripWithoutStepsWhenPlayTripThenDoNotEmitPosition() {

    TripPlayerListener listener = Mockito.mock(TripPlayerListener.class);
    this.tripPlayer.addListener(listener);

    Trip trip = TripObjectMother.aTripWithoutSteps();

    this.tripPlayer.play(trip, OffsetDateTime.now());

    verify(listener, times(1)).onTripPlayerStart(eq(tripPlayer));
    verify(listener, times(0)).onRuleStart(eq(tripPlayer), any(StandstillStepCalculator.class));
    verify(listener, times(0)).onRuleEnd(eq(tripPlayer), any(StandstillStepCalculator.class));
    verify(listener, times(1)).onTripPlayerEnd(eq(tripPlayer));
    verify(listener, times(0)).onPositionGenerated(eq(tripPlayer), any(Position.class));

  }

  @Test
  public void givenTripWithTwoStepsWhenPlayTripThenDoCallCallbacks() {
    TripPlayerListener listener = Mockito.mock(TripPlayerListener.class);
    this.tripPlayer.addListener(listener);
    Trip trip = TripObjectMother.aTripWithTwoSteps();

    this.tripPlayer.play(trip, OffsetDateTime.now());

    verify(listener, times(1)).onTripPlayerStart(eq(tripPlayer));
    verify(listener, times(1)).onRuleStart(eq(tripPlayer), any(StandstillStepCalculator.class));
    verify(listener, times(1)).onRuleStart(eq(tripPlayer), any(StraightStepCalculator.class));

    verify(listener, times(1)).onRuleEnd(eq(tripPlayer), any(StandstillStepCalculator.class));
    verify(listener, times(1)).onRuleEnd(eq(tripPlayer), any(StraightStepCalculator.class));

    verify(listener, times(1)).onTripPlayerEnd(eq(tripPlayer));

    verify(listener, times(24)).onPositionGenerated(eq(tripPlayer), any(Position.class));

  }

}


text:
const JDLApplicationConfigurationOption = require('./jdl-application-configuration-option');

module.exports = class StringJDLApplicationConfigurationOption extends JDLApplicationConfigurationOption {
  constructor(name, value, quoted = false) {
    super(name, value);
    this.quoted = quoted;
  }

  toString() {
    const value = this.quoted && !this.value.includes('"') ? `"${this.value}"` : this.value;
    return `${this.name} ${value}`;
  }
};


text:
package org.apache.dubbo.common.extension.adaptive.impl;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt;

@Adaptive
public class HasAdaptiveExt_ManualAdaptive implements HasAdaptiveExt {
    public String echo(URL url, String s) {
        HasAdaptiveExt addExt1 = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key"));
        return addExt1.echo(url, s);
    }
}


text:
(function() {
  'use strict';

  angular
      .module('webApp')
      .controller('ExecutionsListCtrl', ExecutionsListCtrl);

  ExecutionsListCtrl.$inject = ['WizardStatusService', 'PolicyFactory', 'PolicyModelFactory', 'ModalService', '$state',
    '$translate', '$interval', '$scope', '$q', '$filter'];

  function ExecutionsListCtrl(WizardStatusService, PolicyFactory, PolicyModelFactory, ModalService, $state,
                          $translate, $interval, $scope, $q, $filter) {
    /*jshint validthis: true*/
    var vm = this;

    var checkPoliciesStatus = null;

    vm.runPolicy = runPolicy;
    vm.stopPolicy = stopPolicy;
    vm.sortPolicies = sortPolicies;
    vm.deleteCheckpoint = deleteCheckpoint;

    vm.policiesData = [];
    vm.policiesJsonData = {};
    vm.errorMessage = {type: 'error', text: '', internalTrace: ''};
    vm.successMessage = {type: 'success', text: '', internalTrace: ''};
    vm.loading = true;
    vm.tableReverse = false;
    vm.showInfo = showInfo;
    vm.showInfoModal = showInfoModal;

    init();

    /////////////////////////////////

    function init() {
      getPolicies();
    }

    function runPolicy(policyId, policyStatus, policyName) {
      if (policyStatus.toLowerCase() === 'notstarted' || policyStatus.toLowerCase() === 'failed' ||
          policyStatus.toLowerCase() === 'stopped' || policyStatus.toLowerCase() === 'stopping' ||
           policyStatus.toLowerCase() === 'finished') {
        var policyRunning = PolicyFactory.runPolicy(policyId);

        policyRunning.then(function() {
          vm.successMessage.text = $translate.instant('_RUN_POLICY_OK_', {policyName: policyName});
        }, function(error) {
          vm.errorMessage.text = "_ERROR_._" + error.data.i18nCode + "_";
          vm.errorMessage.internalTrace = 'Error: ' + error.data.message;
        });
      }
      else {
        vm.errorMessage.text = $translate.instant('_RUN_POLICY_KO_', {policyName: policyName});
      }
    }

    function stopPolicy(policyId, policyStatus, policyName) {
      if (policyStatus.toLowerCase() !== 'notstarted' && policyStatus.toLowerCase() !== 'failed' &&
       policyStatus.toLowerCase() !== 'stopped' && policyStatus.toLowerCase() !== 'stopping' &&
        policyStatus.toLowerCase() !== 'finished') {

        var stopPolicy =
        {
          "id": policyId,
          "status": "Stopping"
        };

        var policyStopping = PolicyFactory.stopPolicy(stopPolicy);

        policyStopping.then(function() {
          vm.successMessage.text = $translate.instant('_STOP_POLICY_OK_', {policyName: policyName});
        }, function(error) {
          vm.errorMessage.text = '_ERROR_._' + error.data.i18nCode + '_';
          vm.errorMessage.internalTrace = 'Error: ' + error.data.message;
        });
      }
      else {
        vm.errorMessage.text = $translate.instant('_STOP_POLICY_KO_', {policyName: policyName});
      }
    }

    function deleteCheckpoint(policyName){
      var deletePolicyCheckpoint = PolicyFactory.deletePolicyCheckpoint(policyName);
      deletePolicyCheckpoint.then(function(response){
        vm.successMessage.text = $translate.instant('_DELETE_CHECKPOINT_POLICY_OK_', {policyName: policyName});
      });
    }

    function updatePoliciesStatus() {
      var defer = $q.defer();
      var policiesStatus = PolicyFactory.getPoliciesStatus();
      policiesStatus.then(function(result) {
        var policiesWithStatus = result;
        if (policiesWithStatus) {
          for (var i = 0; i < policiesWithStatus.length; i++) {
            var policyData = $filter('filter')(vm.policiesData, {'id': policiesWithStatus[i].id}, true)[0];
            if (policyData) {
              policyData.submissionId = policiesWithStatus[i].submissionId;
              policyData.statusInfo = policiesWithStatus[i].statusInfo;
              policyData.lastError = policiesWithStatus[i].lastError;
              policyData.status = policiesWithStatus[i].status;
              policyData.clusterUI = policiesWithStatus[i].resourceManagerUrl;
              policyData.lastExecutionMode = policiesWithStatus[i].lastExecutionMode;
            } else {
              vm.policiesData.push(policiesWithStatus[i]);
            }
          }
        }
        defer.resolve();
      }, function() {
        defer.reject();
      });
      return defer.promise;
    }

    function getPolicies() {
      var policiesStatus = PolicyFactory.getPoliciesStatus();
      policiesStatus.then(function (result) {
        vm.sortField = 'name';
        vm.policiesData = result;
        vm.loading = false;
        checkPoliciesStatus = $interval(function() {
          updatePoliciesStatus().then(null, function() {
            $interval.cancel(checkPoliciesStatus);
          });
        }, 5000);
      }, function(error) {
        vm.loading = false;
        $interval.cancel(checkPoliciesStatus);
        vm.successMessage.text = '_ERROR_._' + error.data.i18nCode + '_';
      });
    }

    function sortPolicies(fieldName){
      if(fieldName == vm.sortField){
        vm.tableReverse = !vm.tableReverse;
      } else {
        vm.tableReverse = false;
        vm.sortField = fieldName;
      }
    }

    function showInfo(policy){
      PolicyFactory.getExecutionById(policy.id).then(function(execution){
        showInfoModal(policy, execution);
      }, function(error){
        showInfoModal(policy);
      });
    }

    function showInfoModal(policy, execution) {
      var controller = 'PolicyInfoModalCtrl';
      var templateUrl = "templates/modal/policy-info-modal.tpl.html";
      var resolve = {
        policyName: function () {
          return policy.name;
        },
        policyDescription: function () {
          return policy.description;
        },
        status: function () {
          return policy.status;
        },
        statusInfo: function () {
          return policy.statusInfo;
        },
        submissionId: function () {
          return policy.submissionId;
        },
        deployMode: function () {
          return policy.lastExecutionMode;
        },
        executionData: function() {
          return execution;
        },
        error: function () {
          return policy.lastError;
        }
      };
      ModalService.openModal(controller, templateUrl, resolve, '', 'lg');
    }

    /*Stop $interval when changing the view*/
    $scope.$on("$destroy", function() {
      if (checkPoliciesStatus) {
        $interval.cancel(checkPoliciesStatus);
      }
    });
  }
})();