text:
package org.elasticsearch.search.functionscore;

import org.elasticsearch.Version;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.lucene.search.function.FiltersFunctionScoreQuery;
import org.elasticsearch.common.lucene.search.function.FiltersFunctionScoreQuery.ScoreMode;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.MultiValueMode;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalSettingsPlugin;
import org.elasticsearch.test.VersionUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.client.Requests.indexRequest;
import static org.elasticsearch.client.Requests.searchRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.exponentialDecayFunction;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.gaussDecayFunction;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.linearDecayFunction;
import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isOneOf;
import static org.hamcrest.Matchers.lessThan;

public class DecayFunctionScoreIT extends ESIntegTestCase {
    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Arrays.asList(InternalSettingsPlugin.class); // uses index.version.created
    }

    private final QueryBuilder baseQuery = constantScoreQuery(termQuery("test", "value"));

    public void testDistanceScoreGeoLinGaussExp() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("loc").field("type", "geo_point").endObject().endObject().endObject().endObject()));

        List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
        indexBuilders.add(client().prepareIndex()
                .setType("type1")
                .setId("1")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").startObject("loc").field("lat", 10).field("lon", 20).endObject()
                                .endObject()));
        indexBuilders.add(client().prepareIndex()
                .setType("type1")
                .setId("2")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").startObject("loc").field("lat", 11).field("lon", 22).endObject()
                                .endObject()));

        int numDummyDocs = 20;
        for (int i = 1; i <= numDummyDocs; i++) {
            indexBuilders.add(client().prepareIndex()
                    .setType("type1")
                    .setId(Integer.toString(i + 3))
                    .setIndex("test")
                    .setSource(
                            jsonBuilder().startObject().field("test", "value").startObject("loc").field("lat", 11 + i).field("lon", 22 + i)
                                    .endObject().endObject()));
        }

        indexRandom(true, indexBuilders);

        // Test Gauss
        List<Float> lonlat = new ArrayList<>();
        lonlat.add(20f);
        lonlat.add(11f);

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(baseQuery)));
        SearchResponse sr = response.actionGet();
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("loc", lonlat, "1000km")))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat(sh.getAt(1).getId(), equalTo("2"));
        // Test Exp

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(baseQuery)));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, linearDecayFunction("loc", lonlat, "1000km")))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat(sh.getAt(1).getId(), equalTo("2"));
        // Test Lin

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(baseQuery)));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, exponentialDecayFunction("loc", lonlat, "1000km")))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));

        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat(sh.getAt(1).getId(), equalTo("2"));
    }

    public void testDistanceScoreGeoLinGaussExpWithOffset() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num").field("type", "double").endObject().endObject().endObject().endObject()));

        // add tw docs within offset
        List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
        indexBuilders.add(client().prepareIndex().setType("type1").setId("1").setIndex("test")
                .setSource(jsonBuilder().startObject().field("test", "value").field("num", 0.5).endObject()));
        indexBuilders.add(client().prepareIndex().setType("type1").setId("2").setIndex("test")
                .setSource(jsonBuilder().startObject().field("test", "value").field("num", 1.7).endObject()));

        // add docs outside offset
        int numDummyDocs = 20;
        for (int i = 0; i < numDummyDocs; i++) {
            indexBuilders.add(client().prepareIndex().setType("type1").setId(Integer.toString(i + 3)).setIndex("test")
                    .setSource(jsonBuilder().startObject().field("test", "value").field("num", 3.0 + i).endObject()));
        }

        indexRandom(true, indexBuilders);

        // Test Gauss

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource()
                                .size(numDummyDocs + 2)
                                .query(functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("num", 1.0, 5.0, 1.0))
                                        .boostMode(CombineFunction.REPLACE))));
        SearchResponse sr = response.actionGet();
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));
        assertThat(sh.getAt(0).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getScore(), equalTo(sh.getAt(0).getScore()));
        for (int i = 0; i < numDummyDocs; i++) {
            assertThat(sh.getAt(i + 2).getId(), equalTo(Integer.toString(i + 3)));
        }

        // Test Exp

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource()
                                .size(numDummyDocs + 2)
                                .query(functionScoreQuery(termQuery("test", "value"),
                                        exponentialDecayFunction("num", 1.0, 5.0, 1.0)).boostMode(
                                        CombineFunction.REPLACE))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));
        assertThat(sh.getAt(0).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getScore(), equalTo(sh.getAt(0).getScore()));
        for (int i = 0; i < numDummyDocs; i++) {
            assertThat(sh.getAt(i + 2).getId(), equalTo(Integer.toString(i + 3)));
        }
        // Test Lin
        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource()
                                .size(numDummyDocs + 2)
                                .query(functionScoreQuery(termQuery("test", "value"), linearDecayFunction("num", 1.0, 20.0, 1.0))
                                        .boostMode(CombineFunction.REPLACE))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (numDummyDocs + 2)));
        assertThat(sh.getAt(0).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getId(), anyOf(equalTo("1"), equalTo("2")));
        assertThat(sh.getAt(1).getScore(), equalTo(sh.getAt(0).getScore()));
    }

    public void testBoostModeSettingWorks() throws Exception {
        Settings settings = Settings.builder().put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1).build();
        assertAcked(prepareCreate("test").setSettings(settings)
            .addMapping(
                "type1",
                jsonBuilder()
                    .startObject()
                        .startObject("type1")
                            .startObject("properties")
                                .startObject("test").field("type", "text").endObject()
                                .startObject("loc").field("type", "geo_point").endObject()
                            .endObject()
                        .endObject()
                    .endObject()));

        List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
        indexBuilders.add(client().prepareIndex()
                .setType("type1")
                .setId("1")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").startObject("loc").field("lat", 11).field("lon", 21).endObject()
                                .endObject()));
        indexBuilders.add(client().prepareIndex()
                .setType("type1")
                .setId("2")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value value").startObject("loc").field("lat", 11).field("lon", 20)
                                .endObject().endObject()));
        indexRandom(true, false, indexBuilders); // force no dummy docs

        // Test Gauss
        List<Float> lonlat = new ArrayList<>();
        lonlat.add(20f);
        lonlat.add(11f);

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("loc", lonlat, "1000km")).boostMode(
                                        CombineFunction.MULTIPLY))));
        SearchResponse sr = response.actionGet();
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (2)));
        assertThat(sh.getAt(0).getId(), isOneOf("1"));
        assertThat(sh.getAt(1).getId(), equalTo("2"));

        // Test Exp
        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("loc", lonlat, "1000km")).boostMode(
                                        CombineFunction.REPLACE))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (2)));
        assertThat(sh.getAt(0).getId(), equalTo("2"));
        assertThat(sh.getAt(1).getId(), equalTo("1"));

    }

    public void testParseGeoPoint() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("loc").field("type", "geo_point").endObject().endObject().endObject().endObject()));

        client().prepareIndex()
                .setType("type1")
                .setId("1")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject()
                            .field("test", "value")
                            .startObject("loc")
                                .field("lat", 20)
                                .field("lon", 11)
                            .endObject()
                        .endObject()).setRefreshPolicy(IMMEDIATE).get();
        FunctionScoreQueryBuilder baseQuery = functionScoreQuery(constantScoreQuery(termQuery("test", "value")),
                ScoreFunctionBuilders.weightFactorFunction(randomIntBetween(1, 10)));
        GeoPoint point = new GeoPoint(20, 11);
        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("loc", point, "1000km")).boostMode(
                                        CombineFunction.REPLACE))));
        SearchResponse sr = response.actionGet();
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(1.0, 1.e-5));
        // this is equivalent to new GeoPoint(20, 11); just flipped so scores must be same
        float[] coords = { 11, 20 };
        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("loc", coords, "1000km")).boostMode(
                                        CombineFunction.REPLACE))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(1.0f, 1.e-5));
    }

    public void testCombineModes() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num").field("type", "double").endObject().endObject().endObject().endObject()));

        client().prepareIndex().setType("type1").setId("1").setIndex("test").setRefreshPolicy(IMMEDIATE)
                .setSource(jsonBuilder().startObject().field("test", "value value").field("num", 1.0).endObject()).get();
        FunctionScoreQueryBuilder baseQuery = functionScoreQuery(constantScoreQuery(termQuery("test", "value")),
                ScoreFunctionBuilders.weightFactorFunction(2));
        // decay score should return 0.5 for this function and baseQuery should return 2.0f as it's score
        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.MULTIPLY))));
        SearchResponse sr = response.actionGet();
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(1.0, 1.e-5));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.REPLACE))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(0.5, 1.e-5));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.SUM))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(2.0 + 0.5, 1.e-5));
        logger.info("--> Hit[0] {} Explanation:\n {}", sr.getHits().getAt(0).getId(), sr.getHits().getAt(0).getExplanation());

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.AVG))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo((2.0 + 0.5) / 2, 1.e-5));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.MIN))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(0.5, 1.e-5));

        response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5))
                                    .boostMode(CombineFunction.MAX))));
        sr = response.actionGet();
        sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (1)));
        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat((double) sh.getAt(0).getScore(), closeTo(2.0, 1.e-5));

    }

    public void testExceptionThrownIfScaleLE0() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num1").field("type", "date").endObject().endObject().endObject().endObject()));
        client().index(
                indexRequest("test").type("type1").id("1")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-27").endObject())).actionGet();
        client().index(
                indexRequest("test").type("type1").id("2")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-28").endObject())).actionGet();
        refresh();

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("num1", "2013-05-28", "-1d")))));
        try {
            response.actionGet();
            fail("Expected SearchPhaseExecutionException");
        } catch (SearchPhaseExecutionException e) {
            assertThat(e.getMessage(), is("all shards failed"));
        }
    }

    public void testParseDateMath() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject()
                    .startObject("type1")
                        .startObject("properties")
                            .startObject("test")
                                .field("type", "text")
                            .endObject()
                            .startObject("num1")
                                .field("type", "date")
                                .field("format", "epoch_millis")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject()));
        client().index(indexRequest("test").type("type1").id("1")
                .source(jsonBuilder().startObject().field("test", "value").field("num1", System.currentTimeMillis()).endObject()))
                .actionGet();
        client().index(indexRequest("test").type("type1").id("2").source(jsonBuilder().startObject().field("test", "value")
                .field("num1", System.currentTimeMillis() - (1000 * 60 * 60 * 24)).endObject())).actionGet();
        refresh();

        SearchResponse sr = client().search(
                searchRequest().source(
                        searchSource().query(
                                functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("num1", "now", "2d"))))).get();

        assertNoFailures(sr);
        assertOrderedSearchHits(sr, "1", "2");

        sr = client().search(
                searchRequest().source(
                        searchSource().query(
                                functionScoreQuery(termQuery("test", "value"), gaussDecayFunction("num1", "now-1d", "2d"))))).get();

        assertNoFailures(sr);
        assertOrderedSearchHits(sr, "2", "1");

    }

    public void testValueMissingLin() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num1").field("type", "date").endObject().startObject("num2").field("type", "double")
                        .endObject().endObject().endObject().endObject())
        );

        client().index(
                indexRequest("test").type("type1").id("1")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-27").field("num2", "1.0")
                                .endObject())).actionGet();
        client().index(
                indexRequest("test").type("type1").id("2")
                        .source(jsonBuilder().startObject().field("test", "value").field("num2", "1.0").endObject())).actionGet();
        client().index(
                indexRequest("test").type("type1").id("3")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-30").field("num2", "1.0")
                                .endObject())).actionGet();
        client().index(
                indexRequest("test").type("type1").id("4")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-30").endObject())).actionGet();

        refresh();

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(baseQuery, new FilterFunctionBuilder[]{
                                        new FilterFunctionBuilder(linearDecayFunction("num1", "2013-05-28", "+3d")),
                                        new FilterFunctionBuilder(linearDecayFunction("num2", "0.0", "1"))
                                }).scoreMode(FiltersFunctionScoreQuery.ScoreMode.MULTIPLY))));

        SearchResponse sr = response.actionGet();

        assertNoFailures(sr);
        SearchHits sh = sr.getHits();
        assertThat(sh.getHits().length, equalTo(4));
        double[] scores = new double[4];
        for (int i = 0; i < sh.getHits().length; i++) {
            scores[Integer.parseInt(sh.getAt(i).getId()) - 1] = sh.getAt(i).getScore();
        }
        assertThat(scores[0], lessThan(scores[1]));
        assertThat(scores[2], lessThan(scores[3]));

    }

    public void testDateWithoutOrigin() throws Exception {
        DateTime dt = new DateTime(DateTimeZone.UTC);

        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num1").field("type", "date").endObject().endObject().endObject().endObject()));

        DateTime docDate = dt.minusDays(1);
        String docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-"
                + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth());
        client().index(
                indexRequest("test").type("type1").id("1")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", docDateString).endObject())).actionGet();
        docDate = dt.minusDays(2);
        docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-"
                + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth());
        client().index(
                indexRequest("test").type("type1").id("2")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", docDateString).endObject())).actionGet();
        docDate = dt.minusDays(3);
        docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-"
                + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth());
        client().index(
                indexRequest("test").type("type1").id("3")
                        .source(jsonBuilder().startObject().field("test", "value").field("num1", docDateString).endObject())).actionGet();

        refresh();

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(QueryBuilders.matchAllQuery(), new FilterFunctionBuilder[]{
                                        new FilterFunctionBuilder(linearDecayFunction("num1", null, "7000d")),
                                        new FilterFunctionBuilder(gaussDecayFunction("num1", null, "1d")),
                                        new FilterFunctionBuilder(exponentialDecayFunction("num1", null, "7000d"))
                                }).scoreMode(FiltersFunctionScoreQuery.ScoreMode.MULTIPLY))));

        SearchResponse sr = response.actionGet();
        assertNoFailures(sr);
        SearchHits sh = sr.getHits();
        assertThat(sh.getHits().length, equalTo(3));
        double[] scores = new double[4];
        for (int i = 0; i < sh.getHits().length; i++) {
            scores[Integer.parseInt(sh.getAt(i).getId()) - 1] = sh.getAt(i).getScore();
        }
        assertThat(scores[1], lessThan(scores[0]));
        assertThat(scores[2], lessThan(scores[1]));

    }

    public void testManyDocsLin() throws Exception {
        Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0, Version.CURRENT);
        Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
        XContentBuilder xContentBuilder = jsonBuilder().startObject().startObject("type").startObject("properties")
                .startObject("test").field("type", "text").endObject().startObject("date").field("type", "date")
                .field("doc_values", true).endObject().startObject("num").field("type", "double")
                .field("doc_values", true).endObject().startObject("geo").field("type", "geo_point")
                .field("ignore_malformed", true);
        xContentBuilder.endObject().endObject().endObject().endObject();
        assertAcked(prepareCreate("test").setSettings(settings).addMapping("type", xContentBuilder));
        int numDocs = 200;
        List<IndexRequestBuilder> indexBuilders = new ArrayList<>();

        for (int i = 0; i < numDocs; i++) {
            double lat = 100 + (int) (10.0 * (i) / (numDocs));
            double lon = 100;
            int day = (int) (29.0 * (i) / (numDocs)) + 1;
            String dayString = day < 10 ? "0" + Integer.toString(day) : Integer.toString(day);
            String date = "2013-05-" + dayString;

            indexBuilders.add(client().prepareIndex()
                    .setType("type")
                    .setId(Integer.toString(i))
                    .setIndex("test")
                    .setSource(
                            jsonBuilder().startObject().field("test", "value").field("date", date).field("num", i).startObject("geo")
                                    .field("lat", lat).field("lon", lon).endObject().endObject()));
        }
        indexRandom(true, indexBuilders);
        List<Float> lonlat = new ArrayList<>();
        lonlat.add(100f);
        lonlat.add(110f);
        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().size(numDocs).query(
                                functionScoreQuery(termQuery("test", "value"), new FilterFunctionBuilder[]{
                                        new FilterFunctionBuilder(linearDecayFunction("date", "2013-05-30", "+15d")),
                                        new FilterFunctionBuilder(linearDecayFunction("geo", lonlat, "1000km")),
                                        new FilterFunctionBuilder(linearDecayFunction("num", numDocs, numDocs / 2.0))
                                }).scoreMode(ScoreMode.MULTIPLY).boostMode(CombineFunction.REPLACE))));

        SearchResponse sr = response.actionGet();
        assertNoFailures(sr);
        SearchHits sh = sr.getHits();
        assertThat(sh.getHits().length, equalTo(numDocs));
        double[] scores = new double[numDocs];
        for (int i = 0; i < numDocs; i++) {
            scores[Integer.parseInt(sh.getAt(i).getId())] = sh.getAt(i).getScore();
        }
        for (int i = 0; i < numDocs - 1; i++) {
            assertThat(scores[i], lessThan(scores[i + 1]));
        }
    }

    public void testParsingExceptionIfFieldDoesNotExist() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type",
                jsonBuilder().startObject().startObject("type").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("geo").field("type", "geo_point").endObject().endObject().endObject().endObject()));
        int numDocs = 2;
        client().index(
                indexRequest("test").type("type").source(
                        jsonBuilder().startObject().field("test", "value").startObject("geo").field("lat", 1).field("lon", 2).endObject()
                                .endObject())).actionGet();
        refresh();
        List<Float> lonlat = new ArrayList<>();
        lonlat.add(100f);
        lonlat.add(110f);
        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource()
                                .size(numDocs)
                                .query(functionScoreQuery(termQuery("test", "value"), linearDecayFunction("type.geo", lonlat, "1000km"))
                                        .scoreMode(FiltersFunctionScoreQuery.ScoreMode.MULTIPLY))));
        try {
            response.actionGet();
            fail("Expected SearchPhaseExecutionException");
        } catch (SearchPhaseExecutionException e) {
            assertThat(e.getMessage(), is("all shards failed"));
        }
    }

    public void testParsingExceptionIfFieldTypeDoesNotMatch() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type",
                jsonBuilder().startObject().startObject("type").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num").field("type", "text").endObject().endObject().endObject().endObject()));
        client().index(
                indexRequest("test").type("type").source(
                        jsonBuilder().startObject().field("test", "value").field("num", Integer.toString(1)).endObject())).actionGet();
        refresh();
        // so, we indexed a string field, but now we try to score a num field
        ActionFuture<SearchResponse> response = client().search(searchRequest().searchType(SearchType.QUERY_THEN_FETCH)
                .source(searchSource().query(functionScoreQuery(termQuery("test", "value"), linearDecayFunction("num", 1.0, 0.5))
                        .scoreMode(ScoreMode.MULTIPLY))));
        try {
            response.actionGet();
            fail("Expected SearchPhaseExecutionException");
        } catch (SearchPhaseExecutionException e) {
            assertThat(e.getMessage(), is("all shards failed"));
        }
    }

    public void testNoQueryGiven() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type",
                jsonBuilder().startObject().startObject("type").startObject("properties").startObject("test").field("type", "text")
                        .endObject().startObject("num").field("type", "double").endObject().endObject().endObject().endObject()));
        client().index(
                indexRequest("test").type("type").source(jsonBuilder().startObject().field("test", "value").field("num", 1.0).endObject()))
                .actionGet();
        refresh();
        // so, we indexed a string field, but now we try to score a num field
        ActionFuture<SearchResponse> response = client().search(
                searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
                        searchSource().query(
                                functionScoreQuery(linearDecayFunction("num", 1, 0.5)).scoreMode(
                                        FiltersFunctionScoreQuery.ScoreMode.MULTIPLY))));
        response.actionGet();
    }

    public void testMultiFieldOptions() throws Exception {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder().startObject()
                    .startObject("type1")
                        .startObject("properties")
                            .startObject("test").field("type", "text").endObject()
                            .startObject("loc").field("type", "geo_point").endObject()
                            .startObject("num").field("type", "float").endObject()
                        .endObject()
                    .endObject()
                .endObject()));

        // Index for testing MIN and MAX
        IndexRequestBuilder doc1 = client().prepareIndex().setType("type1").setId("1").setIndex("test")
                .setSource(jsonBuilder().startObject()
                        .field("test", "value")
                        .startArray("loc")
                            .startObject().field("lat", 10).field("lon", 20).endObject()
                            .startObject().field("lat", 12).field("lon", 23).endObject()
                        .endArray()
                    .endObject());
        IndexRequestBuilder doc2 = client().prepareIndex()
                .setType("type1")
                .setId("2")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").startObject("loc").field("lat", 11).field("lon", 22).endObject()
                                .endObject());

        indexRandom(true, doc1, doc2);

        ActionFuture<SearchResponse> response = client().search(
                searchRequest().source(
                        searchSource().query(baseQuery)));
        SearchResponse sr = response.actionGet();
        assertSearchHits(sr, "1", "2");
        SearchHits sh = sr.getHits();
        assertThat(sh.getTotalHits(), equalTo((long) (2)));

        List<Float> lonlat = new ArrayList<>();
        lonlat.add(20f);
        lonlat.add(10f);
        response = client().search(searchRequest().source(searchSource()
                .query(functionScoreQuery(baseQuery, gaussDecayFunction("loc", lonlat, "1000km").setMultiValueMode(MultiValueMode.MIN)))));
        sr = response.actionGet();
        assertSearchHits(sr, "1", "2");
        sh = sr.getHits();

        assertThat(sh.getAt(0).getId(), equalTo("1"));
        assertThat(sh.getAt(1).getId(), equalTo("2"));
        response = client().search(searchRequest().source(searchSource()
                .query(functionScoreQuery(baseQuery, gaussDecayFunction("loc", lonlat, "1000km").setMultiValueMode(MultiValueMode.MAX)))));
        sr = response.actionGet();
        assertSearchHits(sr, "1", "2");
        sh = sr.getHits();

        assertThat(sh.getAt(0).getId(), equalTo("2"));
        assertThat(sh.getAt(1).getId(), equalTo("1"));

        // Now test AVG and SUM

        doc1 = client().prepareIndex()
                .setType("type1")
                .setId("1")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").startArray("num").value(0.0).value(1.0).value(2.0).endArray()
                                .endObject());
        doc2 = client().prepareIndex()
                .setType("type1")
                .setId("2")
                .setIndex("test")
                .setSource(
                        jsonBuilder().startObject().field("test", "value").field("num", 1.0)
                                .endObject());

        indexRandom(true, doc1, doc2);
        response = client().search(searchRequest().source(searchSource()
                .query(functionScoreQuery(baseQuery, linearDecayFunction("num", "0", "10").setMultiValueMode(MultiValueMode.SUM)))));
        sr = response.actionGet();
        assertSearchHits(sr, "1", "2");
        sh = sr.getHits();

        assertThat(sh.getAt(0).getId(), equalTo("2"));
        assertThat(sh.getAt(1).getId(), equalTo("1"));
        assertThat(1.0 - sh.getAt(0).getScore(), closeTo((1.0 - sh.getAt(1).getScore())/3.0, 1.e-6d));
        response = client().search(searchRequest().source(searchSource()
                .query(functionScoreQuery(baseQuery, linearDecayFunction("num", "0", "10").setMultiValueMode(MultiValueMode.AVG)))));
        sr = response.actionGet();
        assertSearchHits(sr, "1", "2");
        sh = sr.getHits();
        assertThat((double) (sh.getAt(0).getScore()), closeTo((sh.getAt(1).getScore()), 1.e-6d));
    }
}


