text:
package wikokit.base.wikt.multi.en;

//import wikipedia.sql.Connect;
import wikokit.base.wikt.multi.en.WMeaningEn;
import wikokit.base.wikt.constant.POS;
import wikokit.base.wikt.multi.en.name.LabelEn;
import wikokit.base.wikt.util.WikiWord;
import wikokit.base.wikt.word.WQuote;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import wikokit.base.wikipedia.language.LanguageType;
import wikokit.base.wikt.constant.Label;
import wikokit.base.wikt.util.POSText;
import wikokit.base.wikt.word.WLanguage;
import wikokit.base.wikt.word.WMeaning;

public class WMeaningEnTest {

    //Connect     connect_enwikt; // connect_simplewikt;

    public WMeaningEnTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
        //connect_enwikt = new Connect();
        //connect_enwikt.Open(Connect.ENWIKT_HOST,Connect.ENWIKT_DB,Connect.ENWIKT_USER,Connect.ENWIKT_PASS,LanguageType.ru);
    }

    @After
    public void tearDown() {
        //connect_enwikt.Close();
    }

    @Test
    public void testParseOneDefinition_en() {
        System.out.println("parseOneDefinition_en");
        LanguageType lang_section;
        String page_title;

        page_title      = "luck";
        lang_section    = LanguageType.en; // English word

        LabelEn[] _labels = new LabelEn[0];   //_labels[0] = LabelRu.p;
        String _def1_source =
            "# Something that happens to someone by [[chance]], a chance occurrence.\n" +
            "#: ''The raffle is just a matter of '''luck'''.''";

        String _def1_result = "Something that happens to someone by chance, a chance occurrence.";
        String _quote1_result = "The raffle is just a matter of '''luck'''.";

        String _def2_source =
            "# A superstitious feeling that brings [[fortune]] or [[success]].\n" +
            "#* '''Year''', Author, ''Source title'', Publisher, pages #–#:\n" +
            "#*: First quotation of '''word'''.\n" +
            "#: ''He blew on the dice for '''luck'''.''";

        String _def2_result = "A superstitious feeling that brings fortune or success.";
        String _quote2_result = "He blew on the dice for '''luck'''.";

        WikiWord[] ww = new WikiWord[2];
        //WikiWord(String _word_visible, String _word_link, ContextLabel[] _labels) {
        ww[0] = new WikiWord("fortune", "fortune",  null);
        ww[1] = new WikiWord("success", "success",  null);

        WQuote[] _quote = null;

        //WMeaning expResult1 = new WMeaning(page_title, _labels, _def1_result, _quote, false);//_quote1_result);
        //WMeaning expResult2 = new WMeaning(page_title, _labels, _def2_result, _quote, false);//_quote2_result);

        // 1
        WMeaning result1 = WMeaningEn.parseOneDefinition(
                page_title, lang_section, _def1_source);

        assertTrue(null != result1);
        assertTrue(result1.getDefinition().equalsIgnoreCase(_def1_result));

        // labels == null
        Label[] labels_result = result1.getLabels();
        assertEquals(0, labels_result.length);

        // wikiword.size = 1; chance
        WikiWord[] ww_result = result1.getWikiWords();
        assertEquals(1, ww_result.length);

        // 2
        WMeaning result2 = WMeaningEn.parseOneDefinition(
                page_title, lang_section, _def2_source);

        assertTrue(null != result2);
        assertTrue(result2.getDefinition().equalsIgnoreCase(_def2_result));

        // labels == null
        labels_result = result2.getLabels();
        assertEquals(0, labels_result.length);

        // wikiword.size = 2; fortune and success
        ww_result = result2.getWikiWords();
        assertEquals(2, ww_result.length);
    }

    // ////////////////////////////////////////
    // Form of templates
    //
    // @see http://en.wiktionary.org/wiki/Category:Form_of_templates

    // {{form of|
    @Test
    public void testHasOnlyTemplatesWithoutDefinitions_en_form_of() {
        System.out.println("hasOnlyTemplatesWithoutDefinitions_en_form_of");
        LanguageType wikt_lang;
        String page_title;
        StringBuffer s;
        WLanguage[] lang;
        boolean b;

        wikt_lang       = LanguageType.en; // English Wiktionary
        page_title      = "raggiavo";

        // 1. empty test - usual definition
        s = new StringBuffer(
                "==Italian==\n" +
                "===Verb===\n" +
                "'''raggiavo'''\n" +
                "# the definition\n" +
                "\n");
        lang = WLanguage.parse(wikt_lang, page_title, s);
        b = WLanguage.hasOnlyTemplatesWithoutDefinitions(wikt_lang, lang);
        assertFalse(b);

        // 2. one template {{form of|}}
        s = new StringBuffer(
                "==Italian==\n" +
                "\n" +
                "===Verb===\n" +
                "'''raggiavo'''\n" +
                "# {{form of|[[first-person|First-person]] [[singular]] [[imperfect tense]]|raggiare|lang=Italian}}\n" +
                "\n");
        lang = WLanguage.parse(wikt_lang, page_title, s);
        b = WLanguage.hasOnlyTemplatesWithoutDefinitions(wikt_lang, lang);
        assertTrue(b);

        // 3. only several templates {{form of|}}, no definition text
        s = new StringBuffer(
                "==Italian==\n" +
                "\n" +
                "===Verb===\n" +
                "'''raggiamo'''\n" +
                "\n" +
                "# {{form of|[[first-person|First-person]] [[plural]] [[present tense]]|raggiare|lang=Italian}}\n" +
                "# {{form of|First-person plural [[present subjunctive]]|raggiare|lang=Italian}}\n" +
                "# {{form of|First-person plural [[imperative]]|raggiare|lang=Italian}}\n" +
                "\n");
        lang = WLanguage.parse(wikt_lang, page_title, s);
        b = WLanguage.hasOnlyTemplatesWithoutDefinitions(wikt_lang, lang);
        assertTrue(b);

        // 4. several templates {{form of|}} + definition text
        s = new StringBuffer(
                "==Italian==\n" +
                "\n" +
                "===Verb===\n" +
                "'''raggiamo'''\n" +
                "\n" +
                "# the definition text\n" +
                "# {{form of|[[first-person|First-person]] [[plural]] [[present tense]]|raggiare|lang=Italian}}\n" +
                "# {{form of|First-person plural [[present subjunctive]]|raggiare|lang=Italian}}\n" +
                "# {{form of|First-person plural [[imperative]]|raggiare|lang=Italian}}\n" +
                "\n");
        lang = WLanguage.parse(wikt_lang, page_title, s);
        b = WLanguage.hasOnlyTemplatesWithoutDefinitions(wikt_lang, lang);
        assertFalse(b);
    }

    // {{plural of|
    @Test
    public void testHasOnlyTemplatesWithoutDefinitions_en_plural_of() {
        System.out.println("hasOnlyTemplatesWithoutDefinitions_en_plural_of");
        LanguageType wikt_lang;
        String page_title;
        StringBuffer s;
        WLanguage[] lang;
        boolean b;

        wikt_lang       = LanguageType.en; // English Wiktionary
        page_title      = "stanas";

        // 1. one template {{plural of|}}
        s = new StringBuffer(
                "==Old English==\n" +
                "\n" +
                "===Noun===\n" +
                "{{Latinx|'''stānas'''}}\n" +
                "\n" +
                "# {{plural of|stan#Old English|stān|lang=Old English}}\n" +
                "{{count page|[[Wiktionary:Page count]]}}\n" +
                "\n");
        lang = WLanguage.parse(wikt_lang, page_title, s);
        b = WLanguage.hasOnlyTemplatesWithoutDefinitions(wikt_lang, lang);
        assertTrue(b);
    }

    // {{form of|
    // {{eo-form of|
    // {{fi-form of|
    @Test
    public void testParseOneDefinition_en_language_code_plus_form_of_templates() {
        System.out.println("language_code_plus_form_of_templates");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "raggiamo";
        lang_section    = LanguageType.en; // English word

        // form of
        source = "# {{form of|[[first-person|First-person]] [[plural]] [[present tense]]|[[raggiare#Italian|raggiare]]|lang=Italian}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // eo-form of
        source = "# {{eo-form of|bol|us}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // fi-form of
        source = "# {{fi-form of|kävellä|type=verb|pr=impersonal|mood=conditional|tense=present}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // {{es-verb form of|
    // {{ca-verb form of|
    // {{ru-verb form of|
    // {{fi-verb form of|
    @Test
    public void testParseOneDefinition_en_language_code_plus_verb_form_of_templates() {
        System.out.println("language_code_plus_verb_form_of_templates");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "raggiamo";
        lang_section    = LanguageType.en; // English word

        // es-verb form of
        source = "# {{es-verb form of|mood=ger|ending=er|verb=hacer}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // {{ca-verb form of|
        source = "# {{ca-verb form of|t=pres|m=ptc|acceptar}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // {{fi-verb form of|
        source = "# {{fi-verb form of|pn=pass|tm=pres|nähdä}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // genitive of
    @Test
    public void testParseOneDefinition_en_genitive_of_template() {
        System.out.println("parseOneDefinition_en_genitive_of_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        // 1 genitive of
        source = "# {{genitive of|[[word]]}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 2
        source = "# {{genitive of|word|wörd}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // {{plural of|
    // {{feminine plural of|
    @Test
    public void testParseOneDefinition_en_plural_of_template() {
        System.out.println("parseOneDefinition_en_plural_of_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        // 1 plural of
        source = "# {{plural of| }}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 2 feminine plural of
        source = "# {{feminine plural of|[[bueno]]|lang=es}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // {{past participle of|
    // {{plural past participle of|
    // {{feminine plural past participle of|
    @Test
    public void testParseOneDefinition_en_past_participle_of_template() {
        System.out.println("parseOneDefinition_en_past_participle_of_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        // 1 past participle of, ok - it has definition in really
        source = "# {{obsolete}} {{past participle of|sit}} An alternate form of sat.";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertFalse(wm.isFormOfInflection());

        // 2 plural past participle of
        source = "# {{plural past participle of|}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 3. participle of
        source = "# {{fi-participle of|tense=past|valvoa}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // "Plural form of xilologico"
    @Test
    public void testParseOneDefinition_en_form_of_inflections_without_template() {
        System.out.println("form_of_inflections_without_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        // "Plural form of" without template
        source = "# Plural form of xilologico";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // "Plural form of" without template
        source = "# Feminine plural form of uxoricida";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // adjective
    // {{sv-adj-form-abs-def-m|
    // {{sv-adj-form-abs-def+pl|
    // {{sv-adj-form-abs-indef-n|
    @Test
    public void testParseOneDefinition_en_adj_form_template() {
        System.out.println("parseOneDefinition_en_adj_form_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        source = "# {{sv-adj-form-abs-def-m|}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        source = "# {{sv-adj-form-abs-def+pl|}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        source = "# {{sv-adj-form-abs-indef-n|}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // noun form
    // {{sv-noun-form-def-pl|stup}}
    @Test
    public void testParseOneDefinition_en_noun_form_template() {
        System.out.println("parseOneDefinition_en_noun_form_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "buenas";
        lang_section    = LanguageType.es; // Spanish word

        source = "# {{sv-noun-form-def-pl|stup}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // @see http://en.wiktionary.org/wiki/Template:inflection_of
    // {{inflection of|
    // {{inflection of |
    // {{conjugation of|
    @Test
    public void testParseOneDefinition_en_inflection_of_template() {
        System.out.println("parseOneDefinition_en_form_of_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "anulare";
        lang_section    = LanguageType.la; // Latin word

        // 1 inflection of
        source = "# {{inflection of|anularis|ānulāris|nom|n|s|lang=la}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 1b inflection of with space
        source = "# {{inflection of |О±ОєПЃО№ОІО®П'||nom|n|p|lang=el}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 2 conjugation of
        source = "# {{conjugation of|amo|amō|pres|act|inf|lang=la}} ";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    // @see http://en.wiktionary.org/wiki/Template:alternative_spelling_of
    // {{alternative spelling of|}}
    // misspelling of
    // obsolete spelling of
    // nonstandard spelling of
    @Test
    public void testParseOneDefinition_en_spellings_of_template() {
        System.out.println("parseOneDefinition_en_spellings_of_template");
        LanguageType lang_section;
        String page_title, source;
        WMeaning wm;

        page_title      = "ружье";
        lang_section    = LanguageType.ru; // (second) Russian word

        // 1. alternative spelling of
        source = "# {{alternative spelling of|[[second-guess]]}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        source = "# {{alternative spelling of|ружьё|lang=ru}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 2. misspelling of
        source = "# {{misspelling of|referrer}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 3. obsolete spelling of
        source = "# {{transitive}} {{obsolete spelling of|[[abraid]]}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // 4. nonstandard spelling of
        source = "# {{nonstandard spelling of|lang=cmn|sc=Latn|yЕЌu}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());

        // alternative capitalization of
        source = "# {{alternative capitalization of|Х¦ХЎХїХ«ХЇ|lang=hy}}";
        wm = WMeaningEn.parseOneDefinition(
                page_title, lang_section, source);
        assertNotNull(wm);
        assertTrue(wm.isFormOfInflection());
    }

    //                     eo Form of templates
    // ////////////////////////////////////////

    @Test
    public void testParseOneDefinition_en_labels_and_WikiWord() {
        System.out.println("parseOneDefinition_en_labels_and_WikiWord");
        LanguageType lang_section;
        String page_title;

        page_title      = "beneficiary";
        lang_section    = LanguageType.en; // English word

        LabelEn[] _labels = new LabelEn[0];   //_labels[0] = LabelRu.p;

        String _def_source =
            "# {{legal}} One who [[benefit]]s from the distribution, especially of an estate.\n" +
            "#: ''If any '''beneficiary''' does not survive the Settlor for a period of 30 days then the Trustee shall distribute that '''beneficiary''''s share to the surviving '''beneficiaries''' by right of representation.''";

        String _def_result          = "One who benefits from the distribution, especially of an estate.";
        String _def_result_wikified = "One who [[benefit]]s from the distribution, especially of an estate.";
        String _quote_result = "If any '''beneficiary''' does not survive the Settlor for a period of 30 days then the Trustee shall distribute that '''beneficiary''''s share to the surviving '''beneficiaries''' by right of representation.";

        WikiWord[] ww = new WikiWord[1];

        //WikiWord(String _word_visible, String _word_link, ContextLabel[] _labels) {
        ww[0] = new WikiWord("benefit", "benefits",  null);

        WQuote[] _quote = null;

        //WMeaning expResult = new WMeaning(page_title, _labels, _def_result, _quote);

        WMeaning result = WMeaningEn.parseOneDefinition(page_title, lang_section, _def_source);

        assertTrue(null != result);
        assertTrue(result.getDefinition().equalsIgnoreCase(_def_result));
        assertTrue(result.getWikifiedText().equalsIgnoreCase(_def_result_wikified));

        // labels == null
        Label[] labels_result = result.getLabels();
        assertEquals(0, labels_result.length);

        // wikiword.size = 4;
        WikiWord[] ww_result = result.getWikiWords();
        assertEquals(1, ww_result.length);
    }

    @Test
    public void testParse_3_meaning_parse_labels() {
        System.out.println("parse_3_meaning_parse_labels");

        LanguageType lang_section;
        String page_title;
        POSText pt;
        String str;

        page_title      = "picture";
        lang_section    = LanguageType.en; // English word

        LabelEn[] _labels = new LabelEn[0];   //_labels[0] = LabelRu.p;
        String _definition1 = "A painting.";
        String _definition2 = "A photograph.";
        String _definition3 = "A motion picture.";
        WikiWord[] ww = new WikiWord[4];

        str =   "{{en-noun}}\n" +
                "\n" +
                "# A [[painting]].\n" +
                "#: ''There was a '''picture''' hanging above the fireplace.''\n" +
                "# A [[photograph]].\n" +
                "#: ''I took a '''picture''' of that church.''\n" +
                "# {{informal}} A [[motion picture]].\n" +
                "#: Casablanca ''is my all-time favorite '''picture'''.''\n" +
                "\n";
        pt = new POSText(POS.noun, str);
        WMeaning[] result = WMeaningEn.parse(page_title, lang_section, pt);
        assertNotNull(result);
        assertEquals(3, result.length);
        assertTrue(result[0].getDefinition().equalsIgnoreCase(_definition1));
        assertTrue(result[1].getDefinition().equalsIgnoreCase(_definition2));
        // label test:
        // assertTrue(result[2].getDefinition().equalsIgnoreCase(_definition3));

        // todo
        // test wikiwords

        // todo
        // test quotation

        // todo
        // test labels
    }

    @Test
    public void testParse_2_meaning_with_translation() {
        System.out.println("parse_2_meaning_with_translation");
        LanguageType lang_section;
        String page_title;
        POSText pt;
        String str;

        page_title      = "test_word";
        lang_section    = LanguageType.en; // English word

        LabelEn[] _labels = new LabelEn[0];   //_labels[0] = LabelRu.p;
        String _definition1 = "First definition";
        String _definition2 = "Second definition.";
        WikiWord[] ww = new WikiWord[4];

        str =   "\n" +
                "# First definition\n" +
                "#* '''Year''', Author, ''Source title'', Publisher, pages #–#:\n" +
                "#*: First quotation of '''word'''.\n" +
                "#*:: Translation [if applicable]\n" +
                "#* '''Year''', Author, ''Source title'', Publisher (publication date of later edition), page #:\n" +
                "#*: '''Words''' of second quotation.\n" +
                "# Second definition.\n" +
                "\n";

        pt = new POSText(POS.noun, str);
        WMeaning[] result = WMeaningEn.parse(page_title, lang_section, pt);
        assertNotNull(result);
        assertEquals(2, result.length);
        assertTrue(result[0].getDefinition().equalsIgnoreCase(_definition1));
        assertTrue(result[1].getDefinition().equalsIgnoreCase(_definition2));

        // todo
        // test wikiwords

        // todo
        // test quotation

        // todo
        // test labels

        // todo translation:
        /*'''mán'''
# {{lt-form-pronoun|1s|d|aš}}
#: [[duok|Duok]] '''man''' [[tą]] [[knygą]].
#:: Give me that book.
        */
    }

    @Test
    public void testParse_1_meaning() {
        System.out.println("parse_1_meaning");

        LanguageType lang_section;
        String page_title;
        POSText pt;
        String str;

        page_title      = "airplane";
        lang_section    = LanguageType.en; // English word

        LabelEn[] _labels = new LabelEn[0];   //_labels[0] = LabelRu.p;
        String _definition1 = "First definition";
        String _definition2 = "Second definition.";
        WikiWord[] ww = new WikiWord[4];

        str =   "{{en-noun}}\n" +
                "# {{US}} A powered heavier-than air [[aircraft]] with fixed [[wing]]s.\n" +
                "\n" +
                "====Synonyms====\n" +
                "* [[aeroplane]].\n" +
                "\n" +
                "\n";

        _definition1 = "{{US}} A powered heavier-than air aircraft with fixed wings.";

        pt = new POSText(POS.noun, str);
        WMeaning[] result = WMeaningEn.parse(page_title, lang_section, pt);
        assertNotNull(result);
        assertEquals(1, result.length);
        assertTrue(result[0].getDefinition().equalsIgnoreCase(_definition1));

        // test 2: zero of symbols before the definition #
        str =   "# {{US}} A powered heavier-than air [[aircraft]] with fixed [[wing]]s.\n" +
                "\n" +
                "====Synonyms====\n" +
                "* [[aeroplane]].\n" +
                "\n" +
                "\n";

        pt = new POSText(POS.noun, str);
        result = WMeaningEn.parse(page_title, lang_section, pt);
        assertNotNull(result);
        assertEquals(1, result.length);
        assertTrue(result[0].getDefinition().equalsIgnoreCase(_definition1));
    }

    @Test
    public void testParse_Quotation_header() {
        System.out.println("parse_Quotation_header");

        fail("todo");

    // todo parse Quatation header, see word bark:
    /*
====Noun====
{{en-noun}}

# {{obsolete}} A small sailing vessel, e.g. a pinnace or a fishing smack; a rowing boat or barge.
# {{poetic}} a sailing vessel or boat of any kind.
# {{nautical}} A three-masted vessel, having her foremast and mainmast square-rigged, and her mizzenmast schooner-rigged.

=====Quotations=====
* '''circa 1880''' [[CE]]: Whether my bark went down at sea, Whether she met with gales, ... — Emily Dickinson (1830–86), ''Poems''

=====Translations=====
        */
    }

}


text:
package com.file;
import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.FileDao;
import com.po.Files;

@SuppressWarnings("serial")
public class Del_files extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    	String sid = request.getParameter("id");
		int id = Integer.parseInt(sid);
    	FileDao fileDao = new FileDao();
    	Files file = fileDao.findByNumfile(id);

    	File file2 = new File(file.getFilesroute()+ "\\" + file.getFileonlyname());
    	file2.delete();

    	fileDao.delOne(id);

    	 request.getRequestDispatcher("show_users_for_file").forward(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#define MAXPATBYTES 3
#define MAXSEQPATTERNS 35
typedef enum { NORMAL, RANDOM, VERIFY } ptype_t;
typedef struct {
    ptype_t     ptype;
    int         len;
    int		pat[MAXPATBYTES];
} pattern_t;

typedef struct {
    char       *key;
    char       *desc;
    int         len;
    pattern_t   pat[MAXSEQPATTERNS];
} sequence_t;

const sequence_t *seq_lookup(char *name);
char             *pat2str(pattern_t p);
void              memset_pat(void *s, pattern_t p, size_t n);

/*
 * vi:tabstop=4 shiftwidth=4 expandtab
 */


text:
<?php /** @var BootActiveForm $form */
$form = $this->beginWidget('booster.widgets.TbActiveForm', array(
	'htmlOptions'=>array('class'=>'well'),
	'id'=>'users-form',
	'enableAjaxValidation'=>false,
)); ?>

Полетата маркирани със * са задължителни.

<?php
echo $form->errorSummary($model);
echo $form->textFieldGroup($model, 'userName', array('class'=>'col-sm-5'));
echo $form->passwordFieldGroup($model, 'userPass', array('class'=>'col-sm-5'));
echo $form->passwordFieldGroup($model, 'userPass_repeat', array('class'=>'col-sm-5'));
echo $form->textFieldGroup($model, 'userFullName', array('class'=>'col-sm-5'));
echo $form->dropDownListGroup($model, 'studentId',
	array(
			'wrapperHtmlOptions' => array(
					'class' => 'col-sm-5',
			),
			'widgetOptions' => array(
					'data' => $model->getStudentsList(),
					'htmlOptions' => array(),
			)
	)
);
echo $form->textFieldGroup($model, 'userEmail', array('class'=>'col-sm-5'));
echo $form->textFieldGroup($model, 'userPhones', array('class'=>'col-sm-5'));
//echo $form->checkBoxRow($model, 'userIsVisible', array());
if(Yii::app()->user->getState('userType')>2) {
	echo $form->textAreaGroup($model, 'notes', array('class'=>'col-sm-5', 'rows'=>3));
}
$this->widget(
		'booster.widgets.TbButton',
		array('buttonType' => 'submit', 'label' => ($model->isNewRecord ? 'Създай' : 'Запази'), 'icon'=>'ok')
);
$this->endWidget();


text:
"""
Module
"""
from __future__ import absolute_import

from datacube.index.postgres._fields import SimpleDocField, NumericRangeDocField, parse_fields
from datacube.index.postgres.tables import DATASET

def _assert_same(obj1, obj2):
    assert obj1.__class__ == obj2.__class__
    assert obj1.__dict__ == obj2.__dict__

def test_get_field():
    fields = parse_fields({
        'platform': {
            'description': 'Satellite',
            'offset': ['platform', 'code']
        },
        'instrument': {
            'offset': ['instrument', 'name']
        }
    }, 1, DATASET.c.metadata)

    _assert_same(
        fields['platform'],
        SimpleDocField(
            'platform', 'Satellite',
            1,
            DATASET.c.metadata,
            offset=['platform', 'code']
        )
    )

    storage_fields = parse_fields({
        'lat': {
            'type': 'float-range',
            'max_offset': [['extents', 'geospatial_lat_max']],
            'min_offset': [['extents', 'geospatial_lat_min']],
        },
    }, 2, DATASET.c.metadata)
    _assert_same(
        storage_fields['lat'],
        NumericRangeDocField(
            'lat', None,
            2,
            DATASET.c.metadata,
            max_offset=[['extents', 'geospatial_lat_max']],
            min_offset=[['extents', 'geospatial_lat_min']],
        )
    )


text:
"""distutils.command.install_headers

Implements the Distutils 'install_headers' command, to install C/C++ header
files to the Python include directory."""

# This module should be kept compatible with Python 2.1.

__revision__ = "$Id: install_headers.py 61000 2008-02-23 17:40:11Z christian.heimes $"

from distutils.core import Command

class install_headers (Command):

    description = "install C/C++ header files"

    user_options = [('install-dir=', 'd',
                     "directory to install header files to"),
                    ('force', 'f',
                     "force installation (overwrite existing files)"),
                   ]

    boolean_options = ['force']

    def initialize_options (self):
        self.install_dir = None
        self.force = 0
        self.outfiles = []

    def finalize_options (self):
        self.set_undefined_options('install',
                                   ('install_headers', 'install_dir'),
                                   ('force', 'force'))

    def run (self):
        headers = self.distribution.headers
        if not headers:
            return

        self.mkpath(self.install_dir)
        for header in headers:
            (out, _) = self.copy_file(header, self.install_dir)
            self.outfiles.append(out)

    def get_inputs (self):
        return self.distribution.headers or []

    def get_outputs (self):
        return self.outfiles

# class install_headers


text:
var regions = function (tools) {
  return {

    list: function (callback) {
      tools._get('regions', function (err, data) {
        if (err) return callback(err)
        callback(null, data)
      })
    }

  }
}

module.exports = regions


text:
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace EasyNetQ.DI.Microsoft;

/// <see cref="IServiceRegister"/> implementation for Microsoft.Extensions.DependencyInjection DI container.
public class ServiceCollectionAdapter : IServiceRegister
{
    /// <summary>
    /// Creates an adapter on top of <see cref="IServiceCollection"/>.
    /// </summary>
    public ServiceCollectionAdapter(IServiceCollection serviceCollection)
    {
        ServiceCollection = serviceCollection;

        ServiceCollection.TryAddSingleton<IServiceResolver, ServiceProviderAdapter>();
    }

    public IServiceCollection ServiceCollection { get; }

    /// <inheritdoc />
    public IServiceRegister Register(Type serviceType, Type implementationType, Lifetime lifetime)
    {
        ServiceCollection.Replace(new ServiceDescriptor(serviceType, implementationType, ToLifetime(lifetime)));
        return this;
    }

    /// <inheritdoc />
    public IServiceRegister Register(
        Type serviceType, Func<IServiceResolver, object> implementationFactory, Lifetime lifetime = Lifetime.Singleton
    )
    {
        ServiceCollection.Replace(new ServiceDescriptor(serviceType, PreserveFuncType(implementationFactory), ToLifetime(lifetime)));
        return this;
    }

    /// <inheritdoc />
    public IServiceRegister Register(Type serviceType, object implementationInstance)
    {
        ServiceCollection.Replace(new ServiceDescriptor(serviceType, implementationInstance));
        return this;
    }

    /// <inheritdoc />
    public IServiceRegister TryRegister(
        Type serviceType, Type implementationType, Lifetime lifetime = Lifetime.Singleton
    )
    {
        ServiceCollection.TryAdd(new ServiceDescriptor(serviceType, implementationType, ToLifetime(lifetime)));
        return this;
    }

    /// <inheritdoc />
    public IServiceRegister TryRegister(
        Type serviceType, Func<IServiceResolver, object> implementationFactory, Lifetime lifetime = Lifetime.Singleton
    )
    {
        var descriptor = new ServiceDescriptor(serviceType, PreserveFuncType(implementationFactory), ToLifetime(lifetime));
        ServiceCollection.TryAdd(descriptor);
        return this;
    }

    /// <inheritdoc />
    public IServiceRegister TryRegister(Type serviceType, object implementationInstance)
    {
        ServiceCollection.TryAdd(new ServiceDescriptor(serviceType, implementationInstance));
        return this;
    }

    private static ServiceLifetime ToLifetime(Lifetime lifetime) =>
        lifetime switch
        {
            Lifetime.Singleton => ServiceLifetime.Singleton,
            Lifetime.Transient => ServiceLifetime.Transient,
            _ => throw new ArgumentOutOfRangeException(nameof(lifetime))
        };

    // Without this code, the type of return value will be object
    private static Func<IServiceProvider, object> PreserveFuncType(Func<IServiceResolver, object> implementationFactory)
    {
        if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory));

        var typeArguments = implementationFactory.GetType().GenericTypeArguments;
        if (typeArguments.Length != 2) throw new InvalidOperationException("implementationFactory should be of type Func<IServiceResolver, T>");

        var implementationType = typeArguments[1];
        var implementationFactoryAdapterType = typeof(ImplementationFactoryAdapter<>).MakeGenericType(implementationType);
        var resolveMethodInfo = implementationFactoryAdapterType.GetMethod("Resolve") ?? throw new MissingMethodException();
        return (Func<IServiceProvider, object>)Delegate.CreateDelegate(
            typeof(Func<,>).MakeGenericType(typeof(IServiceProvider), implementationType),
            Activator.CreateInstance(implementationFactoryAdapterType, implementationFactory),
            resolveMethodInfo
        );
    }

    private class ServiceProviderAdapter : IServiceResolver
    {
        private readonly IServiceProvider serviceProvider;

        public ServiceProviderAdapter(IServiceProvider serviceProvider) => this.serviceProvider = serviceProvider;

        public TService Resolve<TService>() where TService : class => serviceProvider.GetService<TService>()!;

        public IServiceResolverScope CreateScope() => new MicrosoftServiceResolverScope(serviceProvider);
    }

    private class MicrosoftServiceResolverScope : IServiceResolverScope
    {
        private readonly IServiceScope serviceScope;

        public MicrosoftServiceResolverScope(IServiceProvider serviceProvider) => serviceScope = serviceProvider.CreateScope();

        public IServiceResolverScope CreateScope() => new MicrosoftServiceResolverScope(serviceScope.ServiceProvider);

        public void Dispose() => serviceScope?.Dispose();

        public TService Resolve<TService>() where TService : class => serviceScope.ServiceProvider.GetService<TService>()!;
    }

    private class ImplementationFactoryAdapter<T>
    {
        private readonly Func<IServiceResolver, object> implementationFactory;

        public ImplementationFactoryAdapter(Func<IServiceResolver, object> implementationFactory) => this.implementationFactory = implementationFactory;

        // ReSharper disable once UnusedMember.Local
        public T Resolve(IServiceProvider provider) => (T)implementationFactory(provider.GetService<IServiceResolver>()!);
    }
}


text:
layout: post
title:  "Récupérer l'url complète en PHP"
date:   2013-05-16
tags:
- php
description: >
  Un mini-article aujourd'hui, comme il y en aura sûrement d'autres. Ces articles concerneront de petites astuces, fonctions utilitaires dont je souhaite garder une version à portée de main, sans avoir a retourner le web et/ou mon bureau.
---

Pour la fonction du jour, elle permet tout simplement de récupérer l'url complète de la page courante en PHP. C'est une fonction dérivée de nombreuses autres trouvables facilement sur le net, qui tient compte du protocole, d'un éventuel port et des variables GET :

```php
function currentURL() {
  $protocol =
    stripos($_SERVER['SERVER_PROTOCOL'], 'https') === FALSE
    ? 'http'
    : 'https';
  $host  = $_SERVER['SERVER_NAME'];
  $port  = $_SERVER["SERVER_PORT"];
  $query = $_SERVER['REQUEST_URI'];
  return $protocol.'://'.$host.($port != 80 ? ':'.$port : '').$query;
}
```


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('boards', '0024_board_visitors'),
    ]

    operations = [
        migrations.AddField(
            model_name='board',
            name='show_on_slideshow',
            field=models.BooleanField(default=False, verbose_name='Should this board be shown on the slideshow?'),
        ),
    ]


text:
package sipparser

import (
	//"bytes"
	//"fmt"
	"unsafe"
)

type TelUriContext struct {
	exist        bool
	isDomainName bool
	desc         AbnfBuf
}

func NewTelUriContext(context *ParseContext) AbnfPtr {
	addr := context.allocator.Alloc(uint32(unsafe.Sizeof(TelUriContext{})))
	if addr == ABNF_PTR_NIL {
		return ABNF_PTR_NIL
	}
	addr.GetTelUriContext(context).Init()
	return addr
}

func (this *TelUriContext) Init() {
	this.exist = false
	this.isDomainName = false
	this.desc.Init()
}

func (this *TelUriContext) Equal(context *ParseContext, rhs *TelUriContext) bool {
	if (this.exist && !rhs.exist) || (!this.exist && rhs.exist) {
		return false
	}

	if this.exist {
		return this.desc.EqualNoCase(context, &rhs.desc)
	}

	return true
}

func (this *TelUriContext) Exist() bool  { return this.exist }
func (this *TelUriContext) SetExist()    { this.exist = true }
func (this *TelUriContext) SetNonExist() { this.exist = false }

func (this *TelUriContext) Encode(context *ParseContext, buf *AbnfByteBuffer) {
	if this.exist {
		buf.WriteString(";phone-context=")
		buf.Write(Escape(this.desc.GetAsByteSlice(context), IsTelPvalue))
	}
}

func (this *TelUriContext) String(context *ParseContext) string {
	return AbnfEncoderToString(context, this)
}

type TelUriParam struct {
	name  AbnfBuf
	value AbnfBuf
}

func NewTelUriParam(context *ParseContext) AbnfPtr {
	addr := context.allocator.Alloc(uint32(unsafe.Sizeof(TelUriParam{})))
	if addr == ABNF_PTR_NIL {
		return ABNF_PTR_NIL
	}
	addr.GetTelUriParam(context).Init()
	return addr
}

func (this *TelUriParam) Init() {
	this.name.Init()
	this.value.Init()
}

func (this *TelUriParam) Parse(context *ParseContext, src []byte, pos int) (newPos int, err error) {
	newPos, err = this.name.ParseEscapable(context, src, pos, IsTelPname)
	if err != nil {
		return newPos, err
	}

	if newPos >= len(src) {
		return newPos, nil
	}

	if src[newPos] == '=' {
		newPos, err = this.value.ParseEscapable(context, src, newPos+1, IsTelPvalue)
		if err != nil {
			return newPos, err
		}
	}
	return newPos, nil
}

func (this *TelUriParam) Encode(context *ParseContext, buf *AbnfByteBuffer) {
	buf.Write(Escape(this.name.GetAsByteSlice(context), IsTelPname))
	if this.value.Exist() {
		buf.WriteByte('=')
		buf.Write(Escape(this.value.GetAsByteSlice(context), IsTelPvalue))
	}
}

func (this *TelUriParam) String(context *ParseContext) string {
	return AbnfEncoderToString(context, this)
}

type TelUriParams struct {
	AbnfList
}

func NewTelUriParams(context *ParseContext) AbnfPtr {
	addr := context.allocator.Alloc(uint32(unsafe.Sizeof(TelUriParams{})))
	if addr == ABNF_PTR_NIL {
		return ABNF_PTR_NIL
	}

	addr.GetTelUriParams(context).Init()
	return addr
}

func (this *TelUriParams) Init() {
	this.AbnfList.Init()
}

func (this *TelUriParams) Size() int32 { return this.Len() }
func (this *TelUriParams) Empty() bool { return this.Len() == 0 }

func (this *TelUriParams) GetParam(context *ParseContext, name string) (val *TelUriParam, ok bool) {
	for e := this.Front(context); e != nil; e = e.Next(context) {
		v := e.Value.GetTelUriParam(context)
		if v.name.EqualStringNoCase(context, name) {
			return v, true
		}
	}

	return nil, false
}

func (this *TelUriParams) Equal(context *ParseContext, rhs *TelUriParams) bool {
	if this.Size() != rhs.Size() {
		return false
	}

	/* RFC3966
	 * Parameters are compared according to 'pname', regardless of the
	 * order they appeared in the URI.  If one URI has a parameter name
	 * not found in the other, the two URIs are not equal.
	 */
	for e := this.Front(context); e != nil; e = e.Next(context) {
		v := e.Value.GetTelUriParam(context)
		param, ok := rhs.GetParam(context, v.name.String(context))
		if !ok {
			return false
		}

		if !param.value.EqualNoCase(context, &v.value) {
			return false
		}
	}

	return true
}

func (this *TelUriParams) Encode(context *ParseContext, buf *AbnfByteBuffer) {
	for e := this.Front(context); e != nil; e = e.Next(context) {
		buf.WriteByte(';')
		e.Value.GetTelUriParam(context).Encode(context, buf)
	}
}

func (this *TelUriParams) String(context *ParseContext) string {
	return AbnfEncoderToString(context, this)
}


text:
from .shaders import ShaderProgram
from .behaviors.ball import Ball
from .behaviors.ball_movement import BallMovement
from .collisions import Collidables, CollidableCategories

from nytram.entity import Entity
from nytram.renderers import EntityRenderer
from nytram.ext.box2d import Body, Fixture, BodyTypes, Box, Filter
from nytram.ext.box2d.collisions import Collider, CollisionRegistration

class BallEntity:
    """ Helper to load the Ball Entity """
    renderer = None

    @classmethod
    def loadRenderer(cls):
        """ Load the renderer """
        cls.renderer = EntityRenderer(ShaderProgram, elements=[0,2,1,3,0,1], vertexData={0:[.5, .5, 0, -.5, -.5, 0, .5, -.5, 0, -.5, .5, 0]})

    @classmethod
    def build(cls, scene, position):
        """ Build the Entity """
        entity = Entity(scene, renderer=cls.renderer)
        fixture = Fixture(Box(1, 1), density=1, restitution=1, friction=0, isSensor=False, filter=Filter(categoryBits=CollidableCategories.Ball))
        entity.body = Body([fixture], bodyType=BodyTypes.Dynamic, fixedRotation=True)
        entity.transform.position = position
        entity.collider = Collider([fixture], {CollisionRegistration(Collidables.Ball, Collidables.Wall, actsAs=Collidables.Ball),
                                               CollisionRegistration(Collidables.Ball, Collidables.Goal, actsAs=Collidables.Ball)})
        entity.movement = BallMovement(5)
        entity.ball = Ball()
        return entity


text:
module SQL
  module Generator
    class Emitter
      class Literal

        # Literal integer emitter
        class Integer < self

          handle :integer

        private

          # Perform dispatch
          #
          # @return [undefined]
          #
          # @api private
          def dispatch
            write(value.to_s)
          end

        end # Integer
      end # Literal
    end # Emitter
  end # Generator
end # SQL


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

package hdfs

import (
	"context"
	"io"
	"net"
	"net/http"
	"os"
	"os/user"
	"path"
	"sort"
	"strings"
	"syscall"
	"time"

	"github.com/minio/cli"
	"github.com/minio/hdfs/v3"
	"github.com/minio/minio-go/v6/pkg/s3utils"
	minio "github.com/minio/minio/cmd"
	"github.com/minio/minio/cmd/logger"
	"github.com/minio/minio/pkg/auth"
	xnet "github.com/minio/minio/pkg/net"
)

const (
	hdfsBackend = "hdfs"

	hdfsSeparator = "/"
)

func init() {
	const hdfsGatewayTemplate = `NAME:
  {{.HelpName}} - {{.Usage}}

USAGE:
  {{.HelpName}} {{if .VisibleFlags}}[FLAGS]{{end}} HDFS-NAMENODE [HDFS-NAMENODE...]
{{if .VisibleFlags}}
FLAGS:
  {{range .VisibleFlags}}{{.}}
  {{end}}{{end}}
HDFS-NAMENODE:
  HDFS namenode URI

ENVIRONMENT VARIABLES:
  ACCESS:
     MINIO_ACCESS_KEY: Username or access key of minimum 3 characters in length.
     MINIO_SECRET_KEY: Password or secret key of minimum 8 characters in length.

  BROWSER:
     MINIO_BROWSER: To disable web browser access, set this value to "off".

  DOMAIN:
     MINIO_DOMAIN: To enable virtual-host-style requests, set this value to Minio host domain name.

  CACHE:
     MINIO_CACHE_DRIVES: List of mounted drives or directories delimited by ";".
     MINIO_CACHE_EXCLUDE: List of cache exclusion patterns delimited by ";".
     MINIO_CACHE_EXPIRY: Cache expiry duration in days.
     MINIO_CACHE_MAXUSE: Maximum permitted usage of the cache in percentage (0-100).

EXAMPLES:
  1. Start minio gateway server for HDFS backend.
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_ACCESS_KEY{{.AssignmentOperator}}accesskey
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_SECRET_KEY{{.AssignmentOperator}}secretkey
     {{.Prompt}} {{.HelpName}} hdfs://namenode:8200

  2. Start minio gateway server for HDFS with edge caching enabled.
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_ACCESS_KEY{{.AssignmentOperator}}accesskey
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_SECRET_KEY{{.AssignmentOperator}}secretkey
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_DRIVES{{.AssignmentOperator}}"/mnt/drive1;/mnt/drive2;/mnt/drive3;/mnt/drive4"
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_EXCLUDE{{.AssignmentOperator}}"bucket1/*;*.png"
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_EXPIRY{{.AssignmentOperator}}40
     {{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_MAXUSE{{.AssignmentOperator}}80
     {{.Prompt}} {{.HelpName}} hdfs://namenode:8200
`

	minio.RegisterGatewayCommand(cli.Command{
		Name:               hdfsBackend,
		Usage:              "Hadoop Distributed File System (HDFS)",
		Action:             hdfsGatewayMain,
		CustomHelpTemplate: hdfsGatewayTemplate,
		HideHelpCommand:    true,
	})
}

// Handler for 'minio gateway hdfs' command line.
func hdfsGatewayMain(ctx *cli.Context) {
	// Validate gateway arguments.
	if !ctx.Args().Present() || ctx.Args().First() == "help" {
		cli.ShowCommandHelpAndExit(ctx, hdfsBackend, 1)
	}

	minio.StartGateway(ctx, &HDFS{args: ctx.Args()})
}

// HDFS implements Gateway.
type HDFS struct {
	args []string
}

// Name implements Gateway interface.
func (g *HDFS) Name() string {
	return hdfsBackend
}

// NewGatewayLayer returns hdfs gatewaylayer.
func (g *HDFS) NewGatewayLayer(creds auth.Credentials) (minio.ObjectLayer, error) {
	dialFunc := (&net.Dialer{
		Timeout:   30 * time.Second,
		KeepAlive: 30 * time.Second,
		DualStack: true,
	}).DialContext

	var addresses []string
	for _, s := range g.args {
		u, err := xnet.ParseURL(s)
		if err != nil {
			return nil, err
		}
		addresses = append(addresses, u.Host)
	}

	user, err := user.Current()
	if err != nil {
		return nil, err
	}

	opts := hdfs.ClientOptions{
		Addresses:        addresses,
		User:             user.Username,
		NamenodeDialFunc: dialFunc,
		DatanodeDialFunc: dialFunc,
	}

	clnt, err := hdfs.NewClient(opts)
	if err != nil {
		return nil, err
	}

	if err = clnt.MkdirAll(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket), os.FileMode(0755)); err != nil {
		return nil, err
	}

	return &hdfsObjects{clnt: clnt, listPool: minio.NewTreeWalkPool(time.Minute * 30)}, nil
}

// Production - hdfs gateway is production ready.
func (g *HDFS) Production() bool {
	return false
}

func (n *hdfsObjects) Shutdown(ctx context.Context) error {
	return n.clnt.Close()
}

func (n *hdfsObjects) StorageInfo(ctx context.Context) minio.StorageInfo {
	fsInfo, err := n.clnt.StatFs()
	if err != nil {
		return minio.StorageInfo{}
	}
	sinfo := minio.StorageInfo{}
	sinfo.Used = fsInfo.Used
	sinfo.Backend.Type = minio.Unknown
	return sinfo
}

// hdfsObjects implements gateway for Minio and S3 compatible object storage servers.
type hdfsObjects struct {
	minio.GatewayUnsupported
	clnt     *hdfs.Client
	listPool *minio.TreeWalkPool
}

func hdfsToObjectErr(ctx context.Context, err error, params ...string) error {
	if err == nil {
		return nil
	}
	bucket := ""
	object := ""
	uploadID := ""
	switch len(params) {
	case 3:
		uploadID = params[2]
		fallthrough
	case 2:
		object = params[1]
		fallthrough
	case 1:
		bucket = params[0]
	}

	switch {
	case os.IsNotExist(err):
		if uploadID != "" {
			return minio.InvalidUploadID{
				UploadID: uploadID,
			}
		}
		if object != "" {
			return minio.ObjectNotFound{Bucket: bucket, Object: object}
		}
		return minio.BucketNotFound{Bucket: bucket}
	case os.IsExist(err):
		if object != "" {
			return minio.PrefixAccessDenied{Bucket: bucket, Object: object}
		}
		return minio.BucketAlreadyOwnedByYou{Bucket: bucket}
	case isSysErrNotEmpty(err):
		if object != "" {
			return minio.PrefixAccessDenied{Bucket: bucket, Object: object}
		}
		return minio.BucketNotEmpty{Bucket: bucket}
	default:
		logger.LogIf(ctx, err)
		return err
	}
}

// hdfsIsValidBucketName verifies whether a bucket name is valid.
func hdfsIsValidBucketName(bucket string) bool {
	return s3utils.CheckValidBucketNameStrict(bucket) == nil
}

func (n *hdfsObjects) DeleteBucket(ctx context.Context, bucket string) error {
	if !hdfsIsValidBucketName(bucket) {
		return minio.BucketNameInvalid{Bucket: bucket}
	}
	return hdfsToObjectErr(ctx, n.clnt.Remove(minio.PathJoin(hdfsSeparator, bucket)), bucket)
}

func (n *hdfsObjects) MakeBucketWithLocation(ctx context.Context, bucket, location string) error {
	if !hdfsIsValidBucketName(bucket) {
		return minio.BucketNameInvalid{Bucket: bucket}
	}
	return hdfsToObjectErr(ctx, n.clnt.Mkdir(minio.PathJoin(hdfsSeparator, bucket), os.FileMode(0755)), bucket)
}

func (n *hdfsObjects) GetBucketInfo(ctx context.Context, bucket string) (bi minio.BucketInfo, err error) {
	fi, err := n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return bi, hdfsToObjectErr(ctx, err, bucket)
	}
	// As hdfs.Stat() doesn't carry anything other than ModTime(), use ModTime() as CreatedTime.
	return minio.BucketInfo{
		Name:    bucket,
		Created: fi.ModTime(),
	}, nil
}

func (n *hdfsObjects) ListBuckets(ctx context.Context) (buckets []minio.BucketInfo, err error) {
	entries, err := n.clnt.ReadDir(hdfsSeparator)
	if err != nil {
		logger.LogIf(ctx, err)
		return nil, hdfsToObjectErr(ctx, err)
	}

	for _, entry := range entries {
		// Ignore all reserved bucket names and invalid bucket names.
		if isReservedOrInvalidBucket(entry.Name(), false) {
			continue
		}
		buckets = append(buckets, minio.BucketInfo{
			Name: entry.Name(),
			// As hdfs.Stat() doesnt carry CreatedTime, use ModTime() as CreatedTime.
			Created: entry.ModTime(),
		})
	}

	// Sort bucket infos by bucket name.
	sort.Sort(byBucketName(buckets))
	return buckets, nil
}

func (n *hdfsObjects) listDirFactory() minio.ListDirFunc {
	// listDir - lists all the entries at a given prefix and given entry in the prefix.
	listDir := func(bucket, prefixDir, prefixEntry string) (entries []string) {
		f, err := n.clnt.Open(minio.PathJoin(hdfsSeparator, bucket, prefixDir))
		if err != nil {
			if os.IsNotExist(err) {
				err = nil
			}
			logger.LogIf(context.Background(), err)
			return
		}
		defer f.Close()
		fis, err := f.Readdir(0)
		if err != nil {
			logger.LogIf(context.Background(), err)
			return
		}
		for _, fi := range fis {
			if fi.IsDir() {
				entries = append(entries, fi.Name()+hdfsSeparator)
			} else {
				entries = append(entries, fi.Name())
			}
		}
		fis = nil
		return minio.FilterMatchingPrefix(entries, prefixEntry)
	}

	// Return list factory instance.
	return listDir
}

// ListObjects lists all blobs in HDFS bucket filtered by prefix.
func (n *hdfsObjects) ListObjects(ctx context.Context, bucket, prefix, marker, delimiter string, maxKeys int) (loi minio.ListObjectsInfo, err error) {
	getObjectInfo := func(ctx context.Context, bucket, entry string) (minio.ObjectInfo, error) {
		return n.GetObjectInfo(ctx, bucket, entry, minio.ObjectOptions{})
	}

	return minio.ListObjects(ctx, n, bucket, prefix, marker, delimiter, maxKeys, n.listPool, n.listDirFactory(), getObjectInfo, getObjectInfo)
}

// Check if the given error corresponds to ENOTEMPTY for unix
// and ERROR_DIR_NOT_EMPTY for windows (directory not empty).
func isSysErrNotEmpty(err error) bool {
	if err == syscall.ENOTEMPTY {
		return true
	}
	if pathErr, ok := err.(*os.PathError); ok {
		if pathErr.Err == syscall.ENOTEMPTY {
			return true
		}
	}
	return false
}

// deleteObject deletes a file path if its empty. If it's successfully deleted,
// it will recursively move up the tree, deleting empty parent directories
// until it finds one with files in it. Returns nil for a non-empty directory.
func (n *hdfsObjects) deleteObject(basePath, deletePath string) error {
	if basePath == deletePath {
		return nil
	}

	// Attempt to remove path.
	if err := n.clnt.Remove(deletePath); err != nil {
		switch {
		case err == syscall.ENOTEMPTY:
		case isSysErrNotEmpty(err):
			// Ignore errors if the directory is not empty. The server relies on
			// this functionality, and sometimes uses recursion that should not
			// error on parent directories.
			return nil
		default:
			return err
		}
	}

	// Trailing slash is removed when found to ensure
	// slashpath.Dir() to work as intended.
	deletePath = strings.TrimSuffix(deletePath, hdfsSeparator)
	deletePath = path.Dir(deletePath)

	// Delete parent directory. Errors for parent directories shouldn't trickle down.
	n.deleteObject(basePath, deletePath)

	return nil
}

// ListObjectsV2 lists all blobs in HDFS bucket filtered by prefix
func (n *hdfsObjects) ListObjectsV2(ctx context.Context, bucket, prefix, continuationToken, delimiter string, maxKeys int,
	fetchOwner bool, startAfter string) (loi minio.ListObjectsV2Info, err error) {
	// fetchOwner is not supported and unused.
	marker := continuationToken
	if marker == "" {
		marker = startAfter
	}
	resultV1, err := n.ListObjects(ctx, bucket, prefix, marker, delimiter, maxKeys)
	if err != nil {
		return loi, err
	}
	return minio.ListObjectsV2Info{
		Objects:               resultV1.Objects,
		Prefixes:              resultV1.Prefixes,
		ContinuationToken:     continuationToken,
		NextContinuationToken: resultV1.NextMarker,
		IsTruncated:           resultV1.IsTruncated,
	}, nil
}

func (n *hdfsObjects) DeleteObject(ctx context.Context, bucket, object string) error {
	return hdfsToObjectErr(ctx, n.deleteObject(minio.PathJoin(hdfsSeparator, bucket), minio.PathJoin(hdfsSeparator, bucket, object)), bucket, object)
}

func (n *hdfsObjects) DeleteObjects(ctx context.Context, bucket string, objects []string) ([]error, error) {
	errs := make([]error, len(objects))
	for idx, object := range objects {
		errs[idx] = n.DeleteObject(ctx, bucket, object)
	}
	return errs, nil
}

func (n *hdfsObjects) GetObjectNInfo(ctx context.Context, bucket, object string, rs *minio.HTTPRangeSpec, h http.Header, lockType minio.LockType, opts minio.ObjectOptions) (gr *minio.GetObjectReader, err error) {
	objInfo, err := n.GetObjectInfo(ctx, bucket, object, opts)
	if err != nil {
		return nil, err
	}

	var startOffset, length int64
	startOffset, length, err = rs.GetOffsetLength(objInfo.Size)
	if err != nil {
		return nil, err
	}

	pr, pw := io.Pipe()
	go func() {
		nerr := n.GetObject(ctx, bucket, object, startOffset, length, pw, objInfo.ETag, opts)
		pw.CloseWithError(nerr)
	}()

	// Setup cleanup function to cause the above go-routine to
	// exit in case of partial read
	pipeCloser := func() { pr.Close() }
	return minio.NewGetObjectReaderFromReader(pr, objInfo, opts.CheckCopyPrecondFn, pipeCloser)

}

func (n *hdfsObjects) CopyObject(ctx context.Context, srcBucket, srcObject, dstBucket, dstObject string, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (minio.ObjectInfo, error) {
	cpSrcDstSame := minio.IsStringEqual(minio.PathJoin(hdfsSeparator, srcBucket, srcObject), minio.PathJoin(hdfsSeparator, dstBucket, dstObject))
	if cpSrcDstSame {
		return n.GetObjectInfo(ctx, srcBucket, srcObject, minio.ObjectOptions{})
	}

	return n.PutObject(ctx, dstBucket, dstObject, srcInfo.PutObjReader, minio.ObjectOptions{
		ServerSideEncryption: dstOpts.ServerSideEncryption,
		UserDefined:          srcInfo.UserDefined,
	})
}

func (n *hdfsObjects) GetObject(ctx context.Context, bucket, key string, startOffset, length int64, writer io.Writer, etag string, opts minio.ObjectOptions) error {
	if _, err := n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket)); err != nil {
		return hdfsToObjectErr(ctx, err, bucket)
	}
	rd, err := n.clnt.Open(minio.PathJoin(hdfsSeparator, bucket, key))
	if err != nil {
		return hdfsToObjectErr(ctx, err, bucket, key)
	}
	defer rd.Close()
	_, err = io.Copy(writer, io.NewSectionReader(rd, startOffset, length))
	if err == io.ErrClosedPipe {
		// hdfs library doesn't send EOF correctly, so io.Copy attempts
		// to write which returns io.ErrClosedPipe - just ignore
		// this for now.
		err = nil
	}
	return hdfsToObjectErr(ctx, err, bucket, key)
}

// GetObjectInfo reads object info and replies back ObjectInfo.
func (n *hdfsObjects) GetObjectInfo(ctx context.Context, bucket, object string, opts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket)
	}
	fi, err := n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket, object))
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
	}
	return minio.ObjectInfo{
		Bucket:  bucket,
		Name:    object,
		ModTime: fi.ModTime(),
		Size:    fi.Size(),
		IsDir:   fi.IsDir(),
		AccTime: fi.(*hdfs.FileInfo).AccessTime(),
	}, nil
}

func (n *hdfsObjects) PutObject(ctx context.Context, bucket string, object string, r *minio.PutObjReader, opts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket)
	}

	name := minio.PathJoin(hdfsSeparator, bucket, object)

	// If its a directory create a prefix {
	if strings.HasSuffix(object, hdfsSeparator) {
		if err = n.clnt.MkdirAll(name, os.FileMode(0755)); err != nil {
			n.deleteObject(minio.PathJoin(hdfsSeparator, bucket), name)
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
	} else {
		tmpname := minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, minio.MustGetUUID())
		var w *hdfs.FileWriter
		w, err = n.clnt.Create(tmpname)
		if err != nil {
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
		defer n.deleteObject(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket), tmpname)
		if _, err = io.Copy(w, r); err != nil {
			w.Close()
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
		dir := path.Dir(name)
		if dir != "" {
			if err = n.clnt.MkdirAll(dir, os.FileMode(0755)); err != nil {
				w.Close()
				n.deleteObject(minio.PathJoin(hdfsSeparator, bucket), dir)
				return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
			}
		}
		w.Close()
		if err = n.clnt.Rename(tmpname, name); err != nil {
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
	}
	fi, err := n.clnt.Stat(name)
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
	}
	return minio.ObjectInfo{
		Bucket:  bucket,
		Name:    object,
		ETag:    r.MD5CurrentHexString(),
		ModTime: fi.ModTime(),
		Size:    fi.Size(),
		IsDir:   fi.IsDir(),
		AccTime: fi.(*hdfs.FileInfo).AccessTime(),
	}, nil
}

func (n *hdfsObjects) NewMultipartUpload(ctx context.Context, bucket string, object string, opts minio.ObjectOptions) (uploadID string, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return uploadID, hdfsToObjectErr(ctx, err, bucket)
	}

	uploadID = minio.MustGetUUID()
	if err = n.clnt.CreateEmptyFile(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID)); err != nil {
		return uploadID, hdfsToObjectErr(ctx, err, bucket)
	}

	return uploadID, nil
}

func (n *hdfsObjects) ListMultipartUploads(ctx context.Context, bucket string, prefix string, keyMarker string, uploadIDMarker string, delimiter string, maxUploads int) (lmi minio.ListMultipartsInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return lmi, hdfsToObjectErr(ctx, err, bucket)
	}

	// It's decided not to support List Multipart Uploads, hence returning empty result.
	return lmi, nil
}

func (n *hdfsObjects) checkUploadIDExists(ctx context.Context, bucket, object, uploadID string) (err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID))
	if err != nil {
		return hdfsToObjectErr(ctx, err, bucket, object, uploadID)
	}
	return nil
}

