<commit_before>
var StringUtilities = {
    getFirstInternVowel: function(word){
        vowels = word.substring(1).match(new RegExp('[AEIOU]'));
        return vowels ? vowels[0] : 'X';
    },
    getFirstInternConsonant: function(word){
        vowels = word.substring(1).match(new RegExp('[BCDFGHJKLMNPQRSTUVWXYZ]'));
        return vowels ? vowels[0] : 'X';
    },
    clearString: function(word) {

        cleanWord = word.trim();
        cleanWord = cleanWord.replace(/\s/g,' ');
        cleanWord = this.removeAccents(cleanWord.toUpperCase());
        return cleanWord;
    },
    removeAccents: function(word)
    {
        accents = {
            'Á': 'A',
            'É': 'E',
            'Í': 'I',
            'Ó': 'O',
            'Ú': 'U'
        }

        for(accented in accents) {
            word = word.replace(new RegExp(accented),accents[accented]);
        }
        return word;
    }

}

var mxk = {

    getCURP: function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

                            name            = StringUtilities.clearString(name);
                            name            = this.removeCommonNames(name);
                            surnameFather   = StringUtilities.clearString(surnameFather);
                            surnameMother   = StringUtilities.clearString(surnameMother);
                            bornDay         = StringUtilities.clearString(bornDay);
                            bornMonth       = StringUtilities.clearString(bornMonth);
                            bornYear        = StringUtilities.clearString(bornYear);

                            curp = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear);

                            //TODO Remove bad words

                            curp += this.getGenderLetter(gender);
                            if(bornState.length !== 2){
                                bornState = this.getBornStateCode(bornState);
                            }
                            curp += born_state
                            curp += StringUtilities.getFirstInternConsonant(surnameFather);
                            curp += StringUtilities.getFirstInternConsonant(surnameMother);
                            curp += StringUtilities.getFirstInternConsonant(name);

                            curp += this.getSpecialChar(bornYear);
                            curp += "?" // The last character is a random cahracter

                            return curp;

                    },
    getRFC: function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

        name            = StringUtilities.clearString(name);
        surnameFather   = StringUtilities.clearString(surnameFather);
        surnameMother   = StringUtilities.clearString(surnameMother);
        bornDay         = StringUtilities.clearString(bornDay);
        bornMonth       = StringUtilities.clearString(bornMonth);
        bornYear        = StringUtilities.clearString(bornYear);

        rfc = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear);
         //impolement key method
        return rfc;

    },

    getCommonPart:  function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear) {

                            commonPart = surnameFather[0];
                            commonPart += StringUtilities.getFirstInternVowel(surnameFather);
                            commonPart += surnameMother[0];
                            commonPart += name[0];

                            commonPart += bornYear.substring(2);
                            commonPart += bornMonth;
                            commonPart += bornDay;

                            //todo, remove bad words
                             return commonPart;
                    },
    getBornStateCode: function(idState){
                        return this.states[idState].code;
                    },
    getGenderLetter: function(idGender){
                        return idGender == 1 ? 'H' : 'M';
                    },
    getSpecialChar: function(bornYear){
                        if(bornYear[0] == '1') {
                            return '0';
                        } else {
                            return 'A';
                        }
                    },
    removeCommonNames: function(name) {
                        this.notAcceptedNames.forEach(
                            function(notAccepted){
                                name = name.replace(new RegExp('^' + notAccepted),'');
                            }
                            );

                        return name;
                    },

    removeBadWordsRFC: function(word){
        if(word in this.badWordsRFC) {
            word[3] = 'X'
        }
        return word;
    },

    states: new Array(
                {name: "AGUASCALIENTES"         , code: "AS"},  //1
                {name: "BAJA CALIFORNIA"        , code: "BC"},
                {name: "BAJA CALIFORNIA SUR"    , code: "BS"},
                {name: "CAMPECHE"               , code: "CC"},
                {name: "COAHUILA"               , code: "CL"},
                {name: "COLIMA"                 , code: "CM"},
                {name: "CHIAPAS"                , code: "CS"},
                {name: "CHIHUAHUA"              , code: "CH"},
                {name: "DISTRITO FEDERAL"       , code: "DF"},
                {name: "DURANGO"                , code: "DG"},
                {name: "GUANAJUATO"             , code: "GT"},
                {name: "GUERRERO"               , code: "GR"},
                {name: "HIDALGO"                , code: "HG"},
                {name: "JALISCO"                , code: "JC"},
                {name: "MÉXICO"                 , code: "MC"},
                {name: "MICHOACÁN"              , code: "MN"},
                {name: "MORELOS"                , code: "MS"},
                {name: "NAYARIT"                , code: "NT"},
                {name: "NUEVO LEÓN"             , code: "NL"},
                {name: "OAXACA"                 , code: "OC"},
                {name: "PUEBLA"                 , code: "PL"},
                {name: "QUERÉTARO"              , code: "QT"},
                {name: "QUINTANA ROO"           , code: "QR"},
                {name: "SAN LUIS POTOSÍ"        , code: "SP"},
                {name: "SINALOA"                , code: "SL"},
                {name: "SONORA"                 , code: "SR"},
                {name: "TABASCO"                , code: "TC"},
                {name: "TAMAULIPAS"             , code: "TS"},
                {name: "TLAXCALA"               , code: "TL"},
                {name: "VERACRUZ"               , code: "VZ"},
                {name: "YUCATÁN"                , code: "YN"},
                {name: "ZACATECAS"              , code: "ZS"}   //32
                ),
    notAcceptedNames: new Array(
        'MARIA DEL ',
        'MARIA DE LOS ',
        'MARIA ',
        'JOSE DE ',
        'JOSE ',
        'MA. ',
        'MA ',
        'M. ',
        'J. ',
        'J '
        ),
    badWords: {
        "BACA": "BXCA",
        "LOCO": "LXCO",
        "BAKA": "BXKA",
        "BUEI": "BXEI",
        "BUEY": "BXEY",
        "CACA": "CXCA",
        "CACO": "CXCO",
        "CAGA": "CXGA",
        "CAGO": "CXGO",
        "CAKA": "CXKA",
        "CAKO": "CXKO",
        "COGE": "CXGE",
        "COGI": "CXGI",
        "COJA": "CXJA",
        "COJE": "CXJE",
        "COJI": "CXJI",
        "COJO": "CXJO",
        "COLA": "CXLA",
        "CULO": "CXLO",
        "FALO": "FXLO",
        "FETO": "FXTO",
        "GETA": "GXTA",
        "GUEI": "GXEI",
        "GUEY": "GXEY",
        "JETA": "JXTA",
        "JOTO": "JXTO",
        "KACA": "KXCA",
        "KACO": "KXCO",
        "KAGA": "KXGA",
        "KAGO": "KXGO",
        "KAKA": "KXKA",
        "KAKO": "KXKO",
        "KOGE": "KXGE",
        "KOGI": "KXGI",
        "KOJA": "KXJA",
        "KOJE": "KXJE",
        "KOJI": "KXJI",
        "KOJO": "KXJO",
        "KOLA": "KXLA",
        "KULO": "KXLO",
        "LILO": "LXLO",
        "LOKA": "LXKA",
        "LOKO": "LXKO",
        "MAME": "MXME",
        "MAMO": "MXMO",
        "MEAR": "MXAR",
        "MEAS": "MXAS",
        "MEON": "MXON",
        "MIAR": "MXAR",
        "MION": "MXON",
        "MOCO": "MXCO",
        "MOKO": "MXKO",
        "MULA": "MXLA",
        "MULO": "MXLO",
        "NACA": "NXCA",
        "NACO": "NXCO",
        "PEDA": "PXDA",
        "PEDO": "PXDO",
        "PENE": "PXNE",
        "PIPI": "PXPI",
        "PITO": "PXTO",
        "POPO": "PXPO",
        "PUTA": "PXTA",
        "PUTO": "PXTO",
        "QULO": "QXLO",
        "RATA": "RXTA",
        "ROBA": "RXBA",
        "ROBE": "RXBE",
        "ROBO": "RXBO",
        "RUIN": "RXIN",
        "SENO": "SXNO",
        "TETA": "TXTA",
        "VACA": "VXCA",
        "VAGA": "VXGA",
        "VAGO": "VXGO",
        "VAKA": "VXKA",
        "VUEI": "VXEI",
        "VUEY": "VXEY",
        "WUEI": "WXEI",
        "WUEY": "WXEY"
    },

    badWordsRFC : [
                    "BUEI",
                    "BUEY",
                    "CACA",
                    "CACO",
                    "CAGA",
                    "CAGO",
                    "CAKA",
                    "COGE",
                    "COJA",
                    "COJE",
                    "COJI",
                    "COJO",
                    "CULO",
                    "FETO",
                    "GUEY",
                    "JOTO",
                    "KACA",
                    "KACO",
                    "KAGA",
                    "KAGO",
                    "KOGE",
                    "KOJO",
                    "KAKA",
                    "KULO",
                    "MAME",
                    "MAMO",
                    "MEAR",
                    "MEON",
                    "MION",
                    "MOCO",
                    "MULA",
                    "PEDA",
                    "PEDO",
                    "PENE",
                    "PUTA",
                    "PUTO",
                    "QULO",
                    "RATA",
                    "RUIN",
                ],
    characterValues: {
                "0" :  '00',
                "1" :  '01',
                "2" :  '02',
                "3" :  '03',
                "4" :  '04',
                "5" :  '05',
                "6" :  '06',
                "7" :  '07',
                "8" :  '08',
                "9" :  '09',
                "A" :  '10',
                "B" :  '11',
                "C" :  '12',
                "D" :  '13',
                "F" :  '15',
                "E" :  '14',
                "G" :  '16',
                "H" :  '17',
                "I" :  '18',
                "J" :  '19',
                "K" :  '20',
                "L" :  '21',
                "M" :  '22',
                "N" :  '23',
                "&" :  '24',
                "O" :  '25',
                "P" :  '26',
                "Q" :  '27',
                "R" :  '28',
                "S" :  '29',
                "T" :  '30',
                "U" :  '31',
                "V" :  '32',
                "W" :  '33',
                "X" :  '34',
                "Y" :  '35',
                "Z" :  '36',
                " " :  '37',
                "Ñ" :  '38'
                },
    fillBornStateSelect: function(field_id){
        element = document.getElementById(field_id);
        console.log(element)
        this.states.forEach(function(state){
            option = new Option(state.name, state.code)
            element.appendChild(option)
        });
    // setRFCResultField: function(field_id){
    //     element= document.getElementById(field_id)
    // }
    //}
    }
}<commit_msg>Removing bad words from curp<commit_after>
var StringUtilities = {
    getFirstInternVowel: function(word){
        vowels = word.substring(1).match(new RegExp('[AEIOU]'));
        return vowels ? vowels[0] : 'X';
    },
    getFirstInternConsonant: function(word){
        vowels = word.substring(1).match(new RegExp('[BCDFGHJKLMNPQRSTUVWXYZ]'));
        return vowels ? vowels[0] : 'X';
    },
    clearString: function(word) {

        cleanWord = word.trim();
        cleanWord = cleanWord.replace(/\s/g,' ');
        cleanWord = this.removeAccents(cleanWord.toUpperCase());
        return cleanWord;
    },
    removeAccents: function(word)
    {
        accents = {
            'Á': 'A',
            'É': 'E',
            'Í': 'I',
            'Ó': 'O',
            'Ú': 'U'
        }

        for(accented in accents) {
            word = word.replace(new RegExp(accented),accents[accented]);
        }
        return word;
    }

}

