text:
package com.dangdang.ddframe.rdb.sharding.jdbc;

import com.dangdang.ddframe.rdb.sharding.api.strategy.slave.RoundRobinSlaveLoadBalanceStrategy;
import com.dangdang.ddframe.rdb.sharding.api.strategy.slave.SlaveLoadBalanceStrategy;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.dangdang.ddframe.rdb.sharding.jdbc.adapter.AbstractDataSourceAdapter;
import com.dangdang.ddframe.rdb.sharding.parser.result.router.SQLStatementType;
import com.google.common.base.Preconditions;
import lombok.RequiredArgsConstructor;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 支持读写分离的数据源.
 *
 * @author zhangliang
 */
@RequiredArgsConstructor
public final class MasterSlaveDataSource extends AbstractDataSourceAdapter {

    private static final ThreadLocal<Boolean> DML_FLAG = new ThreadLocal<Boolean>() {

        @Override
        protected Boolean initialValue() {
            return false;
        }
    };

    private final String name;

    private final DataSource masterDataSource;

    private final List<DataSource> slaveDataSources;

    private final SlaveLoadBalanceStrategy slaveLoadBalanceStrategy = new RoundRobinSlaveLoadBalanceStrategy();

    /**
     * 获取主或从节点的数据源名称.
     *
     * @param sqlStatementType SQL类型
     * @return 主或从节点的数据源
     */
    public DataSource getDataSource(final SQLStatementType sqlStatementType) {
        if (SQLStatementType.SELECT != sqlStatementType || DML_FLAG.get() || HintManagerHolder.isMasterRouteOnly()) {
            DML_FLAG.set(true);
            return masterDataSource;
        }
        return slaveLoadBalanceStrategy.getDataSource(name, slaveDataSources);
    }

    String getDatabaseProductName() throws SQLException {
        String result;
        try (Connection masterConnection = masterDataSource.getConnection()) {
            result = masterConnection.getMetaData().getDatabaseProductName();
        }
        for (DataSource each : slaveDataSources) {
            String slaveDatabaseProductName;
            try (Connection slaveConnection = each.getConnection()) {
                slaveDatabaseProductName = slaveConnection.getMetaData().getDatabaseProductName();
            }
            Preconditions.checkState(result.equals(slaveDatabaseProductName), String.format("Database type inconsistent with '%s' and '%s'", result, slaveDatabaseProductName));
        }
        return result;
    }

    @Override
    public Connection getConnection() throws SQLException {
        throw new UnsupportedOperationException("Master slave data source cannot support get connection directly.");
    }

    /**
     * 重置更新标记.
     */
    public static void resetDMLFlag() {
        DML_FLAG.remove();
    }
}


text:
/**
 * @constructor
 */
function Legend(idName) {
    this.idName=idName;
}

/**
 * Put the list of website name
 * @param listeSites: JSON elem with liste of Site wich each eleme have site.nom
 */
Legend.prototype.addWebSite = function(listeSites) {
    var divList=$("#legend_listWebsite");
    divList.html('');

    for (numSite = 0; numSite < listeSites.length; numSite++) {
        var site=listeSites[numSite];
        divList.append('
'+site.nom+' ' +
            '(derniere maj:'+site.lastUpdate+')
');
    }
}

Legend.prototype.displayBtnMaree = function() {
    var divBtn=$("#legend_btnActions");
    divBtn.html('');
    if (isMaree) {
        var btn = document.createElement('button');
        //var txt = document.createTextNode("Réstrisction dû aux marées");
        btn.innerHTML = "Réstrisction dû aux marées";

        btn.setAttribute('type', 'button');
        btn.setAttribute('class', 'btn btn-primary');
        btn.setAttribute('onclick', "displayRestrictionMaree()");
        divBtn.append(btn);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import datetime
import operator
import warnings
from operator import methodcaller

import numpy as np
import pandas as pd
import pandas.testing as tm
import pytest
from pytest import param

import ibis
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
from ibis.backends.pandas.execution.temporal import day_name

@pytest.mark.parametrize('attr', ['year', 'month', 'day'])
@pytest.mark.parametrize(
    "expr_fn",
    [
        param(lambda c: c.date(), id="date"),
        param(
            lambda c: c.cast("date"),
            id="cast",
            marks=pytest.mark.notimpl(["impala"]),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion"])
def test_date_extract(backend, alltypes, df, attr, expr_fn):
    expr = getattr(expr_fn(alltypes.timestamp_col), attr)()
    expected = getattr(df.timestamp_col.dt, attr).astype('int32')

    result = expr.name(attr).execute()

    backend.assert_series_equal(result, expected.rename(attr))

@pytest.mark.parametrize(
    'attr',
    [
        'year',
        'month',
        'day',
        param('day_of_year', marks=pytest.mark.notimpl(["impala", "mssql"])),
        param('quarter', marks=pytest.mark.notimpl(["mssql"])),
        'hour',
        'minute',
        'second',
    ],
)
@pytest.mark.notimpl(["datafusion"])
def test_timestamp_extract(backend, alltypes, df, attr):
    method = getattr(alltypes.timestamp_col, attr)
    expr = method().name(attr)
    result = expr.execute()
    expected = backend.default_series_rename(
        getattr(df.timestamp_col.dt, attr.replace('_', '')).astype('int32')
    ).rename(attr)
    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    ('func', 'expected'),
    [
        param(methodcaller('year'), 2015, id='year'),
        param(methodcaller('month'), 9, id='month'),
        param(methodcaller('day'), 1, id='day'),
        param(methodcaller('hour'), 14, id='hour'),
        param(methodcaller('minute'), 48, id='minute'),
        param(methodcaller('second'), 5, id='second'),
        param(
            methodcaller('millisecond'),
            359,
            id='millisecond',
            marks=[
                pytest.mark.notimpl(["clickhouse", "pyspark"]),
                pytest.mark.broken(
                    ["mysql"],
                    reason="MySQL implementation of milliseconds is broken",
                ),
            ],
        ),
        param(
            lambda x: x.day_of_week.index(),
            1,
            id='day_of_week_index',
            marks=pytest.mark.notimpl(["mssql"]),
        ),
        param(
            lambda x: x.day_of_week.full_name(),
            'Tuesday',
            id='day_of_week_full_name',
            marks=pytest.mark.notimpl(["mssql"]),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "snowflake"])
def test_timestamp_extract_literal(con, func, expected):
    value = ibis.timestamp('2015-09-01 14:48:05.359')
    assert con.execute(func(value)) == expected

@pytest.mark.notimpl(["datafusion", "clickhouse", "snowflake"])
@pytest.mark.notyet(["sqlite", "pyspark"])
def test_timestamp_extract_milliseconds(backend, alltypes, df):
    expr = alltypes.timestamp_col.millisecond()
    result = expr.execute()
    expected = backend.default_series_rename(
        (df.timestamp_col.dt.microsecond // 1_000).astype('int32')
    ).rename("millisecond")
    backend.assert_series_equal(result, expected)

@pytest.mark.notimpl(["datafusion", "mssql"])
def test_timestamp_extract_epoch_seconds(backend, alltypes, df):
    expr = alltypes.timestamp_col.epoch_seconds().name('tmp')
    result = expr.execute()

    expected = backend.default_series_rename(
        (df.timestamp_col.view("int64") // 1_000_000_000).astype("int32")
    )
    backend.assert_series_equal(result, expected)

@pytest.mark.notimpl(["datafusion", "mssql"])
def test_timestamp_extract_week_of_year(backend, alltypes, df):
    expr = alltypes.timestamp_col.week_of_year().name('tmp')
    result = expr.execute()
    expected = backend.default_series_rename(
        df.timestamp_col.dt.isocalendar().week.astype("int32")
    )
    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    'unit',
    [
        'Y',
        'M',
        'D',
        param(
            'W',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "duckdb",
                    "impala",
                    "mysql",
                    "postgres",
                    "pyspark",
                    "sqlite",
                    "snowflake",
                ]
            ),
        ),
        param('h', marks=pytest.mark.notimpl(["sqlite"])),
        param('m', marks=pytest.mark.notimpl(["sqlite"])),
        param('s', marks=pytest.mark.notimpl(["impala", "sqlite"])),
        param(
            'ms',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "impala",
                    "mysql",
                    "pyspark",
                    "sqlite",
                ]
            ),
        ),
        param(
            'us',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "impala",
                    "mysql",
                    "pyspark",
                    "sqlite",
                ]
            ),
        ),
        param(
            'ns',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "duckdb",
                    "impala",
                    "mysql",
                    "postgres",
                    "pyspark",
                    "sqlite",
                    "snowflake",
                    "polars",
                ]
            ),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "mssql"])
def test_timestamp_truncate(backend, alltypes, df, unit):
    expr = alltypes.timestamp_col.truncate(unit).name('tmp')

    dtype = f'datetime64[{unit}]'
    expected = pd.Series(df.timestamp_col.values.astype(dtype))

    result = expr.execute()
    expected = backend.default_series_rename(expected)

    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    'unit',
    [
        'Y',
        'M',
        'D',
        param(
            'W',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "duckdb",
                    "impala",
                    "mysql",
                    "postgres",
                    "pyspark",
                    "sqlite",
                    "snowflake",
                ]
            ),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "mssql"])
def test_date_truncate(backend, alltypes, df, unit):
    expr = alltypes.timestamp_col.date().truncate(unit).name('tmp')

    dtype = f"datetime64[{unit}]"
    expected = pd.Series(df.timestamp_col.values.astype(dtype))

    result = expr.execute()
    expected = backend.default_series_rename(expected)

    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    ('unit', 'displacement_type'),
    [
        param(
            'Y',
            pd.offsets.DateOffset,
            # TODO - DateOffset - #2553
            marks=pytest.mark.notimpl(['dask', 'polars']),
        ),
        param('Q', pd.offsets.DateOffset, marks=pytest.mark.xfail),
        param(
            'M',
            pd.offsets.DateOffset,
            # TODO - DateOffset - #2553
            marks=pytest.mark.notimpl(['dask', 'polars']),
        ),
        param(
            'W',
            pd.offsets.DateOffset,
            # TODO - DateOffset - #2553
            marks=pytest.mark.notimpl(['dask']),
        ),
        param('D', pd.offsets.DateOffset),
        param('h', pd.Timedelta),
        param('m', pd.Timedelta),
        param('s', pd.Timedelta),
        param(
            'ms',
            pd.Timedelta,
            marks=pytest.mark.notimpl(["clickhouse", "mysql"]),
        ),
        param(
            'us',
            pd.Timedelta,
            marks=pytest.mark.notimpl(["clickhouse"]),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "pyspark", "sqlite", "snowflake", "mssql"])