func (n *hdfsObjects) ListObjectParts(ctx context.Context, bucket, object, uploadID string, partNumberMarker int, maxParts int, opts minio.ObjectOptions) (result minio.ListPartsInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return result, hdfsToObjectErr(ctx, err, bucket)
	}

	if err = n.checkUploadIDExists(ctx, bucket, object, uploadID); err != nil {
		return result, err
	}

	// It's decided not to support List parts, hence returning empty result.
	return result, nil
}

func (n *hdfsObjects) CopyObjectPart(ctx context.Context, srcBucket, srcObject, dstBucket, dstObject, uploadID string, partID int,
	startOffset int64, length int64, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (minio.PartInfo, error) {
	return n.PutObjectPart(ctx, dstBucket, dstObject, uploadID, partID, srcInfo.PutObjReader, dstOpts)
}

func (n *hdfsObjects) PutObjectPart(ctx context.Context, bucket, object, uploadID string, partID int, r *minio.PutObjReader, opts minio.ObjectOptions) (info minio.PartInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return info, hdfsToObjectErr(ctx, err, bucket)
	}

	var w *hdfs.FileWriter
	w, err = n.clnt.Append(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID))
	if err != nil {
		return info, hdfsToObjectErr(ctx, err, bucket, object, uploadID)
	}
	defer w.Close()
	_, err = io.Copy(w, r.Reader)
	if err != nil {
		return info, hdfsToObjectErr(ctx, err, bucket, object, uploadID)
	}

	info.PartNumber = partID
	info.ETag = r.MD5CurrentHexString()
	info.LastModified = minio.UTCNow()
	info.Size = r.Reader.Size()

	return info, nil
}