var mxk = {

    getCURP: function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

                            name            = StringUtilities.clearString(name);
                            name            = this.removeCommonNames(name);
                            surnameFather   = StringUtilities.clearString(surnameFather);
                            surnameMother   = StringUtilities.clearString(surnameMother);
                            bornDay         = StringUtilities.clearString(bornDay);
                            bornMonth       = StringUtilities.clearString(bornMonth);
                            bornYear        = StringUtilities.clearString(bornYear);

                            curp = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear,0);

                            //TODO Remove bad words

                            curp += this.getGenderLetter(gender);
                            if(bornState.length !== 2){
                                bornState = this.getBornStateCode(bornState);
                            }
                            curp += born_state
                            curp += StringUtilities.getFirstInternConsonant(surnameFather);
                            curp += StringUtilities.getFirstInternConsonant(surnameMother);
                            curp += StringUtilities.getFirstInternConsonant(name);

                            curp += this.getSpecialChar(bornYear);
                            curp += "?" // The last character is a random cahracter

                            return curp;

                    },
    getRFC: function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

        name            = StringUtilities.clearString(name);
        surnameFather   = StringUtilities.clearString(surnameFather);
        surnameMother   = StringUtilities.clearString(surnameMother);
        bornDay         = StringUtilities.clearString(bornDay);
        bornMonth       = StringUtilities.clearString(bornMonth);
        bornYear        = StringUtilities.clearString(bornYear);

        rfc = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, 1);
         //impolement key method
        return rfc;

    },

    getCommonPart:  function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, type) {

                            commonPart = surnameFather[0];
                            commonPart += StringUtilities.getFirstInternVowel(surnameFather);
                            commonPart += surnameMother[0];
                            commonPart += name[0];
                            if(type==0){
                                commonPart = this.removeBadWordsCURP(commonPart)
                            }

                            commonPart += bornYear.substring(2);
                            commonPart += bornMonth;
                            commonPart += bornDay;

                            //todo, remove bad words
                             return commonPart;
                    },
    getBornStateCode: function(idState){
                        return this.states[idState].code;
                    },
    getGenderLetter: function(idGender){
                        return idGender == 1 ? 'H' : 'M';
                    },
    getSpecialChar: function(bornYear){
                        if(bornYear[0] == '1') {
                            return '0';
                        } else {
                            return 'A';
                        }
                    },
    removeCommonNames: function(name) {
                        this.notAcceptedNames.forEach(
                            function(notAccepted){
                                name = name.replace(new RegExp('^' + notAccepted),'');
                            }
                            );

                        return name;
                    },

    removeBadWordsRFC: function(word){
        if(word in this.badWordsRFC) {
            word[3] = 'X'
        }
        return word;
    },
    removeBadWordsCURP: function(word){
        if(this.badWordsCURP[word]){
            return this.badWordsCURP[word]
        }
        return word;
    },

    states: new Array(
                {name: "AGUASCALIENTES"         , code: "AS"},  //1
                {name: "BAJA CALIFORNIA"        , code: "BC"},
                {name: "BAJA CALIFORNIA SUR"    , code: "BS"},
                {name: "CAMPECHE"               , code: "CC"},
                {name: "COAHUILA"               , code: "CL"},
                {name: "COLIMA"                 , code: "CM"},
                {name: "CHIAPAS"                , code: "CS"},
                {name: "CHIHUAHUA"              , code: "CH"},
                {name: "DISTRITO FEDERAL"       , code: "DF"},
                {name: "DURANGO"                , code: "DG"},
                {name: "GUANAJUATO"             , code: "GT"},
                {name: "GUERRERO"               , code: "GR"},
                {name: "HIDALGO"                , code: "HG"},
                {name: "JALISCO"                , code: "JC"},
                {name: "MÉXICO"                 , code: "MC"},
                {name: "MICHOACÁN"              , code: "MN"},
                {name: "MORELOS"                , code: "MS"},
                {name: "NAYARIT"                , code: "NT"},
                {name: "NUEVO LEÓN"             , code: "NL"},
                {name: "OAXACA"                 , code: "OC"},
                {name: "PUEBLA"                 , code: "PL"},
                {name: "QUERÉTARO"              , code: "QT"},
                {name: "QUINTANA ROO"           , code: "QR"},
                {name: "SAN LUIS POTOSÍ"        , code: "SP"},
                {name: "SINALOA"                , code: "SL"},
                {name: "SONORA"                 , code: "SR"},
                {name: "TABASCO"                , code: "TC"},
                {name: "TAMAULIPAS"             , code: "TS"},
                {name: "TLAXCALA"               , code: "TL"},
                {name: "VERACRUZ"               , code: "VZ"},
                {name: "YUCATÁN"                , code: "YN"},
                {name: "ZACATECAS"              , code: "ZS"}   //32
                ),
    notAcceptedNames: new Array(
        'MARIA DEL ',
        'MARIA DE LOS ',
        'MARIA ',
        'JOSE DE ',
        'JOSE ',
        'MA. ',
        'MA ',
        'M. ',
        'J. ',
        'J '
        ),
    badWordsCURP: {
        "BACA": "BXCA",
        "LOCO": "LXCO",
        "BAKA": "BXKA",
        "BUEI": "BXEI",
        "BUEY": "BXEY",
        "CACA": "CXCA",
        "CACO": "CXCO",
        "CAGA": "CXGA",
        "CAGO": "CXGO",
        "CAKA": "CXKA",
        "CAKO": "CXKO",
        "COGE": "CXGE",
        "COGI": "CXGI",
        "COJA": "CXJA",
        "COJE": "CXJE",
        "COJI": "CXJI",
        "COJO": "CXJO",
        "COLA": "CXLA",
        "CULO": "CXLO",
        "FALO": "FXLO",
        "FETO": "FXTO",
        "GETA": "GXTA",
        "GUEI": "GXEI",
        "GUEY": "GXEY",
        "JETA": "JXTA",
        "JOTO": "JXTO",
        "KACA": "KXCA",
        "KACO": "KXCO",
        "KAGA": "KXGA",
        "KAGO": "KXGO",
        "KAKA": "KXKA",
        "KAKO": "KXKO",
        "KOGE": "KXGE",
        "KOGI": "KXGI",
        "KOJA": "KXJA",
        "KOJE": "KXJE",
        "KOJI": "KXJI",
        "KOJO": "KXJO",
        "KOLA": "KXLA",
        "KULO": "KXLO",
        "LILO": "LXLO",
        "LOKA": "LXKA",
        "LOKO": "LXKO",
        "MAME": "MXME",
        "MAMO": "MXMO",
        "MEAR": "MXAR",
        "MEAS": "MXAS",
        "MEON": "MXON",
        "MIAR": "MXAR",
        "MION": "MXON",
        "MOCO": "MXCO",
        "MOKO": "MXKO",
        "MULA": "MXLA",
        "MULO": "MXLO",
        "NACA": "NXCA",
        "NACO": "NXCO",
        "PEDA": "PXDA",
        "PEDO": "PXDO",
        "PENE": "PXNE",
        "PIPI": "PXPI",
        "PITO": "PXTO",
        "POPO": "PXPO",
        "PUTA": "PXTA",
        "PUTO": "PXTO",
        "QULO": "QXLO",
        "RATA": "RXTA",
        "ROBA": "RXBA",
        "ROBE": "RXBE",
        "ROBO": "RXBO",
        "RUIN": "RXIN",
        "SENO": "SXNO",
        "TETA": "TXTA",
        "VACA": "VXCA",
        "VAGA": "VXGA",
        "VAGO": "VXGO",
        "VAKA": "VXKA",
        "VUEI": "VXEI",
        "VUEY": "VXEY",
        "WUEI": "WXEI",
        "WUEY": "WXEY"
    },

    badWordsRFC : [
                    "BUEI",
                    "BUEY",
                    "CACA",
                    "CACO",
                    "CAGA",
                    "CAGO",
                    "CAKA",
                    "COGE",
                    "COJA",
                    "COJE",
                    "COJI",
                    "COJO",
                    "CULO",
                    "FETO",
                    "GUEY",
                    "JOTO",
                    "KACA",
                    "KACO",
                    "KAGA",
                    "KAGO",
                    "KOGE",
                    "KOJO",
                    "KAKA",
                    "KULO",
                    "MAME",
                    "MAMO",
                    "MEAR",
                    "MEON",
                    "MION",
                    "MOCO",
                    "MULA",
                    "PEDA",
                    "PEDO",
                    "PENE",
                    "PUTA",
                    "PUTO",
                    "QULO",
                    "RATA",
                    "RUIN",
                ],
    characterValues: {
                "0" :  '00',
                "1" :  '01',
                "2" :  '02',
                "3" :  '03',
                "4" :  '04',
                "5" :  '05',
                "6" :  '06',
                "7" :  '07',
                "8" :  '08',
                "9" :  '09',
                "A" :  '10',
                "B" :  '11',
                "C" :  '12',
                "D" :  '13',
                "F" :  '15',
                "E" :  '14',
                "G" :  '16',
                "H" :  '17',
                "I" :  '18',
                "J" :  '19',
                "K" :  '20',
                "L" :  '21',
                "M" :  '22',
                "N" :  '23',
                "&" :  '24',
                "O" :  '25',
                "P" :  '26',
                "Q" :  '27',
                "R" :  '28',
                "S" :  '29',
                "T" :  '30',
                "U" :  '31',
                "V" :  '32',
                "W" :  '33',
                "X" :  '34',
                "Y" :  '35',
                "Z" :  '36',
                " " :  '37',
                "Ñ" :  '38'
                },
    fillBornStateSelect: function(field_id){
        element = document.getElementById(field_id);
        console.log(element)
        this.states.forEach(function(state){
            option = new Option(state.name, state.code)
            element.appendChild(option)
        });
    // setRFCResultField: function(field_id){
    //     element= document.getElementById(field_id)
    // }
    //}
    }
}<|endoftext|>