text:
import forvo
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename

def Main(lang,limit):
      #APIKEY is stored separately in another file called apikey
      with open('apikey.txt') as a:
        APIKEY=a.read()

      myfile = fileChoose()

      with open(myfile) as words:
            #We will create a directory to store downloaded mp3, it will be named /home/user/forvo/...
            home        = os.path.expanduser('~/forvo')
            lang_dir    = os.path.join(home,lang)

            for i in words:

                  r = ForvoRequest(i,lang,APIKEY)

                  if r:
                        DownloadMp3(r, limit, i, lang_dir)
                  else:
                        file_name = os.path.join(lang_dir,'word_not_found.txt')
                        with open(file_name,'a') as out:
                              out.write(i)

def fileChoose():
      #show a file choose dialog box
      Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
      filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
      return filename

def DownloadMp3(urlList, limit, word, folder):
      #download a mp3 file, rename it and write it in a costum folder
      for i in range(0,limit):
            mp3 = requests.get(urlList[i])
            file_name   = word.replace('\n','')+'.{0}'.format(i)+'.mp3'
            file_path   = os.path.join(folder, file_name)

            if not os.path.exists(folder):
                  os.makedirs(folder)
            else:
                  with open(file_path,"wb") as out:
                        #we open a new mp3 file and we name it after the word we're downloading.
                        #The file it's opened in write-binary mode
                        out.write(mp3.content)

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Game.Beatmaps;
using osu.Game.Replays.Legacy;