func (n *hdfsObjects) CompleteMultipartUpload(ctx context.Context, bucket, object, uploadID string, parts []minio.CompletePart, opts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket)
	}

	if err = n.checkUploadIDExists(ctx, bucket, object, uploadID); err != nil {
		return objInfo, err
	}

	name := minio.PathJoin(hdfsSeparator, bucket, object)
	dir := path.Dir(name)
	if dir != "" {
		if err = n.clnt.MkdirAll(dir, os.FileMode(0755)); err != nil {
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
	}

	err = n.clnt.Rename(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID), name)
	// Object already exists is an error on HDFS
	// remove it and then create it again.
	if os.IsExist(err) {
		if err = n.clnt.Remove(name); err != nil {
			if dir != "" {
				n.deleteObject(minio.PathJoin(hdfsSeparator, bucket), dir)
			}
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
		if err = n.clnt.Rename(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID), name); err != nil {
			if dir != "" {
				n.deleteObject(minio.PathJoin(hdfsSeparator, bucket), dir)
			}
			return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
		}
	}
	fi, err := n.clnt.Stat(name)
	if err != nil {
		return objInfo, hdfsToObjectErr(ctx, err, bucket, object)
	}

	// Calculate s3 compatible md5sum for complete multipart.
	s3MD5 := minio.ComputeCompleteMultipartMD5(parts)

	return minio.ObjectInfo{
		Bucket:  bucket,
		Name:    object,
		ETag:    s3MD5,
		ModTime: fi.ModTime(),
		Size:    fi.Size(),
		IsDir:   fi.IsDir(),
		AccTime: fi.(*hdfs.FileInfo).AccessTime(),
	}, nil
}