def test_integer_to_interval_timestamp(
    backend, con, alltypes, df, unit, displacement_type
):
    interval = alltypes.int_col.to_interval(unit=unit)
    expr = (alltypes.timestamp_col + interval).name('tmp')

    def convert_to_offset(offset, displacement_type=displacement_type):
        resolution = f'{interval.type().resolution}s'
        return displacement_type(**{resolution: offset})

    with warnings.catch_warnings():
        # both the implementation and test code raises pandas
        # PerformanceWarning, because We use DateOffset addition
        warnings.simplefilter("ignore", category=pd.errors.PerformanceWarning)
        result = con.execute(expr)
        offset = df.int_col.apply(convert_to_offset)
        expected = df.timestamp_col + offset

    expected = backend.default_series_rename(expected)
    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    'unit', ['Y', param('Q', marks=pytest.mark.xfail), 'M', 'W', 'D']
)
# TODO - DateOffset - #2553
@pytest.mark.notimpl(
    [
        "dask",
        "datafusion",
        "impala",
        "mysql",
        "pyspark",
        "sqlite",
        "snowflake",
        "polars",
        "mssql",
    ]
)
def test_integer_to_interval_date(backend, con, alltypes, df, unit):
    interval = alltypes.int_col.to_interval(unit=unit)
    array = alltypes.date_string_col.split('/')
    month, day, year = array[0], array[1], array[2]
    date_col = expr = ibis.literal('-').join(['20' + year, month, day]).cast('date')
    expr = (date_col + interval).name('tmp')
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=pd.errors.PerformanceWarning)
        result = con.execute(expr)

    def convert_to_offset(x):
        resolution = f'{interval.type().resolution}s'
        return pd.offsets.DateOffset(**{resolution: x})

    offset = df.int_col.apply(convert_to_offset)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=pd.errors.PerformanceWarning)
        expected = pd.to_datetime(df.date_string_col) + offset
    expected = backend.default_series_rename(expected)

    backend.assert_series_equal(result, expected)

date_value = pd.Timestamp('2017-12-31')
timestamp_value = pd.Timestamp('2018-01-01 18:18:18')

@pytest.mark.parametrize(
    ('expr_fn', 'expected_fn'),
    [
        param(
            lambda t, _: t.timestamp_col + ibis.interval(days=4),
            lambda t, _: t.timestamp_col + pd.Timedelta(days=4),
            id='timestamp-add-interval',
        ),
        param(
            lambda t, _: t.timestamp_col
            + (ibis.interval(days=4) - ibis.interval(days=2)),
            lambda t, _: t.timestamp_col
            + (pd.Timedelta(days=4) - pd.Timedelta(days=2)),
            id='timestamp-add-interval-binop',
            marks=pytest.mark.notimpl(
                [
                    "clickhouse",
                    "dask",
                    "duckdb",
                    "impala",
                    "mysql",
                    "pandas",
                    "postgres",
                    "snowflake",
                ]
            ),
        ),
        param(
            lambda t, _: t.timestamp_col - ibis.interval(days=17),
            lambda t, _: t.timestamp_col - pd.Timedelta(days=17),
            id='timestamp-subtract-interval',
        ),
        param(
            lambda t, _: t.timestamp_col.date() + ibis.interval(days=4),
            lambda t, _: t.timestamp_col.dt.floor('d') + pd.Timedelta(days=4),
            id='date-add-interval',
        ),
        param(
            lambda t, _: t.timestamp_col.date() - ibis.interval(days=14),
            lambda t, _: t.timestamp_col.dt.floor('d') - pd.Timedelta(days=14),
            id='date-subtract-interval',
        ),
        param(
            lambda t, _: t.timestamp_col - ibis.timestamp(timestamp_value),
            lambda t, be: pd.Series(
                t.timestamp_col.sub(timestamp_value).values.astype(
                    f'timedelta64[{be.returned_timestamp_unit}]'
                )
            ),
            id='timestamp-subtract-timestamp',
            marks=pytest.mark.notimpl(["duckdb", "pyspark", "snowflake"]),
        ),
        param(
            lambda t, _: t.timestamp_col.date() - ibis.date(date_value),
            lambda t, _: t.timestamp_col.dt.floor('d') - date_value,
            id='date-subtract-date',
            marks=pytest.mark.notimpl(["pyspark", "snowflake"]),
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "sqlite", "mssql"])
def test_temporal_binop(backend, con, alltypes, df, expr_fn, expected_fn):
    expr = expr_fn(alltypes, backend).name('tmp')
    expected = expected_fn(df, backend)

    result = con.execute(expr)
    expected = backend.default_series_rename(expected)

    backend.assert_series_equal(result, expected)

plus = lambda t, td: t.timestamp_col + pd.Timedelta(td)  # noqa: E731
minus = lambda t, td: t.timestamp_col - pd.Timedelta(td)  # noqa: E731

@pytest.mark.parametrize(
    ('timedelta', 'temporal_fn'),
    [
        ('36500d', plus),
        ('5W', plus),
        ('3d', plus),
        param('1.5d', plus, marks=pytest.mark.notimpl(["mysql"])),
        param('2h', plus, marks=pytest.mark.notimpl(["mysql"])),
        param('3m', plus, marks=pytest.mark.notimpl(["mysql"])),
        param('10s', plus, marks=pytest.mark.notimpl(["mysql"])),
        ('36500d', minus),
        ('5W', minus),
        ('3d', minus),
        param('1.5d', minus, marks=pytest.mark.notimpl(["mysql"])),
        param('2h', minus, marks=pytest.mark.notimpl(["mysql"])),
        param('3m', minus, marks=pytest.mark.notimpl(["mysql"])),
        param('10s', minus, marks=pytest.mark.notimpl(["mysql"])),
    ],
)
@pytest.mark.notimpl(
    ["clickhouse", "datafusion", "impala", "sqlite", "snowflake", "polars", "mssql"]
)
def test_temporal_binop_pandas_timedelta(
    backend, con, alltypes, df, timedelta, temporal_fn
):
    expr = temporal_fn(alltypes, timedelta).name('tmp')
    expected = temporal_fn(df, timedelta)

    result = con.execute(expr)
    expected = backend.default_series_rename(expected)

    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    'comparison_fn',
    [
        operator.gt,
        operator.ge,
        operator.lt,
        operator.le,
        operator.eq,
        operator.ne,
    ],
)
@pytest.mark.notimpl(["mssql"])
def test_timestamp_comparison_filter(backend, con, alltypes, df, comparison_fn):
    ts = pd.Timestamp('20100302', tz="UTC").to_pydatetime()
    expr = alltypes.filter(
        comparison_fn(alltypes.timestamp_col.cast("timestamp('UTC')"), ts)
    )

    col = df.timestamp_col.dt.tz_localize("UTC")
    expected = df[comparison_fn(col, ts)]
    result = con.execute(expr)

    backend.assert_frame_equal(result, expected)

@pytest.mark.notimpl(["datafusion", "sqlite", "snowflake", "mssql"])
def test_interval_add_cast_scalar(backend, alltypes):
    timestamp_date = alltypes.timestamp_col.date()
    delta = ibis.literal(10).cast("interval('D')")
    expr = (timestamp_date + delta).name('result')
    result = expr.execute()
    expected = timestamp_date.name('result').execute() + pd.Timedelta(10, unit='D')
    backend.assert_series_equal(result, expected)

@pytest.mark.never(
    ['pyspark'], reason="PySpark does not support casting columns to intervals"
)
@pytest.mark.notimpl(["datafusion", "sqlite", "snowflake", "mssql"])
def test_interval_add_cast_column(backend, alltypes, df):
    timestamp_date = alltypes.timestamp_col.date()
    delta = alltypes.bigint_col.cast("interval('D')")
    expr = alltypes['id', (timestamp_date + delta).name('tmp')]
    result = expr.execute().sort_values('id').reset_index().tmp
    df = df.sort_values('id').reset_index(drop=True)
    expected = (
        df['timestamp_col']
        .dt.normalize()
        .add(df.bigint_col.astype("timedelta64[D]"))
        .rename("tmp")
    )
    backend.assert_series_equal(result, expected)