<commit_before>(function(){
    var iframe = document.createElement('iframe');
    iframe.style.display = "none";
    iframe.src = 'http://local.serendip.me/sdk.html'
    iframe.src += "#origin="
    if (document.location.origin == null)
        iframe.src += (document.location.protocol + "//" + document.location.hostname)
    else
        iframe.src += document.location.origin
    window.SRNDP_FB_IFRAME = iframe
    document.body.appendChild(iframe);
}());

require.config({
    paths : {
        jquery : 'jquery-1.10.1.min'
    },
    shim :{
        'jstorage' : ['jquery']
    },
    config : {
        'cs!settings' : {
            env : 'prod',
            'dev' : {
                SECURE_PROTOCOL : "http://",
                BASE_API_URL : "localapi.serendip.me:9000/v1",
                BASE_URL : "http://local.serendip.me",
                FB_APP_ID : '180530865322766',
                SESSION_COOKIE_NAME : 'PLAY_SESSION'
            },
            'prod' : {
                SECURE_PROTOCOL : "https://",
                BASE_API_URL : "api.serendip.me/v1",
                BASE_URL : "http://serendip.me",
                FB_APP_ID : '180530865322766',
                SESSION_COOKIE_NAME : 'PLAY_SESSION'
            }
        }
    }
});

require(['cs!main']);
<commit_msg>domain changes<commit_after>(function(){
    var iframe = document.createElement('iframe');
    iframe.style.display = "none";
    iframe.src = 'http://serendip.me/sdk.html'
    iframe.src += "#origin="
    if (document.location.origin == null)
        iframe.src += (document.location.protocol + "//" + document.location.hostname)
    else
        iframe.src += document.location.origin
    window.SRNDP_FB_IFRAME = iframe
    document.body.appendChild(iframe);
}());

require.config({
    paths : {
        jquery : 'jquery-1.10.1.min'
    },
    shim :{
        'jstorage' : ['jquery']
    },
    config : {
        'cs!settings' : {
            env : 'prod',
            'dev' : {
                SECURE_PROTOCOL : "http://",
                BASE_API_URL : "localapi.serendip.me:9000/v1",
                BASE_URL : "http://local.serendip.me",
                FB_APP_ID : '180530865322766',
                SESSION_COOKIE_NAME : 'PLAY_SESSION'
            },
            'prod' : {
                SECURE_PROTOCOL : "https://",
                BASE_API_URL : "api.serendip.me/v1",
                BASE_URL : "http://serendip.me",
                FB_APP_ID : '180530865322766',
                SESSION_COOKIE_NAME : 'PLAY_SESSION'
            }
        }
    }
});

require(['cs!main']);
<|endoftext|>


<commit_before>/**
*	SMX Synchronized Multimedia XML
*
*	@module smx
*
*/

(function(window){

	var smx = {};

	/* software version: major.minor.path */
	smx.version = '0.8.1';

	//expose

	window.smx = smx;

})(window);

	<commit_msg>test commit<commit_after>/**
*	SMX Synchronized Multimedia XML
*
*	@module smx
*
*/

(function(window){

	var smx = {};

	/* software version: major.minor.path */
	smx.version = '0.8.1';

	//expose

	window.smx = smx;

})(window);

	<|endoftext|>


<commit_before>var Crawler = require("crawler").Crawler;
var urls = [];
var fs= require('fs');
var times  = 0;

var c = new Crawler({
	"maxConnections": 1,
});

function writeFs(urls){
	var data = {"news": urls };
    fs.writeFile("yibite.json", JSON.stringify(data), function (err) {
	  	if (err) throw err;
	  	console.log('It\'s saved!');
	});
}

/*
 * mongodb
*/

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/bitcoin');

var newsSchema = Schema({
  title   	: String,
  url 	  	: String,
  time 		: Date,
  origin 	: String,
  intro 	: String,
  no 		: String
});

var News = mongoose.model('News', newsSchema);

News.remove({}, function(err) {
   console.log('News collection removed');
});

function saveMongoDB(urls){
	urls.forEach(function(item){
		var oneNew = new News( item );
		oneNew.save(function (err) {
		  if (err) // ...
		  console.log('insert error');
		});
	});
}

// Queue just one URL, with default callback
var tasks = [];
var max = 40;
for (var i = 1; i <= max; i++) {
	tasks.push({
		"maxConnections": 1,
		"uri": "http://yibite.com/news/index.php?page="+i,
		"callback": function(error,result,$) {
			urls = [];

			$('.li-holder').each( function(index, div){
				var timeDiv = $(div).find('.tags > span.time')[0];
				var linkDiv = $(div).find('.right-intro > a.art-myTitle')[0];
				var originDiv = $(div).find('.tags > a.author')[0];
				var introDiv = $(div).find('.right-intro > span.intro')[0];

				urls.push({
		        	url: linkDiv.href,
		        	title: linkDiv.innerHTML,
		        	time: timeDiv.innerHTML,
		        	origin: originDiv.innerHTML,
		        	intro: introDiv.innerHTML,
		        	no: "page"+times+"-"+index
		        });
				console.log("page"+times+"-"+index);
			});

		    times += 1;
		    console.log('queue call '+times+' times');
	    	// writeFs(urls);
	    	saveMongoDB(urls);
	    	if (i == 41) {
	    		process.exit(0);
	    	};
		}
	});
};

console.dir(tasks);

c.queue(tasks);

// TODO crawler pagination url
// TODO	insert the data
// TODO check the repeat
// TODO 定时任务<commit_msg>remove exit<commit_after>var Crawler = require("crawler").Crawler;
var urls = [];
var fs= require('fs');
var times  = 0;

var c = new Crawler({
	"maxConnections": 1,
});

function writeFs(urls){
	var data = {"news": urls };
    fs.writeFile("yibite.json", JSON.stringify(data), function (err) {
	  	if (err) throw err;
	  	console.log('It\'s saved!');
	});
}

/*
 * mongodb
*/

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/bitcoin');

var newsSchema = Schema({
  title   	: String,
  url 	  	: String,
  time 		: Date,
  origin 	: String,
  intro 	: String,
  no 		: String
});

var News = mongoose.model('News', newsSchema);

News.remove({}, function(err) {
   console.log('News collection removed');
});

function saveMongoDB(urls){
	urls.forEach(function(item){
		var oneNew = new News( item );
		oneNew.save(function (err) {
		  if (err) // ...
		  console.log('insert error');
		});
	});
}

// Queue just one URL, with default callback
var tasks = [];
var max = 40;
for (var i = 1; i <= max; i++) {
	tasks.push({
		"maxConnections": 1,
		"uri": "http://yibite.com/news/index.php?page="+i,
		"callback": function(error,result,$) {
			urls = [];

			$('.li-holder').each( function(index, div){
				var timeDiv = $(div).find('.tags > span.time')[0];
				var linkDiv = $(div).find('.right-intro > a.art-myTitle')[0];
				var originDiv = $(div).find('.tags > a.author')[0];
				var introDiv = $(div).find('.right-intro > span.intro')[0];

				urls.push({
		        	url: linkDiv.href,
		        	title: linkDiv.innerHTML,
		        	time: timeDiv.innerHTML,
		        	origin: originDiv.innerHTML,
		        	intro: introDiv.innerHTML,
		        	no: "page"+times+"-"+index
		        });
				console.log("page"+times+"-"+index);
			});

		    times += 1;
		    console.log('queue call '+times+' times');
	    	// writeFs(urls);
	    	saveMongoDB(urls);
		}
	});
};