func (n *hdfsObjects) AbortMultipartUpload(ctx context.Context, bucket, object, uploadID string) (err error) {
	_, err = n.clnt.Stat(minio.PathJoin(hdfsSeparator, bucket))
	if err != nil {
		return hdfsToObjectErr(ctx, err, bucket)
	}
	return hdfsToObjectErr(ctx, n.clnt.Remove(minio.PathJoin(hdfsSeparator, minioMetaTmpBucket, uploadID)), bucket, object, uploadID)
}


text:
#include <linux/platform_device.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>

int snd_soc_calc_frame_size(int sample_size, int channels, int tdm_slots)
{
	return sample_size * channels * tdm_slots;
}
EXPORT_SYMBOL_GPL(snd_soc_calc_frame_size);

int snd_soc_params_to_frame_size(struct snd_pcm_hw_params *params)
{
	int sample_size;

	sample_size = snd_pcm_format_width(params_format(params));
	if (sample_size < 0)
		return sample_size;

	return snd_soc_calc_frame_size(sample_size, params_channels(params),
				       1);
}
EXPORT_SYMBOL_GPL(snd_soc_params_to_frame_size);

int snd_soc_calc_bclk(int fs, int sample_size, int channels, int tdm_slots)
{
	return fs * snd_soc_calc_frame_size(sample_size, channels, tdm_slots);
}
EXPORT_SYMBOL_GPL(snd_soc_calc_bclk);