namespace osu.Game.Rulesets.Replays.Types
{
    /// <summary>
    /// A type of <see cref="ReplayFrame"/> which can be converted from a <see cref="LegacyReplayFrame"/>.
    /// </summary>
    public interface IConvertibleReplayFrame
    {
        /// <summary>
        /// Populates this <see cref="ReplayFrame"/> using values from a <see cref="LegacyReplayFrame"/>.
        /// </summary>
        /// <param name="currentFrame">The <see cref="LegacyReplayFrame"/> to extract values from.</param>
        /// <param name="beatmap">The beatmap.</param>
        /// <param name="lastFrame">The last post-conversion <see cref="ReplayFrame"/>, used to fill in missing delta information. May be null.</param>
        void ConvertFrom(LegacyReplayFrame currentFrame, IBeatmap beatmap, ReplayFrame lastFrame = null);
    }
}


text:
using System;

namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class OptionalAttribute : Attribute
    {
    }
}


text:
Imports System
Imports OpenCvSharp

' Namespace OpenCvSharpSamplesVB
Imports SampleBase

''' <summary>
''' samples/c/polar_transform.c
''' </summary>
    Friend Module PolarTransform
        Public Sub Start()
        Using imgSrc As IplImage = Cv.LoadImage(FilePath.Image.Fruits, LoadMode.Color)
            Using imgLog As IplImage = Cv.CreateImage(Cv.Size(256, 256), BitDepth.U8, 3)
                Using imgLinear As IplImage = Cv.CreateImage(Cv.Size(256, 256), BitDepth.U8, 3)
                    Using imgRecovered1 As IplImage = Cv.CreateImage(Cv.GetSize(imgSrc), BitDepth.U8, 3)
                        Using imgRecovered2 As IplImage = Cv.CreateImage(Cv.GetSize(imgSrc), BitDepth.U8, 3)
                            Cv.LogPolar(imgSrc, imgLog, Cv.Point2D32f(imgSrc.Width / 2.0F, imgSrc.Height / 2.0F), 40, Interpolation.Linear Or Interpolation.FillOutliers)
                            Cv.LogPolar(imgLog, imgRecovered1, Cv.Point2D32f(imgSrc.Width / 2.0F, imgSrc.Height / 2.0F), 40, Interpolation.Linear Or Interpolation.FillOutliers Or Interpolation.InverseMap)

                            Cv.LinearPolar(imgSrc, imgLinear, Cv.Point2D32f(imgSrc.Width / 2.0F, imgSrc.Height / 2.0F), imgLinear.Width, Interpolation.Linear Or Interpolation.FillOutliers)
                            Cv.LinearPolar(imgLinear, imgRecovered2, Cv.Point2D32f(imgSrc.Width / 2.0F, imgSrc.Height / 2.0F), imgLinear.Width, Interpolation.InverseMap Or Interpolation.Linear Or Interpolation.FillOutliers)

                            Cv.NamedWindow("log-polar")
                            Cv.ShowImage("log-polar", imgLog)
                            Cv.NamedWindow("inverse log-polar")
                            Cv.ShowImage("inverse log-polar", imgRecovered1)
                            Cv.NamedWindow("linear-polar")
                            Cv.ShowImage("linear-polar", imgLinear)
                            Cv.NamedWindow("inverse linear-polar")
                            Cv.ShowImage("inverse linear-polar", imgRecovered2)
                            Cv.WaitKey()
                            Cv.DestroyAllWindows()
                        End Using
                    End Using
                End Using
            End Using
        End Using

        End Sub
    End Module
' End Namespace


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>HelpSectionFactory (Airline - Library 2.1.1 API)</title>
<meta name="date" content="2016-01-19">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.github.rvesse.airline.help.sections.factories

Interface HelpSectionFactory

All Known Implementing Classes:

CommonSectionsFactory

public interface HelpSectionFactory

Interface for factories that convert annotations into HelpSection
 instances

Method Summary

Methods

Modifier and Type
Method and Description

HelpSection
createSection(Annotation annotation)

Tries to create a section from the given annotation

List<Class<? extends Annotation>>
supportedAnnotations()

Gets a list of the supported annotations

Method Detail

createSection

HelpSection createSection(Annotation annotation)

Tries to create a section from the given annotation

Parameters:

annotation - Annotation

Returns:

Help section or null if the annotation is not supported

supportedAnnotations

List<Class<? extends Annotation>> supportedAnnotations()

Gets a list of the supported annotations

Returns:

Supported annotations

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2012–2016. All rights reserved.


text:
namespace GG
{
	bool ShaderLoader::loadDefault(IResource * outResource)
	{
		Shader * shader = (Shader*)outResource;
		static const char * vertexShader =
			"uniform mat4 inMVP;\n"
			"attribute vec4 inVert;\n"
			"varying vec3 modelVert;\n"
			"void main() {\n"
			"   gl_Position = inMVP * inVert;\n"
			"   modelVert = inVert.xyz;\n"
			"}\n";
		static const char * pixelShader =
			"precision mediump float;\n"
			"varying vec3 modelVert;\n"
			"void main(){\n"
			"   gl_FragColor = vec4(abs(cos(modelVert.x)), abs(modelVert.y), abs(sin(modelVert.z)), 1);  \n"
			"}\n";

		shader->bindAttribute(VertexTags::Position, "inVert");
		return shader->compile(vertexShader, pixelShader);
	}
	bool ShaderLoader::loadFromFile(IResource * outResource, const std::string & filePath)
	{
		TRACE_ERROR("Loading shader from file not yet supported");
		return false;
	}

	bool ShaderLoader::loadFromMemory(IResource * outResource, uint64 size, const void* data)
	{

		TRACE_ERROR("Loading shader from memory not yet supported");
		return false;
	}

	bool ShaderLoader::loadFromStream(IResource * outResource, IStream * stream)
	{

		TRACE_ERROR("Loading shader from stream not yet supported");
		return false;
	}

	bool ShaderLoader::loadFromDescriptor(
		IResource * outResource,
		const IResourceDescriptor * descriptor)
	{
		ShaderDescriptor * shaderDesc = (ShaderDescriptor*)descriptor;
		assert(shaderDesc != nullptr);

		Shader * shader = (Shader*)outResource;

		auto it = shaderDesc->vertexAttributeLayout.cbegin();
		for(; it != shaderDesc->vertexAttributeLayout.cend(); ++it)
		{
			shader->bindAttribute((int)it->first, it->second);
		}

	// Vertex shader
		FileStream vertShaderStream(shaderDesc->vertexShaderSource, OpenMode::OPEN_READ);
		std::string vertShader = Stream::ReadStringFromStream(&vertShaderStream);
		vertShaderStream.close();

	// Pixel shader
		FileStream pixelShaderStream(shaderDesc->pixelShaderSource, OpenMode::OPEN_READ);
		std::string pixelShader = Stream::ReadStringFromStream(&pixelShaderStream);
		pixelShaderStream.close();

		return shader->compile(vertShader, pixelShader);
	}
}


text:
/*
 * Arekkuusu / Improbable plot machine. 2018
 *
 * This project is licensed under the MIT.
 * The source code is available on github:
 * https://github.com/ArekkuusuJerii/Improbable-plot-machine
 */
package arekkuusu.implom.common.proxy;

import arekkuusu.implom.common.lib.LibMod;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * Created by <Arekkuusu> on 21/06/2017.
 * It's distributed as part of Improbable plot machine.
 */
@SideOnly(Side.SERVER)
@EventBusSubscriber(modid = LibMod.MOD_ID, value = Side.SERVER)
public class ServerProxy implements IProxy {

	@Override
	public void preInit(FMLPreInitializationEvent event) {

	}

	@Override
	public void init(FMLInitializationEvent event) {

	}

	@SubscribeEvent
	public static void playerServerJoin(PlayerEvent.PlayerLoggedInEvent event) {
		if(event.player instanceof EntityPlayerMP) {

		}
	}

	@Mod.EventHandler
	public static void serverStop(FMLServerStoppedEvent event) {

	}
}


text:
package com.dhgh.mddoc.user;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import com.dhgh.mddoc.util.MDReader;
import com.dhgh.mddoc.util.ParseMD5;

public class User {
	public User() { }
	public User(String loginName,String loginPwd, String...auths) {
		this.loginName = loginName;
		this.loginPwd = loginPwd;
		this.auths = auths;
	}

	private String loginName;
	private String loginPwd;
	private String[] auths;
	public String getLoginName() {
		return loginName;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	public String getLoginPwd() {
		return loginPwd;
	}
	public void setLoginPwd(String loginPwd) {
		this.loginPwd = loginPwd;
	}
	public String[] getAuths() {
		return auths;
	}
	public void setAuths(String[] auths) {
		this.auths = auths;
	}

	public static final String SYS_USER_TOKEN = "*b3(#^.~kD}32V";
	public static final String SYS_PASSWORD_TOKEN = ">3Jo&-=A#>";

	public static Map<String, User> allUser = new HashMap<String, User>();
	public static void registerUser(String loginName,String loginPwd, String[]auths) {
		if (auths == null) {
			auths = new String[]{};
		}
		allUser.put(loginName, new User(loginName, ParseMD5.parseStrToMd5L32((ParseMD5.parseStrToMd5L32(loginPwd).toLowerCase()+SYS_PASSWORD_TOKEN)).toLowerCase(), auths));
	}

	public static boolean hasAuth(String requestProject, User user) {
		if (user == null) {
			return false;
		}
		if (user.getAuths().length == 0) {
			return false;
		}
		for (String au : user.getAuths()) {
			if (au.equals("*") || au.equals(requestProject)) {
				return true;
			}
		}
		return false;
	}
	static {
		allUser = new HashMap<>();

		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(MDReader.class.getResource("/users.properties").getPath()));
			Enumeration<String> names = (Enumeration<String>) prop.propertyNames();
			while(names.hasMoreElements()) {
				String name = names.nextElement();
				String valueStr = prop.getProperty(name);
				String[] valueArr = valueStr.split("\\:");
				String pwd = valueArr[0].trim();
				String[] auths = null;
				if (valueArr.length > 1) {
					auths = valueArr[1].split("\\s*,\\s*");
				}
				registerUser(name, pwd, auths);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}


text:
package command

import (
	"fmt"

	"gopkg.in/alecthomas/kingpin.v2"
)

type RestoreCommand struct {
	*Meta

	GameName   string
	TurnNumber int
}

func (c *RestoreCommand) run(*kingpin.ParseContext) error {
	game, err := c.Meta.RunContext.GameInstallation.AvailableGames.FindGameByName(c.GameName)
	if err != nil {
		return err
	}

	c.Ui.Output(fmt.Sprintf("Restoring turn %v for game %v", c.TurnNumber, game.Name))
	err = game.Restore(c.TurnNumber)
	if err != nil {
		return err
	}

	return nil
}

func (c *RestoreCommand) completion(parseContext *kingpin.ParseContext) error {
	return completionWithGames(c.Meta, parseContext)
}

func ConfigureRestoreCommand(app *kingpin.Application, meta *Meta) (commandName string) {
	commandName = "restore"
	c := &RestoreCommand{Meta: meta}
	cmd := app.Command(commandName, "Restores all backed up files for a given turn for a game.")

	if meta.CompletionOnly {
		cmd.Action(c.completion)
	} else {
		cmd.Action(c.run)
		cmd.Arg("game_name", "Name of the game to restore for").Required().StringVar(&c.GameName)
		cmd.Arg("turn_number", "Restore which turn number?").Required().IntVar(&c.TurnNumber)
	}

	return commandName
}


text:
<template name="contact">

	{{#with item }}
		{{#with contact}}

		{{/with}}
	{{/with}}

Contact us

			<form>

							Your name *
							<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>

							Your email address *
							<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>

							Subject
							<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject" required>

							Message *
							<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>

							<input type="submit" value="Send Message" class="btn btn-primary btn-lg" data-loading-text="Loading...">

			</form>

Get in Touch

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget leo at velit imperdiet varius. In eu ipsum vitae velit congue iaculis vitae at risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

The Office

				{{#with item }}
					{{#with contact}}

 Address: {{ address }}

						{{#each phone}}

 Phone: {{ number }}

						{{/each}}
						{{#each fax}}

 Fax: {{ number }}

						{{/each}}

 Email: {{ email }}

					{{/with }}
				{{/with }}

Business Hours

				{{#with item }}
					{{#with contact}}
						{{#with hours }}

 Monday - Friday  {{ weekdays }}

 Saturday - {{ saturday }}

 Sunday - {{ sunday }}

						{{/with }}
					{{/with }}
				{{/with }}

</template>


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/util/IllegalFormatCodePointException.java
//

#include "../../J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_JavaUtilIllegalFormatCodePointException")
#ifdef RESTRICT_JavaUtilIllegalFormatCodePointException
#define INCLUDE_ALL_JavaUtilIllegalFormatCodePointException 0
#else
#define INCLUDE_ALL_JavaUtilIllegalFormatCodePointException 1
#endif
#undef RESTRICT_JavaUtilIllegalFormatCodePointException

#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#if !defined (JavaUtilIllegalFormatCodePointException_) && (INCLUDE_ALL_JavaUtilIllegalFormatCodePointException || defined(INCLUDE_JavaUtilIllegalFormatCodePointException))
#define JavaUtilIllegalFormatCodePointException_

#define RESTRICT_JavaUtilIllegalFormatException 1
#define INCLUDE_JavaUtilIllegalFormatException 1
#include "../../java/util/IllegalFormatException.h"

#define RESTRICT_JavaIoSerializable 1
#define INCLUDE_JavaIoSerializable 1
#include "../../java/io/Serializable.h"

/*!
 @brief An IllegalFormatCodePointException will be thrown if an invalid
 Unicode code point (defined by Character.isValidCodePoint(int)) is
 passed as a parameter to a Formatter.
 - seealso: java.lang.RuntimeException
 */
@interface JavaUtilIllegalFormatCodePointException : JavaUtilIllegalFormatException < JavaIoSerializable >

#pragma mark Public

/*!
 @brief Constructs a new IllegalFormatCodePointException which is
 specified by the invalid Unicode code point.
 @param c
 the invalid Unicode code point.
 */
- (instancetype)initWithInt:(jint)c;

/*!
 @brief Returns the invalid Unicode code point.
 @return the invalid Unicode code point.
 */
- (jint)getCodePoint;

- (NSString *)getMessage;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaUtilIllegalFormatCodePointException)

FOUNDATION_EXPORT void JavaUtilIllegalFormatCodePointException_initWithInt_(JavaUtilIllegalFormatCodePointException *self, jint c);

FOUNDATION_EXPORT JavaUtilIllegalFormatCodePointException *new_JavaUtilIllegalFormatCodePointException_initWithInt_(jint c) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaUtilIllegalFormatCodePointException *create_JavaUtilIllegalFormatCodePointException_initWithInt_(jint c);

J2OBJC_TYPE_LITERAL_HEADER(JavaUtilIllegalFormatCodePointException)

#endif

#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaUtilIllegalFormatCodePointException")


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Messenger.Models
{
    public class Price
    {
        [JsonProperty("label")]
        public virtual string Label { get; set; }

        [JsonProperty("amount")]
        public virtual string Amount { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WebKitBrowserTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            List<string> largs = new List<string>(args);
            if (largs.Contains("/IgnoreSSL"))
                Environment.SetEnvironmentVariable("WEBKIT_IGNORE_SSL_ERRORS", "1");
            Application.Run(new MainForm());
        }
    }
}


text:
onload = function() {
  debug = true;
  var getURL = chrome.extension.getURL;
  var URL_MAIN = getURL('main.html');
  var URL_FRAME1 = 'http://a.com:PORT/extensions/api_test/webnavigation/' +
      'crossProcessIframe/frame.html';
  var URL_FRAME2 = 'http://b.com:PORT/extensions/api_test/webnavigation/' +
      'crossProcessIframe/frame.html';
  var URL_FRAME3 = 'http://c.com:PORT/extensions/api_test/webnavigation/' +
      'crossProcessIframe/frame.html';
  chrome.tabs.create({'url': 'about:blank'}, function(tab) {
    var tabId = tab.id;
    chrome.test.getConfig(function(config) {
      var fixPort = function(url) {
        return url.replace(/PORT/g, config.testServer.port);
      };
      URL_FRAME1 = fixPort(URL_FRAME1);
      URL_FRAME2 = fixPort(URL_FRAME2);
      URL_FRAME3 = fixPort(URL_FRAME3);

      chrome.test.runTests([
        // Navigates from an extension page to a HTTP page which causes a
        // process switch. The extension page embeds a same-process iframe which
        // embeds another frame that navigates three times (cross-process):
        // c. Loaded by the parent frame.
        // d. Navigated by the parent frame.
        // e. Navigated by the child frame.
        // Tests whether the frameId stays constant across navigations.
        function crossProcessIframe() {
          expect([
            { label: 'main-onBeforeNavigate',
              event: 'onBeforeNavigate',
              details: { frameId: 0,
                         parentFrameId: -1,
                         processId: -1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_MAIN }},
            { label: 'main-onCommitted',
              event: 'onCommitted',
              details: { frameId: 0,
                         processId: 0,
                         tabId: 0,
                         timeStamp: 0,
                         transitionQualifiers: [],
                         transitionType: 'link',
                         url: URL_MAIN }},
            { label: 'main-onDOMContentLoaded',
              event: 'onDOMContentLoaded',
              details: { frameId: 0,
                         processId: 0,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_MAIN }},
            { label: 'main-onCompleted',
              event: 'onCompleted',
              details: { frameId: 0,
                         processId: 0,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_MAIN }},
            { label: 'a.com-onBeforeNavigate',
              event: 'onBeforeNavigate',
              details: { frameId: 1,
                         parentFrameId: 0,
                         processId: -1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME1 }},
            { label: 'a.com-onCommitted',
              event: 'onCommitted',
              details: { frameId: 1,
                         processId: 1,
                         tabId: 0,
                         timeStamp: 0,
                         transitionQualifiers: [],
                         transitionType: 'auto_subframe',
                         url: URL_FRAME1 }},
            { label: 'a.com-onDOMContentLoaded',
              event: 'onDOMContentLoaded',
              details: { frameId: 1,
                         processId: 1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME1 }},
            { label: 'a.com-onCompleted',
              event: 'onCompleted',
              details: { frameId: 1,
                         processId: 1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME1 }},
            { label: 'b.com-onBeforeNavigate',
              event: 'onBeforeNavigate',
              details: { frameId: 1,
                         parentFrameId: 0,
                         processId: -1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME2 }},
            { label: 'b.com-onCommitted',
              event: 'onCommitted',
              details: { frameId: 1,
                         processId: 2,
                         tabId: 0,
                         timeStamp: 0,
                         transitionQualifiers: [],
                         transitionType: 'manual_subframe',
                         url: URL_FRAME2 }},
            { label: 'b.com-onDOMContentLoaded',
              event: 'onDOMContentLoaded',
              details: { frameId: 1,
                         processId: 2,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME2 }},
            { label: 'b.com-onCompleted',
              event: 'onCompleted',
              details: { frameId: 1,
                         processId: 2,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME2 }},
            { label: 'c.com-onBeforeNavigate',
              event: 'onBeforeNavigate',
              details: { frameId: 1,
                         parentFrameId: 0,
                         processId: -1,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME3 }},
            { label: 'c.com-onCommitted',
              event: 'onCommitted',
              details: { frameId: 1,
                         processId: 3,
                         tabId: 0,
                         timeStamp: 0,
                         transitionQualifiers: [],
                         transitionType: 'manual_subframe',
                         url: URL_FRAME3 }},
            { label: 'c.com-onDOMContentLoaded',
              event: 'onDOMContentLoaded',
              details: { frameId: 1,
                         processId: 3,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME3 }},
            { label: 'c.com-onCompleted',
              event: 'onCompleted',
              details: { frameId: 1,
                         processId: 3,
                         tabId: 0,
                         timeStamp: 0,
                         url: URL_FRAME3 }}],
            [
              navigationOrder('main-'),
              navigationOrder('a.com-'),
              navigationOrder('b.com-'),
              navigationOrder('c.com-'),
              ['a.com-onCommitted', 'b.com-onBeforeNavigate'],
              ['b.com-onCommitted', 'c.com-onBeforeNavigate'],
            ]);

          chrome.tabs.update(tabId, {
            url: URL_MAIN + '?' + config.testServer.port
          });
        },

      ]);
    });
  });
};


text:
from flask import Flask
from flask import request
from werkzeug import secure_filename
from flask import make_response
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        f.save('./uploads/'+f.filename)
    return '',202
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)


text:
NSString * const MakersNewsURLKey = @"MakersNewsURLKey";

@interface MKADMainViewController ()

@end

@implementation MKADMainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	NSString *makersURL = [[NSUserDefaults standardUserDefaults] objectForKey:MakersNewsURLKey];
	if ([makersURL length])
	{
		[self.urlTextField setText:makersURL];
	}
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Button Actions

-(IBAction)receiveNewsPressed:(id)sender
{
    if ([self.urlTextField.text length] > 0)
    {
		[[NSUserDefaults standardUserDefaults] setObject:[self.urlTextField text] forKey:MakersNewsURLKey];
		[[NSUserDefaults standardUserDefaults] synchronize];

        //Open a new view with the url
        MKADArticlesTableViewController *articleTableViewController = [[MKADArticlesTableViewController alloc] initWithStyle:UITableViewStylePlain URLString:self.urlTextField.text];
        [self.navigationController pushViewController:articleTableViewController animated:YES];
    }
}

@end


text:
//
//  BBTooltipView.h
//  BBFrameworks
//
//  Created by Willam Towe on 6/17/15.
//  Copyright (c) 2015 Bion Bilateral, LLC. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#import <UIKit/UIKit.h>
#import "BBTooltipViewDefines.h"
#import "BBTooltipAccessoryView.h"

NS_ASSUME_NONNULL_BEGIN

/**
 Enum describing the arrow direction of the receiver.
 */
typedef NS_ENUM(NSInteger, BBTooltipViewArrowDirection) {
    /**
     The arrow is pointing up.
     */
    BBTooltipViewArrowDirectionUp,
    /**
     The arrow is pointing left.
     */
    BBTooltipViewArrowDirectionLeft,
    /**
     The arrow is pointing down.
     */
    BBTooltipViewArrowDirectionDown,
    /**
     The arrow is pointing right.
     */
    BBTooltipViewArrowDirectionRight
};

/**
 BBTooltipView is a UIView subclass that is responsible for displaying a tooltip with BBTooltipViewController.
 */
@interface BBTooltipView : UIView

/**
 Set and get the arrow direction of the receiver.

 @see BBTooltipViewArrowDirection
 */
@property (assign,nonatomic) BBTooltipViewArrowDirection arrowDirection;
/**
 Set and get the arrow style of the receiver.

 The default is BBTooltipViewArrowStyleDefault.

 @see BBTooltipViewArrowStyle
 */
@property (assign,nonatomic) BBTooltipViewArrowStyle arrowStyle UI_APPEARANCE_SELECTOR;

/**
 Set and get the text of the receiver.

 Calls `-[self setAttributedText:[[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: self.tooltipFont, NSForegroundColorAttributeName: self.tooltipTextColor}]]`.
 */
@property (copy,nonatomic) NSString *text;
/**
 Set and get the attributed text of the receiver.
 */
@property (copy,nonatomic) NSAttributedString *attributedText;

/**
 Set and get the attachment view of the receiver.
 */
@property (weak,nonatomic) UIView *attachmentView;

/**
 Set and get the tooltip font of the receiver.

 The default is [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1].
 */
@property (strong,nonatomic,null_resettable) UIFont *tooltipFont UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip text color of the receiver.

 The default is [UIColor whiteColor].
 */
@property (strong,nonatomic,null_resettable) UIColor *tooltipTextColor UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip background color.

 The default is [UIColor darkGrayColor].
 */
@property (strong,nonatomic,null_resettable) UIColor *tooltipBackgroundColor UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip edge insets.

 The default is UIEdgeInsetsMake(8.0, 8.0, 8.0, 8.0).
 */
@property (assign,nonatomic) UIEdgeInsets tooltipEdgeInsets UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip arrow width.

 The default is 8.0.
 */
@property (assign,nonatomic) CGFloat tooltipArrowWidth UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip arrow height.

 The default is 8.0.
 */
@property (assign,nonatomic) CGFloat tooltipArrowHeight UI_APPEARANCE_SELECTOR;
/**
 Set and get the tooltip corner radius.

 The default is 5.0.
 */
@property (assign,nonatomic) CGFloat tooltipCornerRadius UI_APPEARANCE_SELECTOR;

/**
 Set and get the accessory view of the receiver. If non-nil, is displayed underneath the text of the tooltip with insets according to accessoryViewEdgeInsets. The view should implement `sizeThatFits:` so the receiver can determine the appropriate height for the accessory view frame.

 The default is nil.
 */
@property (strong,nonatomic,nullable) UIView<BBTooltipAccessoryView> *accessoryView;
/**
 Set and get the edge insets for the accessory view. These are used when laying out the accessory view with respect to the left, right, and bottom edges of the receiver, as well as the bottom edge of the text.

 The default is UIEdgeInsetsZero.
 */
@property (assign,nonatomic) UIEdgeInsets accessoryViewEdgeInsets UI_APPEARANCE_SELECTOR;

/**
 Returns the background rect for the provided bounds.

 @param bounds The bounds of the receiver
 @return The background rect
 */
- (CGRect)backgroundRectForBounds:(CGRect)bounds;
/**
 Returns the arrow rect for the provided bounds and attachment view.

 @param The bounds of the receiver
 @param attachmentView The attachment view for the receiver
 @return The arrow rect
 */
- (CGRect)arrowRectForBounds:(CGRect)bounds attachmentView:(UIView *)attachmentView;
/**
 Returns the accessory view rect for provided bounds.

 @param The bounds of the receiver
 @return The accessory
 */
- (CGRect)accessoryViewRectForBounds:(CGRect)bounds;

@end

NS_ASSUME_NONNULL_END


text:
@interface GlobalInstance : NSObject
AS_SINGLETON(GlobalInstance)

- (BOOL)checkLoginStatus;

- (void)saveUser:(UserBean *)user;
- (UserBean *)user;

@end


text:
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import './Welcome.scss';

export class Welcome extends React.Component {
    render() {
        return (

                    Congratulations!

You now have lifetime access to the Best ACT Prep Online Course!

You should soon receive an email with your login information, if you have not received it already. To get started immediately, you can log in with this information:

                    Email: {this.props.email}

                    Password: hungrykoala

If you have any questions or trouble, simply contact me at cheng.c.michael@gmail.com.

                    <Link to="/course">
                        <button className="Button">Go to the course</button>
                    </Link>

        );
    }
}

function mapStateToProps(state) {
    return {
        email: state.app.email
    };
};

export default connect(mapStateToProps)(Welcome);


text:
/* $Id: scc.h,v 1.29 1997/04/02 14:56:45 jreuter Exp jreuter $ */
#ifndef	_SCC_H
#define	_SCC_H

#include <uapi/linux/scc.h>

enum {TX_OFF, TX_ON};	/* command for scc_key_trx() */

/* Vector masks in RR2B */

#define VECTOR_MASK	0x06
#define TXINT		0x00
#define EXINT		0x02
#define RXINT		0x04
#define SPINT		0x06

#ifdef CONFIG_SCC_DELAY
#define Inb(port)	inb_p(port)
#define Outb(port, val)	outb_p(val, port)
#else
#define Inb(port)	inb(port)
#define Outb(port, val)	outb(val, port)
#endif

/* SCC channel control structure for KISS */

struct scc_kiss {
	unsigned char txdelay;		/* Transmit Delay 10 ms/cnt */
	unsigned char persist;		/* Persistence (0-255) as a % */
	unsigned char slottime;		/* Delay to wait on persistence hit */
	unsigned char tailtime;		/* Delay after last byte written */
	unsigned char fulldup;		/* Full Duplex mode 0=CSMA 1=DUP 2=ALWAYS KEYED */
	unsigned char waittime;		/* Waittime before any transmit attempt */
	unsigned int  maxkeyup;		/* Maximum time to transmit (seconds) */
	unsigned int  mintime;		/* Minimal offtime after MAXKEYUP timeout (seconds) */
	unsigned int  idletime;		/* Maximum idle time in ALWAYS KEYED mode (seconds) */
	unsigned int  maxdefer;		/* Timer for CSMA channel busy limit */
	unsigned char tx_inhibit;	/* Transmit is not allowed when set */
	unsigned char group;		/* Group ID for AX.25 TX interlocking */
	unsigned char mode;		/* 'normal' or 'hwctrl' mode (unused) */
	unsigned char softdcd;		/* Use DPLL instead of DCD pin for carrier detect */
};

/* SCC channel structure */

struct scc_channel {
	int init;			/* channel exists? */

	struct net_device *dev;		/* link to device control structure */
	struct net_device_stats dev_stat;/* device statistics */

	char brand;			/* manufacturer of the board */
	long clock;			/* used clock */

	io_port ctrl;			/* I/O address of CONTROL register */
	io_port	data;			/* I/O address of DATA register */
	io_port special;		/* I/O address of special function port */
	int irq;			/* Number of Interrupt */

	char option;
	char enhanced;			/* Enhanced SCC support */

	unsigned char wreg[16]; 	/* Copy of last written value in WRx */
	unsigned char status;		/* Copy of R0 at last external interrupt */
	unsigned char dcd;		/* DCD status */

        struct scc_kiss kiss;		/* control structure for KISS params */
        struct scc_stat stat;		/* statistical information */
        struct scc_modem modem; 	/* modem information */

        struct sk_buff_head tx_queue;	/* next tx buffer */
        struct sk_buff *rx_buff;	/* pointer to frame currently received */
        struct sk_buff *tx_buff;	/* pointer to frame currently transmitted */

	/* Timer */
	struct timer_list tx_t;		/* tx timer for this channel */
	struct timer_list tx_wdog;	/* tx watchdogs */

	/* Channel lock */
	spinlock_t	lock;		/* Channel guard lock */
};

#endif /* defined(_SCC_H) */