console.dir(tasks);

c.queue(tasks);

// TODO crawler pagination url
// TODO	insert the data
// TODO check the repeat
// TODO 定时任务<|endoftext|>


<commit_before>(function () {
    'use strict';

    var debug = true,
        src   = './src',
        dest  = './public';

    require('./util/node-path');

    module.exports = {
        src: src,
        dest: dest,
        environment: {
            debug: debug
        },
        sass: {
            src: src + '/styles/*.{sass,scss}',
            dest: dest + '/css',
            settings: {
                sourceComments: (function () {
                    if (debug) {
                        return 'map';
                    }
                })(),
                imagePath: dest + '/images',
                includePaths: []
            }
        },
        autoprefixer: {
            browsers: ['last 2 versions']
        },
        images: {
            src: src + '/images/**',
            dest: dest + '/images'
        },
        phpunit: {
            watch: '/**/*.php',
            src: './test/phpunit/**/*.test.php'
        },
        jasmine: {
            watch: dest + '/**/*.js',
            specs: dest + '/specs.js'
        },
        jshint: {
            src: src + '/scripts/**/*.js',
            reporter: 'jshint-stylish'
        },
        browserSync: {
            proxy: 'aprendermadeira.local',
            files: ['**/*.php', dest + '/**', '!' + dest + '/**.map']
        },
        browserify: {
            debug: debug,
            extensions: ['.cson', '.yaml', '.json', '.hbs', '.dust'],
            bundleConfigs: [{
                entries: src + '/scripts/multisearch.js',
                dest: dest + '/js',
                outputName: 'multisearch.js',
                vendor: false
            }, {
                dest: dest + '/js',
                outputName: 'multisearch-ie.js',
                vendor: true
            }, {
                entries: './test/jasmine/**/*.spec.js',
                dest: dest + '/test',
                outputName: 'specs.js'
            }]
        }
    };
})();
<commit_msg>Gulp config fix<commit_after>(function () {
    'use strict';

    var debug = true,
        src   = './src',
        dest  = './public';

    require('./util/node-path');

    module.exports = {
        src: src,
        dest: dest,
        environment: {
            debug: debug
        },
        sass: {
            src: src + '/styles/*.{sass,scss}',
            dest: dest + '/css',
            settings: {
                sourceComments: (function () {
                    if (debug) {
                        return 'map';
                    }
                })(),
                imagePath: dest + '/images',
                includePaths: []
            }
        },
        autoprefixer: {
            browsers: ['last 2 versions']
        },
        images: {
            src: src + '/images/**',
            dest: dest + '/images'
        },
        phpunit: {
            watch: '/**/*.php',
            src: './test/phpunit/**/*.test.php'
        },
        jasmine: {
            watch: dest + '/**/*.js',
            specs: dest + '/specs.js'
        },
        jshint: {
            src: src + '/scripts/**/*.js',
            reporter: 'jshint-stylish'
        },
        browserSync: {
            server: {
                baseDir: [dest, src]
            },
            files: ['**/*.php', dest + '/**', '!' + dest + '/**.map']
        },
        browserify: {
            debug: debug,
            extensions: ['.cson', '.yaml', '.json', '.hbs', '.dust'],
            bundleConfigs: [{
                entries: src + '/scripts/main.js',
                dest: dest + '/js',
                outputName: 'main.js',
                vendor: false
            }, {
                dest: dest + '/js',
                outputName: 'infrastructure.js',
                vendor: true
            }, {
                entries: './test/jasmine/**/*.spec.js',
                dest: dest + '/test',
                outputName: 'specs.js'
            }]
        }
    };
})();
<|endoftext|>


<commit_before>if(!TASK_CONFIG.javascripts) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(process.env.PWD, PATH_CONFIG.src, PATH_CONFIG.javascripts.src)
  var jsDest = path.resolve(process.env.PWD, PATH_CONFIG.dest, PATH_CONFIG.javascripts.dest)
  var publicPath = pathToUrl(TASK_CONFIG.javascripts.publicPath || PATH_CONFIG.javascripts.dest, '/')

  var extensions = TASK_CONFIG.javascripts.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = TASK_CONFIG.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  // TODO: To work in < node 6, prepend process.env.PWD + node_modules/babel-preset- to each
  var defaultBabelConfig = {
    presets: ['es2015', 'stage-1']
  }

  var testPattern = new RegExp(`(\\${TASK_CONFIG.javascripts.extensions.join('$|\\.')}$)`)

  var webpackConfig = {
    context: jsSrc,
    output: {},
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin()
    ],
    resolve: {
      root: jsSrc,
      extensions: [''].concat(extensions),
      alias: TASK_CONFIG.javascripts.alias,
      fallback: path.resolve(process.env.PWD, 'node_modules')
    }, // See https://github.com/facebook/react/issues/4566
    resolveLoader: {
      fallback: path.resolve(process.env.PWD, 'node_modules')
    },
    module: {
      loaders: [
        {
          test: testPattern,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: TASK_CONFIG.javascripts.babel || defaultBabelConfig
        }
      ]
    }
  }

  // Add additional loaders from config
  webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.loaders || [])

  if(env === 'development') {
    webpackConfig.devtool = TASK_CONFIG.javascripts.devtool || 'eval-cheap-module-source-map'
    webpackConfig.output.pathinfo = true

    // Create new entries object with webpack-hot-middleware and react-hot-loader (if enabled)
    if(TASK_CONFIG.javascripts.hot && TASK_CONFIG.javascripts.hot.enabled !== false) {
      for (var key in TASK_CONFIG.javascripts.entries) {
        var entry = TASK_CONFIG.javascripts.entries[key]
        // TODO: To work in < node 6, prepend process.env.PWD + node_modules/
        const entries = []
        let middleware = 'webpack-hot-middleware/client?'

        if(TASK_CONFIG.javascripts.hot.reload !== false) {
          middleware+= '&reload=true'
        }

        if(TASK_CONFIG.javascripts.hot.noInfo) {
          middleware+= '&noInfo=true'
        }

        if(TASK_CONFIG.javascripts.hot.quiet) {
          middleware+= '&quiet=true'
        }

        if(TASK_CONFIG.javascripts.hot.react) {
          entries.push('react-hot-loader/patch')
        }

        TASK_CONFIG.javascripts.entries[key] = entries.concat(middleware).concat(entry)
      }

      webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
    }
    // Addtional loaders for dev
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.developmentLoaders || [])
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = TASK_CONFIG.javascripts.entries

    webpackConfig.output.path = path.normalize(jsDest),
    webpackConfig.output.filename = filenamePattern,
    webpackConfig.output.publicPath = publicPath

    if(TASK_CONFIG.javascripts.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }

    // Addtional loaders for tests
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.testLoaders || [])
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(PATH_CONFIG.javascripts.dest, PATH_CONFIG.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoErrorsPlugin()
    )

    // Addtional loaders for production
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.productionLoaders || [])
  }

  return webpackConfig
}
<commit_msg>fixed boolean conditions to prevent undefined<commit_after>if(!TASK_CONFIG.javascripts) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(process.env.PWD, PATH_CONFIG.src, PATH_CONFIG.javascripts.src)
  var jsDest = path.resolve(process.env.PWD, PATH_CONFIG.dest, PATH_CONFIG.javascripts.dest)
  var publicPath = pathToUrl(TASK_CONFIG.javascripts.publicPath || PATH_CONFIG.javascripts.dest, '/')

  var extensions = TASK_CONFIG.javascripts.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = TASK_CONFIG.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  // TODO: To work in < node 6, prepend process.env.PWD + node_modules/babel-preset- to each
  var defaultBabelConfig = {
    presets: ['es2015', 'stage-1']
  }

  var testPattern = new RegExp(`(\\${TASK_CONFIG.javascripts.extensions.join('$|\\.')}$)`)

  var webpackConfig = {
    context: jsSrc,
    output: {},
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin()
    ],
    resolve: {
      root: jsSrc,
      extensions: [''].concat(extensions),
      alias: TASK_CONFIG.javascripts.alias,
      fallback: path.resolve(process.env.PWD, 'node_modules')
    }, // See https://github.com/facebook/react/issues/4566
    resolveLoader: {
      fallback: path.resolve(process.env.PWD, 'node_modules')
    },
    module: {
      loaders: [
        {
          test: testPattern,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: TASK_CONFIG.javascripts.babel || defaultBabelConfig
        }
      ]
    }
  }

  // Add additional loaders from config
  webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.loaders || [])

  if(env === 'development') {
    webpackConfig.devtool = TASK_CONFIG.javascripts.devtool || 'eval-cheap-module-source-map'
    webpackConfig.output.pathinfo = true

    // Create new entries object with webpack-hot-middleware and react-hot-loader (if enabled)
    if(!TASK_CONFIG.javascripts.hot || TASK_CONFIG.javascripts.hot.enabled !== false) {
      for (var key in TASK_CONFIG.javascripts.entries) {
        var entry = TASK_CONFIG.javascripts.entries[key]
        // TODO: To work in < node 6, prepend process.env.PWD + node_modules/
        const entries = []
        let middleware = 'webpack-hot-middleware/client?'

        if(!TASK_CONFIG.javascripts.hot || TASK_CONFIG.javascripts.hot.reload !== false) {
          middleware+= '&reload=true'
        }

        if(TASK_CONFIG.javascripts.hot && TASK_CONFIG.javascripts.hot.noInfo) {
          middleware+= '&noInfo=true'
        }

        if(TASK_CONFIG.javascripts.hot && TASK_CONFIG.javascripts.hot.quiet) {
          middleware+= '&quiet=true'
        }

        if(TASK_CONFIG.javascripts.hot && TASK_CONFIG.javascripts.hot.react) {
          entries.push('react-hot-loader/patch')
        }

        TASK_CONFIG.javascripts.entries[key] = entries.concat(middleware).concat(entry)
      }

      webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
    }
    // Addtional loaders for dev
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.developmentLoaders || [])
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = TASK_CONFIG.javascripts.entries

    webpackConfig.output.path = path.normalize(jsDest),
    webpackConfig.output.filename = filenamePattern,
    webpackConfig.output.publicPath = publicPath

    if(TASK_CONFIG.javascripts.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }

    // Addtional loaders for tests
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.testLoaders || [])
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(PATH_CONFIG.javascripts.dest, PATH_CONFIG.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoErrorsPlugin()
    )

    // Addtional loaders for production
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.productionLoaders || [])
  }

  return webpackConfig
}
<|endoftext|>