int snd_soc_params_to_bclk(struct snd_pcm_hw_params *params)
{
	int ret;

	ret = snd_soc_params_to_frame_size(params);

	if (ret > 0)
		return ret * params_rate(params);
	else
		return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_params_to_bclk);

static const struct snd_pcm_hardware dummy_dma_hardware = {
	.formats		= 0xffffffff,
	.channels_min		= 1,
	.channels_max		= UINT_MAX,

	/* Random values to keep userspace happy when checking constraints */
	.info			= SNDRV_PCM_INFO_INTERLEAVED |
				  SNDRV_PCM_INFO_BLOCK_TRANSFER,
	.buffer_bytes_max	= 128*1024,
	.period_bytes_min	= PAGE_SIZE,
	.period_bytes_max	= PAGE_SIZE*2,
	.periods_min		= 2,
	.periods_max		= 128,
};

static int dummy_dma_open(struct snd_pcm_substream *substream)
{
	snd_soc_set_runtime_hwparams(substream, &dummy_dma_hardware);

	return 0;
}

static struct snd_pcm_ops dummy_dma_ops = {
	.open		= dummy_dma_open,
	.ioctl		= snd_pcm_lib_ioctl,
};

static struct snd_soc_platform_driver dummy_platform = {
	.ops = &dummy_dma_ops,
};