@pytest.mark.parametrize(
    ('expr_fn', 'pandas_pattern'),
    [
        param(
            lambda t: t.timestamp_col.strftime('%Y%m%d').name("formatted"),
            '%Y%m%d',
            id="literal_format_str",
        ),
        param(
            lambda t: (
                t.mutate(suffix="%d")
                .select(
                    [
                        lambda t: t.timestamp_col.strftime("%Y%m" + t.suffix).name(
                            "formatted"
                        )
                    ]
                )
                .formatted
            ),
            '%Y%m%d',
            marks=[
                pytest.mark.notimpl(
                    [
                        "dask",
                        "pandas",
                        "postgres",
                        "pyspark",
                        "snowflake",
                        "polars",
                    ]
                ),
                pytest.mark.notyet(["duckdb", "impala"]),
            ],
            id="column_format_str",
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "mssql"])
def test_strftime(backend, alltypes, df, expr_fn, pandas_pattern):
    expr = expr_fn(alltypes)
    expected = df.timestamp_col.dt.strftime(pandas_pattern).rename("formatted")

    result = expr.execute()
    backend.assert_series_equal(result, expected)

unit_factors = {'s': int(1e9), 'ms': int(1e6), 'us': int(1e3), 'ns': 1}

@pytest.mark.parametrize(
    'unit',
    [
        's',
        param(
            'ms',
            marks=pytest.mark.notimpl(["clickhouse", "pyspark"]),
        ),
        param(
            'us',
            marks=pytest.mark.notimpl(["clickhouse", "duckdb", "pyspark"]),
        ),
        param(
            'ns',
            marks=pytest.mark.notimpl(["clickhouse", "duckdb", "pyspark"]),
        ),
    ],
)
@pytest.mark.notimpl(
    ["datafusion", "mysql", "postgres", "sqlite", "snowflake", "mssql"]
)
def test_integer_to_timestamp(backend, con, unit):
    backend_unit = backend.returned_timestamp_unit
    factor = unit_factors[unit]

    ts = ibis.timestamp('2018-04-13 09:54:11.872832')
    pandas_ts = ibis.pandas.execute(ts).floor(unit).value

    # convert the now timestamp to the input unit being tested
    int_expr = ibis.literal(pandas_ts // factor)
    expr = int_expr.to_timestamp(unit)
    result = con.execute(expr)
    expected = pd.Timestamp(pandas_ts, unit='ns').floor(backend_unit)

    assert result == expected

@pytest.mark.parametrize(
    'fmt, timezone',
    [
        # "11/01/10" - "month/day/year"
        param(
            '%m/%d/%y',
            "UTC",
            id="mysql_format",
            marks=pytest.mark.never(
                ["pyspark"], reason="datetime formatting style not supported"
            ),
        ),
        param(
            'MM/dd/yy',
            "UTC",
            id="pyspark_format",
            marks=pytest.mark.never(
                ["mysql", "polars"], reason="datetime formatting style not supported"
            ),
        ),
    ],
)
@pytest.mark.notimpl(
    [
        'dask',
        'pandas',
        'postgres',
        'duckdb',
        'clickhouse',
        'sqlite',
        'impala',
        'datafusion',
        'snowflake',
        'mssql',
    ]
)
def test_string_to_timestamp(alltypes, fmt, timezone):
    table = alltypes
    result = table.mutate(
        date=table.date_string_col.to_timestamp(fmt, timezone)
    ).execute()

    # TEST: do we get the same date out, that we put in?
    # format string assumes that we are using pandas' strftime
    for i, val in enumerate(result["date"]):
        assert val.strftime("%m/%d/%y") == result["date_string_col"][i]

@pytest.mark.notimpl(
    [
        'dask',
        'pandas',
        'postgres',
        'duckdb',
        'clickhouse',
        'sqlite',
        'impala',
        'datafusion',
        'snowflake',
        'polars',
        'mssql',
    ]
)
def test_string_to_timestamp_tz_error(alltypes):
    table = alltypes

    with pytest.raises(com.UnsupportedArgumentError):
        table.mutate(
            date=table.date_string_col.to_timestamp("%m/%d/%y", 'non-utc-timezone')
        ).compile()

@pytest.mark.parametrize(
    ('date', 'expected_index', 'expected_day'),
    [
        param('2017-01-01', 6, 'Sunday', id="sunday"),
        param('2017-01-02', 0, 'Monday', id="monday"),
        param('2017-01-03', 1, 'Tuesday', id="tuesday"),
        param('2017-01-04', 2, 'Wednesday', id="wednesday"),
        param('2017-01-05', 3, 'Thursday', id="thursday"),
        param('2017-01-06', 4, 'Friday', id="friday"),
        param('2017-01-07', 5, 'Saturday', id="saturday"),
    ],
)
@pytest.mark.notimpl(["datafusion", "impala", "snowflake", "mssql"])
def test_day_of_week_scalar(con, date, expected_index, expected_day):
    expr = ibis.literal(date).cast(dt.date)
    result_index = con.execute(expr.day_of_week.index())
    assert result_index == expected_index

    result_day = con.execute(expr.day_of_week.full_name())
    assert result_day.lower() == expected_day.lower()

@pytest.mark.notimpl(["datafusion", "snowflake", "mssql"])
def test_day_of_week_column(backend, alltypes, df):
    expr = alltypes.timestamp_col.day_of_week

    result_index = expr.index().execute()
    expected_index = df.timestamp_col.dt.dayofweek.astype('int16')

    backend.assert_series_equal(result_index, expected_index, check_names=False)

    result_day = expr.full_name().execute()
    expected_day = day_name(df.timestamp_col.dt)

    backend.assert_series_equal(result_day, expected_day, check_names=False)

@pytest.mark.parametrize(
    ('day_of_week_expr', 'day_of_week_pandas'),
    [
        param(
            lambda t: t.timestamp_col.day_of_week.index().count(),
            lambda s: s.dt.dayofweek.count(),
            id="day_of_week_index",
        ),
        param(
            lambda t: t.timestamp_col.day_of_week.full_name().length().sum(),
            lambda s: day_name(s.dt).str.len().sum(),
            id="day_of_week_full_name",
            marks=[pytest.mark.notimpl(["snowflake"])],
        ),
    ],
)
@pytest.mark.notimpl(["datafusion", "mssql"])
def test_day_of_week_column_group_by(
    backend, alltypes, df, day_of_week_expr, day_of_week_pandas
):
    expr = alltypes.group_by('string_col').aggregate(
        day_of_week_result=day_of_week_expr
    )
    schema = expr.schema()
    assert schema['day_of_week_result'] == dt.int64

    result = expr.execute().sort_values('string_col')
    expected = (
        df.groupby('string_col')
        .timestamp_col.apply(day_of_week_pandas)
        .reset_index()
        .rename(columns={'timestamp_col': 'day_of_week_result'})
    )

    # FIXME(#1536): Pandas backend should use query.schema().apply_to
    backend.assert_frame_equal(result, expected, check_dtype=False)

@pytest.mark.notimpl(["datafusion", "snowflake", "mssql"])
def test_now(con):
    expr = ibis.now()
    result = con.execute(expr)
    assert isinstance(result, pd.Timestamp)

    pattern = "%Y%m%d %H"
    result_strftime = con.execute(expr.strftime(pattern))
    expected_strftime = datetime.datetime.utcnow().strftime(pattern)
    assert result_strftime == expected_strftime

@pytest.mark.notimpl(["dask"], reason="Limit #2553")
@pytest.mark.notimpl(["datafusion", "snowflake", "polars"])
def test_now_from_projection(alltypes):
    n = 5
    expr = alltypes[[ibis.now().name('ts')]].limit(n)
    result = expr.execute()
    ts = result.ts
    assert isinstance(result, pd.DataFrame)
    assert isinstance(ts, pd.Series)
    assert issubclass(ts.dtype.type, np.datetime64)
    assert len(result) == n
    assert ts.nunique() == 1

    now = pd.Timestamp('now')
    year_expected = pd.Series([now.year] * n, name='ts')
    tm.assert_series_equal(ts.dt.year, year_expected)

@pytest.mark.notimpl(
    ["pandas", "datafusion", "mysql", "dask", "pyspark", "snowflake", "mssql"]
)
@pytest.mark.notyet(["clickhouse", "impala"])
def test_date_literal(con):
    expr = ibis.date(2022, 2, 4)
    result = con.execute(expr)
    assert result.strftime('%Y-%m-%d') == '2022-02-04'

@pytest.mark.notimpl(
    ["pandas", "datafusion", "mysql", "dask", "pyspark", "snowflake", "mssql"]
)
@pytest.mark.notyet(["clickhouse", "impala"])
def test_timestamp_literal(con):
    expr = ibis.timestamp(2022, 2, 4, 16, 20, 0)
    result = con.execute(expr)
    if not isinstance(result, str):
        result = result.strftime('%Y-%m-%d %H:%M:%S%Z')
    assert result == '2022-02-04 16:20:00'

@pytest.mark.notimpl(
    ["pandas", "datafusion", "mysql", "dask", "pyspark", "polars", "mssql"]
)
@pytest.mark.notyet(["clickhouse", "impala"])
def test_time_literal(con):
    expr = ibis.time(16, 20, 0)
    result = con.execute(expr)
    if not isinstance(result, str):
        result = result.strftime('%H:%M:%S')
    assert result == '16:20:00'

@pytest.mark.notimpl(
    ["pandas", "datafusion", "mysql", "dask", "pyspark", "snowflake", "mssql"]
)
@pytest.mark.notyet(["clickhouse", "impala"])
def test_date_column_from_ymd(con, alltypes, df):
    c = alltypes.timestamp_col
    expr = ibis.date(c.year(), c.month(), c.day())
    tbl = alltypes[
        expr.name('timestamp_col'),
    ]
    result = con.execute(tbl)

    golden = df.timestamp_col.dt.date.astype('datetime64[ns]')
    tm.assert_series_equal(golden, result.timestamp_col)

@pytest.mark.notimpl(["datafusion", "impala"])
def test_date_scalar_from_iso(con):
    expr = ibis.literal('2022-02-24')
    expr2 = ibis.date(expr)

    result = con.execute(expr2)
    assert result.strftime('%Y-%m-%d') == '2022-02-24'

@pytest.mark.notimpl(["datafusion", "impala", "pyspark", "mssql"])
def test_date_column_from_iso(con, alltypes, df):
    expr = (
        alltypes.year.cast('string')
        + '-'
        + alltypes.month.cast('string').lpad(2, '0')
        + '-13'
    )
    expr = ibis.date(expr)

    result = con.execute(expr)
    golden = df.year.astype(str) + '-' + df.month.astype(str).str.rjust(2, '0') + '-13'
    actual = result.dt.strftime('%Y-%m-%d')
    tm.assert_series_equal(golden.rename('tmp'), actual.rename('tmp'))

@pytest.mark.notimpl(["datafusion", "snowflake"])
@pytest.mark.notyet(["clickhouse", "pyspark"])
@pytest.mark.broken(["mysql"])
def test_timestamp_extract_milliseconds_with_big_value(con):
    timestamp = ibis.timestamp("2021-01-01 01:30:59.333")
    millis = timestamp.millisecond()
    result = con.execute(millis)
    assert result == 333

@pytest.mark.notimpl(["datafusion", "mssql"])
@pytest.mark.broken(
    ["dask", "pandas"],
    reason="Pandas and Dask interpret integers as nanoseconds since epoch",
)
def test_integer_cast_to_timestamp(backend, alltypes, df):
    expr = alltypes.int_col.cast("timestamp")
    expected = pd.to_datetime(df.int_col, unit="s").rename(expr.get_name())
    result = expr.execute()
    backend.assert_series_equal(result, expected)

@pytest.mark.broken(
    ["clickhouse", "impala"],
    reason=(
        "Impala returns a string; "
        "the clickhouse driver returns invalid results for big timestamps"
    ),
)
@pytest.mark.notimpl(
    ["datafusion", "polars"],
    reason="Arrow backends assume a ns resolution timestamps",
)
@pytest.mark.notyet(
    ["pyspark"],
    reason="PySpark doesn't handle big timestamps",
)
@pytest.mark.notimpl(["snowflake", "mssql"])
def test_big_timestamp(con):
    # TODO: test with a timezone
    value = ibis.timestamp("2419-10-11 10:10:25")
    result = con.execute(value)
    expected = datetime.datetime(2419, 10, 11, 10, 10, 25)
    assert result == expected

DATE = datetime.date(2010, 11, 1)

def build_date_col(t):
    return (
        t.year.cast("string")
        + "-"
        + t.month.cast("string").lpad(2, "0")
        + "-"
        + (t.int_col + 1).cast("string").lpad(2, "0")
    ).cast("date")

@pytest.mark.notimpl(["datafusion", "mssql"])
@pytest.mark.notyet(["impala"], reason="impala doesn't support dates")
@pytest.mark.parametrize(
    ("left_fn", "right_fn"),
    [
        param(build_date_col, lambda _: DATE, id="column_date"),
        param(lambda _: DATE, build_date_col, id="date_column"),
    ],
)
def test_timestamp_date_comparison(backend, alltypes, df, left_fn, right_fn):
    left = left_fn(alltypes)
    right = right_fn(alltypes)
    expr = left == right
    result = expr.execute().rename("result")
    expected = (
        pd.to_datetime(
            (
                df.year.astype(str)
                .add("-")
                .add(df.month.astype(str).str.rjust(2, "0"))
                .add("-")
                .add(df.int_col.add(1).astype(str).str.rjust(2, "0"))
            ),
            format="%Y-%m-%d",
            exact=True,
        )
        .eq(pd.Timestamp(DATE))
        .rename("result")
    )
    backend.assert_series_equal(result, expected)


text:
statsd-rb
=========
A ruby client for [StatsD](https://github.com/etsy/statsd).

Installation
------------

    gem install statsd-rb

Usage
-----
Connecting to a StatsD instance:

    require "statsd"
    client = StatsD::Client.new

By default, clients will connect to `localhost:8125`.  If you need to
connect to a remote server or a different port, use the `:hostname` and
`:port` options.

    client = StatsD::Client.new(:hostname => "statsd", :port => 5000)

### Commands
Once you have a client, sending statistics is easy.

Increment the downloads count:

    client.incr :downloads

Increment the downloads count, telling StatsD that the counter is being
sampled every 10th time.  All commands take an optional last argument
`sample_rate`.

    client.incr :downloads, 0.1

Decrement the invites count by two:

    client.decrby :invites, 2

Time the archive job:

    client.time :archive do
      # something
    end

Send an already calculated timing:

    client.timing :archive, 300  # milliseconds

TODO
----

- Bulk updating

Author
------
Matt Duncan | [mattduncan.org](http://mattduncan.org) | [matt@mattduncan.org](mailto:matt@mattduncan.org)


text:
#include <cybergarage/x3d/SceneGraph.h>

using namespace CyberX3D;

LODNode::LODNode()
{
	setHeaderFlag(false);
	setType(LOD_NODE);

	// center field
	centerField = new SFVec3f(0.0f, 0.0f, 0.0f);
	addField(centerFieldString, centerField);

	// range field
	rangeField = new MFFloat();
	addField(rangeFieldString, rangeField);
}

LODNode::~LODNode()
{
}

////////////////////////////////////////////////
//	center
////////////////////////////////////////////////

SFVec3f *LODNode::getCenterField() const
{
	if (isInstanceNode() == false)
		return centerField;
	return (SFVec3f *)getField(centerFieldString);
}

void LODNode::setCenter(float value[])
{
	getCenterField()->setValue(value);
}

void LODNode::setCenter(float x, float y, float z)
{
	getCenterField()->setValue(x, y, z);
}

void LODNode::getCenter(float value[]) const
{
	getCenterField()->getValue(value);
}

////////////////////////////////////////////////
//	range
////////////////////////////////////////////////

MFFloat *LODNode::getRangeField() const
{
	if (isInstanceNode() == false)
		return rangeField;
	return (MFFloat *)getField(rangeFieldString);
}

void LODNode::addRange(float value)
{
	getRangeField()->addValue(value);
}

int LODNode::getNRanges() const
{
	return getRangeField()->getSize();
}

float LODNode::getRange(int index) const
{
	return getRangeField()->get1Value(index);
}

////////////////////////////////////////////////
//	List
////////////////////////////////////////////////

LODNode *LODNode::next() const
{
	return (LODNode *)Node::next(getType());
}

LODNode *LODNode::nextTraversal() const
{
	return (LODNode *)Node::nextTraversalByType(getType());
}

////////////////////////////////////////////////
//	functions
////////////////////////////////////////////////

bool LODNode::isChildNodeType(Node *node) const
{
	if (node->isCommonNode() || node->isBindableNode() ||node->isInterpolatorNode() || node->isSensorNode() || node->isGroupingNode() || node->isSpecialGroupNode())
		return true;
	else
		return false;
}

////////////////////////////////////////////////
//	Infomation
////////////////////////////////////////////////

void LODNode::outputContext(std::ostream &printStream, const char *indentString) const
{
	SFVec3f *center = getCenterField();
	printStream << indentString << "\t" << "center " << center << std::endl;

	if (0 < getNRanges()) {
		MFFloat *range = getRangeField();
		printStream << indentString << "\t" << "range [" << std::endl;
		range->MField::outputContext(printStream, indentString, "\t\t");
		printStream << indentString << "\t" << "]" << std::endl;
	}
}

////////////////////////////////////////////////
//	LODNode::update
////////////////////////////////////////////////

void UpdateLOD(LODNode *lod)
{
	int nNodes = lod->getNPrivateNodeElements();
	for (int n=0; n<nNodes; n++) {
		Node *node = lod->getPrivateNodeElementAt(n);
		node->remove();
	}

	SceneGraph *sg = lod->getSceneGraph();

	ViewpointNode *vpoint = sg->getViewpointNode();
	if (vpoint == NULL)
		vpoint = sg->getDefaultViewpointNode();

	if (vpoint) {
		SFMatrix	viewMatrix;
		float		viewPosition[3];
		vpoint->getTransformMatrix(&viewMatrix);
		vpoint->getPosition(viewPosition);
		viewMatrix.multi(viewPosition);

		SFMatrix	lodMatrix;
		float		lodCenter[3];
		lod->getTransformMatrix(&lodMatrix);
		lod->getCenter(lodCenter);
		lodMatrix.multi(lodCenter);

		float lx = lodCenter[0] - viewPosition[0];
		float ly = lodCenter[1] - viewPosition[1];
		float lz = lodCenter[2] - viewPosition[2];
		float distance = (float)sqrt(lx*lx + ly*ly + lz*lz);

		int numRange = lod->getNRanges();
		int nRange = 0;
		for (nRange=0; nRange<numRange; nRange++) {
			if (distance < lod->getRange(nRange))
				break;
		}

		Node *node = lod->getPrivateNodeElementAt(nRange);
		if (!node)
			node = lod->getPrivateNodeElementAt(lod->getNPrivateNodeElements() - 1);
		assert(node);
		lod->addChildNode(node);
	}
}

void LODNode::update()
{
	UpdateLOD(this);
}

////////////////////////////////////////////////
//	LODNode::initialize
////////////////////////////////////////////////

void InitializeLOD(LODNode *lod)
{
	lod->uninitialize();

	Node *node = lod->getChildNodes();
	while (node) {
		Node *nextNode = node->next();
//		node->remove();
		lod->addPrivateNodeElement(node);
		node = nextNode;
	}
/*
	Node *firstNode = lod->getPrivateNodeElementAt(0);
	if (firstNode)
		lod->addChildNode(firstNode);
*/
}

void LODNode::initialize()
{
	if (isInitialized() == false) {
		InitializeLOD(this);
		setInitialized(true);
	}
}

////////////////////////////////////////////////
//	LODNode::uninitialize
////////////////////////////////////////////////

void UninitializeLOD(LODNode *lod)
{
	int nNodes = lod->getNPrivateNodeElements();
	for (int n=0; n<nNodes; n++) {
		Node *node = lod->getPrivateNodeElementAt(n);
		node->remove();
		lod->addChildNode(node);
	}
	lod->removeAllNodeElement();
}

void LODNode::uninitialize()
{
	if (isInitialized() == true) {
		UninitializeLOD(this);
		setInitialized(false);
	}
}


text: Shows the battery level of your xinput-compatible controller!


text:
import React from 'react'
import { render } from 'react-dom'
import {
  init,
  locations,
  DialogExtensionSDK,
  EditorExtensionSDK,
  SidebarExtensionSDK,
  PageExtensionSDK,
  FieldExtensionSDK
} from 'contentful-ui-extensions-sdk'
import '@contentful/forma-36-react-components/dist/styles.css'
import '@contentful/forma-36-fcss/dist/styles.css'
import './index.css'
import { FieldExtension } from './field-extension'
import { PageExtension } from './page-extension'
import { SidebarExtension } from './sidebar-extension'
import { EntryEditorExtension } from './entry-editor-extension'
import { DialogExtension } from './dialog-extension'

function renderExtension(element) {
  render(element, document.getElementById('root'))
}

init(sdk => {
  ;(window as any).sdk = sdk
  if (sdk.location.is(locations.LOCATION_ENTRY_FIELD)) {
    renderExtension(<FieldExtension sdk={sdk as FieldExtensionSDK} />)
  } else if (sdk.location.is(locations.LOCATION_PAGE)) {
    renderExtension(<PageExtension sdk={sdk as PageExtensionSDK} />)
  } else if (sdk.location.is(locations.LOCATION_ENTRY_SIDEBAR)) {
    renderExtension(<SidebarExtension sdk={sdk as SidebarExtensionSDK} />)
  } else if (sdk.location.is(locations.LOCATION_ENTRY_EDITOR)) {
    renderExtension(<EntryEditorExtension sdk={sdk as EditorExtensionSDK} />)
  } else if (sdk.location.is(locations.LOCATION_DIALOG)) {
    renderExtension(<DialogExtension sdk={sdk as DialogExtensionSDK} />)
  }
})


text:
A simple node module to parse address information (such as an email signature)
into component parts.  It's in use over at [Barnivore](http://barnivore.com/)
where we input a lot of addresses.

At present it's optimized for North America; other address formats will be
supported as we hammer the bugs out in production.

## Installation

`npm install contact-parser`

## Usage

Include the module

```javascript
var ContactParser = require('contact-parser');
```

Parse some address strings

```javascript
var parser = new ContactParser()
var result = parser.parse('Jason, 1 Yonge St')
console.log(result); // {name: 'Jason', email: '', province: '', country: '', address: '1 Yonge St', postal: '', website: '', phone: ''}
```

## Bugs

I'm sure there are several :) Help fix them by submitting an issue, or better yet, a tested pull request.

## License

** MIT **


text:
import BasicAdapter from "adapters/basic";

var ChromeAdapter = BasicAdapter.extend({
  init: function() {
    this._super();
    this._connect();
  },

  sendMessage: function(options) {
    options = options || {};
    this.get('_chromePort').postMessage(options);
  },

  inspectElement: function(elem) {
    inspect(elem);
  },

  _channel: Ember.computed(function() {
    return new MessageChannel();
  }).property(),

  _chromePort: Ember.computed(function() {
    return this.get('_channel.port1');
  }).property(),

  _connect: function() {
    var channel = this.get('_channel'),
        self = this,
        chromePort = this.get('_chromePort');

    window.postMessage('debugger-client', [channel.port2], '*');

    chromePort.addEventListener('message', function(event) {
      var message = event.data;
      Ember.run(function() {
        self._messageReceived(message);
      });
    });

    chromePort.start();

  }
});

export default ChromeAdapter;


text:
package mcjty.rftools;

import mcjty.rftools.render.ModRenderers;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;

public class ClientProxy extends CommonProxy {
    @Override
    public void preInit(FMLPreInitializationEvent e) {
        super.preInit(e);
    }

    @Override
    public void init(FMLInitializationEvent e) {
        super.init(e);
        ModRenderers.init();
        MinecraftForge.EVENT_BUS.register(this);
    }

    @Override
    public void postInit(FMLPostInitializationEvent e) {
        super.postInit(e);
    }

    @SubscribeEvent
    public void renderWorldLastEvent(RenderWorldLastEvent evt) {
        RenderWorldLastEventHandler.tick(evt);
    }

    @SubscribeEvent
    public void renderGameOverlayEvent(RenderGameOverlayEvent evt) {
        RenderGameOverlayEventHandler.onRender(evt);
    }

}


text:
#ifndef _EFI_DRIVER_CONFIGURATION_H_
#define _EFI_DRIVER_CONFIGURATION_H_

//
// Global ID for the Driver Configuration Protocol
//
#define EFI_DRIVER_CONFIGURATION_PROTOCOL_GUID \
  { \
    0x107a772b, 0xd5e1, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d} \
  }

EFI_FORWARD_DECLARATION (EFI_DRIVER_CONFIGURATION_PROTOCOL);

typedef enum {
  EfiDriverConfigurationActionNone              = 0,
  EfiDriverConfigurationActionStopController    = 1,
  EfiDriverConfigurationActionRestartController = 2,
  EfiDriverConfigurationActionRestartPlatform   = 3,
  EfiDriverConfigurationActionMaximum
} EFI_DRIVER_CONFIGURATION_ACTION_REQUIRED;

#define EFI_DRIVER_CONFIGURATION_SAFE_DEFAULTS          0x00000000
#define EFI_DRIVER_CONFIGURATION_MANUFACTURING_DEFAULTS 0x00000001
#define EFI_DRIVER_CONFIGURATION_CUSTOM_DEFAULTS        0x00000002
#define EFI_DRIVER_CONFIGURATION_PERORMANCE_DEFAULTS    0x00000003

typedef
EFI_STATUS
(EFIAPI *EFI_DRIVER_CONFIGURATION_SET_OPTIONS) (
  IN EFI_DRIVER_CONFIGURATION_PROTOCOL                        * This,
  IN  EFI_HANDLE                                              ControllerHandle,
  IN  EFI_HANDLE                                              ChildHandle  OPTIONAL,
  IN  CHAR8                                                   *Language,
  OUT EFI_DRIVER_CONFIGURATION_ACTION_REQUIRED                * ActionRequired
  );

/*++

  Routine Description:
    Allows the user to set controller specific options for a controller that a
    driver is currently managing.

  Arguments:
    This             - A pointer to the EFI_DRIVER_CONFIGURATION_ PROTOCOL instance.
    ControllerHandle - The handle of the controller to set options on.
    ChildHandle      - The handle of the child controller to set options on.  This
                       is an optional parameter that may be NULL.  It will be NULL
                       for device drivers, and for a bus drivers that wish to set
                       options for the bus controller.  It will not be NULL for a
                       bus driver that wishes to set options for one of its child
                       controllers.
    Language         - A pointer to a three character ISO 639-2 language identifier.
                       This is the language of the user interface that should be
                       presented to the user, and it must match one of the languages
                       specified in SupportedLanguages.  The number of languages
                       supported by a driver is up to the driver writer.
    ActionRequired   - A pointer to the action that the calling agent is required
                       to perform when this function returns.  See "Related
                       Definitions" for a list of the actions that the calling
                       agent is required to perform prior to accessing
                       ControllerHandle again.

  Returns:
    EFI_SUCCESS           - The driver specified by This successfully set the
                            configuration options for the controller specified
                            by ControllerHandle..
    EFI_INVALID_PARAMETER - ControllerHandle is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ChildHandle is not NULL and it is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ActionRequired is NULL.
    EFI_UNSUPPORTED       - The driver specified by This does not support setting
                            configuration options for the controller specified by
                            ControllerHandle and ChildHandle.
    EFI_UNSUPPORTED       - The driver specified by This does not support the
                            language specified by Language.
    EFI_DEVICE_ERROR      - A device error occurred while attempt to set the
                            configuration options for the controller specified
                            by ControllerHandle and ChildHandle.
    EFI_OUT_RESOURCES     - There are not enough resources available to set the
                            configuration options for the controller specified
                            by ControllerHandle and ChildHandle.

--*/
typedef
EFI_STATUS
(EFIAPI *EFI_DRIVER_CONFIGURATION_OPTIONS_VALID) (
  IN EFI_DRIVER_CONFIGURATION_PROTOCOL                        * This,
  IN  EFI_HANDLE                                              ControllerHandle,
  IN  EFI_HANDLE                                              ChildHandle  OPTIONAL
  );

/*++

  Routine Description:
    Tests to see if a controller's current configuration options are valid.

  Arguments:
    This             - A pointer to the EFI_DRIVER_CONFIGURATION_PROTOCOL instance.
    ControllerHandle - The handle of the controller to test if it's current
                       configuration options are valid.
    ChildHandle      - The handle of the child controller to test if it's current
                       configuration options are valid.  This is an optional
                       parameter that may be NULL.  It will be NULL for device
                       drivers.  It will also be NULL for a bus drivers that wish
                       to test the configuration options for the bus controller.
                       It will not be NULL for a bus driver that wishes to test
                       configuration options for one of its child controllers.

  Returns:
    EFI_SUCCESS           - The controller specified by ControllerHandle and
                            ChildHandle that is being managed by the driver
                            specified by This has a valid set of  configuration
                            options.
    EFI_INVALID_PARAMETER - ControllerHandle is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ChildHandle is not NULL and it is not a valid EFI_HANDLE.
    EFI_UNSUPPORTED       - The driver specified by This is not currently
                            managing the controller specified by ControllerHandle
                            and ChildHandle.
    EFI_DEVICE_ERROR      - The controller specified by ControllerHandle and
                            ChildHandle that is being managed by the driver
                            specified by This has an invalid set of configuration
                            options.

--*/
typedef
EFI_STATUS
(EFIAPI *EFI_DRIVER_CONFIGURATION_FORCE_DEFAULTS) (
  IN EFI_DRIVER_CONFIGURATION_PROTOCOL                        * This,
  IN  EFI_HANDLE                                              ControllerHandle,
  IN  EFI_HANDLE                                              ChildHandle  OPTIONAL,
  IN  UINT32                                                  DefaultType,
  OUT EFI_DRIVER_CONFIGURATION_ACTION_REQUIRED                * ActionRequired
  );

/*++

  Routine Description:
    Forces a driver to set the default configuration options for a controller.

  Arguments:
    This             - A pointer to the EFI_DRIVER_CONFIGURATION_ PROTOCOL instance.
    ControllerHandle - The handle of the controller to force default configuration options on.
    ChildHandle      - The handle of the child controller to force default configuration options on  This is an optional parameter that may be NULL.  It will be NULL for device drivers.  It will also be NULL for a bus drivers that wish to force default configuration options for the bus controller.  It will not be NULL for a bus driver that wishes to force default configuration options for one of its child controllers.
    DefaultType      - The type of default configuration options to force on the controller specified by ControllerHandle and ChildHandle.  See Table 9-1 for legal values.  A DefaultType of 0x00000000 must be supported by this protocol.
    ActionRequired   - A pointer to the action that the calling agent is required to perform when this function returns.  See "Related Definitions" in Section 9.1for a list of the actions that the calling agent is required to perform prior to accessing ControllerHandle again.

  Returns:
    EFI_SUCCESS           - The driver specified by This successfully forced the default configuration options on the controller specified by ControllerHandle and ChildHandle.
    EFI_INVALID_PARAMETER - ControllerHandle is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ChildHandle is not NULL and it is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ActionRequired is NULL.
    EFI_UNSUPPORTED       - The driver specified by This does not support forcing the default configuration options on the controller specified by ControllerHandle and ChildHandle.
    EFI_UNSUPPORTED       - The driver specified by This does not support the configuration type specified by DefaultType.
    EFI_DEVICE_ERROR      - A device error occurred while attempt to force the default configuration options on the controller specified by  ControllerHandle and ChildHandle.
    EFI_OUT_RESOURCES     - There are not enough resources available to force the default configuration options on the controller specified by ControllerHandle and ChildHandle.

--*/

//
// Interface structure for the Driver Configuration Protocol
//
struct _EFI_DRIVER_CONFIGURATION_PROTOCOL {
  EFI_DRIVER_CONFIGURATION_SET_OPTIONS    SetOptions;
  EFI_DRIVER_CONFIGURATION_OPTIONS_VALID  OptionsValid;
  EFI_DRIVER_CONFIGURATION_FORCE_DEFAULTS ForceDefaults;
  CHAR8                                   *SupportedLanguages;
};

/*++

  Protocol Description:
    Used to set configuration options for a controller that an EFI Driver is managing.

  Parameters:
    SetOptions         - Allows the use to set drivers specific configuration
                         options for a controller that the driver is currently
                         managing.
    OptionsValid       - Tests to see if a controller's current configuration
                         options are valid.
    ForceDefaults      - Forces a driver to set the default configuration options
                         for a controller.
    SupportedLanguages - A Null-terminated ASCII string that contains one or more
                         ISO 639-2 language codes.  This is the list of language
                         codes that this protocol supports.

--*/
extern EFI_GUID gEfiDriverConfigurationProtocolGuid;

#endif


text:
using NetMud.Data.Architectural.PropertyBinding;
using NetMud.Data.Linguistic;
using NetMud.DataAccess.Cache;
using NetMud.DataStructure.Architectural;
using NetMud.DataStructure.Linguistic;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace NetMud.Models.Admin
{
    public class ManageLanguageDataViewModel : PagedDataModel<ILanguage>
    {
        public ManageLanguageDataViewModel(IEnumerable<ILanguage> items)
            : base(items)
        {
            CurrentPageNumber = 1;
            ItemsPerPage = 20;
        }

        internal override Func<ILanguage, bool> SearchFilter
        {
            get
            {
                return item => item.Name.ToLower().Contains(SearchTerms.ToLower());
            }
        }

        internal override Func<ILanguage, object> OrderPrimary
        {
            get
            {
                return item => item.UIOnly ? 0 : 1;
            }
        }

        internal override Func<ILanguage, object> OrderSecondary
        {
            get
            {
                return item => item.Name;
            }
        }
    }

    public class AddEditLanguageViewModel : AddEditConfigDataModel<ILanguage>
    {
        [Display(Name = "Apply Existing Template", Description = "Apply an existing object's data to this new data.")]
        [UIHint("LanguageList")]
        [LanguageDataBinder]
        public override ILanguage Template { get; set; }

        public AddEditLanguageViewModel() : base("", ConfigDataType.Language)
        {
            ValidWords = ConfigDataCache.GetAll<ILexeme>().OrderBy(word => word.Language.Name).ThenBy(word => word.Name);
            ValidLanguages = ConfigDataCache.GetAll<ILanguage>();
            DataObject = new Language();
        }

        public AddEditLanguageViewModel(string uniqueKey) : base(uniqueKey, ConfigDataType.Language)
        {
            ValidWords = ConfigDataCache.GetAll<ILexeme>().OrderBy(word => word.Language.Name).ThenBy(word => word.Name);
            ValidLanguages = ConfigDataCache.GetAll<ILanguage>();
            DataObject = new Language();

            //apply template
            if (DataTemplate != null)
            {
                DataObject.AntecendentPunctuation = DataTemplate.AntecendentPunctuation;
                DataObject.BaseWords = DataTemplate.BaseWords;
                DataObject.ContractionRules = DataTemplate.ContractionRules;
                DataObject.TransformationRules = DataTemplate.TransformationRules;
                DataObject.Gendered = DataTemplate.Gendered;
                DataObject.PrecedentPunctuation = DataTemplate.PrecedentPunctuation;
                DataObject.WordPairRules = DataTemplate.WordPairRules;
                DataObject.WordRules = DataTemplate.WordRules;
                DataObject.SentenceRules = DataTemplate.SentenceRules;
                DataObject.UIOnly = DataTemplate.UIOnly;
            }
        }

        public AddEditLanguageViewModel(string archivePath, ILanguage item) : base(archivePath, ConfigDataType.Language, item)
        {
            ValidWords = ConfigDataCache.GetAll<ILexeme>().Where(word => word.Language == item).OrderBy(word => word.Name);
            ValidLanguages = ConfigDataCache.GetAll<ILanguage>();
            DataObject = (Language)item;
        }

        public IEnumerable<ILanguage> ValidLanguages { get; set; }
        public IEnumerable<ILexeme> ValidWords { get; set; }
        public Language DataObject { get; set; }
    }
}


text:
require 'mkmf'

$defs.push("-DUUID") if have_library("uuid")

create_makefile("identifier")


text:
//=============================================================================
// Yanfly Engine Plugins - Equip Extension - Equip Customize Command
// YEP_X_EquipCustomize.js
//=============================================================================

var Imported = Imported || {};
Imported.YEP_X_EquipCustomize = true;

var Yanfly = Yanfly || {};
Yanfly.ECC = Yanfly.ECC || {};

//=============================================================================
 /*:
 * @plugindesc v1.00 (Requires YEP_ItemCore && YEP_EquipCore.js)
 * Adds a 'Customize' command to the Equip menu.
 * @author Yanfly Engine Plugins
 *
 * @param Command Name
 * @desc The text used for the command name in the Equip menu.
 * @default Customize
 *
 * @param Default Enable
 * @desc Show the Customize command in the Equip menu by default?
 * NO - false     YES - true
 * @default true
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * This plugin requires YEP_ItemCore && YEP_EquipCore.js. Make sure this plugin
 * is located under both of those plugins in the plugin list.
 *
 * Games that use the YEP_X_ItemUpgradeSlots, YEP_X_ItemDurability, and
 * YEP_X_AttachAugment plugins may notice that it's not too intuitive to
 * modify items from the item menu when they're equipped to the actors in the
 * equip menu. This plugin will add a "Customize" option to the Equip menu that
 * will function as a shortcut to the Item menu for quick customization access.
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * There's a couple of plugin commands you can use with this plugin.
 *
 * Plugin Command:
 *
 *   ShowEquipCustomize
 *   - This will show the 'Customize' command in the equip menu.
 *
 *   HideEquipCustomize
 *   - This will hide the 'Customize' command in the equip menu.
 */
//=============================================================================

if (Imported.YEP_ItemCore && Imported.YEP_EquipCore) {

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_X_EquipCustomize');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.ItemSceneItem = 'true';
Yanfly.Param.ItemShEquipped = 'false';

Yanfly.Param.EECName = String(Yanfly.Parameters['Command Name']);
Yanfly.Param.EECEnable = String(Yanfly.Parameters['Default Enable']);

//=============================================================================
// Game_System
//=============================================================================

Yanfly.ECC.Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
    Yanfly.ECC.Game_System_initialize.call(this);
    this.initECC();
};

Game_System.prototype.initECC = function() {
    this._ECCShown = Yanfly.Param.EECEnable;
};

Game_System.prototype.isEquipCustomizable = function() {
    if (this._ECCShown === undefined) this.initECC();
    return this._ECCShown;
};

Game_System.prototype.setEquipCustomizable = function(value) {
    if (this._ECCShown === undefined) this.initECC();
    this._ECCShown = value;
};

//=============================================================================
// Game_Interpreter
//=============================================================================

Yanfly.ECC.Game_Interpreter_pluginCommand =
  Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
  Yanfly.ECC.Game_Interpreter_pluginCommand.call(this, command, args);
  if (command === 'ShowEquipCustomize') $gameSystem.setEquipCustomizable(true);
  if (command === 'HideEquipCustomize') $gameSystem.setEquipCustomizable(false);
};

//=============================================================================
// Window_Command
//=============================================================================

Window_Command.prototype.addCommandAt = function(index, name, symbol, en, ext) {
    if (en === undefined) enabled = true;
    if (ext === undefined) ext = null;
    var obj = { name: name, symbol: symbol, enabled: en, ext: ext};
    this._list.splice(index, 0, obj);
};

//=============================================================================
// Window_EquipCommand
//=============================================================================

Yanfly.ECC.Window_EquipCommand_addCustomCommand =
    Window_EquipCommand.prototype.addCustomCommand;
Window_EquipCommand.prototype.addCustomCommand = function() {
    Yanfly.ECC.Window_EquipCommand_addCustomCommand.call(this);
    if ($gameSystem.isEquipCustomizable()) this.addEquipCustomizeCommand();
};

Window_EquipCommand.prototype.addEquipCustomizeCommand = function() {
    var index = this.findSymbol('equip') + 1;
    if ($gameParty.inBattle()) {
      var enabled = BattleManager.isBattleTest();
    } else {
      var enabled = true;
    }
    this.addCommandAt(index, Yanfly.Param.EECName, 'customize', enabled);
};

//=============================================================================
// Window_EquipSlot
//=============================================================================

Window_EquipSlot.prototype.playOkSound = function() {
    var win = SceneManager._scene._commandWindow;
    if (win && win.currentSymbol() === 'customize' && !this.item()) return;
    Window_Selectable.prototype.playOkSound.call(this);
};

//=============================================================================
// Scene_Equip
//=============================================================================

Yanfly.ECC.Scene_Equip_createCommandWindow =
    Scene_Equip.prototype.createCommandWindow;
Scene_Equip.prototype.createCommandWindow = function() {
    Yanfly.ECC.Scene_Equip_createCommandWindow.call(this);
    this._commandWindow.setHandler('customize', this.commandEquip.bind(this));
};

Yanfly.ECC.Scene_Equip_refreshActor = Scene_Equip.prototype.refreshActor;
Scene_Equip.prototype.refreshActor = function() {
    Yanfly.ECC.Scene_Equip_refreshActor.call(this);
    if ($gameTemp._customizeReturning) {
      var index = this._commandWindow.findSymbol('customize');
      this._commandWindow.select(index);
      this._commandWindow.deactivate();
      this._commandWindow._scrollY = $gameTemp._commandScrollY;
      $gameTemp._commandScrollY = 0;
      this._slotWindow.activate();
      this._slotWindow.select($gameTemp._slotIndex);
      this._slotWindow._scrollY = $gameTemp._slotScrollY;
      $gameTemp._customizeReturning = false;
      $gameTemp._slotIndex = 0;
      $gameTemp._slotScrollY = 0;
      this._slotWindow.updateHelp();
    }
};

Yanfly.ECC.Scene_Equip_onSlotOk = Scene_Equip.prototype.onSlotOk;
Scene_Equip.prototype.onSlotOk = function() {
    if (this._commandWindow.currentSymbol() === 'customize') {
      return this.customizeSlot();
    }
    Yanfly.ECC.Scene_Equip_onSlotOk.call(this);
};

Scene_Equip.prototype.customizeSlot = function() {
    var item = this._slotWindow.item();
    if (item === null) {
      this._slotWindow.activate();
      return SoundManager.playBuzzer();
    }
    $gameTemp._equipCustomize = true;
    $gameTemp._slotIndex = this._slotWindow.index();
    $gameTemp._customizeItem = item;
    $gameTemp._commandScrollY = this._commandWindow._scrollY;
    $gameTemp._slotScrollY = this._slotWindow._scrollY;
    SceneManager.push(Scene_EquipCustomize);
};

//=============================================================================
// Scene_EquipCustomize
//=============================================================================

function Scene_EquipCustomize() {
    this.initialize.apply(this, arguments);
}

Scene_EquipCustomize.prototype = Object.create(Scene_Item.prototype);
Scene_EquipCustomize.prototype.constructor = Scene_Item;

Scene_EquipCustomize.prototype.initialize = function() {
    Scene_Item.prototype.initialize.call(this);
};

Scene_EquipCustomize.prototype.createCategoryWindow = function() {
    Scene_Item.prototype.createCategoryWindow.call(this);
    this._categoryWindow.deactivate();
    this._categoryWindow.hide();
    var wy = this._helpWindow.height;
    this._commandWindow = new Window_EquipCommand(0, wy, 240);
    this.addWindow(this._commandWindow);
    this._commandWindow.deactivate();
    var index = this._commandWindow.findSymbol('customize');
    this._commandWindow.select(index);
};

Scene_EquipCustomize.prototype.item = function() {
    return $gameTemp._customizeItem;
};

Scene_EquipCustomize.prototype.createItemWindow = function() {
    Scene_Item.prototype.createItemWindow.call(this);
    this._itemWindow._data = [$gameTemp._customizeItem];
    this._itemWindow.select(1);
    this._itemWindow.hide();
};

Scene_EquipCustomize.prototype.createActionWindow = function() {
    Scene_Item.prototype.createActionWindow.call(this);
    this.setCustomizedItem();
};

Scene_EquipCustomize.prototype.setCustomizedItem = function() {
    this._helpWindow.setItem(this.item());
    this._statusWindow.setItem(this.item());
    this._infoWindow.setItem(this.item());
    this._itemActionWindow.setItem(this.item());
};

Scene_EquipCustomize.prototype.onActionCancel = function() {
    $gameTemp._customizeItem = null;
    $gameTemp._customizeReturning = true;
    $gameTemp._equipCustomize = false;
    SceneManager.pop();
};

Scene_EquipCustomize.prototype.onUpgradeFullReset = function() {
    ItemManager._fullReset = false;
    this.onActionCancel();
};

//=============================================================================
// End of File
//=============================================================================
};


text:
<?php namespace Spec\Buffer;

use PhpSpec\ObjectBehavior;

class BufferSpec extends ObjectBehavior {

    function let()
    {
        $this->beConstructedWith('foo');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Buffer\Buffer');
    }

    function it_receives_a_string()
    {
        $this->setString('bar');

        $this->getString()->shouldReturn('bar');
    }

    function it_disallows_an_invalid_string()
    {
        $this->shouldThrow('InvalidArgumentException')->duringSetString(null);

        $this->shouldNotThrow('InvalidArgumentException')->duringSetString('bar');
    }

    function it_receives_a_selector()
    {
        $this->beAwareOf('<');

        $this->getSelectors()->shouldReturn(['<']);
    }

    function it_disallows_an_invalid_character()
    {
        $this->shouldThrow('InvalidArgumentException')->duringBeAwareOf(null);

        $this->shouldNotThrow('InvalidArgumentException')->duringBeAwareOf('<');
    }

    function it_splits_a_string_correctly()
    {
        $this->explode(':')->shouldReturn(['foo']);

        $this->setString('');
        $this->explode(':')->shouldReturn([]);

        $this->setString('foo:bar:baz');
        $this->explode(':')->shouldReturn(['foo', 'bar', 'baz']);

        $this->beAwareOf("\"");
        $this->setString('foo:"bar:baz"');
        $this->explode(':')->shouldReturn(['foo', 'bar:baz']);

        $this->setString('foo:"bar:baz":wow');
        $this->explode(':')->shouldReturn(['foo', 'bar:baz', 'wow']);
    }

    function it_disallows_an_invalid_separator()
    {
        $this->shouldThrow('InvalidArgumentException')->duringExplode(null);

        $this->shouldNotThrow('InvalidArgumentException')->duringExplode(':');
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2015 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
	<identity>
		<version number="$Revision: 11914 $"/>
		<language type="en"/>
		<territory type="VU"/>
	</identity>
	<numbers>
		<currencies>
			<currency type="VUV">
				<symbol>VT</symbol>
			</currency>
		</currencies>
	</numbers>
</ldml>


text:
class DataSet
{
public:
  typedef dax::internal::BaseArray Field;
  typedef dax::Coordinates Coordinates;

  DataSet( const std::size_t& numPoints, const std::size_t& numCells);
  DataSet();
  virtual ~DataSet(){}

  std::size_t numPoints() const { return NumPoints; }
  std::size_t numCells() const { return NumCells; }

  std::size_t numPointFields() const { return PointFields.size(); }
  std::size_t numCellFields() const { return CellFields.size(); }

  bool addPointField(Field* field);
  bool addCellField(Field* field);

  Field* pointField(const std::string& n);
  Field* cellField(const std::string& n);

  virtual const Coordinates* points() const=0;

  bool removePointField(const std::string& n);
  bool removeCellField(const std::string& n);

protected:
  std::vector<Field*> PointFields;
  std::vector<Field*> CellFields;

  std::size_t NumPoints;
  std::size_t NumCells;

private:
  bool addField(Field* f, std::vector<Field*>& fields);
  bool removeField(const std::string& n,std::vector<Field*>& fields);
  Field* getField(const std::string& n, std::vector<Field*>& fields);

  DataSet(const DataSet&);
  void operator=(const DataSet&);
};

//------------------------------------------------------------------------------
DataSet::DataSet( const std::size_t& numPoints, const std::size_t& numCells):
  NumPoints(numPoints), NumCells(numCells)
{
}

//------------------------------------------------------------------------------
DataSet::DataSet():
  NumPoints(0), NumCells(0)
{
}

//------------------------------------------------------------------------------
bool DataSet::addPointField(Field* field)
{
  return this->addField(field,this->PointFields);
}

//------------------------------------------------------------------------------
bool DataSet::addCellField(Field* field)
{
  return this->addField(field,this->CellFields);
}

//------------------------------------------------------------------------------
bool DataSet::addField(Field* field,std::vector<Field*>& fields)
{
  //need proper ownership of the array
  //currently we are copying it rather than properly using a smart pointer
  fields.push_back(field);
  return true;
}

//------------------------------------------------------------------------------
DataSet::Field* DataSet::pointField(const std::string& n)
{
  return this->getField(n,this->PointFields);
}

//------------------------------------------------------------------------------
DataSet::Field* DataSet::cellField(const std::string& n)
{
  return this->getField(n,this->CellFields);
}

//------------------------------------------------------------------------------
DataSet::Field* DataSet::getField(const std::string& n,
                                      std::vector<Field*>& fields)
{
  std::vector<Field*>::iterator i;
  for(i=fields.begin();i!=fields.end();++i)
    {
    if(n == (*i)->name())
      {
      return (*i);
      }
    }
  return NULL;
}

//------------------------------------------------------------------------------
bool DataSet::removePointField(const std::string& n)
{
  return this->removeField(n,this->PointFields);
}

//------------------------------------------------------------------------------
bool DataSet::removeCellField(const std::string& n)
{
  return this->removeField(n,this->CellFields);
}

//------------------------------------------------------------------------------
bool DataSet::removeField(const std::string& n, std::vector<Field*>& fields)
{
  std::vector<Field*>::iterator it;
  for(it=fields.begin();it!=fields.end();++it)
    {
    if ((*it)->name() == n)
      {
      fields.erase(it);
      return true;
      }
    }
  return false;
}

#endif // DATASET_H


text:
package com.intellij.refactoring.openapi.impl;

import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.refactoring.IntroduceParameterRefactoring;
import com.intellij.refactoring.RefactoringImpl;
import com.intellij.refactoring.introduceParameter.IntroduceParameterProcessor;

/**
 * @author dsl
 */
public class IntroduceParameterRefactoringImpl extends RefactoringImpl<IntroduceParameterProcessor>
  implements IntroduceParameterRefactoring {

  private IntroduceParameterRefactoringImpl(Project project,
                                            PsiMethod methodToReplaceIn,
                                            PsiMethod methodToSearchFor,
                                            String parameterName, PsiExpression parameterInitializer,
                                            PsiExpression expressionToSearch, PsiLocalVariable localVariable,
                                            boolean removeLocalVariable, boolean declareFinal, final boolean replaceAllOccurences) {
    super(
      new IntroduceParameterProcessor(project, methodToReplaceIn, methodToSearchFor,
                                      parameterInitializer, expressionToSearch, localVariable, removeLocalVariable, parameterName, replaceAllOccurences,
                                      REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE, declareFinal, false, null, null));
  }

  IntroduceParameterRefactoringImpl(Project project,
                                           PsiMethod methodToReplaceIn,
                                           PsiMethod methodToSearchFor,
                                           String parameterName, PsiExpression parameterInitializer,
                                           PsiLocalVariable localVariable,
                                           boolean removeLocalVariable, boolean declareFinal) {
    this(project, methodToReplaceIn, methodToSearchFor, parameterName, parameterInitializer, null, localVariable, removeLocalVariable, declareFinal, false);

  }

  IntroduceParameterRefactoringImpl(Project project,
                                    PsiMethod methodToReplaceIn,
                                    PsiMethod methodToSearchFor,
                                    String parameterName, PsiExpression parameterInitializer,
                                    PsiExpression expressionToSearchFor,
                                    boolean declareFinal, final boolean replaceAllOccurences) {
    this(project, methodToReplaceIn, methodToSearchFor, parameterName, parameterInitializer, expressionToSearchFor, null, false, declareFinal, replaceAllOccurences);

  }

  public void enforceParameterType(PsiType forcedType) {
    myProcessor.setForcedType(forcedType);
  }

  public void setFieldReplacementPolicy(int policy) {
    myProcessor.setReplaceFieldsWithGetters(policy);
  }

  public PsiType getForcedType() {
    return myProcessor.getForcedType();
  }

  public int getFieldReplacementPolicy() {
    return myProcessor.getReplaceFieldsWithGetters();
  }
}


text:
<?php

namespace Fabr\CoreBundle\DataFixtures\ORM;

use DateTime;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Fabr\CoreBundle\Entity\User;

class UserFixture extends AbstractFixture implements OrderedFixtureInterface
{
    public function load($manager)
    {
        $user = new User();
        $user->setCreatedAt(new DateTime());
        $user->setDepartment($this->getReference('department:rnd'));
        $user->setFirstname('Максим');
        $user->setMidname('Сергеевич');
        $user->setLastname('Пряхин');
        $user->setEmail('m.pryakhin@gmail.com');
        $user->setPassword('123');

        $manager->persist($user);
        $this->addReference('user:' . $user->getUsername(), $user);

        $user = new User();
        $user->setCreatedAt(new DateTime());
        $user->setDepartment($this->getReference('department:it'));
        $user->setFirstname('Алексей');
        $user->setMidname('Викторович');
        $user->setLastname('Александров');
        $user->setEmail('cherep86@gmail.com');
        $user->setPassword('123');

        $manager->persist($user);
        $this->addReference('user:' . $user->getUsername(), $user);

        $manager->flush();
    }

    public function getOrder()
    {
        return 2;
    }
}


text:
<!DOCTYPE html>

<meta name="robots" content="noindex">
  <meta name="project_path" value="/web/tools/workbox/_project.yaml" />
  <meta name="book_path" value="/web/tools/workbox/_book.yaml" />
  <meta name="gtm_var" data-key="docType" data-value="reference">
  <title>Source: workbox-routing/setDefaultHandler.mjs</title>
  <link href="jsdoc.css" rel="stylesheet">

Source: workbox-routing/setDefaultHandler.mjs

import {getOrCreateDefaultRouter} from './utils/getOrCreateDefaultRouter.mjs';

import './_version.mjs';

/**
 * Define a default `handler` that's called when no routes explicitly
 * match the incoming request.
 *
 * Without a default handler, unmatched requests will go against the
 * network as if there were no service worker present.
 *
 * @param {workbox.routing.Route~handlerCallback} handler A callback
 * function that returns a Promise resulting in a Response.
 *
 * @alias workbox.routing.setDefaultHandler
 */
export const setDefaultHandler = (handler) => {
  const defaultRouter = getOrCreateDefaultRouter();
  defaultRouter.setDefaultHandler(handler);
};


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('sectioned', function() {
  'use strict';

  function computeClasses(isCombined) {
    if (isCombined)
      return 'section expandable expanded';
    return 'section';
  }

  function onContinue() {
    chrome.send('handleContinue');
  }

  function onOpenSettings() {
    chrome.send('handleSetDefaultBrowser');
  }

  function onToggle(app) {
    if (app.isCombined) {
      // Toggle sections.
      var sections = document.querySelectorAll('.section.expandable');
      sections.forEach(function(section) {
        section.classList.toggle('expanded');
      });
      // Toggle screenshots.
      var screenshots = document.querySelectorAll('.screenshot-image');
      screenshots.forEach(function(screenshot) {
        screenshot.classList.toggle('hidden');
      });
    }
  }

  function initialize() {
    var app = $('sectioned-app');

    // Set variables.
    // Determines if the combined variant should be displayed. The combined
    // variant includes instructions on how to pin Chrome to the taskbar.
    app.isCombined = false;

    // Set handlers.
    app.computeClasses = computeClasses;
    app.onContinue = onContinue;
    app.onOpenSettings = onOpenSettings;
    app.onToggle = onToggle.bind(this, app);

    // Asynchronously check if Chrome is pinned to the taskbar.
    cr.sendWithPromise('getPinnedToTaskbarState').then(
      function(isPinnedToTaskbar) {
        // Allow overriding of the result via a query parameter.
        // TODO(pmonette): Remove these checks when they are no longer needed.
        /** @const */ var VARIANT_KEY = 'variant';
        var VariantType = {
          DEFAULT_ONLY: 'defaultonly',
          COMBINED: 'combined'
        };
        var params = new URLSearchParams(location.search.slice(1));
        if (params.has(VARIANT_KEY)) {
          if (params.get(VARIANT_KEY) === VariantType.DEFAULT_ONLY)
            app.isCombined = false;
          else if (params.get(VARIANT_KEY) === VariantType.COMBINED)
            app.isCombined = true;
        } else {
          app.isCombined = !isPinnedToTaskbar;
        }
      });
  }

  return {
    initialize: initialize
  };
});

document.addEventListener('DOMContentLoaded', sectioned.initialize);


text:
layout: post
title: Fast Gallery - Introduction for developers
tags:
- api
- Drupal
- drupal
- entwicklung
- fast gallery
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  _wp_old_slug: fast-gallery---introduction-for-developers
  dsq_thread_id: '782485114'
  better-related-: ''
---
This blogpost should give a quick kickstart to every developer who is interested in helping to advance Fast Gallery. The architecture is intended to have a swapable storage engine. So far I've only written one storage engine, which means that interfaces are not 100% clearly defined, but would instead need some work when actually going to be used in practice.  First a quick overview over the files and what their responsibilities are.

fast_gallery-image-wrapper.tpl.php: template file to display the image

fast_gallery.admin.inc: the general admin stuff (UI), that would be used by any storage engine (setting up galleries, scanning galleries...)

fast_gallery.cache.class.php: incase Imagecache is not available there's a simple caching class, that creates thumbnails and caches them.

fast_gallery.class.php: this is the heart of the module. Here we recursively explore directories for images and send them to the storage engine or get images from the storage engine and return them to the frontend

fast_gallery.css: if you are developing, you should know what this is for ;)

fast_gallery.info: same here

fast_gallery.install: and same here

fast_gallery.module: Mostly it's just implementations of hooks and actually displaying the gallery in fast_gallery_alias()

fast_gallery.test: I started once writing some tests.... this really needs some work!

FGImage.class.php: Internally Fast Gallery treats images as objects of this class.

Ok, then we have a couple folders:

images: just some images

integrations: possible integrations into other modules. So far: features integration

modules: Other modules for fast gallery. I started once the Fast Gallery API module, which should provide some kind of REST API... but it's not there yet

storageengine: well this contains some classes and interfaces that are responsible for actually storing and retrieving images and hierarchy retrieved from directories

tests: just some folders that are used when doing the simpletests

Just some more info on the storageengine folder:

Istorage.php: contains and interface that all possible storageengines must implement.

default.config.inc: Well, just some UI stuff for storageeninge specific configuration

default.storage.inc: the actual storage engine, that stores data into the db, makes sure hierarchy is correct and returns the right images depening on the path.

node.config.inc, node.storage.inc: sample data to build a nodestorage, which was actually my goal at a given point.... but unfortunately not there yet :(

Oky, this is the first attempt. I'll write another blogpost and describe some of the important concepts in detail.


text:
require 'ffi'

require 'harfbuzz/ffi_additions'

module Harfbuzz

  extend FFI::Library

  ffi_lib 'harfbuzz'

  typedef :pointer, :hb_destroy_func_t
  typedef :uint32,  :hb_codepoint_t
  typedef :bool,    :hb_bool_t
  typedef :int32,   :hb_position_t

  # hb_direction_t enum
  HB_DIRECTION_INVALID = 0
  HB_DIRECTION_LTR = 4
  HB_DIRECTION_RTL = 5
  HB_DIRECTION_TTB = 6
  HB_DIRECTION_BTT = 7

  def self.hb_direction_is_valid(dir)
    dir & ~3 == 4
  end

  def self.hb_direction_is_horizontal(dir)
    dir & ~1 == 4
  end

  def self.hb_direction_is_vertical(dir)
    dir & ~1 == 6
  end

  def self.hb_direction_is_forward(dir)
    dir & ~2 == 4
  end

  def self.hb_direction_is_backward(dir)
    dir & ~2 == 5
  end

  def self.hb_direction_reverse(dir)
    dir ^ 1
  end

end

require 'harfbuzz/version'
require 'harfbuzz/base'
require 'harfbuzz/blob'
require 'harfbuzz/face'
require 'harfbuzz/font'
require 'harfbuzz/buffer'
require 'harfbuzz/shaping'


text:
using UnityEngine;

namespace RoomAliveToolkit
{
    public enum ViewDebugMode
    {
        None, RGB//, Depth
    }
    [AddComponentMenu("RoomAliveToolkit/RATUserViewCamera")]
    /// <summary>
    /// Unity Camera for rendering the user's view in view-dependent projection mapping scenarios.
    ///
    /// The logic behind the RoomAlive User Views explained:
    ///
    /// Let's assume that there are at least 4 different layers in the scene that will control what objects are
    /// visible from which camera (user or projector)
    ///
    /// Create 4 layers in your scene:
    /// - VirtualTextures - for virtual objects that should be texture mapped onto existing surfaces
    /// - Virtual3DObjects - for virtual 3D objects that could be perspective mapped
    /// - StaticSurfaces - for existing static room geometry that is loaded from a file(obj mesh for example)
    /// - DynamicSurfaces- for dynamic depth meshes that represent the physical space
    ///
    /// In RATProjectionManager set Texture Layers to be "VirtualTextures". These are view independent and therefore do not need to be rendered in user's views.
    ///
    /// In this component, select Virtual3DObjects as VirtualObjectMask (layer mask). This will render only the virtual (view-dependent) 3D objects for each user.
    ///
    /// However, it is also important to account for real world geometry to correctly occlude the virtual objects. To accomplish that, use RATProjectionPass components and set them up for each
    /// type of real world objects in the scene. The most common situations are for static (OBJ meshes captured during scene calibration) and dynamic objects (Kinect depth meshes)
    ///
    /// To each RATUserViewCamera add a component RATProjectionPass for each physical layer that you want to projecto on:
    /// select: StaticSurfaces For TargetSurfaceLayer
    /// Press on "Set Static Defaults" button
    ///
    /// select: DynamicSurfaces For TargetSurfaceLayer
    /// Press on "Set Dynamic Defaults" button
    ///
    /// </summary>
    public class RATUserViewCamera : MonoBehaviour
    {
        public RATProjectionManager projectionManager;

        [ReadOnly]
        public RenderTexture targetRGBTexture;

        [Space(10)]

        [Space(10)]
        public float fieldOfView = 90;
        public float nearClippingPlane = 0.1f;
        public float farClippingPlane = 8f;
        public LayerMask virtualObjectsMask; //select only the layers you want to see in the user's view

        [Space(10)]
        public ViewDebugMode debugPlane = ViewDebugMode.RGB;
        /// <summary>
        /// the size of the debug view plane visible in the scene view
        /// </summary>
        [Range(0.1f,3)]
        public float debugPlaneSize = 0.1f;

        [Space(10)]
        public Color backgroundColor = new Color(0, 0, 0, 0);
        public Color realSurfaceColor = new Color(0, 0, 0, 0);

        public RATProjectionPass[] projectionLayers;

        public Camera viewCamera
        {
            get { return cam; }
        }

        protected int texWidth = 2048; //width of the off-screen render texture for this user view (needs to be power of 2)
        protected int texHeight = 2048;//height of the off-screen render texture for this user view (needs to be power of 2)

        protected Mesh debugPlaneM;
        protected MeshFilter meshFilter;
        protected MeshRenderer meshRenderer;
        protected Material meshMat;

        protected int[] indices = new int[] { 0,1,2, 3,2,1};
        protected Vector2[] uv = new Vector2[] { new Vector2(0,1),new Vector2(1,1),new Vector2(0,0),new Vector2(1,0) };
        protected Vector3[] pos = new Vector3[4];

        protected bool initialized = false;
        protected GameObject cameraGO;
        protected Camera cam;
        protected Rect rectReadRT;
        protected RATDepthMesh[] depthMeshes;

        public bool hasManager
        {
            get
            {
                return projectionManager != null && projectionManager.isActiveAndEnabled;
            }
        }

        void Awake()
        {
            projectionLayers = gameObject.GetComponents<RATProjectionPass>();

            foreach (RATProjectionPass layer in projectionLayers)
                layer.Init();
        }

        void Start()
        {
            meshFilter = gameObject.AddComponent<MeshFilter>();
            meshRenderer = gameObject.AddComponent<MeshRenderer>();
            Shader unlitShader = Shader.Find("Unlit/Texture");
            meshMat = new Material(unlitShader);
            debugPlaneM = new Mesh();
            meshFilter.hideFlags = HideFlags.HideInInspector;
            meshRenderer.hideFlags = HideFlags.HideInInspector;
            meshMat.hideFlags = HideFlags.HideInInspector;

            if (projectionManager==null)
                projectionManager = GameObject.FindObjectOfType<RATProjectionManager>();
            if(projectionManager!=null)
                projectionManager.RegisterUser(this);

            //Code assumes that this script is added to the camera GO
            cameraGO = this.gameObject;

            cam = this.GetComponent<Camera>();
            if (cam == null)
                cam = gameObject.AddComponent<Camera>();
            cam.hideFlags = HideFlags.HideInInspector;  // | HideFlags.HideInHierarchy

            cam.rect = new Rect(0, 0, 1, 1);
            cam.enabled = false; //important to disable this camera as we will be calling Render() directly.
            cam.aspect = texWidth / texHeight;

            cameraGO.transform.localPosition = new Vector3();

            targetRGBTexture = new RenderTexture(texWidth, texHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default);
            targetRGBTexture.filterMode = FilterMode.Trilinear;
            targetRGBTexture.autoGenerateMips = true;
            targetRGBTexture.depth = 24;
            targetRGBTexture.Create();

            rectReadRT = new Rect(0, 0, texWidth, texHeight);

            depthMeshes = GameObject.FindObjectsOfType<RATDepthMesh>();

            initialized = true;
        }

        public void Update()
        {
            // this mostly updates the little debug view in the scene editor view
            if (debugPlaneSize < 0)
                debugPlaneSize = 0;

            cam.nearClipPlane = nearClippingPlane;
            cam.farClipPlane = farClippingPlane;
            cam.fieldOfView = fieldOfView;

            meshRenderer.enabled = debugPlane != ViewDebugMode.None;
            if (meshRenderer.enabled)
            {
                //meshMat.mainTexture = debugPlane == ViewDebugMode.RGB?targetRGBTexture:targetDepthTexture;
                meshMat.mainTexture = targetRGBTexture;
                meshRenderer.sharedMaterial = meshMat;

                float z = debugPlaneSize<= nearClippingPlane ? nearClippingPlane:debugPlaneSize;
                float fac = Mathf.Tan(cam.fieldOfView / 2 / 180f * Mathf.PI);
                float w = z * fac;
                float h = z * fac;
                pos[0] = new Vector3(-w, h, nearClippingPlane);
                pos[1] = new Vector3(w, h, nearClippingPlane);
                pos[2] = new Vector3(-w, -h, nearClippingPlane);
                pos[3] = new Vector3(w, -h, nearClippingPlane);
                debugPlaneM.vertices = pos;
                debugPlaneM.uv = uv;
                debugPlaneM.triangles = indices;
                meshFilter.mesh = debugPlaneM;
            }
        }

        public void LateUpdate()
        {
            if (!initialized)
                return;

            RenderUserView();

            // Projection mapping rendering is actually done by each of the projector cameras
            // Setup things for the last pass which will be rendered from the perspective of the projectors (i.e., Render Pass 3)
            // this "pass" doesn't  do any rendering at this point, but merely sets the correct shaders/materials on all
            // physical objects in the scene.
        }

        /// <summary>
        /// Render both virtual and physical objects together from the perspective of the user
        /// </summary>
        public void RenderUserView()
        {
            cam.cullingMask = virtualObjectsMask;
            cam.backgroundColor = backgroundColor;
            cam.targetTexture = targetRGBTexture;
            cam.clearFlags = CameraClearFlags.SolidColor;
            cam.Render();

            cam.clearFlags = CameraClearFlags.Nothing;

            foreach (RATProjectionPass layer in projectionLayers)
            {
                if (layer.renderUserView && layer.userViewShader != null && layer.enabled)
                {
                    cam.cullingMask = layer.targetSurfaceLayers;
                    Shader.SetGlobalColor("_ReplacementColor", realSurfaceColor);

                    cam.RenderWithShader(layer.userViewShader, null);

                }
            }
            cam.clearFlags = CameraClearFlags.SolidColor;
        }

        public virtual void RenderProjection(Camera camera)
        {
            RATProjectionPass[] layers = projectionLayers;
            for (int layerId=0; layerId < layers.Length; layerId++) {
                RATProjectionPass layer = layers[layerId];
                if (layer == null || !layer.enabled || layer.projectionShader==null || !layer.renderProjectionPass)
                    continue;
                camera.cullingMask = layer.targetSurfaceLayers;

                //todo preload IDs
                Shader.SetGlobalVector("_UserViewPos", this.cam.transform.position);
                Shader.SetGlobalTexture("_UserViewPointRGB", targetRGBTexture);
                //Shader.SetGlobalTexture("_UserViewPointDepth", targetDepthTexture);
                Shader.SetGlobalMatrix("_UserVP", this.cam.projectionMatrix * this.cam.worldToCameraMatrix);
                camera.RenderWithShader(layer.projectionShader, null);
            }
        }
    }
}