<commit_before>'use strict'

// track varies kinds of events and listeners.
const handlerTraker = {}

const globalEvent = {

  /**
   * addEventListener
   * @param {string} evt - the event name to add a listener on.
   */
  addEventListener (evt, callbackId) {
    // const cb = e => this.sender.performCallback(callbackId, e)
    const cb = function (e) {
      debugger;
      this.sender.performCallback(callbackId, e)
    }.bind(this)
    if (!handlerTraker[evt]) {
      handlerTraker[evt] = [cb]
    } else {
      handlerTraker.push(cb)
    }
    document.addEventListener(evt, cb)
  },

  /**
   * removeEventListener
   * @param {string} evt - the event name to remove a listener from.
   */
  removeEventListener (evt) {
    handlerTraker[evt].forEach(cb => document.removeEventListener(evt, cb))
  }
}

const meta = {
  globalEvent: [{
    name: 'addEventListener',
    args: ['string', 'function']
  }, {
    name: 'removeEventListener',
    args: ['string']
  }]
}

export default {
  init (Weex) {
    Weex.registerApiModule('globalEvent', globalEvent, meta)
  }
}
<commit_msg>* [html5] fix lint<commit_after>'use strict'

// track varies kinds of events and listeners.
const handlerTraker = {}

const globalEvent = {

  /**
   * addEventListener
   * @param {string} evt - the event name to add a listener on.
   */
  addEventListener (evt, callbackId) {
    const cb = e => this.sender.performCallback(callbackId, e)
    if (!handlerTraker[evt]) {
      handlerTraker[evt] = [cb]
    }
    else {
      handlerTraker.push(cb)
    }
    document.addEventListener(evt, cb)
  },

  /**
   * removeEventListener
   * @param {string} evt - the event name to remove a listener from.
   */
  removeEventListener (evt) {
    handlerTraker[evt].forEach(cb => document.removeEventListener(evt, cb))
  }
}

const meta = {
  globalEvent: [{
    name: 'addEventListener',
    args: ['string', 'function']
  }, {
    name: 'removeEventListener',
    args: ['string']
  }]
}

export default {
  init (Weex) {
    Weex.registerApiModule('globalEvent', globalEvent, meta)
  }
}
<|endoftext|>


<commit_before>/*
document.getElementById("deimperialize").addEventListener("click", function deimperialize() {
    chrome.tabs.query({active: true}, function(tabs) {
        chrome.tabs.sendRequest(tabs[0].id, {method: "getText"}, function(response) {
            if (response && response.method == "getText"){
                alert("deimperialize: " + response.data);
            }
        });
    })
});
*/

window.addEventListener("DOMContentLoaded", function() {
    var deimperialize = document.getElementById("deimperialize");
    deimperialize.addEventListener("click", function() {
        var highlight = document.getElementById("highlight");
        var highlightChecked = highlight.checked;
        console.log("highlightChecked = " + highlightChecked);
        // Get the active tab
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function(tabs) {
            // If there is an active tab...
            if (tabs.length > 0) {
                // ...send a message requesting the DOM...
                chrome.tabs.sendMessage(tabs[0].id, {
                    method: "convertToSI",
                    highlight: highlightChecked
                }, function(response) {
                    if (chrome.runtime.lastError) {
                        // An error occurred :(
                        console.log("ERROR: ", chrome.runtime.lastError);
                    } else {
                        // Do something useful with the HTML content
                        console.log(response.text);
                    }
                });
            }
        });
    });

    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; ++i) {
        var elem = inputs[i];
        if (elem.type === "checkbox") {
            console.log(elem.id + " - " + elem.type);
            elem.addEventListener("click", function() {
                var checkboxState = {
                    action: "checkbox-state",
                    id: this.id,
                    state: this.checked
                }
                chrome.runtime.sendMessage(checkboxState, function(response) {
                    if (response.success) {
                        console.log("Saved successfully");
                    } else {
                        console.log("There was an error while saving");
                    }
                });
            });
        }
    }

    chrome.runtime.sendMessage({action: "get-ui-state"}, function(response) {
        console.log("response: " + JSON.stringify(response, null, 4));
        for (key in response) {
            var elem = document.getElementById(key);
            elem.checked = response[key];
        }
    });
});
<commit_msg>jslint yunosi.js: add use strict and indent all file<commit_after>(function() {
    'use strict';
    /*
    document.getElementById("deimperialize").addEventListener("click", function deimperialize() {
        chrome.tabs.query({active: true}, function(tabs) {
            chrome.tabs.sendRequest(tabs[0].id, {method: "getText"}, function(response) {
                if (response && response.method == "getText"){
                    alert("deimperialize: " + response.data);
                }
            });
        })
    });
    */

    window.addEventListener("DOMContentLoaded", function() {
        var deimperialize = document.getElementById("deimperialize");
        deimperialize.addEventListener("click", function() {
            var highlight = document.getElementById("highlight");
            var highlightChecked = highlight.checked;
            console.log("highlightChecked = " + highlightChecked);
            // Get the active tab
            chrome.tabs.query({
                active: true,
                currentWindow: true
            }, function(tabs) {
                // If there is an active tab...
                if (tabs.length > 0) {
                    // ...send a message requesting the DOM...
                    chrome.tabs.sendMessage(tabs[0].id, {
                        method: "convertToSI",
                        highlight: highlightChecked
                    }, function(response) {
                        if (chrome.runtime.lastError) {
                            // An error occurred :(
                            console.log("ERROR: ", chrome.runtime.lastError);
                        } else {
                            // Do something useful with the HTML content
                            console.log(response.text);
                        }
                    });
                }
            });
        });

        var inputs = document.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; ++i) {
            var elem = inputs[i];
            if (elem.type === "checkbox") {
                console.log(elem.id + " - " + elem.type);
                elem.addEventListener("click", function() {
                    var checkboxState = {
                        action: "checkbox-state",
                        id: this.id,
                        state: this.checked
                    }
                    chrome.runtime.sendMessage(checkboxState, function(response) {
                        if (response.success) {
                            console.log("Saved successfully");
                        } else {
                            console.log("There was an error while saving");
                        }
                    });
                });
            }
        }

        chrome.runtime.sendMessage({action: "get-ui-state"}, function(response) {
            console.log("response: " + JSON.stringify(response, null, 4));
            for (key in response) {
                var elem = document.getElementById(key);
                elem.checked = response[key];
            }
        });
    });
}());
<|endoftext|>


<commit_before>// Requires cors.js to be loaded first

"use strict";

var ZOTERO_CONFIG = {
    "publicGroupId": "2055673",  // ID of public group to search in Zotero
    "limit": 10,  // Max number of results to retrieve per page
    "resultsElementId": "searchResults",  // Element to contain results
    "urlElementId": "searchUrl",  // Element to display search URL
    "countElementId": "resultCount",  // Element showing number of results
    "pagesElementId": "pagination",  // Element to display result page links
    "showPages": 5  // MUST BE ODD NUMBER! Max number of page links to show
};