static struct snd_soc_codec_driver dummy_codec;

#define STUB_RATES	SNDRV_PCM_RATE_8000_192000
#define STUB_FORMATS	(SNDRV_PCM_FMTBIT_S8 | \
			SNDRV_PCM_FMTBIT_U8 | \
			SNDRV_PCM_FMTBIT_S16_LE | \
			SNDRV_PCM_FMTBIT_U16_LE | \
			SNDRV_PCM_FMTBIT_S24_LE | \
			SNDRV_PCM_FMTBIT_U24_LE | \
			SNDRV_PCM_FMTBIT_S32_LE | \
			SNDRV_PCM_FMTBIT_U32_LE | \
			SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE)
static struct snd_soc_dai_driver dummy_dai = {
	.name = "snd-soc-dummy-dai",
	.playback = {
		.stream_name	= "Playback",
		.channels_min	= 1,
		.channels_max	= 384,
		.rates		= STUB_RATES,
		.formats	= STUB_FORMATS,
	},
	.capture = {
		.stream_name	= "Capture",
		.channels_min	= 1,
		.channels_max	= 384,
		.rates = STUB_RATES,
		.formats = STUB_FORMATS,
	 },
};

static int snd_soc_dummy_probe(struct platform_device *pdev)
{
	int ret;

	ret = snd_soc_register_codec(&pdev->dev, &dummy_codec, &dummy_dai, 1);
	if (ret < 0)
		return ret;

	ret = snd_soc_register_platform(&pdev->dev, &dummy_platform);
	if (ret < 0) {
		snd_soc_unregister_codec(&pdev->dev);
		return ret;
	}

	return ret;
}

static int snd_soc_dummy_remove(struct platform_device *pdev)
{
	snd_soc_unregister_platform(&pdev->dev);
	snd_soc_unregister_codec(&pdev->dev);

	return 0;
}

static struct platform_driver soc_dummy_driver = {
	.driver = {
		.name = "snd-soc-dummy",
		.owner = THIS_MODULE,
	},
	.probe = snd_soc_dummy_probe,
	.remove = snd_soc_dummy_remove,
};

static struct platform_device *soc_dummy_dev;

int __init snd_soc_util_init(void)
{
	int ret;

	soc_dummy_dev = platform_device_alloc("snd-soc-dummy", -1);
	if (!soc_dummy_dev)
		return -ENOMEM;

	ret = platform_device_add(soc_dummy_dev);
	if (ret != 0) {
		platform_device_put(soc_dummy_dev);
		return ret;
	}

	ret = platform_driver_register(&soc_dummy_driver);
	if (ret != 0)
		platform_device_unregister(soc_dummy_dev);

	return ret;
}

void __exit snd_soc_util_exit(void)
{
	platform_device_unregister(soc_dummy_dev);
	platform_driver_unregister(&soc_dummy_driver);
}


text:
using System.Data.Entity;
using System.Linq;

namespace Journey.Utils
{
    /// <summary>
    /// Usability extensions for DbContexts.
    /// </summary>
    public static class DbContextExtensions
    {
        public static void AddToUnityOfWork<T>(this DbContext context, T entity) where T : class
        {
            var entry = context.Entry(entity);

            if (entry.State == EntityState.Detached)
                context.Set<T>().Add(entity);
        }

        public static IQueryable<T> Query<T>(this DbContext context) where T : class
        {
            return context.Set<T>();
        }
    }
}


text:
package org.apache.catalina.tribes.transport.bio;

import org.apache.catalina.tribes.transport.DataSender;
import org.apache.catalina.tribes.transport.PooledSender;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.ChannelException;
import org.apache.catalina.tribes.transport.MultiPointSender;
import org.apache.catalina.tribes.ChannelMessage;

public class PooledMultiSender extends PooledSender {

    public PooledMultiSender() {
    }

    public void sendMessage(Member[] destination, ChannelMessage msg) throws ChannelException {
        MultiPointSender sender = null;
        try {
            sender = (MultiPointSender)getSender();
            if (sender == null) {
                ChannelException cx = new ChannelException("Unable to retrieve a data sender, time out error.");
                for (int i = 0; i < destination.length; i++) cx.addFaultyMember(destination[i], new NullPointerException("Unable to retrieve a sender from the sender pool"));
                throw cx;
            } else {
                sender.sendMessage(destination, msg);
            }
            sender.keepalive();
        }finally {
            if ( sender != null ) returnSender(sender);
        }
    }

    public DataSender getNewDataSender() {
        MultipointBioSender sender = new MultipointBioSender();
        sender.transferProperties(this,sender);
        return sender;
    }
}


text:
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/if_team.h>

static bool bc_transmit(struct team *team, struct sk_buff *skb)
{
	struct team_port *cur;
	struct team_port *last = NULL;
	struct sk_buff *skb2;
	bool ret;
	bool sum_ret = false;

	list_for_each_entry_rcu(cur, &team->port_list, list) {
		if (team_port_txable(cur)) {
			if (last) {
				skb2 = skb_clone(skb, GFP_ATOMIC);
				if (skb2) {
					ret = !team_dev_queue_xmit(team, last,
								   skb2);
					if (!sum_ret)
						sum_ret = ret;
				}
			}
			last = cur;
		}
	}
	if (last) {
		ret = !team_dev_queue_xmit(team, last, skb);
		if (!sum_ret)
			sum_ret = ret;
	}
	return sum_ret;
}

static const struct team_mode_ops bc_mode_ops = {
	.transmit		= bc_transmit,
	.port_enter		= team_modeop_port_enter,
	.port_change_dev_addr	= team_modeop_port_change_dev_addr,
};

static const struct team_mode bc_mode = {
	.kind		= "broadcast",
	.owner		= THIS_MODULE,
	.ops		= &bc_mode_ops,
	.lag_tx_type	= NETDEV_LAG_TX_TYPE_BROADCAST,
};

static int __init bc_init_module(void)
{
	return team_mode_register(&bc_mode);
}

static void __exit bc_cleanup_module(void)
{
	team_mode_unregister(&bc_mode);
}

module_init(bc_init_module);
module_exit(bc_cleanup_module);

MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Jiri Pirko <jpirko@redhat.com>");
MODULE_DESCRIPTION("Broadcast mode for team");
MODULE_ALIAS("team-mode-broadcast");


text:
class Profile;

namespace content {
class NavigationEntry;
}

namespace browser_sync {

// A SyncedTabDelegate is used to insulate the sync code from depending
// directly on WebContents, TabContents and NavigationController.
class SyncedTabDelegate {
 public:
  virtual ~SyncedTabDelegate() {}

  // Method from TabContents.

  virtual SessionID::id_type GetWindowId() const = 0;
  virtual SessionID::id_type GetSessionId() const = 0;
  virtual bool IsBeingDestroyed() const = 0;
  virtual Profile* profile() const = 0;

  // Method derived from TabContents.

  virtual bool HasExtensionAppId() const = 0;
  virtual const std::string& GetExtensionAppId() const = 0;

  // Method from NavigationController

  virtual int GetCurrentEntryIndex() const = 0;
  virtual int GetEntryCount() const = 0;
  virtual int GetPendingEntryIndex() const = 0;
  virtual content::NavigationEntry* GetPendingEntry() const = 0;
  virtual content::NavigationEntry* GetEntryAtIndex(int i) const = 0;
  virtual content::NavigationEntry* GetActiveEntry() const = 0;
};

}  // namespace browser_sync

#endif  // CHROME_BROWSER_SYNC_GLUE_SYNCED_TAB_DELEGATE_H__


text:
value hx_PhysicsVehicleWheel_getFrictionBreakout(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getFrictionBreakout());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getFrictionBreakout, 1);

// DECL: float getRollInfluence() const;
value hx_PhysicsVehicleWheel_getRollInfluence(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getRollInfluence());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getRollInfluence, 1);

// DECL: void getStrutConnectionOffset(Vector3* strutConnectionOffset) const;
void hx_PhysicsVehicleWheel_getStrutConnectionOffset(value thisObj, value strutConnectionOffset)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_strutConnectionOffset;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(strutConnectionOffset, _strutConnectionOffset);
    _thisObj->getStrutConnectionOffset(_strutConnectionOffset);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutConnectionOffset, 2);

// DECL: float getStrutDampingCompression() const;
value hx_PhysicsVehicleWheel_getStrutDampingCompression(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutDampingCompression());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutDampingCompression, 1);

// DECL: float getStrutDampingRelaxation() const;
value hx_PhysicsVehicleWheel_getStrutDampingRelaxation(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutDampingRelaxation());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutDampingRelaxation, 1);

// DECL: float getStrutForceMax() const;
value hx_PhysicsVehicleWheel_getStrutForceMax(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutForceMax());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutForceMax, 1);

// DECL: float getStrutRestLength() const;
value hx_PhysicsVehicleWheel_getStrutRestLength(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutRestLength());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutRestLength, 1);

// DECL: float getStrutStiffness() const;
value hx_PhysicsVehicleWheel_getStrutStiffness(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutStiffness());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutStiffness, 1);

// DECL: float getStrutTravelMax() const;
value hx_PhysicsVehicleWheel_getStrutTravelMax(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getStrutTravelMax());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getStrutTravelMax, 1);

// DECL: PhysicsCollisionObject::Type getType() const;
value hx_PhysicsVehicleWheel_getType(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return EnumToValue(_thisObj->getType());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getType, 1);

// DECL: void getWheelAxle(Vector3* wheelAxle) const;
void hx_PhysicsVehicleWheel_getWheelAxle(value thisObj, value wheelAxle)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_wheelAxle;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(wheelAxle, _wheelAxle);
    _thisObj->getWheelAxle(_wheelAxle);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getWheelAxle, 2);

// DECL: void getWheelDirection(Vector3* wheelDirection) const;
void hx_PhysicsVehicleWheel_getWheelDirection(value thisObj, value wheelDirection)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_wheelDirection;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(wheelDirection, _wheelDirection);
    _thisObj->getWheelDirection(_wheelDirection);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getWheelDirection, 2);

// DECL: float getWheelRadius() const;
value hx_PhysicsVehicleWheel_getWheelRadius(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_float(_thisObj->getWheelRadius());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_getWheelRadius, 1);

// DECL: bool isSteerable() const;
value hx_PhysicsVehicleWheel_isSteerable(value thisObj)
{
    PhysicsVehicleWheel *_thisObj;
    ValueToObject(thisObj, _thisObj);
    return alloc_bool(_thisObj->isSteerable());
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_isSteerable, 1);

// DECL: void setEnabled(bool enable);
void hx_PhysicsVehicleWheel_setEnabled(value thisObj, value enable)
{
    PhysicsVehicleWheel *_thisObj;
    bool _enable = val_get_bool(enable);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setEnabled(_enable);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setEnabled, 2);

// DECL: void setFrictionBreakout(float frictionBreakout);
void hx_PhysicsVehicleWheel_setFrictionBreakout(value thisObj, value frictionBreakout)
{
    PhysicsVehicleWheel *_thisObj;
    float _frictionBreakout = ValueToFloat(frictionBreakout);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setFrictionBreakout(_frictionBreakout);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setFrictionBreakout, 2);

// DECL: void setRollInfluence(float rollInfluence);
void hx_PhysicsVehicleWheel_setRollInfluence(value thisObj, value rollInfluence)
{
    PhysicsVehicleWheel *_thisObj;
    float _rollInfluence = ValueToFloat(rollInfluence);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setRollInfluence(_rollInfluence);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setRollInfluence, 2);

// DECL: void setSteerable(bool steerable);
void hx_PhysicsVehicleWheel_setSteerable(value thisObj, value steerable)
{
    PhysicsVehicleWheel *_thisObj;
    bool _steerable = val_get_bool(steerable);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setSteerable(_steerable);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setSteerable, 2);

// DECL: void setStrutConnectionOffset(const Vector3& strutConnectionOffset);
void hx_PhysicsVehicleWheel_setStrutConnectionOffset(value thisObj, value strutConnectionOffset)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_strutConnectionOffset;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(strutConnectionOffset, _strutConnectionOffset);
    _thisObj->setStrutConnectionOffset(*_strutConnectionOffset);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutConnectionOffset, 2);