// Get URL arguments
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// Parse Zotero search results into HTML
function parseZoteroResults(resultText) {
    var results = JSON.parse(resultText);
    var html = [];
    for (var i = 0; i < results.length; i++) {
        var result = results[i];
        html.push(result["bib"]);
    }
    if (html.length) {
        return html.join("
");
    }
    else {
        return "
Your search returned no results.
";
    }
}

function show_loading(isLoading) {
    var x = document.getElementById("loading-div");
    if (isLoading) {
        document.body.style.cursor = "wait";
        x.style.display = "block";
    }
    else {
        document.body.style.cursor = "default";
        x.style.display = "none";
    }
}

// Function to call if CORS request is successful
function successCallback(headers, response) {
    show_loading(false);

    // Write results to page
    var resultHtml = parseZoteroResults(response);
    var elementId = ZOTERO_CONFIG["resultsElementId"];
    document.getElementById(elementId).innerHTML = resultHtml;

    // Add links to additional search result pages if necessary
    var currentStart = getParameterByName("start");
    if (!currentStart) {
        currentStart = 0;
    }
    else {
        currentStart = parseInt(currentStart);
    }
    var count = parseInt(headers["total-results"]);
    var limit = parseInt(ZOTERO_CONFIG["limit"]);
    var showPages = parseInt(ZOTERO_CONFIG["showPages"]);
    var pageElementId = ZOTERO_CONFIG["pagesElementId"];
    showPageLinks(count, limit, showPages, currentStart, pageElementId);
    var query = getParameterByName("q");
    showResultCount(query, count, limit, currentStart, ZOTERO_CONFIG["countElementId"]);
}

// Function to call if CORS request fails
function errorCallback() {
    show_loading(false);
    alert("There was an error making the request.");
}

// Writes CORS request URL to the page so user can see it
function showUrl(url) {
    var txt = '' + url + '';
    var element = document.getElementById(ZOTERO_CONFIG["urlElementId"]);
    element.innerHTML = txt;
}

// Passes search URL and callbacks to CORS function
function searchZotero(query, publicGroupId, start=0) {
    var base = "https://api.zotero.org/groups/";
    var params = "/items?v=3&include=bib&sort=date&q=";
    var limit = "&limit=" + ZOTERO_CONFIG["limit"];
    start = "&start=" + start;
    var url = base + publicGroupId + params + query + limit + start;
    showUrl(url);
    show_loading(true);
    makeCorsRequest(url, successCallback, errorCallback);
}

// When the window loads, read query parameters and perform search
window.onload = function() {
    var query = getParameterByName("q");
    var start = getParameterByName("start");
    if (query == null) {
        query = "";
    }
    document.forms.zoteroSearchForm.q.value = query;
    if (!start) {
        start = 0;
    }
    searchZotero(query, ZOTERO_CONFIG["publicGroupId"], start);
};<commit_msg>don't include attachments in results<commit_after>// Requires cors.js to be loaded first

"use strict";

var ZOTERO_CONFIG = {
    "publicGroupId": "2055673",  // ID of public group to search in Zotero
    "limit": 10,  // Max number of results to retrieve per page
    "resultsElementId": "searchResults",  // Element to contain results
    "urlElementId": "searchUrl",  // Element to display search URL
    "countElementId": "resultCount",  // Element showing number of results
    "pagesElementId": "pagination",  // Element to display result page links
    "showPages": 5  // MUST BE ODD NUMBER! Max number of page links to show
};

// Get URL arguments
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// Parse Zotero search results into HTML
function parseZoteroResults(resultText) {
    var results = JSON.parse(resultText);
    var html = [];
    for (var i = 0; i < results.length; i++) {
        var result = results[i];
        html.push(result["bib"]);
    }
    if (html.length) {
        return html.join("
");
    }
    else {
        return "
Your search returned no results.
";
    }
}

function show_loading(isLoading) {
    var x = document.getElementById("loading-div");
    if (isLoading) {
        document.body.style.cursor = "wait";
        x.style.display = "block";
    }
    else {
        document.body.style.cursor = "default";
        x.style.display = "none";
    }
}

// Function to call if CORS request is successful
function successCallback(headers, response) {
    show_loading(false);

    // Write results to page
    var resultHtml = parseZoteroResults(response);
    var elementId = ZOTERO_CONFIG["resultsElementId"];
    document.getElementById(elementId).innerHTML = resultHtml;

    // Add links to additional search result pages if necessary
    var currentStart = getParameterByName("start");
    if (!currentStart) {
        currentStart = 0;
    }
    else {
        currentStart = parseInt(currentStart);
    }
    var count = parseInt(headers["total-results"]);
    var limit = parseInt(ZOTERO_CONFIG["limit"]);
    var showPages = parseInt(ZOTERO_CONFIG["showPages"]);
    var pageElementId = ZOTERO_CONFIG["pagesElementId"];
    showPageLinks(count, limit, showPages, currentStart, pageElementId);
    var query = getParameterByName("q");
    showResultCount(query, count, limit, currentStart, ZOTERO_CONFIG["countElementId"]);
}

// Function to call if CORS request fails
function errorCallback() {
    show_loading(false);
    alert("There was an error making the request.");
}

// Writes CORS request URL to the page so user can see it
function showUrl(url) {
    var txt = '' + url + '';
    var element = document.getElementById(ZOTERO_CONFIG["urlElementId"]);
    element.innerHTML = txt;
}

// Passes search URL and callbacks to CORS function
function searchZotero(query, publicGroupId, start=0) {
    var base = "https://api.zotero.org/groups/";
    var params = "/items?v=3&include=bib&sort=date&itemType=-attachment&q=";
    var limit = "&limit=" + ZOTERO_CONFIG["limit"];
    start = "&start=" + start;
    var url = base + publicGroupId + params + query + limit + start;
    showUrl(url);
    show_loading(true);
    makeCorsRequest(url, successCallback, errorCallback);
}

// When the window loads, read query parameters and perform search
window.onload = function() {
    var query = getParameterByName("q");
    var start = getParameterByName("start");
    if (query == null) {
        query = "";
    }
    document.forms.zoteroSearchForm.q.value = query;
    if (!start) {
        start = 0;
    }
    searchZotero(query, ZOTERO_CONFIG["publicGroupId"], start);
};<|endoftext|>


<commit_before>//Author-Albert Sanchez
//Description-Create a Metric Hex Nut
function run(context) {
  "use strict";
  var metricHexNutMatrix = [
    {nominalSize: 'M1.6', d: 1.6, af: 3.2, k: 1.3},
    {nominalSize: 'M2',   d: 2,   af: 4,   k: 1.6},
    {nominalSize: 'M2.5', d: 2.5, af: 5,   k: 2},
    {nominalSize: 'M3',   d: 3,   af: 5.5, k: 2.4},
    {nominalSize: 'M4',   d: 4,   af: 7,   k: 3.2},
    {nominalSize: 'M5',   d: 5,   af: 8,   k: 4.7},
    {nominalSize: 'M6',   d: 6,   af: 10,  k: 5.2},
    {nominalSize: 'M8',   d: 8,   af: 13,  k: 6.8},
    {nominalSize: 'M10',  d: 10,  af: 16,  k: 8.4},
    {nominalSize: 'M12',  d: 12,  af: 18,  k: 10.8},
    {nominalSize: 'M14',  d: 14,  af: 21,  k: 12.8},
    {nominalSize: 'M16',  d: 16,  af: 24,  k: 14.8},
    {nominalSize: 'M20',  d: 20,  af: 30,  k: 18},
    {nominalSize: 'M24',  d: 24,  af: 36,  k: 21.5},
    {nominalSize: 'M30',  d: 30,  af: 46,  k: 25.6},
    {nominalSize: 'M36',  d: 36,  af: 55,  k: 31},
    {nominalSize: 'M42',  d: 42,  af: 65,  k: 34},
    {nominalSize: 'M48',  d: 48,  af: 75,  k: 38},
    {nominalSize: 'M56',  d: 56,  af: 85,  k: 45},
    {nominalSize: 'M64',  d: 64,  af: 95,  k: 51}
  ];
  for (var i = 0; i < metricHexNutMatrix.length; i++) {
    metricHexNutMatrix[i].d = metricHexNutMatrix[i].d / 10;
    metricHexNutMatrix[i].ac = (2 * metricHexNutMatrix[i].af) / Math.sqrt(3);
    metricHexNutMatrix[i].af = metricHexNutMatrix[i].af / 10;
    metricHexNutMatrix[i].ac = metricHexNutMatrix[i].ac / 10;
    metricHexNutMatrix[i].k = metricHexNutMatrix[i].k / 10;
  }
  var app = adsk.core.Application.get(), ui;
  if (app) {
    ui = app.userInterface;
  }
  var product = app.activeProduct;
  var design = adsk.fusion.Design(product);
  if (!design) {
    ui.messageBox('It is not supported in current workspace, please change to MODEL workspace and try again.');
    adsk.terminate();
    return;
  }
  var newComp;
  function createNewComponent() {
    var rootComp = design.rootComponent;
    var allOccs = rootComp.occurrences;
    var newOcc = allOccs.addNewComponent(adsk.core.Matrix3D.create());
    newComp = newOcc.component;
  };
  var createCommandDefinition = function() {
    var commandDefinitions = ui.commandDefinitions;
    var cmDef = commandDefinitions.itemById('MetricHexNut');
    if (!cmDef) {
      cmDef = commandDefinitions.addButtonDefinition('MetricHexNut', 'Create Metric Hex Nut', 'Create a Metric Hex Nut.', './resources');
    }
    return cmDef;
  };
  var onCommandCreated = function(args) {
    try {
      var command = args.command;
      command.isRepeatable = false;
      command.execute.add(onCommandExecuted);
      command.executePreview.add(onCommandExecuted);
      command.destroy.add(function() {
        adsk.terminate();
      });
      var inputs = command.commandInputs;
      inputs.addImageCommandInput("image", "", "resources/example.png");
      inputs.addStringValueInput('metricHexNutName', 'Hex Nut Name', 'Metric Hex Nut');
      var initNominalSize = inputs.addDropDownCommandInput('nominalSize', 'Nominal Size', adsk.core.DropDownStyles.TextListDropDownStyle);
      initNominalSize.listItems.add(metricHexNutMatrix[0].nominalSize, true, '');
      for (var i = 1; i < metricHexNutMatrix.length; i++) {
        initNominalSize.listItems.add(metricHexNutMatrix[i].nominalSize, false, '');
      }
      initNominalSize.listItems.add('Custom', false, '');
      var initD = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].d);
      inputs.addValueInput('D', '(d) Diameter', 'cm', initD);
      var initAf = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].af);
      inputs.addValueInput('Af', '(af) Width Across Flats', 'cm', initAf);
      var initWidthAc = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].ac);
      inputs.addValueInput('Ac', '(ac) Width Across Corners', 'cm', initWidthAc);
      var initK = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].k);
      inputs.addValueInput('K', '(k) Thickness', 'cm', initK);
    }
    catch (e) {
      ui.messageBox('Failed to create command : ' + (e.description ? e.description : e));
    }
  };
  var onCommandExecuted = function(args) {
    try {
      var unitsMgr = app.activeProduct.unitsManager;
      var command = adsk.core.Command(args.firingEvent.sender);
      var inputs = command.commandInputs;
      var metricHexNut = new MetricHexNut();
      var selectedItemObject = new Object();
      for (var i = 0; i < inputs.count; i++) {
        var input = inputs.item(i);
        if (input.id === 'nominalSize') {
          var selectedItem = input.selectedItem.name;
          for (var j = 0; j < metricHexNutMatrix.length; j++) {
            if (selectedItem == metricHexNutMatrix[j].nominalSize) {
              selectedItemObject = metricHexNutMatrix[j];
              break;
            }
          }
          break;
        }
      }
      for (var i = 0; i < inputs.count; i++) {
        var input = inputs.item(i);
        if (input.id === 'metricHexNutName') {
          metricHexNut.values.metricHexNutName = input.value;
        } else if (input.id === 'D') {
          input.value = selectedItemObject.d;
          metricHexNut.values.d = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'Af') {
          input.value = selectedItemObject.af;
          metricHexNut.values.af = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'Ac') {
          input.value = selectedItemObject.ac;
          metricHexNut.values.ac = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'K') {
          input.value = selectedItemObject.k;
          metricHexNut.values.k = unitsMgr.evaluateExpression(input.expression, "cm");
        }
      }
      metricHexNut.buildMetricHexNut();
      args.isValidResult = true;
    }
    catch (e) {
      ui.messageBox('Failed to create Metric Hex Nut: ' + (e.description ? e.description : e));
    }
  };
  var MetricHexNut = function() {
    this.values = {
      metricHexNutName: 'Metric Hex Nut',
      d: metricHexNutMatrix[0].d,
      af: metricHexNutMatrix[0].af,
      ac: metricHexNutMatrix[0].ac,
      k: metricHexNutMatrix[0].k,
      thread: ""
    };
    this.buildMetricHexNut = function() {
      createNewComponent();
      if (!newComp) {
        ui.messageBox('New component failed to create', 'New Component Failed');
        adsk.terminate();
        return;
      }
      var sketches = newComp.sketches;
      var sketch = sketches.add(newComp.xYConstructionPlane);
      var center = adsk.core.Point3D.create(0, 0, 0);
      var vertices = [];
      for (var i = 0; i < 6; i++) {
        var vertex = adsk.core.Point3D.create((this.values.af / Math.sqrt(3)) * Math.cos(Math.PI * i / 3 + (30 * (Math.PI / 180))), (this.values.af / Math.sqrt(3)) * Math.sin(Math.PI * i / 3 + (30 * (Math.PI / 180))), 0);
        vertices.push(vertex);
      }
      for (i = 0; i < 6; i++) {
        sketch.sketchCurves.sketchLines.addByTwoPoints(vertices[(i + 1) % 6], vertices[i]);
      }
      var prof = sketch.profiles.item(0);
      var extrudes = newComp.features.extrudeFeatures;
      var extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation);
      var distance = adsk.core.ValueInput.createByReal(this.values.k);
      extInput.setDistanceExtent(false, distance);
      var ext = extrudes.add(extInput);
      var body = ext.bodies.item(0);
      body.name = this.values.metricHexNutName;
      var endFaces = ext.endFaces;
      var endFace = endFaces.item(0);
      var planes = newComp.constructionPlanes;
      var planeInput = planes.createInput();
      var offsetVal = adsk.core.ValueInput.createByString('0 cm');
      planeInput.setByOffset(endFace, offsetVal);
      var offsetPlane = planes.add(planeInput);
      var offsetSketch = sketches.add(offsetPlane);
      var offsetSketchPoints = offsetSketch.sketchPoints;
      var centerHole = offsetSketchPoints.add(center);
      var ptColl = adsk.core.ObjectCollection.create();
      ptColl.add(centerHole);
      var holes = newComp.features.holeFeatures;
      var holeInput = holes.createSimpleInput(adsk.core.ValueInput.createByReal(this.values.d));
      holeInput.setPositionBySketchPoints(ptColl);
      holeInput.setDistanceExtent(distance);
      holes.add(holeInput);
      var revolveSketch = sketches.add(newComp.xZConstructionPlane);
      var radius = this.values.ac / 2;
      var point1 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius * Math.cos(Math.PI / 6), 0, 0));
      var point2 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius, 0, 0));
      var point3 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(point2.x, 0, (point2.x - point1.x) * Math.tan(30 * (Math.PI / 180))));
      var point4 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius * Math.cos(Math.PI / 6), 0, this.values.k - center.y));
      var point5 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius, 0, this.values.k - center.y));
      var point6 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(point2.x, 0, this.values.k - center.y - (point5.x - point4.x) * Math.tan(30 * (Math.PI / 180))));
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point1, point2);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point2, point3);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point3, point1);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point4, point5);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point5, point6);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point6, point4);
      var revolves = newComp.features.revolveFeatures;
      var revInputOne = revolves.createInput(revolveSketch.profiles.item(0), newComp.zConstructionAxis, adsk.fusion.FeatureOperations.CutFeatureOperation);
      var revInputTwo = revolves.createInput(revolveSketch.profiles.item(1), newComp.zConstructionAxis, adsk.fusion.FeatureOperations.CutFeatureOperation);
      var angle = adsk.core.ValueInput.createByReal(Math.PI * 2);
      revInputOne.setAngleExtent(false, angle);
      revInputTwo.setAngleExtent(false, angle);
      revolves.add(revInputOne);
      revolves.add(revInputTwo);
      var threadFeatures = newComp.features.threadFeatures;
      var threadDataQuery = threadFeatures.threadDataQuery;
      var defaultThreadType = threadDataQuery.defaultMetricThreadType;
      var designate = new Object();
      var threadClass = new Object();
      var isOk = threadDataQuery.recommendThreadData(this.values.d, true, defaultThreadType, designate, threadClass);
      if (isOk) {
        this.values.thread = designate.value;
        var hole = holes.item(0);
        var sideFace = hole.sideFaces.item(0);
        var threadInfo = threadFeatures.createThreadInfo(true, defaultThreadType, designate.value, threadClass.value);
        var threadInput = threadFeatures.createInput(sideFace, threadInfo);
        threadInput.threadLength = adsk.core.ValueInput.createByReal(this.values.k - (this.values.k * 0.01));
        threadFeatures.add(threadInput);
      }
    };
  };
  try {
    if (adsk.debug === true) {
      debugger;
    }
    var command = createCommandDefinition();
    var commandCreatedEvent = command.commandCreated;
    commandCreatedEvent.add(onCommandCreated);
    command.execute();
  }
  catch (e) {
    if (ui) {
      ui.messageBox('Failed : ' + (e.description ? e.description : e));
    }
    adsk.terminate();
  }
}
<commit_msg>show thread pitch<commit_after>//Author-Albert Sanchez
//Description-Create a Metric Hex Nut
function run(context) {
  "use strict";
  var metricHexNutMatrix = [
    {nominalSize: 'M1.6', d: 1.6, af: 3.2, k: 1.3},
    {nominalSize: 'M2',   d: 2,   af: 4,   k: 1.6},
    {nominalSize: 'M2.5', d: 2.5, af: 5,   k: 2},
    {nominalSize: 'M3',   d: 3,   af: 5.5, k: 2.4},
    {nominalSize: 'M4',   d: 4,   af: 7,   k: 3.2},
    {nominalSize: 'M5',   d: 5,   af: 8,   k: 4.7},
    {nominalSize: 'M6',   d: 6,   af: 10,  k: 5.2},
    {nominalSize: 'M8',   d: 8,   af: 13,  k: 6.8},
    {nominalSize: 'M10',  d: 10,  af: 16,  k: 8.4},
    {nominalSize: 'M12',  d: 12,  af: 18,  k: 10.8},
    {nominalSize: 'M14',  d: 14,  af: 21,  k: 12.8},
    {nominalSize: 'M16',  d: 16,  af: 24,  k: 14.8},
    {nominalSize: 'M20',  d: 20,  af: 30,  k: 18},
    {nominalSize: 'M24',  d: 24,  af: 36,  k: 21.5},
    {nominalSize: 'M30',  d: 30,  af: 46,  k: 25.6},
    {nominalSize: 'M36',  d: 36,  af: 55,  k: 31},
    {nominalSize: 'M42',  d: 42,  af: 65,  k: 34},
    {nominalSize: 'M48',  d: 48,  af: 75,  k: 38},
    {nominalSize: 'M56',  d: 56,  af: 85,  k: 45},
    {nominalSize: 'M64',  d: 64,  af: 95,  k: 51}
  ];
  for (var i = 0; i < metricHexNutMatrix.length; i++) {
    metricHexNutMatrix[i].d = metricHexNutMatrix[i].d / 10;
    metricHexNutMatrix[i].ac = (2 * metricHexNutMatrix[i].af) / Math.sqrt(3);
    metricHexNutMatrix[i].af = metricHexNutMatrix[i].af / 10;
    metricHexNutMatrix[i].ac = metricHexNutMatrix[i].ac / 10;
    metricHexNutMatrix[i].k = metricHexNutMatrix[i].k / 10;
  }
  var app = adsk.core.Application.get(), ui;
  if (app) {
    ui = app.userInterface;
  }
  var product = app.activeProduct;
  var design = adsk.fusion.Design(product);
  if (!design) {
    ui.messageBox('It is not supported in current workspace, please change to MODEL workspace and try again.');
    adsk.terminate();
    return;
  }
  var newComp;
  function createNewComponent() {
    var rootComp = design.rootComponent;
    var allOccs = rootComp.occurrences;
    var newOcc = allOccs.addNewComponent(adsk.core.Matrix3D.create());
    newComp = newOcc.component;
  };
  var createCommandDefinition = function() {
    var commandDefinitions = ui.commandDefinitions;
    var cmDef = commandDefinitions.itemById('MetricHexNut');
    if (!cmDef) {
      cmDef = commandDefinitions.addButtonDefinition('MetricHexNut', 'Create Metric Hex Nut', 'Create a Metric Hex Nut.', './resources');
    }
    return cmDef;
  };
  var onCommandCreated = function(args) {
    try {
      var command = args.command;
      command.isRepeatable = false;
      command.execute.add(onCommandExecuted);
      command.executePreview.add(onCommandExecuted);
      command.destroy.add(function() {
        adsk.terminate();
      });
      var inputs = command.commandInputs;
      inputs.addImageCommandInput("image", "", "resources/example.png");
      inputs.addStringValueInput('metricHexNutName', 'Hex Nut Name', 'Metric Hex Nut');
      var initNominalSize = inputs.addDropDownCommandInput('nominalSize', 'Nominal Size', adsk.core.DropDownStyles.TextListDropDownStyle);
      initNominalSize.listItems.add(metricHexNutMatrix[0].nominalSize, true, '');
      for (var i = 1; i < metricHexNutMatrix.length; i++) {
        initNominalSize.listItems.add(metricHexNutMatrix[i].nominalSize, false, '');
      }
      initNominalSize.listItems.add('Custom', false, '');
      var initD = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].d);
      inputs.addValueInput('D', '(d) Diameter', 'cm', initD);
      var initAf = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].af);
      inputs.addValueInput('Af', '(af) Width Across Flats', 'cm', initAf);
      var initWidthAc = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].ac);
      inputs.addValueInput('Ac', '(ac) Width Across Corners', 'cm', initWidthAc);
      var initK = adsk.core.ValueInput.createByReal(metricHexNutMatrix[0].k);
      inputs.addValueInput('K', '(k) Thickness', 'cm', initK);
      var threadText = inputs.addStringValueInput('thread', 'Thread Pitch', '');
      threadText.isReadOnly = true;
    }
    catch (e) {
      ui.messageBox('Failed to create command : ' + (e.description ? e.description : e));
    }
  };
  var onCommandExecuted = function(args) {
    try {
      var unitsMgr = app.activeProduct.unitsManager;
      var command = adsk.core.Command(args.firingEvent.sender);
      var inputs = command.commandInputs;
      var metricHexNut = new MetricHexNut();
      var selectedItemObject = new Object();
      for (var i = 0; i < inputs.count; i++) {
        var input = inputs.item(i);
        if (input.id === 'nominalSize') {
          var selectedItem = input.selectedItem.name;
          for (var j = 0; j < metricHexNutMatrix.length; j++) {
            if (selectedItem == metricHexNutMatrix[j].nominalSize) {
              selectedItemObject = metricHexNutMatrix[j];
              break;
            }
          }
          break;
        }
      }
      for (var i = 0; i < inputs.count; i++) {
        var input = inputs.item(i);
        if (input.id === 'metricHexNutName') {
          metricHexNut.values.metricHexNutName = input.value;
        } else if (input.id === 'D') {
          input.value = selectedItemObject.d;
          metricHexNut.values.d = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'Af') {
          input.value = selectedItemObject.af;
          metricHexNut.values.af = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'Ac') {
          input.value = selectedItemObject.ac;
          metricHexNut.values.ac = unitsMgr.evaluateExpression(input.expression, "cm");
        } else if (input.id === 'K') {
          input.value = selectedItemObject.k;
          metricHexNut.values.k = unitsMgr.evaluateExpression(input.expression, "cm");
        }
      }
      metricHexNut.buildMetricHexNut();
      for (var i = 0; i < inputs.count; i++) {
        var input = inputs.item(i);
        if (input.id === 'thread') {
          input.value = metricHexNut.values.thread;
          break;
        }
      }
      args.isValidResult = true;
    }
    catch (e) {
      ui.messageBox('Failed to create Metric Hex Nut: ' + (e.description ? e.description : e));
    }
  };
  var MetricHexNut = function() {
    this.values = {
      metricHexNutName: 'Metric Hex Nut',
      d: metricHexNutMatrix[0].d,
      af: metricHexNutMatrix[0].af,
      ac: metricHexNutMatrix[0].ac,
      k: metricHexNutMatrix[0].k,
      thread: ""
    };
    this.buildMetricHexNut = function() {
      createNewComponent();
      if (!newComp) {
        ui.messageBox('New component failed to create', 'New Component Failed');
        adsk.terminate();
        return;
      }
      var sketches = newComp.sketches;
      var sketch = sketches.add(newComp.xYConstructionPlane);
      var center = adsk.core.Point3D.create(0, 0, 0);
      var vertices = [];
      for (var i = 0; i < 6; i++) {
        var vertex = adsk.core.Point3D.create((this.values.af / Math.sqrt(3)) * Math.cos(Math.PI * i / 3 + (30 * (Math.PI / 180))), (this.values.af / Math.sqrt(3)) * Math.sin(Math.PI * i / 3 + (30 * (Math.PI / 180))), 0);
        vertices.push(vertex);
      }
      for (i = 0; i < 6; i++) {
        sketch.sketchCurves.sketchLines.addByTwoPoints(vertices[(i + 1) % 6], vertices[i]);
      }
      var prof = sketch.profiles.item(0);
      var extrudes = newComp.features.extrudeFeatures;
      var extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation);
      var distance = adsk.core.ValueInput.createByReal(this.values.k);
      extInput.setDistanceExtent(false, distance);
      var ext = extrudes.add(extInput);
      var body = ext.bodies.item(0);
      body.name = this.values.metricHexNutName;
      var endFaces = ext.endFaces;
      var endFace = endFaces.item(0);
      var planes = newComp.constructionPlanes;
      var planeInput = planes.createInput();
      var offsetVal = adsk.core.ValueInput.createByString('0 cm');
      planeInput.setByOffset(endFace, offsetVal);
      var offsetPlane = planes.add(planeInput);
      var offsetSketch = sketches.add(offsetPlane);
      var offsetSketchPoints = offsetSketch.sketchPoints;
      var centerHole = offsetSketchPoints.add(center);
      var ptColl = adsk.core.ObjectCollection.create();
      ptColl.add(centerHole);
      var holes = newComp.features.holeFeatures;
      var holeInput = holes.createSimpleInput(adsk.core.ValueInput.createByReal(this.values.d));
      holeInput.setPositionBySketchPoints(ptColl);
      holeInput.setDistanceExtent(distance);
      holes.add(holeInput);
      var revolveSketch = sketches.add(newComp.xZConstructionPlane);
      var radius = this.values.ac / 2;
      var point1 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius * Math.cos(Math.PI / 6), 0, 0));
      var point2 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius, 0, 0));
      var point3 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(point2.x, 0, (point2.x - point1.x) * Math.tan(30 * (Math.PI / 180))));
      var point4 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius * Math.cos(Math.PI / 6), 0, this.values.k - center.y));
      var point5 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(radius, 0, this.values.k - center.y));
      var point6 = revolveSketch.modelToSketchSpace(adsk.core.Point3D.create(point2.x, 0, this.values.k - center.y - (point5.x - point4.x) * Math.tan(30 * (Math.PI / 180))));
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point1, point2);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point2, point3);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point3, point1);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point4, point5);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point5, point6);
      revolveSketch.sketchCurves.sketchLines.addByTwoPoints(point6, point4);
      var revolves = newComp.features.revolveFeatures;
      var revInputOne = revolves.createInput(revolveSketch.profiles.item(0), newComp.zConstructionAxis, adsk.fusion.FeatureOperations.CutFeatureOperation);
      var revInputTwo = revolves.createInput(revolveSketch.profiles.item(1), newComp.zConstructionAxis, adsk.fusion.FeatureOperations.CutFeatureOperation);
      var angle = adsk.core.ValueInput.createByReal(Math.PI * 2);
      revInputOne.setAngleExtent(false, angle);
      revInputTwo.setAngleExtent(false, angle);
      revolves.add(revInputOne);
      revolves.add(revInputTwo);
      var threadFeatures = newComp.features.threadFeatures;
      var threadDataQuery = threadFeatures.threadDataQuery;
      var defaultThreadType = threadDataQuery.defaultMetricThreadType;
      var designate = new Object();
      var threadClass = new Object();
      var isOk = threadDataQuery.recommendThreadData(this.values.d, true, defaultThreadType, designate, threadClass);
      if (isOk) {
        this.values.thread = designate.value;
        var hole = holes.item(0);
        var sideFace = hole.sideFaces.item(0);
        var threadInfo = threadFeatures.createThreadInfo(true, defaultThreadType, designate.value, threadClass.value);
        var threadInput = threadFeatures.createInput(sideFace, threadInfo);
        threadInput.threadLength = adsk.core.ValueInput.createByReal(this.values.k - (this.values.k * 0.01));
        threadFeatures.add(threadInput);
      }
    };
  };
  try {
    if (adsk.debug === true) {
      debugger;
    }
    var command = createCommandDefinition();
    var commandCreatedEvent = command.commandCreated;
    commandCreatedEvent.add(onCommandCreated);
    command.execute();
  }
  catch (e) {
    if (ui) {
      ui.messageBox('Failed : ' + (e.description ? e.description : e));
    }
    adsk.terminate();
  }
}
<|endoftext|>