// DECL: void setStrutDampingCompression(float strutDampingCompression);
void hx_PhysicsVehicleWheel_setStrutDampingCompression(value thisObj, value strutDampingCompression)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutDampingCompression = ValueToFloat(strutDampingCompression);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutDampingCompression(_strutDampingCompression);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutDampingCompression, 2);

// DECL: void setStrutDampingRelaxation(float strutDampingRelaxation);
void hx_PhysicsVehicleWheel_setStrutDampingRelaxation(value thisObj, value strutDampingRelaxation)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutDampingRelaxation = ValueToFloat(strutDampingRelaxation);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutDampingRelaxation(_strutDampingRelaxation);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutDampingRelaxation, 2);

// DECL: void setStrutForceMax(float strutForceMax);
void hx_PhysicsVehicleWheel_setStrutForceMax(value thisObj, value strutForceMax)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutForceMax = ValueToFloat(strutForceMax);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutForceMax(_strutForceMax);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutForceMax, 2);

// DECL: void setStrutRestLength(float strutRestLength);
void hx_PhysicsVehicleWheel_setStrutRestLength(value thisObj, value strutRestLength)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutRestLength = ValueToFloat(strutRestLength);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutRestLength(_strutRestLength);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutRestLength, 2);

// DECL: void setStrutStiffness(float strutStiffness);
void hx_PhysicsVehicleWheel_setStrutStiffness(value thisObj, value strutStiffness)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutStiffness = ValueToFloat(strutStiffness);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutStiffness(_strutStiffness);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutStiffness, 2);

// DECL: void setStrutTravelMax(float strutTravelMax);
void hx_PhysicsVehicleWheel_setStrutTravelMax(value thisObj, value strutTravelMax)
{
    PhysicsVehicleWheel *_thisObj;
    float _strutTravelMax = ValueToFloat(strutTravelMax);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setStrutTravelMax(_strutTravelMax);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setStrutTravelMax, 2);

// DECL: void setWheelAxle(const Vector3& wheelAxle);
void hx_PhysicsVehicleWheel_setWheelAxle(value thisObj, value wheelAxle)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_wheelAxle;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(wheelAxle, _wheelAxle);
    _thisObj->setWheelAxle(*_wheelAxle);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setWheelAxle, 2);

// DECL: void setWheelDirection(const Vector3& wheelDirection);
void hx_PhysicsVehicleWheel_setWheelDirection(value thisObj, value wheelDirection)
{
    PhysicsVehicleWheel *_thisObj;
    Vector3 *_wheelDirection;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(wheelDirection, _wheelDirection);
    _thisObj->setWheelDirection(*_wheelDirection);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setWheelDirection, 2);

// DECL: void setWheelRadius(float wheelRadius);
void hx_PhysicsVehicleWheel_setWheelRadius(value thisObj, value wheelRadius)
{
    PhysicsVehicleWheel *_thisObj;
    float _wheelRadius = ValueToFloat(wheelRadius);
    ValueToObject(thisObj, _thisObj);
    _thisObj->setWheelRadius(_wheelRadius);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_setWheelRadius, 2);

// DECL: void transform(Node* node) const;
void hx_PhysicsVehicleWheel_transform(value thisObj, value node)
{
    PhysicsVehicleWheel *_thisObj;
    Node *_node;
    ValueToObject(thisObj, _thisObj);
    ValueToObject(node, _node);
    _thisObj->transform(_node);
}
DEFINE_PRIM(hx_PhysicsVehicleWheel_transform, 2);

// END
//


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>lichess - maintenance</title>

    <meta content="noindex, nofollow" name="robots">

lichess.org is down for maintenance
We expect to be back very soon. Thanks for your patience.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!-- Theme  -->
	<style name="Common_Theme" parent="android:Theme">
		<item name="android:windowNoTitle">true</item>
		<item name="android:typeface">sans</item>
	</style>
</resources>


text:
tinyMCELang['lang_insert_attachment_target_same'] = 'Open in this window / frame';
tinyMCELang['lang_insert_attachment_target_parent'] = 'Open in parent window / frame';
tinyMCELang['lang_insert_attachment_target_top'] = 'Open in top frame (replaces all frames)';
tinyMCELang['lang_insert_attachment_target_blank'] = 'Open in new window';
tinyMCELang['lang_insert_attachment_target_named'] = 'Open in the window';
tinyMCELang['lang_insert_attachment_popup'] = 'JS-Popup';
tinyMCELang['lang_insert_attachment_popup_url'] = 'Popup URL';
tinyMCELang['lang_insert_attachment_popup_name'] = 'Window name';
tinyMCELang['lang_insert_attachment_popup_return'] = 'insert \'return false\'';
tinyMCELang['lang_insert_attachment_popup_scrollbars'] = 'Show scrollbars';
tinyMCELang['lang_insert_attachment_popup_statusbar'] = 'Show statusbar';
tinyMCELang['lang_insert_attachment_popup_toolbar'] = 'Show toolbars';
tinyMCELang['lang_insert_attachment_popup_menubar'] = 'Show menubar';
tinyMCELang['lang_insert_attachment_popup_location'] = 'Show locationbar';
tinyMCELang['lang_insert_attachment_popup_resizable'] = 'Make window resizable';
tinyMCELang['lang_insert_attachment_popup_size'] = 'Size';
tinyMCELang['lang_insert_attachment_popup_position'] = 'Position (X/Y)';
tinyMCELang['lang_insert_attachment_popup_missingtarget'] = 'Please insert a name for the target or choose another option.';


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <meta charset="utf-8" />
    <title>Pages - Front End</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link rel="apple-touch-icon" href="pages/ico/60.png">
    <link rel="apple-touch-icon" sizes="76x76" href="pages/ico/76.png">
    <link rel="apple-touch-icon" sizes="120x120" href="pages/ico/120.png">
    <link rel="apple-touch-icon" sizes="152x152" href="pages/ico/152.png">
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta content="" name="description" />
    <meta content="" name="author" />

    <link href="assets/plugins/pace/pace-theme-flash.css" rel="stylesheet" type="text/css" />
    <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" />
    <link href="assets/plugins/swiper/css/swiper.css" rel="stylesheet" type="text/css" media="screen" />

    <link class="main-stylesheet" href="pages/css/pages.css" rel="stylesheet" type="text/css" />
    <link class="main-stylesheet" href="pages/css/pages-icons.css" rel="stylesheet" type="text/css" />


text:
import { Meteor } from 'meteor/meteor';

import logger from './logger';
import { Messages, Subscriptions } from '../../models';

Meteor.methods({
	unreadMessages(firstUnreadMessage, room) {
		const userId = Meteor.userId();
		if (!userId) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', {
				method: 'unreadMessages',
			});
		}

		if (room && typeof room === 'string') {
			const lastMessage = Messages.findVisibleByRoomId(room, { limit: 1, sort: { ts: -1 } }).fetch()[0];

			if (lastMessage == null) {
				throw new Meteor.Error('error-no-message-for-unread', 'There are no messages to mark unread', {
					method: 'unreadMessages',
					action: 'Unread_messages',
				});
			}

			return Subscriptions.setAsUnreadByRoomIdAndUserId(lastMessage.rid, userId, lastMessage.ts);
		}

		if (typeof firstUnreadMessage?._id !== 'string') {
			throw new Meteor.Error('error-action-not-allowed', 'Not allowed', {
				method: 'unreadMessages',
				action: 'Unread_messages',
			});
		}

		const originalMessage = Messages.findOneById(firstUnreadMessage._id, {
			fields: {
				u: 1,
				rid: 1,
				file: 1,
				ts: 1,
			},
		});
		if (originalMessage == null || userId === originalMessage.u._id) {
			throw new Meteor.Error('error-action-not-allowed', 'Not allowed', {
				method: 'unreadMessages',
				action: 'Unread_messages',
			});
		}
		const lastSeen = Subscriptions.findOneByRoomIdAndUserId(originalMessage.rid, userId).ls;
		if (firstUnreadMessage.ts >= lastSeen) {
			return logger.connection.debug('Provided message is already marked as unread');
		}
		logger.connection.debug(`Updating unread  message of ${ originalMessage.ts } as the first unread`);
		return Subscriptions.setAsUnreadByRoomIdAndUserId(originalMessage.rid, userId, originalMessage.ts);
	},
});


text:
SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
  while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd  > /dev/null

if ! [ -f $SCRIPT_PATH/src/.nuget/nuget.exe ]
    then
        wget "https://www.nuget.org/nuget.exe" -P $SCRIPT_PATH/src/.nuget/
fi

mono $SCRIPT_PATH/src/.nuget/nuget.exe update -self

SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
  while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd  > /dev/null

mono $SCRIPT_PATH/src/.nuget/nuget.exe update -self

mono $SCRIPT_PATH/src/.nuget/nuget.exe install FAKE -OutputDirectory $SCRIPT_PATH/src/packages -ExcludeVersion -Version 4.16.1
mono $SCRIPT_PATH/src/.nuget/nuget.exe install xunit.runner.console -OutputDirectory $SCRIPT_PATH/src/packages/FAKE -ExcludeVersion -Version 2.0.0
mono $SCRIPT_PATH/src/.nuget/nuget.exe install NBench.Runner -OutputDirectory $SCRIPT_PATH/src/packages -ExcludeVersion -Version 0.3.3

if ! [ -e $SCRIPT_PATH/src/packages/SourceLink.Fake/tools/SourceLink.fsx ] ; then
	mono $SCRIPT_PATH/src/.nuget/nuget.exe install SourceLink.Fake -OutputDirectory $SCRIPT_PATH/src/packages -ExcludeVersion

fi

export encoding=utf-8

mono $SCRIPT_PATH/src/packages/FAKE/tools/FAKE.exe build.fsx "$@"


text:
package com.asymmetrik.utils.hash;

import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public abstract class TestHashGen {

    private static final File TEST_IMAGE_GOOD = new File(TestHashGen.class.getClassLoader()
            .getResource("apple.jpg").getFile());
    private static final File TEST_IMAGE_BAD = new File(TestHashGen.class.getClassLoader()
            .getResource("not_an_image.txt").getFile());

    private HashGen hashGen;

    protected abstract HashGen createInstance();

    @Before
    public void setUp() {
        hashGen = createInstance();
    }

    @Test
    public void testValidImage() throws IOException {
        String hash = hashGen.getHash(new FileInputStream(TEST_IMAGE_GOOD));
        assertTrue(hash != null && !hash.isEmpty());
    }

    @Test
    public void testInvalidImage() throws IOException {
        String hash = hashGen.getHash(new FileInputStream(TEST_IMAGE_BAD));
        assertEquals(null, hash);
    }

}


text:
To migrate a Git LFS repository from one hosting provider to another,
you can use a combination of `git lfs fetch` and `git lfs push` with the `--all` option specified.

Via [Atlassian](https://www.atlassian.com/git/tutorials/git-lfs).