entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"2John\"]\n\t\tregexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ", "end": 15465, "score": 0.6340222358703613, "start": 15464, "tag": "NAME", "value": "2" }, { "context": "\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"2John\"]\n\t\tregexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-", "end": 15469, "score": 0.4958961606025696, "start": 15465, "tag": "NAME", "value": "John" }, { "context": "-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:2John)|(?:2[\\s\\xa0]*Joh(?:annes(?:['’][\\s\\xa0]*Brev", "end": 15542, "score": 0.5597615242004395, "start": 15541, "tag": "NAME", "value": "2" }, { "context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"3John\"]\n\t\tregexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ", "end": 15876, "score": 0.832212507724762, "start": 15875, "tag": "NAME", "value": "3" }, { "context": "\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"3John\"]\n\t\tregexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-", "end": 15880, "score": 0.5119724273681641, "start": 15876, "tag": "NAME", "value": "John" }, { "context": "-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:3John)|(?:(?:3(?:\\.[\\s\\xa0]*Johannes['’]|[\\s\\xa0]*J", "end": 15953, "score": 0.7581199407577515, "start": 15952, "tag": "NAME", "value": "3" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/da/regexps.coffee
saiba-mais/bible-lessons
149
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | title (?! [a-z] ) #could be followed by a number | kapitlerne | kapitel | vers | kap | ff | og | jf | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* title | \d \W* ff (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Første|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Anden|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Tredje|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:og|jf)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Mos(?:ebog)?|Gen(?:esis)?|1\.[\s\xa0]*Mos(?:ebog)?|F\xF8rste[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Mos(?:ebog)?|Exod(?:us)?|2\.[\s\xa0]*Mos(?:ebog)?|Anden[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*og[\s\xa0]*Dragen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3[\s\xa0]*Mos(?:ebog)?|Lev(?:iticus)?|3\.[\s\xa0]*Mos(?:ebog)?|Tredje[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4[\s\xa0]*Mos(?:ebog)?|Num(?:eri)?|4\.[\s\xa0]*Mos(?:ebog)?|Fjerde[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sir(?:ak(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Visdommen(?:s[\s\xa0]*Bog)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Klag(?:es(?:angene)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jeremias['’][\s\xa0]*Brev|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:A(?:benbaringsbo|abenbarin)|\xC5benbaringsbo)gen|[A\xC5]benbaringen|Rev|Apokalypsen|[A\xC5]b|Joh(?:annes(?:['’][\s\xa0]*[A\xC5]benbaring|apokalypsen)|s(?:\.[\s\xa0]*[A\xC5]|[\s\xa0]*[A\xC5])benbaring)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Manasses[\s\xa0]*B\xF8|PrMa)n) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Femte|5\.?)[\s\xa0]*Mosebog|(?:Femte|5\.?)[\s\xa0]*Mos|Deut(?:eronomium)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jos(?:va(?:bog(?:en)?|s[\s\xa0]*Bog)|ua|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dom(?:mer(?:bogen)?)?|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rut(?:h(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:[13][\s\xa0]*Esdrasbog|1Esd|[13]\.[\s\xa0]*Esdrasbog|Tredje[\s\xa0]*Esdrasbog|F\xF8rste[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|[24]\.)[\s\xa0]*Esdrasbog|[24][\s\xa0]*Esdrasbog|2Esd|Fjerde[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Es(?:ajas(?:['’][\s\xa0]*Bog)?)?|(?:Jesai|Is)a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|Anden[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|F\xF8rste[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Kongebog)|(?:(?:Anden|2\.?)[\s\xa0]*Kong|2Kgs|4[\s\xa0]*Kongerigernes[\s\xa0]*Bog|4\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Fjerde[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Kongebog)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Kong|1Kgs|3[\s\xa0]*Kongerigernes[\s\xa0]*Bog|3\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Tredje[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|Anden[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|F\xF8rste[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er(?:s[\s\xa0]*Bog)?|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job(?:s[\s\xa0]*Bog)?|Hiob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:alme(?:rne(?:s[\s\xa0]*Bog)?)?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Azarjas[\s\xa0]*[Bb]\xF8n|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ordsp(?:rogene(?:s[\s\xa0]*Bog)?)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:\xE6d(?:ikeren(?:s[\s\xa0]*Bog)?)?|ad)|Eccl) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:De[\s\xa0]*(?:Tre[\s\xa0]*M\xE6nds[\s\xa0]*L|tre[\s\xa0]*m\xE6nds[\s\xa0]*l)ovsang|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:\xF8jsangen|ojs|\xF8js)|S(?:alomons[\s\xa0]*H\xF8jsa|o)ng) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jer(?:emias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:ek(?:iel(?:s’?[\s\xa0]*Bog)?)?)?|Hezechiel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dan(?:iel(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:eas(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joel(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Obad(?:ias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:a(?:s(?:['’][\s\xa0]*Bog)?|h))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:ka(?:s(?:[\s\xa0]*Bog)?)?|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akkuk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Zefanias’[\s\xa0]*Bog)|(?:Sef(?:anias['’][\s\xa0]*Bog)?|Ze(?:fanias|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:aj(?:s[\s\xa0]*Bog)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ak(?:arias(?:['’][\s\xa0]*Bog)?)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:akias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matt(?:h\xE6us(?:evangeliet)?|\xE6usevangeliet)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mark(?:us(?:evangeliet)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:as(?:evangeliet)?|e)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Johannes['’][\s\xa0]*(?:F\xF8rste|1\.)[\s\xa0]*Brev|Johannes['’][\s\xa0]*1[\s\xa0]*Brev|1John|1[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|1\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|F\xF8rste[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2John)|(?:2[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Johannes['’][\s\xa0]*Andet[\s\xa0]*Brev|2\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Ande(?:n[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|t[\s\xa0]*Johannesbrev)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3John)|(?:(?:3(?:\.[\s\xa0]*Johannes['’]|[\s\xa0]*Johannes['’])|Tredje[\s\xa0]*Johannes['’])[\s\xa0]*Brev|(?:Tredje|3\.?)[\s\xa0]*Johannesbrev|(?:Tredje|3\.?)[\s\xa0]*Joh|Johannes['’][\s\xa0]*(?:Tredje|3\.?)[\s\xa0]*Brev)|(?:(?:Tredje|3\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joh(?:annes(?:evangeliet)?|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:p(?:ostlenes[\s\xa0]*Gerninger|[Gg]|\.G)|cts)|Gerninger) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Romerne|Rom(?:erbrevet|erne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Korinterne)|(?:2(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|Ande(?:n[\s\xa0]*Korinth?|t[\s\xa0]*Korinth)erbrev|(?:Anden|2\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Korinterne)|(?:1(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|F\xF8rste[\s\xa0]*Korinth?erbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aterbrevet|aterne)?|Brevet[\s\xa0]*til[\s\xa0]*Galaterne|Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Galaterne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Efeserne)|(?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Efeserne|E(?:feserbrevet|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filipperne|hil)|Fil(?:ipperbrevet|ipperne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Kolossenserne|Kolossenser(?:brevet|n)|Col|Kol) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|Ande[nt][\s\xa0]*Thessalonikerbrev|(?:Anden|2\.?)[\s\xa0]*Thess|(?:Anden|2\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|F\xF8rste[\s\xa0]*Thessalonikerbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Thess|(?:F\xF8rste|1\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|Ande(?:n[\s\xa0]*Timoth?|t[\s\xa0]*Timoth)eusbrev|2(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|Anden[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|F\xF8rste[\s\xa0]*Timoth?eusbrev|1(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|F\xF8rste[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Titus|Tit(?:usbrevet|us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filemon|hlm)|F(?:ilemonbrevet|lm|ilem(?:on)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hebr\xE6erne)|(?:Brevet[\s\xa0]*til[\s\xa0]*Hebr\xE6erne|Heb(?:r\xE6erbrevet|r)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:ob(?:s(?:brevet|[\s\xa0]*Brev))?)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Petersbrev)|(?:2(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|Anden[\s\xa0]*Peter|(?:Anden|2\.?)[\s\xa0]*Pet|Andet[\s\xa0]*Petersbrev|Peters[\s\xa0]*Andet[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Petersbrev)|(?:1(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|F\xF8rste[\s\xa0]*Peter|(?:F\xF8rste|1\.?)[\s\xa0]*Pet|Peters[\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as(?:['’][\s\xa0]*Brev|brevet)?|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:it(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udit(?:s[\s\xa0]*Bog)?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Anden[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Tredje[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Fjerde[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|F\xF8rste[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
16686
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | title (?! [a-z] ) #could be followed by a number | kapitlerne | kapitel | vers | kap | ff | og | jf | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* title | \d \W* ff (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Første|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Anden|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Tredje|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:og|jf)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Mos(?:ebog)?|Gen(?:esis)?|1\.[\s\xa0]*Mos(?:ebog)?|F\xF8rste[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Mos(?:ebog)?|Exod(?:us)?|2\.[\s\xa0]*Mos(?:ebog)?|Anden[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*og[\s\xa0]*Dragen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3[\s\xa0]*Mos(?:ebog)?|Lev(?:iticus)?|3\.[\s\xa0]*Mos(?:ebog)?|Tredje[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4[\s\xa0]*Mos(?:ebog)?|Num(?:eri)?|4\.[\s\xa0]*Mos(?:ebog)?|Fjerde[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sir(?:ak(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Visdommen(?:s[\s\xa0]*Bog)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Klag(?:es(?:angene)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jeremias['’][\s\xa0]*Brev|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:A(?:benbaringsbo|abenbarin)|\xC5benbaringsbo)gen|[A\xC5]benbaringen|Rev|Apokalypsen|[A\xC5]b|Joh(?:annes(?:['’][\s\xa0]*[A\xC5]benbaring|apokalypsen)|s(?:\.[\s\xa0]*[A\xC5]|[\s\xa0]*[A\xC5])benbaring)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Manasses[\s\xa0]*B\xF8|PrMa)n) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Femte|5\.?)[\s\xa0]*Mosebog|(?:Femte|5\.?)[\s\xa0]*Mos|Deut(?:eronomium)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jos(?:va(?:bog(?:en)?|s[\s\xa0]*Bog)|ua|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dom(?:mer(?:bogen)?)?|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rut(?:h(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:[13][\s\xa0]*Esdrasbog|1Esd|[13]\.[\s\xa0]*Esdrasbog|Tredje[\s\xa0]*Esdrasbog|F\xF8rste[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|[24]\.)[\s\xa0]*Esdrasbog|[24][\s\xa0]*Esdrasbog|2Esd|Fjerde[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Es(?:ajas(?:['’][\s\xa0]*Bog)?)?|(?:Jesai|Is)a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|Anden[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|F\xF8rste[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Kongebog)|(?:(?:Anden|2\.?)[\s\xa0]*Kong|2Kgs|4[\s\xa0]*Kongerigernes[\s\xa0]*Bog|4\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Fjerde[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Kongebog)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Kong|1Kgs|3[\s\xa0]*Kongerigernes[\s\xa0]*Bog|3\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Tredje[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|Anden[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|F\xF8rste[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er(?:s[\s\xa0]*Bog)?|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job(?:s[\s\xa0]*Bog)?|Hiob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:alme(?:rne(?:s[\s\xa0]*Bog)?)?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Azarjas[\s\xa0]*[Bb]\xF8n|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ordsp(?:rogene(?:s[\s\xa0]*Bog)?)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:\xE6d(?:ikeren(?:s[\s\xa0]*Bog)?)?|ad)|Eccl) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:De[\s\xa0]*(?:Tre[\s\xa0]*M\xE6nds[\s\xa0]*L|tre[\s\xa0]*m\xE6nds[\s\xa0]*l)ovsang|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:\xF8jsangen|ojs|\xF8js)|S(?:alomons[\s\xa0]*H\xF8jsa|o)ng) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jer(?:emias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:ek(?:iel(?:s’?[\s\xa0]*Bog)?)?)?|Hezechiel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dan(?:iel(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:eas(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joel(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Obad(?:ias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:a(?:s(?:['’][\s\xa0]*Bog)?|h))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:ka(?:s(?:[\s\xa0]*Bog)?)?|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akkuk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Zefanias’[\s\xa0]*Bog)|(?:Sef(?:anias['’][\s\xa0]*Bog)?|Ze(?:fanias|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:aj(?:s[\s\xa0]*Bog)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ak(?:arias(?:['’][\s\xa0]*Bog)?)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:akias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matt(?:h\xE6us(?:evangeliet)?|\xE6usevangeliet)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mark(?:us(?:evangeliet)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:as(?:evangeliet)?|e)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Johannes['’][\s\xa0]*(?:F\xF8rste|1\.)[\s\xa0]*Brev|Johannes['’][\s\xa0]*1[\s\xa0]*Brev|1John|1[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|1\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|F\xF8rste[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["<NAME> <NAME>"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:<NAME>John)|(?:2[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Johannes['’][\s\xa0]*Andet[\s\xa0]*Brev|2\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Ande(?:n[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|t[\s\xa0]*Johannesbrev)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["<NAME> <NAME>"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:<NAME>John)|(?:(?:3(?:\.[\s\xa0]*Johannes['’]|[\s\xa0]*Johannes['’])|Tredje[\s\xa0]*Johannes['’])[\s\xa0]*Brev|(?:Tredje|3\.?)[\s\xa0]*Johannesbrev|(?:Tredje|3\.?)[\s\xa0]*Joh|Johannes['’][\s\xa0]*(?:Tredje|3\.?)[\s\xa0]*Brev)|(?:(?:Tredje|3\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joh(?:annes(?:evangeliet)?|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:p(?:ostlenes[\s\xa0]*Gerninger|[Gg]|\.G)|cts)|Gerninger) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Romerne|Rom(?:erbrevet|erne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Korinterne)|(?:2(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|Ande(?:n[\s\xa0]*Korinth?|t[\s\xa0]*Korinth)erbrev|(?:Anden|2\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Korinterne)|(?:1(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|F\xF8rste[\s\xa0]*Korinth?erbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aterbrevet|aterne)?|Brevet[\s\xa0]*til[\s\xa0]*Galaterne|Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Galaterne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Efeserne)|(?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Efeserne|E(?:feserbrevet|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filipperne|hil)|Fil(?:ipperbrevet|ipperne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Kolossenserne|Kolossenser(?:brevet|n)|Col|Kol) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|Ande[nt][\s\xa0]*Thessalonikerbrev|(?:Anden|2\.?)[\s\xa0]*Thess|(?:Anden|2\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|F\xF8rste[\s\xa0]*Thessalonikerbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Thess|(?:F\xF8rste|1\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|Ande(?:n[\s\xa0]*Timoth?|t[\s\xa0]*Timoth)eusbrev|2(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|Anden[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|F\xF8rste[\s\xa0]*Timoth?eusbrev|1(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|F\xF8rste[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Titus|Tit(?:usbrevet|us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filemon|hlm)|F(?:ilemonbrevet|lm|ilem(?:on)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hebr\xE6erne)|(?:Brevet[\s\xa0]*til[\s\xa0]*Hebr\xE6erne|Heb(?:r\xE6erbrevet|r)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:ob(?:s(?:brevet|[\s\xa0]*Brev))?)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Petersbrev)|(?:2(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|Anden[\s\xa0]*Peter|(?:Anden|2\.?)[\s\xa0]*Pet|Andet[\s\xa0]*Petersbrev|Peters[\s\xa0]*Andet[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Petersbrev)|(?:1(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|F\xF8rste[\s\xa0]*Peter|(?:F\xF8rste|1\.?)[\s\xa0]*Pet|Peters[\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as(?:['’][\s\xa0]*Brev|brevet)?|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:it(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udit(?:s[\s\xa0]*Bog)?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Anden[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Tredje[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Fjerde[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|F\xF8rste[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
true
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | title (?! [a-z] ) #could be followed by a number | kapitlerne | kapitel | vers | kap | ff | og | jf | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* title | \d \W* ff (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Første|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Anden|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Tredje|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:og|jf)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Mos(?:ebog)?|Gen(?:esis)?|1\.[\s\xa0]*Mos(?:ebog)?|F\xF8rste[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Mos(?:ebog)?|Exod(?:us)?|2\.[\s\xa0]*Mos(?:ebog)?|Anden[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*og[\s\xa0]*Dragen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3[\s\xa0]*Mos(?:ebog)?|Lev(?:iticus)?|3\.[\s\xa0]*Mos(?:ebog)?|Tredje[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4[\s\xa0]*Mos(?:ebog)?|Num(?:eri)?|4\.[\s\xa0]*Mos(?:ebog)?|Fjerde[\s\xa0]*Mos(?:ebog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sir(?:ak(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Visdommen(?:s[\s\xa0]*Bog)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Klag(?:es(?:angene)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jeremias['’][\s\xa0]*Brev|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:A(?:benbaringsbo|abenbarin)|\xC5benbaringsbo)gen|[A\xC5]benbaringen|Rev|Apokalypsen|[A\xC5]b|Joh(?:annes(?:['’][\s\xa0]*[A\xC5]benbaring|apokalypsen)|s(?:\.[\s\xa0]*[A\xC5]|[\s\xa0]*[A\xC5])benbaring)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:(?:Manasses[\s\xa0]*B\xF8|PrMa)n) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Femte|5\.?)[\s\xa0]*Mosebog|(?:Femte|5\.?)[\s\xa0]*Mos|Deut(?:eronomium)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jos(?:va(?:bog(?:en)?|s[\s\xa0]*Bog)|ua|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dom(?:mer(?:bogen)?)?|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rut(?:h(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:[13][\s\xa0]*Esdrasbog|1Esd|[13]\.[\s\xa0]*Esdrasbog|Tredje[\s\xa0]*Esdrasbog|F\xF8rste[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|[24]\.)[\s\xa0]*Esdrasbog|[24][\s\xa0]*Esdrasbog|2Esd|Fjerde[\s\xa0]*Esdrasbog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Es(?:ajas(?:['’][\s\xa0]*Bog)?)?|(?:Jesai|Is)a) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|Anden[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)|Sam|\.[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog))|F\xF8rste[\s\xa0]*(?:Sam(?:uelsbog|uel)?|Kongerigernes[\s\xa0]*Bog)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Kongebog)|(?:(?:Anden|2\.?)[\s\xa0]*Kong|2Kgs|4[\s\xa0]*Kongerigernes[\s\xa0]*Bog|4\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Fjerde[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Kongebog)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Kong|1Kgs|3[\s\xa0]*Kongerigernes[\s\xa0]*Bog|3\.[\s\xa0]*Kongerigernes[\s\xa0]*Bog|Tredje[\s\xa0]*Kongerigernes[\s\xa0]*Bog) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|Anden[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)|Chr|\.[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on))|F\xF8rste[\s\xa0]*Kr(?:\xF8n(?:ikebog)?|on)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er(?:s[\s\xa0]*Bog)?|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job(?:s[\s\xa0]*Bog)?|Hiob) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:alme(?:rne(?:s[\s\xa0]*Bog)?)?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Azarjas[\s\xa0]*[Bb]\xF8n|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ordsp(?:rogene(?:s[\s\xa0]*Bog)?)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:\xE6d(?:ikeren(?:s[\s\xa0]*Bog)?)?|ad)|Eccl) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:De[\s\xa0]*(?:Tre[\s\xa0]*M\xE6nds[\s\xa0]*L|tre[\s\xa0]*m\xE6nds[\s\xa0]*l)ovsang|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:\xF8jsangen|ojs|\xF8js)|S(?:alomons[\s\xa0]*H\xF8jsa|o)ng) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jer(?:emias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:ek(?:iel(?:s’?[\s\xa0]*Bog)?)?)?|Hezechiel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Dan(?:iel(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:eas(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joel(?:s[\s\xa0]*Bog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Obad(?:ias(?:['’][\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:a(?:s(?:['’][\s\xa0]*Bog)?|h))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:ka(?:s(?:[\s\xa0]*Bog)?)?|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akkuk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Zefanias’[\s\xa0]*Bog)|(?:Sef(?:anias['’][\s\xa0]*Bog)?|Ze(?:fanias|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:aj(?:s[\s\xa0]*Bog)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ak(?:arias(?:['’][\s\xa0]*Bog)?)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:akias(?:’[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matt(?:h\xE6us(?:evangeliet)?|\xE6usevangeliet)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mark(?:us(?:evangeliet)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:uk(?:as(?:evangeliet)?|e)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Johannes['’][\s\xa0]*(?:F\xF8rste|1\.)[\s\xa0]*Brev|Johannes['’][\s\xa0]*1[\s\xa0]*Brev|1John|1[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|1\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?|F\xF8rste[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*B|b)rev)?)|(?:(?:F\xF8rste|1\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:PI:NAME:<NAME>END_PIJohn)|(?:2[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Johannes['’][\s\xa0]*Andet[\s\xa0]*Brev|2\.[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|Ande(?:n[\s\xa0]*Joh(?:annes(?:['’][\s\xa0]*Brev|brev)?)?|t[\s\xa0]*Johannesbrev)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:PI:NAME:<NAME>END_PIJohn)|(?:(?:3(?:\.[\s\xa0]*Johannes['’]|[\s\xa0]*Johannes['’])|Tredje[\s\xa0]*Johannes['’])[\s\xa0]*Brev|(?:Tredje|3\.?)[\s\xa0]*Johannesbrev|(?:Tredje|3\.?)[\s\xa0]*Joh|Johannes['’][\s\xa0]*(?:Tredje|3\.?)[\s\xa0]*Brev)|(?:(?:Tredje|3\.?)[\s\xa0]*Johannes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Joh(?:annes(?:evangeliet)?|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:p(?:ostlenes[\s\xa0]*Gerninger|[Gg]|\.G)|cts)|Gerninger) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Romerne|Rom(?:erbrevet|erne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Korinterne)|(?:2(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|Ande(?:n[\s\xa0]*Korinth?|t[\s\xa0]*Korinth)erbrev|(?:Anden|2\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Korinterne)|(?:1(?:[\s\xa0]*Korinth?erbrev|Cor|\.[\s\xa0]*Korinth?erbrev)|F\xF8rste[\s\xa0]*Korinth?erbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Kor|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Korintherne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aterbrevet|aterne)?|Brevet[\s\xa0]*til[\s\xa0]*Galaterne|Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Galaterne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Efeserne)|(?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Efeserne|E(?:feserbrevet|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filipperne|hil)|Fil(?:ipperbrevet|ipperne)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Kolossenserne|Kolossenser(?:brevet|n)|Col|Kol) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|Ande[nt][\s\xa0]*Thessalonikerbrev|(?:Anden|2\.?)[\s\xa0]*Thess|(?:Anden|2\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Thessalonikerbrev|Thess|\.[\s\xa0]*Thessalonikerbrev)|F\xF8rste[\s\xa0]*Thessalonikerbrev|(?:F\xF8rste|1\.?)[\s\xa0]*Thess|(?:F\xF8rste|1\.?)[\s\xa0]*Tessalonikerne|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Thessalonikerne) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|Ande(?:n[\s\xa0]*Timoth?|t[\s\xa0]*Timoth)eusbrev|2(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|Anden[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*Andet[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Timoth?eusbrev|Tim|\.[\s\xa0]*Timoth?eusbrev)|F\xF8rste[\s\xa0]*Timoth?eusbrev|1(?:\.[\s\xa0]*Tim(?:oteus)?|[\s\xa0]*Tim(?:oteus)?)|F\xF8rste[\s\xa0]*Tim(?:oteus)?|Paulus['’][\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Timotheus) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Paulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Titus|Tit(?:usbrevet|us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:P(?:aulus['’][\s\xa0]*Brev[\s\xa0]*til[\s\xa0]*Filemon|hlm)|F(?:ilemonbrevet|lm|ilem(?:on)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hebr\xE6erne)|(?:Brevet[\s\xa0]*til[\s\xa0]*Hebr\xE6erne|Heb(?:r\xE6erbrevet|r)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:ob(?:s(?:brevet|[\s\xa0]*Brev))?)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:Anden|2\.?)[\s\xa0]*Petersbrev)|(?:2(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|Anden[\s\xa0]*Peter|(?:Anden|2\.?)[\s\xa0]*Pet|Andet[\s\xa0]*Petersbrev|Peters[\s\xa0]*Andet[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:F\xF8rste|1\.?)[\s\xa0]*Petersbrev)|(?:1(?:[\s\xa0]*Peter|Pet|\.[\s\xa0]*Peter)|F\xF8rste[\s\xa0]*Peter|(?:F\xF8rste|1\.?)[\s\xa0]*Pet|Peters[\s\xa0]*(?:F\xF8rste|1\.?)[\s\xa0]*Brev) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as(?:['’][\s\xa0]*Brev|brevet)?|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:it(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udit(?:s[\s\xa0]*Bog)?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uk(?:s[\s\xa0]*Bog)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Anden[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Tredje[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|Fjerde[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Makk(?:ab\xE6erbog)?|Macc|\.[\s\xa0]*Makk(?:ab\xE6erbog)?)|F\xF8rste[\s\xa0]*Makk(?:ab\xE6erbog)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
[ { "context": " form = req.form()\n form.append('username', '012345678901234567890123456789012345')\n form.append('pas", "end": 981, "score": 0.8803354501724243, "start": 970, "tag": "USERNAME", "value": "01234567890" }, { "context": "m()\n form.append('username', '012345678901234567890123456789012345')\n form.append('password', '12345')\n )\n ", "end": 1006, "score": 0.9638223052024841, "start": 985, "tag": "PASSWORD", "value": "567890123456789012345" }, { "context": "0123456789012345')\n form.append('password', '12345')\n )\n form = req.form()\n form.append('io", "end": 1045, "score": 0.9993699789047241, "start": 1040, "tag": "PASSWORD", "value": "12345" }, { "context": "orm()\n form.append('iosIdentifierForVendor', '012345678901234567890123456789012345')\n form.append('password', '12345')\n \n it 'c", "end": 1155, "score": 0.9782623052597046, "start": 1120, "tag": "PASSWORD", "value": "12345678901234567890123456789012345" }, { "context": "890123456789012345')\n form.append('password', '12345')\n \n it 'clears Users', (done) ->\n clearMode", "end": 1192, "score": 0.999413788318634, "start": 1187, "tag": "PASSWORD", "value": "12345" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', 'nada", "end": 1609, "score": 0.9888311624526978, "start": 1608, "tag": "USERNAME", "value": "s" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'crea", "end": 1623, "score": 0.9999324679374695, "start": 1609, "tag": "EMAIL", "value": "cott@gmail.com" }, { "context": ", 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'creates a user', (done) ->\n req = req", "end": 1659, "score": 0.9994716644287109, "start": 1655, "tag": "PASSWORD", "value": "nada" }, { "context": ")\n form = req.form()\n form.append('email', 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'find", "end": 1935, "score": 0.9999227523803711, "start": 1920, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": ", 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'finds that created user', (done) ->\n ", "end": 1971, "score": 0.9994874000549316, "start": 1967, "tag": "PASSWORD", "value": "nada" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'reje", "end": 2237, "score": 0.999917209148407, "start": 2222, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": ", 'scott@gmail.com')\n form.append('password', 'nada')\n\n it 'rejects wrong passwords', (done) ->\n ", "end": 2273, "score": 0.9994760155677795, "start": 2269, "tag": "PASSWORD", "value": "nada" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', 'blahblah')\n\n it '", "end": 2567, "score": 0.9999119639396667, "start": 2552, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": ", 'scott@gmail.com')\n form.append('password', 'blahblah')\n\n it 'is completely case insensitive', (done) ", "end": 2607, "score": 0.9994752407073975, "start": 2599, "tag": "PASSWORD", "value": "blahblah" }, { "context": " form = req.form()\n form.append('username', 'scoTT@gmaIL.com')\n form.append('password', 'NaDa')\n\ndescribe '", "end": 2843, "score": 0.999919056892395, "start": 2828, "tag": "EMAIL", "value": "scoTT@gmaIL.com" }, { "context": ", 'scoTT@gmaIL.com')\n form.append('password', 'NaDa')\n\ndescribe '/auth/reset', ->\n passwordReset = '", "end": 2879, "score": 0.9994721412658691, "start": 2875, "tag": "PASSWORD", "value": "NaDa" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n\n it 'can\\'t reset an unknown user', (done) ->", "end": 3185, "score": 0.9999194741249084, "start": 3170, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": ")\n form = req.form()\n form.append('email', 'scott@gmail.com')\n\n it 'can login after resetting', (done) ->\n ", "end": 3782, "score": 0.9999176859855652, "start": 3767, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', passwordReset)\n\n i", "end": 4050, "score": 0.999900758266449, "start": 4035, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": "e', 'scott@gmail.com')\n form.append('password', passwordReset)\n\n it 'resetting password is not permanent', (do", "end": 4094, "score": 0.9724664688110352, "start": 4081, "tag": "PASSWORD", "value": "passwordReset" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', passwordReset)\n\n\n ", "end": 4371, "score": 0.9998878836631775, "start": 4356, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": "e', 'scott@gmail.com')\n form.append('password', passwordReset)\n\n\n it 'can still login with old password', (don", "end": 4415, "score": 0.9801411032676697, "start": 4402, "tag": "PASSWORD", "value": "passwordReset" }, { "context": " form = req.form()\n form.append('username', 'scott@gmail.com')\n form.append('password', 'nada')\n\ndescribe '", "end": 4691, "score": 0.9998928904533386, "start": 4676, "tag": "EMAIL", "value": "scott@gmail.com" }, { "context": ", 'scott@gmail.com')\n form.append('password', 'nada')\n\ndescribe '/auth/unsubscribe', ->\n it 'clears ", "end": 4727, "score": 0.9992369413375854, "start": 4723, "tag": "PASSWORD", "value": "nada" }, { "context": ").toBe 200\n expect(response.body.name).toBe 'Gandalf'\n done()\n\n it 'can GET a new name in case o", "end": 5947, "score": 0.768572986125946, "start": 5940, "tag": "NAME", "value": "Gandalf" } ]
spec/server/functional/auth.spec.coffee
JurianLock/codecombat
1
require '../common' request = require 'request' User = require '../../../server/users/User' urlLogin = getURL('/auth/login') urlReset = getURL('/auth/reset') describe '/auth/whoami', -> it 'returns 200', (done) -> request.get(getURL('/auth/whoami'), (err, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) describe '/auth/login', -> it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'allows logging in by iosIdentifierForVendor', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '012345678901234567890123456789012345') form.append('password', '12345') ) form = req.form() form.append('iosIdentifierForVendor', '012345678901234567890123456789012345') form.append('password', '12345') it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'finds no user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', 'nada') it 'creates a user', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('email', 'scott@gmail.com') form.append('password', 'nada') it 'finds that created user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', 'nada') it 'rejects wrong passwords', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(401) expect(response.body.indexOf('wrong')).toBeGreaterThan(-1) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', 'blahblah') it 'is completely case insensitive', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'scoTT@gmaIL.com') form.append('password', 'NaDa') describe '/auth/reset', -> passwordReset = '' it 'emails require', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(422) done() ) form = req.form() form.append('username', 'scott@gmail.com') it 'can\'t reset an unknown user', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(404) done() ) form = req.form() form.append('email', 'unknow') it 'resets user password', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) expect(response.body).toBeDefined() passwordReset = response.body done() ) form = req.form() form.append('email', 'scott@gmail.com') it 'can login after resetting', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', passwordReset) it 'resetting password is not permanent', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', passwordReset) it 'can still login with old password', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'scott@gmail.com') form.append('password', 'nada') describe '/auth/unsubscribe', -> it 'clears Users first', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'removes just recruitment emails if you include ?recruitNotes=1', (done) -> loginJoe (joe) -> url = getURL('/auth/unsubscribe?recruitNotes=1&email='+joe.get('email')) request.get url, (error, response) -> expect(response.statusCode).toBe(200) user = User.findOne(joe.get('_id')).exec (err, user) -> expect(user.get('emails').recruitNotes.enabled).toBe(false) expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() done() describe '/auth/name', -> url = '/auth/name' it 'must provide a name to check with', (done) -> request.get {url: getURL(url + '/'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 422 done() it 'can GET a non-conflicting name', (done) -> request.get {url: getURL(url + '/Gandalf'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 expect(response.body.name).toBe 'Gandalf' done() it 'can GET a new name in case of conflict', (done) -> request.get {url: getURL(url + '/joe'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 expect(response.body.name).not.toBe 'joe' expect(response.body.name.length).toBe 4 # 'joe' and a random number done()
150201
require '../common' request = require 'request' User = require '../../../server/users/User' urlLogin = getURL('/auth/login') urlReset = getURL('/auth/reset') describe '/auth/whoami', -> it 'returns 200', (done) -> request.get(getURL('/auth/whoami'), (err, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) describe '/auth/login', -> it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'allows logging in by iosIdentifierForVendor', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '012345678901234<PASSWORD>') form.append('password', '<PASSWORD>') ) form = req.form() form.append('iosIdentifierForVendor', '0<PASSWORD>') form.append('password', '<PASSWORD>') it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'finds no user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', 's<EMAIL>') form.append('password', '<PASSWORD>') it 'creates a user', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('email', '<EMAIL>') form.append('password', '<PASSWORD>') it 'finds that created user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', '<PASSWORD>') it 'rejects wrong passwords', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(401) expect(response.body.indexOf('wrong')).toBeGreaterThan(-1) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', '<PASSWORD>') it 'is completely case insensitive', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', '<PASSWORD>') describe '/auth/reset', -> passwordReset = '' it 'emails require', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(422) done() ) form = req.form() form.append('username', '<EMAIL>') it 'can\'t reset an unknown user', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(404) done() ) form = req.form() form.append('email', 'unknow') it 'resets user password', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) expect(response.body).toBeDefined() passwordReset = response.body done() ) form = req.form() form.append('email', '<EMAIL>') it 'can login after resetting', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', <PASSWORD>) it 'resetting password is not permanent', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', <PASSWORD>) it 'can still login with old password', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '<EMAIL>') form.append('password', '<PASSWORD>') describe '/auth/unsubscribe', -> it 'clears Users first', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'removes just recruitment emails if you include ?recruitNotes=1', (done) -> loginJoe (joe) -> url = getURL('/auth/unsubscribe?recruitNotes=1&email='+joe.get('email')) request.get url, (error, response) -> expect(response.statusCode).toBe(200) user = User.findOne(joe.get('_id')).exec (err, user) -> expect(user.get('emails').recruitNotes.enabled).toBe(false) expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() done() describe '/auth/name', -> url = '/auth/name' it 'must provide a name to check with', (done) -> request.get {url: getURL(url + '/'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 422 done() it 'can GET a non-conflicting name', (done) -> request.get {url: getURL(url + '/Gandalf'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 expect(response.body.name).toBe '<NAME>' done() it 'can GET a new name in case of conflict', (done) -> request.get {url: getURL(url + '/joe'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 expect(response.body.name).not.toBe 'joe' expect(response.body.name.length).toBe 4 # 'joe' and a random number done()
true
require '../common' request = require 'request' User = require '../../../server/users/User' urlLogin = getURL('/auth/login') urlReset = getURL('/auth/reset') describe '/auth/whoami', -> it 'returns 200', (done) -> request.get(getURL('/auth/whoami'), (err, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) describe '/auth/login', -> it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'allows logging in by iosIdentifierForVendor', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', '012345678901234PI:PASSWORD:<PASSWORD>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') ) form = req.form() form.append('iosIdentifierForVendor', '0PI:PASSWORD:<PASSWORD>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') it 'clears Users', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'finds no user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', 'sPI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') it 'creates a user', (done) -> req = request.post(getURL('/db/user'), (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('email', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') it 'finds that created user', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') it 'rejects wrong passwords', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(401) expect(response.body.indexOf('wrong')).toBeGreaterThan(-1) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') it 'is completely case insensitive', (done) -> req = request.post(urlLogin, (error, response) -> expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') describe '/auth/reset', -> passwordReset = '' it 'emails require', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(422) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') it 'can\'t reset an unknown user', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(404) done() ) form = req.form() form.append('email', 'unknow') it 'resets user password', (done) -> req = request.post(urlReset, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) expect(response.body).toBeDefined() passwordReset = response.body done() ) form = req.form() form.append('email', 'PI:EMAIL:<EMAIL>END_PI') it 'can login after resetting', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', PI:PASSWORD:<PASSWORD>END_PI) it 'resetting password is not permanent', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(401) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', PI:PASSWORD:<PASSWORD>END_PI) it 'can still login with old password', (done) -> req = request.post(urlLogin, (error, response) -> expect(response).toBeDefined() expect(response.statusCode).toBe(200) done() ) form = req.form() form.append('username', 'PI:EMAIL:<EMAIL>END_PI') form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI') describe '/auth/unsubscribe', -> it 'clears Users first', (done) -> clearModels [User], (err) -> throw err if err request.get getURL('/auth/whoami'), -> throw err if err done() it 'removes just recruitment emails if you include ?recruitNotes=1', (done) -> loginJoe (joe) -> url = getURL('/auth/unsubscribe?recruitNotes=1&email='+joe.get('email')) request.get url, (error, response) -> expect(response.statusCode).toBe(200) user = User.findOne(joe.get('_id')).exec (err, user) -> expect(user.get('emails').recruitNotes.enabled).toBe(false) expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() done() describe '/auth/name', -> url = '/auth/name' it 'must provide a name to check with', (done) -> request.get {url: getURL(url + '/'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 422 done() it 'can GET a non-conflicting name', (done) -> request.get {url: getURL(url + '/Gandalf'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 expect(response.body.name).toBe 'PI:NAME:<NAME>END_PI' done() it 'can GET a new name in case of conflict', (done) -> request.get {url: getURL(url + '/joe'), json: {}}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 expect(response.body.name).not.toBe 'joe' expect(response.body.name.length).toBe 4 # 'joe' and a random number done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9989607334136963, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-vm-run-in-new-context.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Flags: --expose-gc changeFoo = -> foo = 100 return common = require("../common") assert = require("assert") vm = require("vm") assert.equal typeof gc, "function", "Run this test with --expose-gc" common.globalCheck = false console.error "run a string" result = vm.runInNewContext("'passed';") assert.equal "passed", result console.error "thrown error" assert.throws -> vm.runInNewContext "throw new Error('test');" return hello = 5 vm.runInNewContext "hello = 2" assert.equal 5, hello console.error "pass values in and out" code = "foo = 1;" + "bar = 2;" + "if (baz !== 3) throw new Error('test fail');" foo = 2 obj = foo: 0 baz: 3 baz = vm.runInNewContext(code, obj) assert.equal 1, obj.foo assert.equal 2, obj.bar assert.equal 2, foo console.error "call a function by reference" vm.runInNewContext "f()", f: changeFoo assert.equal foo, 100 console.error "modify an object by reference" f = a: 1 vm.runInNewContext "f.a = 2", f: f assert.equal f.a, 2 console.error "use function in context without referencing context" fn = vm.runInNewContext("(function() { obj.p = {}; })", obj: {} ) gc() fn() # Should not crash
164928
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Flags: --expose-gc changeFoo = -> foo = 100 return common = require("../common") assert = require("assert") vm = require("vm") assert.equal typeof gc, "function", "Run this test with --expose-gc" common.globalCheck = false console.error "run a string" result = vm.runInNewContext("'passed';") assert.equal "passed", result console.error "thrown error" assert.throws -> vm.runInNewContext "throw new Error('test');" return hello = 5 vm.runInNewContext "hello = 2" assert.equal 5, hello console.error "pass values in and out" code = "foo = 1;" + "bar = 2;" + "if (baz !== 3) throw new Error('test fail');" foo = 2 obj = foo: 0 baz: 3 baz = vm.runInNewContext(code, obj) assert.equal 1, obj.foo assert.equal 2, obj.bar assert.equal 2, foo console.error "call a function by reference" vm.runInNewContext "f()", f: changeFoo assert.equal foo, 100 console.error "modify an object by reference" f = a: 1 vm.runInNewContext "f.a = 2", f: f assert.equal f.a, 2 console.error "use function in context without referencing context" fn = vm.runInNewContext("(function() { obj.p = {}; })", obj: {} ) gc() fn() # Should not crash
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Flags: --expose-gc changeFoo = -> foo = 100 return common = require("../common") assert = require("assert") vm = require("vm") assert.equal typeof gc, "function", "Run this test with --expose-gc" common.globalCheck = false console.error "run a string" result = vm.runInNewContext("'passed';") assert.equal "passed", result console.error "thrown error" assert.throws -> vm.runInNewContext "throw new Error('test');" return hello = 5 vm.runInNewContext "hello = 2" assert.equal 5, hello console.error "pass values in and out" code = "foo = 1;" + "bar = 2;" + "if (baz !== 3) throw new Error('test fail');" foo = 2 obj = foo: 0 baz: 3 baz = vm.runInNewContext(code, obj) assert.equal 1, obj.foo assert.equal 2, obj.bar assert.equal 2, foo console.error "call a function by reference" vm.runInNewContext "f()", f: changeFoo assert.equal foo, 100 console.error "modify an object by reference" f = a: 1 vm.runInNewContext "f.a = 2", f: f assert.equal f.a, 2 console.error "use function in context without referencing context" fn = vm.runInNewContext("(function() { obj.p = {}; })", obj: {} ) gc() fn() # Should not crash
[ { "context": "#\n# MConn Framework\n# https://www.github.com/livespotting/mconn\n#\n# @copyright 2015 Livespotting Media GmbH", "end": 57, "score": 0.9948635101318359, "start": 45, "tag": "USERNAME", "value": "livespotting" }, { "context": "tting Media GmbH\n# @license Apache-2.0\n#\n# @author Christoph Johannsdotter [c.johannsdotter@livespottingmedia.com]\n# @author", "end": 165, "score": 0.9998743534088135, "start": 142, "tag": "NAME", "value": "Christoph Johannsdotter" }, { "context": "e Apache-2.0\n#\n# @author Christoph Johannsdotter [c.johannsdotter@livespottingmedia.com]\n# @author Jan Stabenow [j.stabenow@livespottingm", "end": 204, "score": 0.9999269247055054, "start": 167, "tag": "EMAIL", "value": "c.johannsdotter@livespottingmedia.com" }, { "context": " [c.johannsdotter@livespottingmedia.com]\n# @author Jan Stabenow [j.stabenow@livespottingmedia.com]\n#\n\nModule = re", "end": 228, "score": 0.9998652338981628, "start": 216, "tag": "NAME", "value": "Jan Stabenow" }, { "context": "er@livespottingmedia.com]\n# @author Jan Stabenow [j.stabenow@livespottingmedia.com]\n#\n\nModule = require(require(\"path\").join(process", "end": 262, "score": 0.9999229907989502, "start": 230, "tag": "EMAIL", "value": "j.stabenow@livespottingmedia.com" } ]
src/module.coffee
livespotting/mconn-helloworld
0
# # MConn Framework # https://www.github.com/livespotting/mconn # # @copyright 2015 Livespotting Media GmbH # @license Apache-2.0 # # @author Christoph Johannsdotter [c.johannsdotter@livespottingmedia.com] # @author Jan Stabenow [j.stabenow@livespottingmedia.com] # Module = require(require("path").join(process.env.MCONN_PATH, "bin/classes/Module")) Q = require("q") class HelloWorld extends Module timeout: 600000 constructor: -> super("HelloWorld") @ init: (options, moduleRouter, folder) -> Q = require("q") #requirement for init method deferred = Q.defer() super(options, moduleRouter, folder) .then => moduleRouter.get @createModuleRoute("custom"), (req, res) => res.render(@getTemplatePath("custom"), modulename: @name activeSubmenu: "custom" ) fruits = ["Bananas", "Apple", "Blackberries", "Cranberries"] i = 0 setInterval => @getWebsocketHandler().then (io) -> if io fruitsSnippet = fruits.slice(0,i) i = (i + 1) % 4 io.of("/HelloWorld").emit("updateHelloWorld", fruitsSnippet) , 1500 deferred.resolve() .catch (error) => @logger.error error deferred.promise on_TASK_RUNNING: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId customData = modulePreset.options.actions.add return @addToZKInventory(path, customData, taskData) .then => @logger.info(modulePreset.options.actions.add + " \"" + taskData.getData().taskId + "\"") @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_FAILED: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId @removeFromZKInventory(path) .then => @logger.info(modulePreset.options.actions.remove + " " + taskData.getData().taskId) @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_UNDEFINED_STATUS: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 0 Q.delay(delay) .then => @logger.info("\"" + taskData.getData().taskStatus + "\" is an undefined taskStatus and the task \"" + taskData.getData().taskId + "\" will be proceed without actions") @undefinedStatus(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_KILLED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_LOST: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_FINISHED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_STAGING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) on_TASK_STARTING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) cleanUpInventory: (result) -> @logger.debug("INFO", "Starting inventory cleanup") deferred = Q.defer() for m in result.missing m.taskStatus = "TASK_RUNNING" @addTask(m, => @logger.info("Cleanup task \"" + m.getData().taskId + "\" successfully added") ) for o in result.wrong o.taskStatus = "TASK_KILLED" @addTask(o, => @logger.info("Cleanup task \"" + o.getData().taskId + "\" successfully removed") ) @logger.info("Cleanup initiated, added \"" + (result.wrong.length + result.missing.length) + "\" tasks") deferred.resolve() deferred.promise module.exports = HelloWorld
104877
# # MConn Framework # https://www.github.com/livespotting/mconn # # @copyright 2015 Livespotting Media GmbH # @license Apache-2.0 # # @author <NAME> [<EMAIL>] # @author <NAME> [<EMAIL>] # Module = require(require("path").join(process.env.MCONN_PATH, "bin/classes/Module")) Q = require("q") class HelloWorld extends Module timeout: 600000 constructor: -> super("HelloWorld") @ init: (options, moduleRouter, folder) -> Q = require("q") #requirement for init method deferred = Q.defer() super(options, moduleRouter, folder) .then => moduleRouter.get @createModuleRoute("custom"), (req, res) => res.render(@getTemplatePath("custom"), modulename: @name activeSubmenu: "custom" ) fruits = ["Bananas", "Apple", "Blackberries", "Cranberries"] i = 0 setInterval => @getWebsocketHandler().then (io) -> if io fruitsSnippet = fruits.slice(0,i) i = (i + 1) % 4 io.of("/HelloWorld").emit("updateHelloWorld", fruitsSnippet) , 1500 deferred.resolve() .catch (error) => @logger.error error deferred.promise on_TASK_RUNNING: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId customData = modulePreset.options.actions.add return @addToZKInventory(path, customData, taskData) .then => @logger.info(modulePreset.options.actions.add + " \"" + taskData.getData().taskId + "\"") @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_FAILED: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId @removeFromZKInventory(path) .then => @logger.info(modulePreset.options.actions.remove + " " + taskData.getData().taskId) @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_UNDEFINED_STATUS: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 0 Q.delay(delay) .then => @logger.info("\"" + taskData.getData().taskStatus + "\" is an undefined taskStatus and the task \"" + taskData.getData().taskId + "\" will be proceed without actions") @undefinedStatus(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_KILLED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_LOST: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_FINISHED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_STAGING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) on_TASK_STARTING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) cleanUpInventory: (result) -> @logger.debug("INFO", "Starting inventory cleanup") deferred = Q.defer() for m in result.missing m.taskStatus = "TASK_RUNNING" @addTask(m, => @logger.info("Cleanup task \"" + m.getData().taskId + "\" successfully added") ) for o in result.wrong o.taskStatus = "TASK_KILLED" @addTask(o, => @logger.info("Cleanup task \"" + o.getData().taskId + "\" successfully removed") ) @logger.info("Cleanup initiated, added \"" + (result.wrong.length + result.missing.length) + "\" tasks") deferred.resolve() deferred.promise module.exports = HelloWorld
true
# # MConn Framework # https://www.github.com/livespotting/mconn # # @copyright 2015 Livespotting Media GmbH # @license Apache-2.0 # # @author PI:NAME:<NAME>END_PI [PI:EMAIL:<EMAIL>END_PI] # @author PI:NAME:<NAME>END_PI [PI:EMAIL:<EMAIL>END_PI] # Module = require(require("path").join(process.env.MCONN_PATH, "bin/classes/Module")) Q = require("q") class HelloWorld extends Module timeout: 600000 constructor: -> super("HelloWorld") @ init: (options, moduleRouter, folder) -> Q = require("q") #requirement for init method deferred = Q.defer() super(options, moduleRouter, folder) .then => moduleRouter.get @createModuleRoute("custom"), (req, res) => res.render(@getTemplatePath("custom"), modulename: @name activeSubmenu: "custom" ) fruits = ["Bananas", "Apple", "Blackberries", "Cranberries"] i = 0 setInterval => @getWebsocketHandler().then (io) -> if io fruitsSnippet = fruits.slice(0,i) i = (i + 1) % 4 io.of("/HelloWorld").emit("updateHelloWorld", fruitsSnippet) , 1500 deferred.resolve() .catch (error) => @logger.error error deferred.promise on_TASK_RUNNING: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId customData = modulePreset.options.actions.add return @addToZKInventory(path, customData, taskData) .then => @logger.info(modulePreset.options.actions.add + " \"" + taskData.getData().taskId + "\"") @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_FAILED: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 250 Q.delay(delay) .then => path = taskData.getData().taskId @removeFromZKInventory(path) .then => @logger.info(modulePreset.options.actions.remove + " " + taskData.getData().taskId) @success(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_UNDEFINED_STATUS: (taskData, modulePreset, callback) -> delay = if process.env.MCONN_MODULE_HELLOWORLD_DELAY then process.env.MCONN_MODULE_HELLOWORLD_DELAY else 0 Q.delay(delay) .then => @logger.info("\"" + taskData.getData().taskStatus + "\" is an undefined taskStatus and the task \"" + taskData.getData().taskId + "\" will be proceed without actions") @undefinedStatus(taskData, callback) @updateInventoryOnGui() .catch (error) => @failed(taskData, callback, error) on_TASK_KILLED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_LOST: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_FINISHED: (taskData, modulePreset, callback) -> @on_TASK_FAILED(taskData, modulePreset, callback) on_TASK_STAGING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) on_TASK_STARTING: (taskData, modulePreset, callback) -> @on_UNDEFINED_STATUS(taskData, modulePreset, callback) cleanUpInventory: (result) -> @logger.debug("INFO", "Starting inventory cleanup") deferred = Q.defer() for m in result.missing m.taskStatus = "TASK_RUNNING" @addTask(m, => @logger.info("Cleanup task \"" + m.getData().taskId + "\" successfully added") ) for o in result.wrong o.taskStatus = "TASK_KILLED" @addTask(o, => @logger.info("Cleanup task \"" + o.getData().taskId + "\" successfully removed") ) @logger.info("Cleanup initiated, added \"" + (result.wrong.length + result.missing.length) + "\" tasks") deferred.resolve() deferred.promise module.exports = HelloWorld
[ { "context": "w Tests for require-unicode-regexp rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 84, "score": 0.9998664855957031, "start": 70, "tag": "NAME", "value": "Toru Nagashima" } ]
src/tests/rules/require-unicode-regexp.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for require-unicode-regexp rule. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/require-unicode-regexp' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'require-unicode-regexp', rule, valid: [ '/foo/u' '/foo/gimuy' "RegExp('', 'u')" "new RegExp('', 'u')" "RegExp '', 'gimuy'" "new RegExp('', 'gimuy')" ''' flags = 'u' new RegExp('', flags) ''' ''' flags = 'g' new RegExp('', flags + 'u') ''' ''' flags = 'gimu' new RegExp('foo', flags.slice(1)) ''' "new RegExp('', flags)" "f = (flags) -> new RegExp('', flags)" "f = (RegExp) -> return new RegExp('foo')" ] invalid: [ code: '/foo/' errors: [messageId: 'requireUFlag'] , code: '/foo/gimy' errors: [messageId: 'requireUFlag'] , code: "RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "RegExp 'foo', 'gimy'" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', 'gimy')" errors: [messageId: 'requireUFlag'] , # , # code: """ # flags = 'gi' # new RegExp('foo', flags) # """ # errors: [messageId: 'requireUFlag'] # , # code: """ # flags = 'gimu' # new RegExp('foo', flags.slice(0, -1)) # """ # errors: [messageId: 'requireUFlag'] code: "new window.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: browser: yes , code: "new global.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: node: yes ]
10283
###* # @fileoverview Tests for require-unicode-regexp rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/require-unicode-regexp' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'require-unicode-regexp', rule, valid: [ '/foo/u' '/foo/gimuy' "RegExp('', 'u')" "new RegExp('', 'u')" "RegExp '', 'gimuy'" "new RegExp('', 'gimuy')" ''' flags = 'u' new RegExp('', flags) ''' ''' flags = 'g' new RegExp('', flags + 'u') ''' ''' flags = 'gimu' new RegExp('foo', flags.slice(1)) ''' "new RegExp('', flags)" "f = (flags) -> new RegExp('', flags)" "f = (RegExp) -> return new RegExp('foo')" ] invalid: [ code: '/foo/' errors: [messageId: 'requireUFlag'] , code: '/foo/gimy' errors: [messageId: 'requireUFlag'] , code: "RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "RegExp 'foo', 'gimy'" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', 'gimy')" errors: [messageId: 'requireUFlag'] , # , # code: """ # flags = 'gi' # new RegExp('foo', flags) # """ # errors: [messageId: 'requireUFlag'] # , # code: """ # flags = 'gimu' # new RegExp('foo', flags.slice(0, -1)) # """ # errors: [messageId: 'requireUFlag'] code: "new window.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: browser: yes , code: "new global.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: node: yes ]
true
###* # @fileoverview Tests for require-unicode-regexp rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/require-unicode-regexp' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'require-unicode-regexp', rule, valid: [ '/foo/u' '/foo/gimuy' "RegExp('', 'u')" "new RegExp('', 'u')" "RegExp '', 'gimuy'" "new RegExp('', 'gimuy')" ''' flags = 'u' new RegExp('', flags) ''' ''' flags = 'g' new RegExp('', flags + 'u') ''' ''' flags = 'gimu' new RegExp('foo', flags.slice(1)) ''' "new RegExp('', flags)" "f = (flags) -> new RegExp('', flags)" "f = (RegExp) -> return new RegExp('foo')" ] invalid: [ code: '/foo/' errors: [messageId: 'requireUFlag'] , code: '/foo/gimy' errors: [messageId: 'requireUFlag'] , code: "RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "RegExp 'foo', 'gimy'" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', '')" errors: [messageId: 'requireUFlag'] , code: "new RegExp('foo', 'gimy')" errors: [messageId: 'requireUFlag'] , # , # code: """ # flags = 'gi' # new RegExp('foo', flags) # """ # errors: [messageId: 'requireUFlag'] # , # code: """ # flags = 'gimu' # new RegExp('foo', flags.slice(0, -1)) # """ # errors: [messageId: 'requireUFlag'] code: "new window.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: browser: yes , code: "new global.RegExp('foo')" errors: [messageId: 'requireUFlag'] env: node: yes ]
[ { "context": " { name: '+', description: '+' } }\n name: 'Name'\n description: 'Description'\n inner", "end": 4579, "score": 0.998112678527832, "start": 4575, "tag": "NAME", "value": "Name" }, { "context": "' }, de: { name: '+' }, fr: {} }\n name: 'Name'\n }\n })\n\n m.updateI18NCoverage()", "end": 4725, "score": 0.9920344948768616, "start": 4721, "tag": "NAME", "value": "Name" }, { "context": " new FlexibleClass()\n m.set({\n name: 'Name'\n i18n: {\n '-': {'-':'-'}\n ", "end": 4975, "score": 0.997887909412384, "start": 4971, "tag": "NAME", "value": "Name" } ]
test/app/models/CocoModel.spec.coffee
pickettd/codecombat
0
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: 'Name' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: 'Name' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: 'Name' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
97785
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: '<NAME>' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: '<NAME>' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: '<NAME>' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
true
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: 'PI:NAME:<NAME>END_PI' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: 'PI:NAME:<NAME>END_PI' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: 'PI:NAME:<NAME>END_PI' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
[ { "context": "l: '2212 3456'\n ci:\n country_name:\n en: 'Cote D\\'Ivoire'\n es: 'Costa de Marfil'\n country_", "end": 5851, "score": 0.7325536608695984, "start": 5845, "tag": "NAME", "value": "Cote D" }, { "context": " 3456'\n ci:\n country_name:\n en: 'Cote D\\'Ivoire'\n es: 'Costa de Marfil'\n country_code: 22", "end": 5859, "score": 0.8163171410560608, "start": 5853, "tag": "NAME", "value": "Ivoire" }, { "context": "untry_name:\n en: 'Cote D\\'Ivoire'\n es: 'Costa de Marfil'\n country_code: 225\n example_dial: '21 23 4", "end": 5887, "score": 0.9510963559150696, "start": 5872, "tag": "NAME", "value": "Costa de Marfil" }, { "context": "2 12 34 56'\n io:\n country_name:\n en: 'Diego Garcia'\n es: 'Diego García'\n country_code", "end": 6731, "score": 0.8009935617446899, "start": 6729, "tag": "NAME", "value": "go" }, { "context": " 34 56'\n io:\n country_name:\n en: 'Diego Garcia'\n es: 'Diego García'\n country_code: 246\n ", "end": 6738, "score": 0.75225830078125, "start": 6733, "tag": "NAME", "value": "arcia" }, { "context": "ntry_name:\n en: 'Diego Garcia'\n es: 'Diego García'\n country_code: 246\n example_dial: '", "end": 6756, "score": 0.6633169054985046, "start": 6754, "tag": "NAME", "value": "go" } ]
src/countries.coffee
Tangol/widget
2
module.exports = af: country_name: en: 'Afghanistan' es: 'Afganistán' country_code: 93 example_dial: '023 456 7890' al: country_name: en: 'Albania' es: 'Albania' country_code: 355 example_dial: '022 345 678' dz: country_name: en: 'Algeria' es: 'Argelia' country_code: 213 example_dial: '012 34 56 78' as: country_name: en: 'American Samoa' es: 'Samoa Americana' country_code: 1684 example_dial: '(684) 622-1234' ad: country_name: en: 'Andorra' es: 'Andorra' country_code: 376 example_dial: '712 345' ao: country_name: en: 'Angola' es: 'Angola' country_code: 244 example_dial: '222 123 456' ai: country_name: en: 'Anguilla' es: 'Anguila' country_code: 1264 example_dial: '(264) 461-2345' aq: country_name: en: 'Antarctic Territories' es: 'Antártida' country_code: 672 example_dial: '' ag: country_name: en: 'Antigua & Barbuda' es: 'Antigua & Barbuda' country_code: 1268 example_dial: '(268) 460-1234' an: country_name: en: 'Antilles' es: 'Antillas' country_code: 599 example_dial: '' ar: country_name: en: 'Argentina' es: 'Argentina' country_code: 54 example_dial: '11 2345-6789' am: country_name: en: 'Armenia' es: 'Armenia' country_code: 374 example_dial: '(010) 123456' aw: country_name: en: 'Aruba' es: 'Aruba' country_code: 297 example_dial: '521 2345' au: country_name: en: 'Australia' es: 'Australia' country_code: 61 example_dial: '(02) 1234 5678' at: country_name: en: 'Austria' es: 'Austria' country_code: 43 example_dial: '01 234567890' az: country_name: en: 'Azerbaijan' es: 'Azerbaiyán' country_code: 994 example_dial: '(012) 312 34 56' bs: country_name: en: 'Bahamas' es: 'Bahamas' country_code: 1242 example_dial: '(242) 345-6789' bh: country_name: en: 'Bahrain' es: 'Bahrein' country_code: 973 example_dial: '1700 1234' bd: country_name: en: 'Bangladesh' es: 'Bangladesh' country_code: 880 example_dial: '02-7111234' bb: country_name: en: 'Barbados' es: 'Barbados' country_code: 1246 example_dial: '(246) 234-5678' by: country_name: en: 'Belarus' es: 'Bielorrusia' country_code: 375 example_dial: '8 015 245 0911' be: country_name: en: 'Belgium' es: 'Bélgica' country_code: 32 example_dial: '012 34 56 78' bz: country_name: en: 'Belize' es: 'Belice' country_code: 501 example_dial: '222-1234' bj: country_name: en: 'Benin' es: 'Benin' country_code: 229 example_dial: '20 21 12 34' bm: country_name: en: 'Bermuda' es: 'Bermuda' country_code: 1441 example_dial: '(441) 234-5678' bt: country_name: en: 'Bhutan' es: 'Bután' country_code: 975 example_dial: '2 345 678' bo: country_name: en: 'Bolivia' es: 'Bolivia' country_code: 591 example_dial: '2 2123456' ba: country_name: en: 'Bosnia & H.' es: 'Bosnia & H.' country_code: 387 example_dial: '030 123-456' bw: country_name: en: 'Botswana' es: 'Botswana' country_code: 267 example_dial: '240 1234' br: country_name: en: 'Brazil' es: 'Brasil' country_code: 55 example_dial: '(11) 2345-6789' bn: country_name: en: 'Brunei' es: 'Brunéi' country_code: 673 example_dial: '234 5678' bg: country_name: en: 'Bulgaria' es: 'Bulgaria' country_code: 359 example_dial: '02 123 456' bf: country_name: en: 'Burkina Faso' es: 'Burkina Faso' country_code: 226 example_dial: '20 49 12 34' bi: country_name: en: 'Burundi' es: 'Burundi' country_code: 257 example_dial: '22 20 12 34' kh: country_name: en: 'Cambodia' es: 'Camboya' country_code: 855 example_dial: '023 456 789' cm: country_name: en: 'Cameroon' es: 'Camerún' country_code: 237 example_dial: '22 12 34 56' ca: country_name: en: 'Canada' es: 'Canada' country_code: 1 example_dial: '(204) 234-5678' cv: country_name: en: 'Cape Verde Island' es: 'Isla Cabo Verde' country_code: 238 example_dial: '221 12 34' ky: country_name: en: 'Cayman Islands' es: 'Islas Caimán' country_code: 1345 example_dial: '(345) 222-1234' cf: country_name: en: 'Central African Rep.' es: 'Rep Centroafricana.' country_code: 236 example_dial: '21 61 23 45' td: country_name: en: 'Chad' es: 'Chad' country_code: 235 example_dial: '22 50 12 34' cl: country_name: en: 'Chile' es: 'Chile' country_code: 56 example_dial: '(2) 2123 4567' cn: country_name: en: 'China' es: 'China' country_code: 86 example_dial: '010 1234 5678' co: country_name: en: 'Colombia' es: 'Colombia' country_code: 57 example_dial: '(1) 2345678' km: country_name: en: 'Comoros' es: 'Comoras' country_code: 269 example_dial: '771 23 45' cg: country_name: en: 'Congo' es: 'Congo' country_code: 242 example_dial: '22 212 3456' ck: country_name: en: 'Cook Islands' es: 'Islas Cook' country_code: 682 example_dial: '21 234' cr: country_name: en: 'Costa Rica' es: 'Costa Rica' country_code: 506 example_dial: '2212 3456' ci: country_name: en: 'Cote D\'Ivoire' es: 'Costa de Marfil' country_code: 225 example_dial: '21 23 45 67' hr: country_name: en: 'Croatia' es: 'Croacia' country_code: 385 example_dial: '01 2345 678' cu: country_name: en: 'Cuba' es: 'Cuba' country_code: 53 example_dial: '(07) 1234567' cy: country_name: en: 'Cyprus South' es: 'Chipre' country_code: 357 example_dial: '22 345678' cz: country_name: en: 'Czech Republic' es: 'República Checa' country_code: 420 example_dial: '212 345 678' cd: country_name: en: 'Dem Rep Congo' es: 'República Democrática del Congo' country_code: 243 example_dial: '012 34567' dk: country_name: en: 'Denmark' es: 'Dinamarca' country_code: 45 example_dial: '32 12 34 56' io: country_name: en: 'Diego Garcia' es: 'Diego García' country_code: 246 example_dial: '370 9100' dj: country_name: en: 'Djibouti' es: 'Djibouti' country_code: 253 example_dial: '21 36 00 03' dm: country_name: en: 'Dominica' es: 'Dominica' country_code: 1767 example_dial: '(767) 420-1234' tl: country_name: en: 'East Timor' es: 'Timor del Este' country_code: 670 example_dial: '211 2345' ec: country_name: en: 'Ecuador' es: 'Ecuador' country_code: 593 example_dial: '(02) 212-3456' eg: country_name: en: 'Egypt' es: 'Egipto' country_code: 20 example_dial: '02 34567890' sv: country_name: en: 'El Salvador' es: 'El Salvador' country_code: 503 example_dial: '2123 4567' gq: country_name: en: 'Equatorial Guinea' es: 'Guinea Ecuatorial' country_code: 240 example_dial: '333 091 234' er: country_name: en: 'Eritrea' es: 'Eritrea' country_code: 291 example_dial: '08 370 362' ee: country_name: en: 'Estonia' es: 'Estonia' country_code: 372 example_dial: '321 2345' et: country_name: en: 'Ethiopia' es: 'Etiopía' country_code: 251 example_dial: '011 111 2345' fo: country_name: en: 'Faeroe Islands' es: 'Islas Feroe' country_code: 298 example_dial: '201234' fk: country_name: en: 'Falkland Islands' es: 'Islas Malvinas' country_code: 500 example_dial: '31234' fj: country_name: en: 'Fiji' es: 'Fiji' country_code: 679 example_dial: '321 2345' fi: country_name: en: 'Finland' es: 'Finlandia' country_code: 358 example_dial: '013 12345678' fr: country_name: en: 'France' es: 'Francia' country_code: 33 example_dial: '01 23 45 67 89' gf: country_name: en: 'French Guiana' es: 'Guayana Francesa' country_code: 594 example_dial: '0594 10 12 34' pf: country_name: en: 'French Polynesia' es: 'Polinesia Francesa' country_code: 689 example_dial: '40 12 34' ga: country_name: en: 'Gabon' es: 'Gabón' country_code: 241 example_dial: '01 44 12 34' gm: country_name: en: 'Gambia' es: 'Gambia' country_code: 220 example_dial: '566 1234' ge: country_name: en: 'Georgia' es: 'Georgia' country_code: 995 example_dial: '8 322 12 34 56' de: country_name: en: 'Germany' es: 'Alemania' country_code: 49 example_dial: '030 123456' gh: country_name: en: 'Ghana' es: 'Ghana' country_code: 233 example_dial: '030 234 5678' gi: country_name: en: 'Gibraltar' es: 'Gibraltar' country_code: 350 example_dial: '20012345' gr: country_name: en: 'Greece' es: 'Grecia' country_code: 30 example_dial: '21 2345 6789' gl: country_name: en: 'Greenland' es: 'Groenlandia' country_code: 299 example_dial: '32 10 00' gd: country_name: en: 'Grenada' es: 'Granada' country_code: 1473 example_dial: '(473) 269-1234' bl: country_name: en: 'Guadeloupe' es: 'Guadalupe' country_code: 590 example_dial: '0590 27-1234' gu: country_name: en: 'Guam' es: 'Guam' country_code: 1671 example_dial: '(671) 300-1234' gt: country_name: en: 'Guatemala' es: 'Guatemala' country_code: 502 example_dial: '2245 6789' gn: country_name: en: 'Guinea' es: 'Guinea' country_code: 224 example_dial: '30 24 12 34' gy: country_name: en: 'Guyana' es: 'Guyana' country_code: 592 example_dial: '220 1234' ht: country_name: en: 'Haiti' es: 'Haití' country_code: 509 example_dial: '22 45 3300' hn: country_name: en: 'Honduras' es: 'Honduras' country_code: 504 example_dial: '2212-3456' hk: country_name: en: 'Hong Kong' es: 'Hong Kong' country_code: 852 example_dial: '2123 4567' hu: country_name: en: 'Hungary' es: 'Hungría' country_code: 36 example_dial: '(1) 234 5678' is: country_name: en: 'Iceland' es: 'Islandia' country_code: 354 example_dial: '410 1234' in: country_name: en: 'India' es: 'India' country_code: 91 example_dial: '011 2345 6789' id: country_name: en: 'Indonesia' es: 'Indonesia' country_code: 62 example_dial: '(061) 2345678' pn: country_name: en: 'Inmarsat HSD' es: 'Inmarsat HSD' country_code: 870 example_dial: '' ir: country_name: en: 'Iran' es: 'Irán' country_code: 98 example_dial: '021 2345 6789' iq: country_name: en: 'Iraq' es: 'Irak' country_code: 964 example_dial: '01 234 5678' ie: country_name: en: 'Ireland' es: 'Irlanda' country_code: 353 example_dial: '(022) 12345' il: country_name: en: 'Israel' es: 'Israel' country_code: 972 example_dial: '02-123-4567' it: country_name: en: 'Italy' es: 'Italia' country_code: 39 example_dial: '02 1234 5678' jm: country_name: en: 'Jamaica' es: 'Jamaica' country_code: 1876 example_dial: '(876) 512-3456' jp: country_name: en: 'Japan' es: 'Japón' country_code: 81 example_dial: '' jo: country_name: en: 'Jordan' es: 'Jordan' country_code: 962 example_dial: '(06) 200 1234' kz: country_name: en: 'Kazakhstan' es: 'Kazajstán' country_code: 7 example_dial: '8 (712) 345 6789' ke: country_name: en: 'Kenya' es: 'Kenya' country_code: 254 example_dial: '020 2012345' ki: country_name: en: 'Kiribati' es: 'Kiribati' country_code: 686 example_dial: '31234' kp: country_name: en: 'Korea North' es: 'Corea del Norte' country_code: 850 example_dial: '02 123 4567' kr: country_name: en: 'Korea South' es: 'Corea del Sur' country_code: 82 example_dial: '02-212-3456' kw: country_name: en: 'Kuwait' es: 'Kuwait' country_code: 965 example_dial: '2234 5678' kg: country_name: en: 'Kyrgyzstan' es: 'Kirguistán' country_code: 996 example_dial: '0312 123 456' la: country_name: en: 'Laos' es: 'Laos' country_code: 856 example_dial: '021 212 862' lv: country_name: en: 'Latvia' es: 'Letonia' country_code: 371 example_dial: '63 123 456' lb: country_name: en: 'Lebanon' es: 'Líbano' country_code: 961 example_dial: '01 123 456' ls: country_name: en: 'Lesotho' es: 'Lesotho' country_code: 266 example_dial: '2212 3456' lr: country_name: en: 'Liberia' es: 'Liberia' country_code: 231 example_dial: '021 234 567' ly: country_name: en: 'Libya' es: 'Libia' country_code: 218 example_dial: '021-2345678' li: country_name: en: 'Liechtenstein' es: 'Liechtenstein' country_code: 423 example_dial: '234 56 78' lt: country_name: en: 'Lithuania' es: 'Lituania' country_code: 370 example_dial: '(8-312) 34567' lu: country_name: en: 'Luxembourg' es: 'Luxemburgo' country_code: 352 example_dial: '27 12 34 56' mo: country_name: en: 'Macao' es: 'Macao' country_code: 853 example_dial: '2821 2345' mk: country_name: en: 'Macedonia' es: 'Macedonia' country_code: 389 example_dial: '02 221 2345' mg: country_name: en: 'Madagascar' es: 'Madagascar' country_code: 261 example_dial: '020 21 234 56' mw: country_name: en: 'Malawi' es: 'Malawi' country_code: 265 example_dial: '01 234 567' my: country_name: en: 'Malaysia' es: 'Malasia' country_code: 60 example_dial: '03-2345 6789' mv: country_name: en: 'Maldives' es: 'Maldivas' country_code: 960 example_dial: '670-1234' ml: country_name: en: 'Mali' es: 'Malí' country_code: 223 example_dial: '20 21 23 45' mt: country_name: en: 'Malta' es: 'Malta' country_code: 356 example_dial: '2100 1234' mh: country_name: en: 'Marshall Islands' es: 'Islas Marshall' country_code: 692 example_dial: '247-1234' mq: country_name: en: 'Martinique' es: 'Martinica' country_code: 596 example_dial: '0596 30 12 34' mr: country_name: en: 'Mauritania' es: 'Mauritania' country_code: 222 example_dial: '35 12 34 56' mu: country_name: en: 'Mauritius' es: 'Mauricio' country_code: 230 example_dial: '201 2345' yt: country_name: en: 'Mayotte' es: 'Mayotte' country_code: 262 example_dial: '0269 60 12 34' mx: country_name: en: 'Mexico' es: 'México' country_code: 52 example_dial: '55 1234 5678' fm: country_name: en: 'Micronesia' es: 'Micronesia' country_code: 691 example_dial: '320 1234' md: country_name: en: 'Moldova' es: 'Moldavia' country_code: 373 example_dial: '022 212 345' mc: country_name: en: 'Monaco' es: 'Mónaco' country_code: 377 example_dial: '99 12 34 56' mn: country_name: en: 'Mongolia' es: 'Mongolia' country_code: 976 example_dial: '5012 3456' ms: country_name: en: 'Montserrat' es: 'Montserrat' country_code: 1664 example_dial: '(664) 491-2345' ma: country_name: en: 'Morocco' es: 'Marruecos' country_code: 212 example_dial: '0520-123456' mz: country_name: en: 'Mozambique' es: 'Mozambique' country_code: 258 example_dial: '21 123 456' mm: country_name: en: 'Myanmar' es: 'Myanmar' country_code: 95 example_dial: '01 234 567' na: country_name: en: 'Namibia' es: 'Namibia' country_code: 264 example_dial: '061 201 2345' nr: country_name: en: 'Nauru' es: 'Nauru' country_code: 674 example_dial: '444 1234' np: country_name: en: 'Nepal' es: 'Nepal' country_code: 977 example_dial: '01-4567890' nl: country_name: en: 'Netherlands' es: 'Países Bajos' country_code: 31 example_dial: '010 123 4567' nc: country_name: en: 'New Caledonia' es: 'Nueva Caledonia' country_code: 687 example_dial: '20.12.34' nz: country_name: en: 'New Zealand' es: 'Nueva Zelanda' country_code: 64 example_dial: '03-234 5678' ni: country_name: en: 'Nicaragua' es: 'Nicaragua' country_code: 505 example_dial: '2123 4567' ne: country_name: en: 'Niger' es: 'Níger' country_code: 227 example_dial: '20 20 12 34' nu: country_name: en: 'Niue' es: 'Niue' country_code: 683 example_dial: '4002' nf: country_name: en: 'Norfolk Islands' es: 'Islas Norfolk' country_code: 6723 example_dial: '10 6609' mp: country_name: en: 'Northern Marianas' es: 'Islas Marianas del Norte' country_code: 1670 example_dial: '(670) 234-5678' no: country_name: en: 'Norway' es: 'Noruega' country_code: 47 example_dial: '21 23 45 67' om: country_name: en: 'Oman' es: 'Omán' country_code: 968 example_dial: '23 123456' pk: country_name: en: 'Pakistan' es: 'Pakistán' country_code: 92 example_dial: '(021) 23456789' pw: country_name: en: 'Palau' es: 'Palau' country_code: 680 example_dial: '277 1234' ps: country_name: en: 'Palestine' es: 'Palestina' country_code: 970 example_dial: '02 223 4567' pa: country_name: en: 'Panama' es: 'Panamá' country_code: 507 example_dial: '200-1234' pg: country_name: en: 'Papua New Guinea' es: 'Papúa Nueva Guinea' country_code: 675 example_dial: '312 3456' py: country_name: en: 'Paraguay' es: 'Paraguay' country_code: 595 example_dial: '(21) 2345678' pe: country_name: en: 'Peru' es: 'Perú' country_code: 51 example_dial: '(01) 1234567' ph: country_name: en: 'Philippines' es: 'Filipinas' country_code: 63 example_dial: '(02) 123 4567' pl: country_name: en: 'Poland' es: 'Polonia' country_code: 48 example_dial: '12 345 67 89' pt: country_name: en: 'Portugal' es: 'Portugal' country_code: 351 example_dial: '212 345 678' 'pr-1': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1939 example_dial: '(939) 234-5678' 'pr-2': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1787 example_dial: '(787) 234-5678' qa: country_name: en: 'Qatar' es: 'Qatar' country_code: 974 example_dial: '4412 3456' re: country_name: en: 'Reunion' es: 'Reunion' country_code: 262 example_dial: '0262 16 12 34' ro: country_name: en: 'Romania' es: 'Rumania' country_code: 40 example_dial: '021 123 4567' ru: country_name: en: 'Russia' es: 'Rusia' country_code: 7 example_dial: '8 (301) 123-45-67' rw: country_name: en: 'Rwanda' es: 'Rwanda' country_code: 250 example_dial: '250 123 456' sm: country_name: en: 'San Marino' es: 'San Marino' country_code: 378 example_dial: '0549 886377' st: country_name: en: 'Sao Tome & Principe' es: 'Sao Tome & Principe' country_code: 239 example_dial: '222 1234' sa: country_name: en: 'Saudi Arabia' es: 'Arabia Saudita' country_code: 966 example_dial: '01 234 5678' sn: country_name: en: 'Senegal' es: 'Senegal' country_code: 221 example_dial: '30 101 23 45' rs: country_name: en: 'Serbia' es: 'Serbia' country_code: 381 example_dial: '010 234567' sc: country_name: en: 'Seychelles' es: 'Seychelles' country_code: 248 example_dial: '4 217 123' sl: country_name: en: 'Sierra Leone' es: 'Sierra Leona' country_code: 232 example_dial: '(022) 221234' sg: country_name: en: 'Singapore' es: 'Singapur' country_code: 65 example_dial: '6123 4567' sk: country_name: en: 'Slovak Rep' es: 'República Eslovaca' country_code: 421 example_dial: '02x2F123 456 78' si: country_name: en: 'Slovenia' es: 'Eslovenia' country_code: 386 example_dial: '(01) 123 45 67' sb: country_name: en: 'Solomon Islands' es: 'Islas Salomón' country_code: 677 example_dial: '40123' so: country_name: en: 'Somalia' es: 'Somalia' country_code: 252 example_dial: '5 522010' za: country_name: en: 'South Africa' es: 'Sudáfrica' country_code: 27 example_dial: '010 123 4567' es: country_name: en: 'Spain' es: 'España' country_code: 34 example_dial: '810 12 34 56' lk: country_name: en: 'Sri Lanka' es: 'Sri Lanka' country_code: 94 example_dial: '011 2 345678' sh: country_name: en: 'St. Helena' es: 'St. Helena' country_code: 290 example_dial: '2158' kn: country_name: en: 'St. Kitts & Nevis' es: 'St. Kitts & Nieves' country_code: 1869 example_dial: '(869) 236-1234' lc: country_name: en: 'St. Lucia' es: 'Santa Lucía' country_code: 1758 example_dial: '(758) 234-5678' pm: country_name: en: 'St. Pierre & Miquelon' es: 'St. Pierre & Miquelón' country_code: 508 example_dial: '041 12 34' vc: country_name: en: 'St. Vincents' es: 'St. Vincent' country_code: 1784 example_dial: '(784) 266-1234' sd: country_name: en: 'Sudan' es: 'Sudán' country_code: 249 example_dial: '012 123 1234' sr: country_name: en: 'Suriname' es: 'Suriname' country_code: 597 example_dial: '211-234' sz: country_name: en: 'Swaziland' es: 'Swazilandia' country_code: 268 example_dial: '2217 1234' se: country_name: en: 'Sweden' es: 'Suecia' country_code: 46 example_dial: '08-12 34 56' ch: country_name: en: 'Switzerland' es: 'Suiza' country_code: 41 example_dial: '021 234 56 78' sy: country_name: en: 'Syria' es: 'Siria' country_code: 963 example_dial: '011 234 5678' tw: country_name: en: 'Taiwan' es: 'Taiwan' country_code: 886 example_dial: '02 123 4567' tj: country_name: en: 'Tajikstan' es: 'Tayikistán' country_code: 992 example_dial: '(8) 372 12 3456' tz: country_name: en: 'Tanzania' es: 'Tanzania' country_code: 255 example_dial: '022 234 5678' th: country_name: en: 'Thailand' es: 'Tailandia' country_code: 66 example_dial: '02 123 4567' tg: country_name: en: 'Togo' es: 'Togo' country_code: 228 example_dial: '22 21 23 45' tk: country_name: en: 'Tokelau' es: 'Tokelau' country_code: 690 example_dial: '3010' to: country_name: en: 'Tonga' es: 'Tonga' country_code: 676 example_dial: '20-123' tt: country_name: en: 'Trinidad & Tobago' es: 'Trinidad & amp; Tobago' country_code: 1868 example_dial: '(868) 221-1234' tn: country_name: en: 'Tunisia' es: 'Túnez' country_code: 216 example_dial: '71 234 567' tr: country_name: en: 'Turkey' es: 'pavo' country_code: 90 example_dial: '(0212) 345 6789' tm: country_name: en: 'Turkmenistan' es: 'Turkmenistán' country_code: 993 example_dial: '(8 12) 34-56-78' tc: country_name: en: 'Turks & Caicos' es: 'Turks & amp; Caicos' country_code: 1649 example_dial: '(649) 712-1234' tv: country_name: en: 'Tuvalu' es: 'Tuvalu' country_code: 688 example_dial: '20123' ug: country_name: en: 'Uganda' es: 'Uganda' country_code: 256 example_dial: '031 2345678' gb: country_name: en: 'United Kingdom' es: 'Reino Unido' country_code: 44 example_dial: '0121 234 5678' ua: country_name: en: 'Ukraine' es: 'Ucrania' country_code: 380 example_dial: '03112 34567' ae: country_name: en: 'United Arab Emirates' es: 'Emiratos Árabes Unidos' country_code: 971 example_dial: '02 234 5678' uy: country_name: en: 'Uruguay' es: 'Uruguay' country_code: 598 example_dial: '2123 1234' us: country_name: en: 'United States' es: 'Estados Unidos' country_code: 1 example_dial: '(201) 555-0123' uz: country_name: en: 'Uzbekistan' es: 'Uzbekistán' country_code: 998 example_dial: '8 66 234 56 78' vu: country_name: en: 'Vanuatu' es: 'Vanuatu' country_code: 678 example_dial: '22123' ve: country_name: en: 'Venezuela' es: 'Venezuela' country_code: 58 example_dial: '0212-1234567' vn: country_name: en: 'Vietnam' es: 'Vietnam' country_code: 84 example_dial: '0210 1234 567' vg: country_name: en: 'Virgin Islands GB' es: 'Islas Vírgenes GB' country_code: 1284 example_dial: '(284) 229-1234' vi: country_name: en: 'Virgin Islands USA' es: 'Islas Vírgenes de EE.UU.' country_code: 1340 example_dial: '(340) 642-1234' wf: country_name: en: 'Wallis & Futuna' es: 'Wallis & Futuna' country_code: 681 example_dial: '50 12 34' ws: country_name: en: 'Western Samoa' es: 'Samoa Occidental' country_code: 685 example_dial: '22123' ye: country_name: en: 'Yemen' es: 'Yemen' country_code: 967 example_dial: '01 234 567' zm: country_name: en: 'Zambia' es: 'Zambia' country_code: 260 example_dial: '021 1234567' zw: country_name: en: 'Zimbabwe' es: 'Zimbabwe' country_code: 263 example_dial: '013 12345' 'do-1': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1849 example_dial: '(849) 234-5678' 'do-2': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1809 example_dial: '(809) 234-5678' 'do-3': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1829 example_dial: '(829) 234-5678' gw: country_name: en: 'Guinea-Bissau' es: 'Guinea-Bissau' country_code: 245 example_dial: '320 1234' me: country_name: en: 'Montenegro' es: 'Montenegro' country_code: 382 example_dial: '030 234 567' ng: country_name: en: 'Nigeria' es: 'Nigeria' country_code: 234 example_dial: '01 234 5678' mf: country_name: en: 'Saint Martin' es: 'saint Martin' country_code: 1599 example_dial: '0590 27-1234' gp: country_name: en: 'Saint Barthelemy' es: 'San Bartolomé' country_code: 590 example_dial: '0590 20-1234' ss: country_name: en: 'South Sudan' es: 'Sudán del Sur' country_code: 211 example_dial: '' sx: country_name: en: 'Sint Maarten' es: 'Sint Maarten' country_code: 1721 example_dial: ''
49015
module.exports = af: country_name: en: 'Afghanistan' es: 'Afganistán' country_code: 93 example_dial: '023 456 7890' al: country_name: en: 'Albania' es: 'Albania' country_code: 355 example_dial: '022 345 678' dz: country_name: en: 'Algeria' es: 'Argelia' country_code: 213 example_dial: '012 34 56 78' as: country_name: en: 'American Samoa' es: 'Samoa Americana' country_code: 1684 example_dial: '(684) 622-1234' ad: country_name: en: 'Andorra' es: 'Andorra' country_code: 376 example_dial: '712 345' ao: country_name: en: 'Angola' es: 'Angola' country_code: 244 example_dial: '222 123 456' ai: country_name: en: 'Anguilla' es: 'Anguila' country_code: 1264 example_dial: '(264) 461-2345' aq: country_name: en: 'Antarctic Territories' es: 'Antártida' country_code: 672 example_dial: '' ag: country_name: en: 'Antigua & Barbuda' es: 'Antigua & Barbuda' country_code: 1268 example_dial: '(268) 460-1234' an: country_name: en: 'Antilles' es: 'Antillas' country_code: 599 example_dial: '' ar: country_name: en: 'Argentina' es: 'Argentina' country_code: 54 example_dial: '11 2345-6789' am: country_name: en: 'Armenia' es: 'Armenia' country_code: 374 example_dial: '(010) 123456' aw: country_name: en: 'Aruba' es: 'Aruba' country_code: 297 example_dial: '521 2345' au: country_name: en: 'Australia' es: 'Australia' country_code: 61 example_dial: '(02) 1234 5678' at: country_name: en: 'Austria' es: 'Austria' country_code: 43 example_dial: '01 234567890' az: country_name: en: 'Azerbaijan' es: 'Azerbaiyán' country_code: 994 example_dial: '(012) 312 34 56' bs: country_name: en: 'Bahamas' es: 'Bahamas' country_code: 1242 example_dial: '(242) 345-6789' bh: country_name: en: 'Bahrain' es: 'Bahrein' country_code: 973 example_dial: '1700 1234' bd: country_name: en: 'Bangladesh' es: 'Bangladesh' country_code: 880 example_dial: '02-7111234' bb: country_name: en: 'Barbados' es: 'Barbados' country_code: 1246 example_dial: '(246) 234-5678' by: country_name: en: 'Belarus' es: 'Bielorrusia' country_code: 375 example_dial: '8 015 245 0911' be: country_name: en: 'Belgium' es: 'Bélgica' country_code: 32 example_dial: '012 34 56 78' bz: country_name: en: 'Belize' es: 'Belice' country_code: 501 example_dial: '222-1234' bj: country_name: en: 'Benin' es: 'Benin' country_code: 229 example_dial: '20 21 12 34' bm: country_name: en: 'Bermuda' es: 'Bermuda' country_code: 1441 example_dial: '(441) 234-5678' bt: country_name: en: 'Bhutan' es: 'Bután' country_code: 975 example_dial: '2 345 678' bo: country_name: en: 'Bolivia' es: 'Bolivia' country_code: 591 example_dial: '2 2123456' ba: country_name: en: 'Bosnia & H.' es: 'Bosnia & H.' country_code: 387 example_dial: '030 123-456' bw: country_name: en: 'Botswana' es: 'Botswana' country_code: 267 example_dial: '240 1234' br: country_name: en: 'Brazil' es: 'Brasil' country_code: 55 example_dial: '(11) 2345-6789' bn: country_name: en: 'Brunei' es: 'Brunéi' country_code: 673 example_dial: '234 5678' bg: country_name: en: 'Bulgaria' es: 'Bulgaria' country_code: 359 example_dial: '02 123 456' bf: country_name: en: 'Burkina Faso' es: 'Burkina Faso' country_code: 226 example_dial: '20 49 12 34' bi: country_name: en: 'Burundi' es: 'Burundi' country_code: 257 example_dial: '22 20 12 34' kh: country_name: en: 'Cambodia' es: 'Camboya' country_code: 855 example_dial: '023 456 789' cm: country_name: en: 'Cameroon' es: 'Camerún' country_code: 237 example_dial: '22 12 34 56' ca: country_name: en: 'Canada' es: 'Canada' country_code: 1 example_dial: '(204) 234-5678' cv: country_name: en: 'Cape Verde Island' es: 'Isla Cabo Verde' country_code: 238 example_dial: '221 12 34' ky: country_name: en: 'Cayman Islands' es: 'Islas Caimán' country_code: 1345 example_dial: '(345) 222-1234' cf: country_name: en: 'Central African Rep.' es: 'Rep Centroafricana.' country_code: 236 example_dial: '21 61 23 45' td: country_name: en: 'Chad' es: 'Chad' country_code: 235 example_dial: '22 50 12 34' cl: country_name: en: 'Chile' es: 'Chile' country_code: 56 example_dial: '(2) 2123 4567' cn: country_name: en: 'China' es: 'China' country_code: 86 example_dial: '010 1234 5678' co: country_name: en: 'Colombia' es: 'Colombia' country_code: 57 example_dial: '(1) 2345678' km: country_name: en: 'Comoros' es: 'Comoras' country_code: 269 example_dial: '771 23 45' cg: country_name: en: 'Congo' es: 'Congo' country_code: 242 example_dial: '22 212 3456' ck: country_name: en: 'Cook Islands' es: 'Islas Cook' country_code: 682 example_dial: '21 234' cr: country_name: en: 'Costa Rica' es: 'Costa Rica' country_code: 506 example_dial: '2212 3456' ci: country_name: en: '<NAME>\'<NAME>' es: '<NAME>' country_code: 225 example_dial: '21 23 45 67' hr: country_name: en: 'Croatia' es: 'Croacia' country_code: 385 example_dial: '01 2345 678' cu: country_name: en: 'Cuba' es: 'Cuba' country_code: 53 example_dial: '(07) 1234567' cy: country_name: en: 'Cyprus South' es: 'Chipre' country_code: 357 example_dial: '22 345678' cz: country_name: en: 'Czech Republic' es: 'República Checa' country_code: 420 example_dial: '212 345 678' cd: country_name: en: 'Dem Rep Congo' es: 'República Democrática del Congo' country_code: 243 example_dial: '012 34567' dk: country_name: en: 'Denmark' es: 'Dinamarca' country_code: 45 example_dial: '32 12 34 56' io: country_name: en: 'Die<NAME> G<NAME>' es: 'Die<NAME> García' country_code: 246 example_dial: '370 9100' dj: country_name: en: 'Djibouti' es: 'Djibouti' country_code: 253 example_dial: '21 36 00 03' dm: country_name: en: 'Dominica' es: 'Dominica' country_code: 1767 example_dial: '(767) 420-1234' tl: country_name: en: 'East Timor' es: 'Timor del Este' country_code: 670 example_dial: '211 2345' ec: country_name: en: 'Ecuador' es: 'Ecuador' country_code: 593 example_dial: '(02) 212-3456' eg: country_name: en: 'Egypt' es: 'Egipto' country_code: 20 example_dial: '02 34567890' sv: country_name: en: 'El Salvador' es: 'El Salvador' country_code: 503 example_dial: '2123 4567' gq: country_name: en: 'Equatorial Guinea' es: 'Guinea Ecuatorial' country_code: 240 example_dial: '333 091 234' er: country_name: en: 'Eritrea' es: 'Eritrea' country_code: 291 example_dial: '08 370 362' ee: country_name: en: 'Estonia' es: 'Estonia' country_code: 372 example_dial: '321 2345' et: country_name: en: 'Ethiopia' es: 'Etiopía' country_code: 251 example_dial: '011 111 2345' fo: country_name: en: 'Faeroe Islands' es: 'Islas Feroe' country_code: 298 example_dial: '201234' fk: country_name: en: 'Falkland Islands' es: 'Islas Malvinas' country_code: 500 example_dial: '31234' fj: country_name: en: 'Fiji' es: 'Fiji' country_code: 679 example_dial: '321 2345' fi: country_name: en: 'Finland' es: 'Finlandia' country_code: 358 example_dial: '013 12345678' fr: country_name: en: 'France' es: 'Francia' country_code: 33 example_dial: '01 23 45 67 89' gf: country_name: en: 'French Guiana' es: 'Guayana Francesa' country_code: 594 example_dial: '0594 10 12 34' pf: country_name: en: 'French Polynesia' es: 'Polinesia Francesa' country_code: 689 example_dial: '40 12 34' ga: country_name: en: 'Gabon' es: 'Gabón' country_code: 241 example_dial: '01 44 12 34' gm: country_name: en: 'Gambia' es: 'Gambia' country_code: 220 example_dial: '566 1234' ge: country_name: en: 'Georgia' es: 'Georgia' country_code: 995 example_dial: '8 322 12 34 56' de: country_name: en: 'Germany' es: 'Alemania' country_code: 49 example_dial: '030 123456' gh: country_name: en: 'Ghana' es: 'Ghana' country_code: 233 example_dial: '030 234 5678' gi: country_name: en: 'Gibraltar' es: 'Gibraltar' country_code: 350 example_dial: '20012345' gr: country_name: en: 'Greece' es: 'Grecia' country_code: 30 example_dial: '21 2345 6789' gl: country_name: en: 'Greenland' es: 'Groenlandia' country_code: 299 example_dial: '32 10 00' gd: country_name: en: 'Grenada' es: 'Granada' country_code: 1473 example_dial: '(473) 269-1234' bl: country_name: en: 'Guadeloupe' es: 'Guadalupe' country_code: 590 example_dial: '0590 27-1234' gu: country_name: en: 'Guam' es: 'Guam' country_code: 1671 example_dial: '(671) 300-1234' gt: country_name: en: 'Guatemala' es: 'Guatemala' country_code: 502 example_dial: '2245 6789' gn: country_name: en: 'Guinea' es: 'Guinea' country_code: 224 example_dial: '30 24 12 34' gy: country_name: en: 'Guyana' es: 'Guyana' country_code: 592 example_dial: '220 1234' ht: country_name: en: 'Haiti' es: 'Haití' country_code: 509 example_dial: '22 45 3300' hn: country_name: en: 'Honduras' es: 'Honduras' country_code: 504 example_dial: '2212-3456' hk: country_name: en: 'Hong Kong' es: 'Hong Kong' country_code: 852 example_dial: '2123 4567' hu: country_name: en: 'Hungary' es: 'Hungría' country_code: 36 example_dial: '(1) 234 5678' is: country_name: en: 'Iceland' es: 'Islandia' country_code: 354 example_dial: '410 1234' in: country_name: en: 'India' es: 'India' country_code: 91 example_dial: '011 2345 6789' id: country_name: en: 'Indonesia' es: 'Indonesia' country_code: 62 example_dial: '(061) 2345678' pn: country_name: en: 'Inmarsat HSD' es: 'Inmarsat HSD' country_code: 870 example_dial: '' ir: country_name: en: 'Iran' es: 'Irán' country_code: 98 example_dial: '021 2345 6789' iq: country_name: en: 'Iraq' es: 'Irak' country_code: 964 example_dial: '01 234 5678' ie: country_name: en: 'Ireland' es: 'Irlanda' country_code: 353 example_dial: '(022) 12345' il: country_name: en: 'Israel' es: 'Israel' country_code: 972 example_dial: '02-123-4567' it: country_name: en: 'Italy' es: 'Italia' country_code: 39 example_dial: '02 1234 5678' jm: country_name: en: 'Jamaica' es: 'Jamaica' country_code: 1876 example_dial: '(876) 512-3456' jp: country_name: en: 'Japan' es: 'Japón' country_code: 81 example_dial: '' jo: country_name: en: 'Jordan' es: 'Jordan' country_code: 962 example_dial: '(06) 200 1234' kz: country_name: en: 'Kazakhstan' es: 'Kazajstán' country_code: 7 example_dial: '8 (712) 345 6789' ke: country_name: en: 'Kenya' es: 'Kenya' country_code: 254 example_dial: '020 2012345' ki: country_name: en: 'Kiribati' es: 'Kiribati' country_code: 686 example_dial: '31234' kp: country_name: en: 'Korea North' es: 'Corea del Norte' country_code: 850 example_dial: '02 123 4567' kr: country_name: en: 'Korea South' es: 'Corea del Sur' country_code: 82 example_dial: '02-212-3456' kw: country_name: en: 'Kuwait' es: 'Kuwait' country_code: 965 example_dial: '2234 5678' kg: country_name: en: 'Kyrgyzstan' es: 'Kirguistán' country_code: 996 example_dial: '0312 123 456' la: country_name: en: 'Laos' es: 'Laos' country_code: 856 example_dial: '021 212 862' lv: country_name: en: 'Latvia' es: 'Letonia' country_code: 371 example_dial: '63 123 456' lb: country_name: en: 'Lebanon' es: 'Líbano' country_code: 961 example_dial: '01 123 456' ls: country_name: en: 'Lesotho' es: 'Lesotho' country_code: 266 example_dial: '2212 3456' lr: country_name: en: 'Liberia' es: 'Liberia' country_code: 231 example_dial: '021 234 567' ly: country_name: en: 'Libya' es: 'Libia' country_code: 218 example_dial: '021-2345678' li: country_name: en: 'Liechtenstein' es: 'Liechtenstein' country_code: 423 example_dial: '234 56 78' lt: country_name: en: 'Lithuania' es: 'Lituania' country_code: 370 example_dial: '(8-312) 34567' lu: country_name: en: 'Luxembourg' es: 'Luxemburgo' country_code: 352 example_dial: '27 12 34 56' mo: country_name: en: 'Macao' es: 'Macao' country_code: 853 example_dial: '2821 2345' mk: country_name: en: 'Macedonia' es: 'Macedonia' country_code: 389 example_dial: '02 221 2345' mg: country_name: en: 'Madagascar' es: 'Madagascar' country_code: 261 example_dial: '020 21 234 56' mw: country_name: en: 'Malawi' es: 'Malawi' country_code: 265 example_dial: '01 234 567' my: country_name: en: 'Malaysia' es: 'Malasia' country_code: 60 example_dial: '03-2345 6789' mv: country_name: en: 'Maldives' es: 'Maldivas' country_code: 960 example_dial: '670-1234' ml: country_name: en: 'Mali' es: 'Malí' country_code: 223 example_dial: '20 21 23 45' mt: country_name: en: 'Malta' es: 'Malta' country_code: 356 example_dial: '2100 1234' mh: country_name: en: 'Marshall Islands' es: 'Islas Marshall' country_code: 692 example_dial: '247-1234' mq: country_name: en: 'Martinique' es: 'Martinica' country_code: 596 example_dial: '0596 30 12 34' mr: country_name: en: 'Mauritania' es: 'Mauritania' country_code: 222 example_dial: '35 12 34 56' mu: country_name: en: 'Mauritius' es: 'Mauricio' country_code: 230 example_dial: '201 2345' yt: country_name: en: 'Mayotte' es: 'Mayotte' country_code: 262 example_dial: '0269 60 12 34' mx: country_name: en: 'Mexico' es: 'México' country_code: 52 example_dial: '55 1234 5678' fm: country_name: en: 'Micronesia' es: 'Micronesia' country_code: 691 example_dial: '320 1234' md: country_name: en: 'Moldova' es: 'Moldavia' country_code: 373 example_dial: '022 212 345' mc: country_name: en: 'Monaco' es: 'Mónaco' country_code: 377 example_dial: '99 12 34 56' mn: country_name: en: 'Mongolia' es: 'Mongolia' country_code: 976 example_dial: '5012 3456' ms: country_name: en: 'Montserrat' es: 'Montserrat' country_code: 1664 example_dial: '(664) 491-2345' ma: country_name: en: 'Morocco' es: 'Marruecos' country_code: 212 example_dial: '0520-123456' mz: country_name: en: 'Mozambique' es: 'Mozambique' country_code: 258 example_dial: '21 123 456' mm: country_name: en: 'Myanmar' es: 'Myanmar' country_code: 95 example_dial: '01 234 567' na: country_name: en: 'Namibia' es: 'Namibia' country_code: 264 example_dial: '061 201 2345' nr: country_name: en: 'Nauru' es: 'Nauru' country_code: 674 example_dial: '444 1234' np: country_name: en: 'Nepal' es: 'Nepal' country_code: 977 example_dial: '01-4567890' nl: country_name: en: 'Netherlands' es: 'Países Bajos' country_code: 31 example_dial: '010 123 4567' nc: country_name: en: 'New Caledonia' es: 'Nueva Caledonia' country_code: 687 example_dial: '20.12.34' nz: country_name: en: 'New Zealand' es: 'Nueva Zelanda' country_code: 64 example_dial: '03-234 5678' ni: country_name: en: 'Nicaragua' es: 'Nicaragua' country_code: 505 example_dial: '2123 4567' ne: country_name: en: 'Niger' es: 'Níger' country_code: 227 example_dial: '20 20 12 34' nu: country_name: en: 'Niue' es: 'Niue' country_code: 683 example_dial: '4002' nf: country_name: en: 'Norfolk Islands' es: 'Islas Norfolk' country_code: 6723 example_dial: '10 6609' mp: country_name: en: 'Northern Marianas' es: 'Islas Marianas del Norte' country_code: 1670 example_dial: '(670) 234-5678' no: country_name: en: 'Norway' es: 'Noruega' country_code: 47 example_dial: '21 23 45 67' om: country_name: en: 'Oman' es: 'Omán' country_code: 968 example_dial: '23 123456' pk: country_name: en: 'Pakistan' es: 'Pakistán' country_code: 92 example_dial: '(021) 23456789' pw: country_name: en: 'Palau' es: 'Palau' country_code: 680 example_dial: '277 1234' ps: country_name: en: 'Palestine' es: 'Palestina' country_code: 970 example_dial: '02 223 4567' pa: country_name: en: 'Panama' es: 'Panamá' country_code: 507 example_dial: '200-1234' pg: country_name: en: 'Papua New Guinea' es: 'Papúa Nueva Guinea' country_code: 675 example_dial: '312 3456' py: country_name: en: 'Paraguay' es: 'Paraguay' country_code: 595 example_dial: '(21) 2345678' pe: country_name: en: 'Peru' es: 'Perú' country_code: 51 example_dial: '(01) 1234567' ph: country_name: en: 'Philippines' es: 'Filipinas' country_code: 63 example_dial: '(02) 123 4567' pl: country_name: en: 'Poland' es: 'Polonia' country_code: 48 example_dial: '12 345 67 89' pt: country_name: en: 'Portugal' es: 'Portugal' country_code: 351 example_dial: '212 345 678' 'pr-1': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1939 example_dial: '(939) 234-5678' 'pr-2': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1787 example_dial: '(787) 234-5678' qa: country_name: en: 'Qatar' es: 'Qatar' country_code: 974 example_dial: '4412 3456' re: country_name: en: 'Reunion' es: 'Reunion' country_code: 262 example_dial: '0262 16 12 34' ro: country_name: en: 'Romania' es: 'Rumania' country_code: 40 example_dial: '021 123 4567' ru: country_name: en: 'Russia' es: 'Rusia' country_code: 7 example_dial: '8 (301) 123-45-67' rw: country_name: en: 'Rwanda' es: 'Rwanda' country_code: 250 example_dial: '250 123 456' sm: country_name: en: 'San Marino' es: 'San Marino' country_code: 378 example_dial: '0549 886377' st: country_name: en: 'Sao Tome & Principe' es: 'Sao Tome & Principe' country_code: 239 example_dial: '222 1234' sa: country_name: en: 'Saudi Arabia' es: 'Arabia Saudita' country_code: 966 example_dial: '01 234 5678' sn: country_name: en: 'Senegal' es: 'Senegal' country_code: 221 example_dial: '30 101 23 45' rs: country_name: en: 'Serbia' es: 'Serbia' country_code: 381 example_dial: '010 234567' sc: country_name: en: 'Seychelles' es: 'Seychelles' country_code: 248 example_dial: '4 217 123' sl: country_name: en: 'Sierra Leone' es: 'Sierra Leona' country_code: 232 example_dial: '(022) 221234' sg: country_name: en: 'Singapore' es: 'Singapur' country_code: 65 example_dial: '6123 4567' sk: country_name: en: 'Slovak Rep' es: 'República Eslovaca' country_code: 421 example_dial: '02x2F123 456 78' si: country_name: en: 'Slovenia' es: 'Eslovenia' country_code: 386 example_dial: '(01) 123 45 67' sb: country_name: en: 'Solomon Islands' es: 'Islas Salomón' country_code: 677 example_dial: '40123' so: country_name: en: 'Somalia' es: 'Somalia' country_code: 252 example_dial: '5 522010' za: country_name: en: 'South Africa' es: 'Sudáfrica' country_code: 27 example_dial: '010 123 4567' es: country_name: en: 'Spain' es: 'España' country_code: 34 example_dial: '810 12 34 56' lk: country_name: en: 'Sri Lanka' es: 'Sri Lanka' country_code: 94 example_dial: '011 2 345678' sh: country_name: en: 'St. Helena' es: 'St. Helena' country_code: 290 example_dial: '2158' kn: country_name: en: 'St. Kitts & Nevis' es: 'St. Kitts & Nieves' country_code: 1869 example_dial: '(869) 236-1234' lc: country_name: en: 'St. Lucia' es: 'Santa Lucía' country_code: 1758 example_dial: '(758) 234-5678' pm: country_name: en: 'St. Pierre & Miquelon' es: 'St. Pierre & Miquelón' country_code: 508 example_dial: '041 12 34' vc: country_name: en: 'St. Vincents' es: 'St. Vincent' country_code: 1784 example_dial: '(784) 266-1234' sd: country_name: en: 'Sudan' es: 'Sudán' country_code: 249 example_dial: '012 123 1234' sr: country_name: en: 'Suriname' es: 'Suriname' country_code: 597 example_dial: '211-234' sz: country_name: en: 'Swaziland' es: 'Swazilandia' country_code: 268 example_dial: '2217 1234' se: country_name: en: 'Sweden' es: 'Suecia' country_code: 46 example_dial: '08-12 34 56' ch: country_name: en: 'Switzerland' es: 'Suiza' country_code: 41 example_dial: '021 234 56 78' sy: country_name: en: 'Syria' es: 'Siria' country_code: 963 example_dial: '011 234 5678' tw: country_name: en: 'Taiwan' es: 'Taiwan' country_code: 886 example_dial: '02 123 4567' tj: country_name: en: 'Tajikstan' es: 'Tayikistán' country_code: 992 example_dial: '(8) 372 12 3456' tz: country_name: en: 'Tanzania' es: 'Tanzania' country_code: 255 example_dial: '022 234 5678' th: country_name: en: 'Thailand' es: 'Tailandia' country_code: 66 example_dial: '02 123 4567' tg: country_name: en: 'Togo' es: 'Togo' country_code: 228 example_dial: '22 21 23 45' tk: country_name: en: 'Tokelau' es: 'Tokelau' country_code: 690 example_dial: '3010' to: country_name: en: 'Tonga' es: 'Tonga' country_code: 676 example_dial: '20-123' tt: country_name: en: 'Trinidad & Tobago' es: 'Trinidad & amp; Tobago' country_code: 1868 example_dial: '(868) 221-1234' tn: country_name: en: 'Tunisia' es: 'Túnez' country_code: 216 example_dial: '71 234 567' tr: country_name: en: 'Turkey' es: 'pavo' country_code: 90 example_dial: '(0212) 345 6789' tm: country_name: en: 'Turkmenistan' es: 'Turkmenistán' country_code: 993 example_dial: '(8 12) 34-56-78' tc: country_name: en: 'Turks & Caicos' es: 'Turks & amp; Caicos' country_code: 1649 example_dial: '(649) 712-1234' tv: country_name: en: 'Tuvalu' es: 'Tuvalu' country_code: 688 example_dial: '20123' ug: country_name: en: 'Uganda' es: 'Uganda' country_code: 256 example_dial: '031 2345678' gb: country_name: en: 'United Kingdom' es: 'Reino Unido' country_code: 44 example_dial: '0121 234 5678' ua: country_name: en: 'Ukraine' es: 'Ucrania' country_code: 380 example_dial: '03112 34567' ae: country_name: en: 'United Arab Emirates' es: 'Emiratos Árabes Unidos' country_code: 971 example_dial: '02 234 5678' uy: country_name: en: 'Uruguay' es: 'Uruguay' country_code: 598 example_dial: '2123 1234' us: country_name: en: 'United States' es: 'Estados Unidos' country_code: 1 example_dial: '(201) 555-0123' uz: country_name: en: 'Uzbekistan' es: 'Uzbekistán' country_code: 998 example_dial: '8 66 234 56 78' vu: country_name: en: 'Vanuatu' es: 'Vanuatu' country_code: 678 example_dial: '22123' ve: country_name: en: 'Venezuela' es: 'Venezuela' country_code: 58 example_dial: '0212-1234567' vn: country_name: en: 'Vietnam' es: 'Vietnam' country_code: 84 example_dial: '0210 1234 567' vg: country_name: en: 'Virgin Islands GB' es: 'Islas Vírgenes GB' country_code: 1284 example_dial: '(284) 229-1234' vi: country_name: en: 'Virgin Islands USA' es: 'Islas Vírgenes de EE.UU.' country_code: 1340 example_dial: '(340) 642-1234' wf: country_name: en: 'Wallis & Futuna' es: 'Wallis & Futuna' country_code: 681 example_dial: '50 12 34' ws: country_name: en: 'Western Samoa' es: 'Samoa Occidental' country_code: 685 example_dial: '22123' ye: country_name: en: 'Yemen' es: 'Yemen' country_code: 967 example_dial: '01 234 567' zm: country_name: en: 'Zambia' es: 'Zambia' country_code: 260 example_dial: '021 1234567' zw: country_name: en: 'Zimbabwe' es: 'Zimbabwe' country_code: 263 example_dial: '013 12345' 'do-1': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1849 example_dial: '(849) 234-5678' 'do-2': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1809 example_dial: '(809) 234-5678' 'do-3': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1829 example_dial: '(829) 234-5678' gw: country_name: en: 'Guinea-Bissau' es: 'Guinea-Bissau' country_code: 245 example_dial: '320 1234' me: country_name: en: 'Montenegro' es: 'Montenegro' country_code: 382 example_dial: '030 234 567' ng: country_name: en: 'Nigeria' es: 'Nigeria' country_code: 234 example_dial: '01 234 5678' mf: country_name: en: 'Saint Martin' es: 'saint Martin' country_code: 1599 example_dial: '0590 27-1234' gp: country_name: en: 'Saint Barthelemy' es: 'San Bartolomé' country_code: 590 example_dial: '0590 20-1234' ss: country_name: en: 'South Sudan' es: 'Sudán del Sur' country_code: 211 example_dial: '' sx: country_name: en: 'Sint Maarten' es: 'Sint Maarten' country_code: 1721 example_dial: ''
true
module.exports = af: country_name: en: 'Afghanistan' es: 'Afganistán' country_code: 93 example_dial: '023 456 7890' al: country_name: en: 'Albania' es: 'Albania' country_code: 355 example_dial: '022 345 678' dz: country_name: en: 'Algeria' es: 'Argelia' country_code: 213 example_dial: '012 34 56 78' as: country_name: en: 'American Samoa' es: 'Samoa Americana' country_code: 1684 example_dial: '(684) 622-1234' ad: country_name: en: 'Andorra' es: 'Andorra' country_code: 376 example_dial: '712 345' ao: country_name: en: 'Angola' es: 'Angola' country_code: 244 example_dial: '222 123 456' ai: country_name: en: 'Anguilla' es: 'Anguila' country_code: 1264 example_dial: '(264) 461-2345' aq: country_name: en: 'Antarctic Territories' es: 'Antártida' country_code: 672 example_dial: '' ag: country_name: en: 'Antigua & Barbuda' es: 'Antigua & Barbuda' country_code: 1268 example_dial: '(268) 460-1234' an: country_name: en: 'Antilles' es: 'Antillas' country_code: 599 example_dial: '' ar: country_name: en: 'Argentina' es: 'Argentina' country_code: 54 example_dial: '11 2345-6789' am: country_name: en: 'Armenia' es: 'Armenia' country_code: 374 example_dial: '(010) 123456' aw: country_name: en: 'Aruba' es: 'Aruba' country_code: 297 example_dial: '521 2345' au: country_name: en: 'Australia' es: 'Australia' country_code: 61 example_dial: '(02) 1234 5678' at: country_name: en: 'Austria' es: 'Austria' country_code: 43 example_dial: '01 234567890' az: country_name: en: 'Azerbaijan' es: 'Azerbaiyán' country_code: 994 example_dial: '(012) 312 34 56' bs: country_name: en: 'Bahamas' es: 'Bahamas' country_code: 1242 example_dial: '(242) 345-6789' bh: country_name: en: 'Bahrain' es: 'Bahrein' country_code: 973 example_dial: '1700 1234' bd: country_name: en: 'Bangladesh' es: 'Bangladesh' country_code: 880 example_dial: '02-7111234' bb: country_name: en: 'Barbados' es: 'Barbados' country_code: 1246 example_dial: '(246) 234-5678' by: country_name: en: 'Belarus' es: 'Bielorrusia' country_code: 375 example_dial: '8 015 245 0911' be: country_name: en: 'Belgium' es: 'Bélgica' country_code: 32 example_dial: '012 34 56 78' bz: country_name: en: 'Belize' es: 'Belice' country_code: 501 example_dial: '222-1234' bj: country_name: en: 'Benin' es: 'Benin' country_code: 229 example_dial: '20 21 12 34' bm: country_name: en: 'Bermuda' es: 'Bermuda' country_code: 1441 example_dial: '(441) 234-5678' bt: country_name: en: 'Bhutan' es: 'Bután' country_code: 975 example_dial: '2 345 678' bo: country_name: en: 'Bolivia' es: 'Bolivia' country_code: 591 example_dial: '2 2123456' ba: country_name: en: 'Bosnia & H.' es: 'Bosnia & H.' country_code: 387 example_dial: '030 123-456' bw: country_name: en: 'Botswana' es: 'Botswana' country_code: 267 example_dial: '240 1234' br: country_name: en: 'Brazil' es: 'Brasil' country_code: 55 example_dial: '(11) 2345-6789' bn: country_name: en: 'Brunei' es: 'Brunéi' country_code: 673 example_dial: '234 5678' bg: country_name: en: 'Bulgaria' es: 'Bulgaria' country_code: 359 example_dial: '02 123 456' bf: country_name: en: 'Burkina Faso' es: 'Burkina Faso' country_code: 226 example_dial: '20 49 12 34' bi: country_name: en: 'Burundi' es: 'Burundi' country_code: 257 example_dial: '22 20 12 34' kh: country_name: en: 'Cambodia' es: 'Camboya' country_code: 855 example_dial: '023 456 789' cm: country_name: en: 'Cameroon' es: 'Camerún' country_code: 237 example_dial: '22 12 34 56' ca: country_name: en: 'Canada' es: 'Canada' country_code: 1 example_dial: '(204) 234-5678' cv: country_name: en: 'Cape Verde Island' es: 'Isla Cabo Verde' country_code: 238 example_dial: '221 12 34' ky: country_name: en: 'Cayman Islands' es: 'Islas Caimán' country_code: 1345 example_dial: '(345) 222-1234' cf: country_name: en: 'Central African Rep.' es: 'Rep Centroafricana.' country_code: 236 example_dial: '21 61 23 45' td: country_name: en: 'Chad' es: 'Chad' country_code: 235 example_dial: '22 50 12 34' cl: country_name: en: 'Chile' es: 'Chile' country_code: 56 example_dial: '(2) 2123 4567' cn: country_name: en: 'China' es: 'China' country_code: 86 example_dial: '010 1234 5678' co: country_name: en: 'Colombia' es: 'Colombia' country_code: 57 example_dial: '(1) 2345678' km: country_name: en: 'Comoros' es: 'Comoras' country_code: 269 example_dial: '771 23 45' cg: country_name: en: 'Congo' es: 'Congo' country_code: 242 example_dial: '22 212 3456' ck: country_name: en: 'Cook Islands' es: 'Islas Cook' country_code: 682 example_dial: '21 234' cr: country_name: en: 'Costa Rica' es: 'Costa Rica' country_code: 506 example_dial: '2212 3456' ci: country_name: en: 'PI:NAME:<NAME>END_PI\'PI:NAME:<NAME>END_PI' es: 'PI:NAME:<NAME>END_PI' country_code: 225 example_dial: '21 23 45 67' hr: country_name: en: 'Croatia' es: 'Croacia' country_code: 385 example_dial: '01 2345 678' cu: country_name: en: 'Cuba' es: 'Cuba' country_code: 53 example_dial: '(07) 1234567' cy: country_name: en: 'Cyprus South' es: 'Chipre' country_code: 357 example_dial: '22 345678' cz: country_name: en: 'Czech Republic' es: 'República Checa' country_code: 420 example_dial: '212 345 678' cd: country_name: en: 'Dem Rep Congo' es: 'República Democrática del Congo' country_code: 243 example_dial: '012 34567' dk: country_name: en: 'Denmark' es: 'Dinamarca' country_code: 45 example_dial: '32 12 34 56' io: country_name: en: 'DiePI:NAME:<NAME>END_PI GPI:NAME:<NAME>END_PI' es: 'DiePI:NAME:<NAME>END_PI García' country_code: 246 example_dial: '370 9100' dj: country_name: en: 'Djibouti' es: 'Djibouti' country_code: 253 example_dial: '21 36 00 03' dm: country_name: en: 'Dominica' es: 'Dominica' country_code: 1767 example_dial: '(767) 420-1234' tl: country_name: en: 'East Timor' es: 'Timor del Este' country_code: 670 example_dial: '211 2345' ec: country_name: en: 'Ecuador' es: 'Ecuador' country_code: 593 example_dial: '(02) 212-3456' eg: country_name: en: 'Egypt' es: 'Egipto' country_code: 20 example_dial: '02 34567890' sv: country_name: en: 'El Salvador' es: 'El Salvador' country_code: 503 example_dial: '2123 4567' gq: country_name: en: 'Equatorial Guinea' es: 'Guinea Ecuatorial' country_code: 240 example_dial: '333 091 234' er: country_name: en: 'Eritrea' es: 'Eritrea' country_code: 291 example_dial: '08 370 362' ee: country_name: en: 'Estonia' es: 'Estonia' country_code: 372 example_dial: '321 2345' et: country_name: en: 'Ethiopia' es: 'Etiopía' country_code: 251 example_dial: '011 111 2345' fo: country_name: en: 'Faeroe Islands' es: 'Islas Feroe' country_code: 298 example_dial: '201234' fk: country_name: en: 'Falkland Islands' es: 'Islas Malvinas' country_code: 500 example_dial: '31234' fj: country_name: en: 'Fiji' es: 'Fiji' country_code: 679 example_dial: '321 2345' fi: country_name: en: 'Finland' es: 'Finlandia' country_code: 358 example_dial: '013 12345678' fr: country_name: en: 'France' es: 'Francia' country_code: 33 example_dial: '01 23 45 67 89' gf: country_name: en: 'French Guiana' es: 'Guayana Francesa' country_code: 594 example_dial: '0594 10 12 34' pf: country_name: en: 'French Polynesia' es: 'Polinesia Francesa' country_code: 689 example_dial: '40 12 34' ga: country_name: en: 'Gabon' es: 'Gabón' country_code: 241 example_dial: '01 44 12 34' gm: country_name: en: 'Gambia' es: 'Gambia' country_code: 220 example_dial: '566 1234' ge: country_name: en: 'Georgia' es: 'Georgia' country_code: 995 example_dial: '8 322 12 34 56' de: country_name: en: 'Germany' es: 'Alemania' country_code: 49 example_dial: '030 123456' gh: country_name: en: 'Ghana' es: 'Ghana' country_code: 233 example_dial: '030 234 5678' gi: country_name: en: 'Gibraltar' es: 'Gibraltar' country_code: 350 example_dial: '20012345' gr: country_name: en: 'Greece' es: 'Grecia' country_code: 30 example_dial: '21 2345 6789' gl: country_name: en: 'Greenland' es: 'Groenlandia' country_code: 299 example_dial: '32 10 00' gd: country_name: en: 'Grenada' es: 'Granada' country_code: 1473 example_dial: '(473) 269-1234' bl: country_name: en: 'Guadeloupe' es: 'Guadalupe' country_code: 590 example_dial: '0590 27-1234' gu: country_name: en: 'Guam' es: 'Guam' country_code: 1671 example_dial: '(671) 300-1234' gt: country_name: en: 'Guatemala' es: 'Guatemala' country_code: 502 example_dial: '2245 6789' gn: country_name: en: 'Guinea' es: 'Guinea' country_code: 224 example_dial: '30 24 12 34' gy: country_name: en: 'Guyana' es: 'Guyana' country_code: 592 example_dial: '220 1234' ht: country_name: en: 'Haiti' es: 'Haití' country_code: 509 example_dial: '22 45 3300' hn: country_name: en: 'Honduras' es: 'Honduras' country_code: 504 example_dial: '2212-3456' hk: country_name: en: 'Hong Kong' es: 'Hong Kong' country_code: 852 example_dial: '2123 4567' hu: country_name: en: 'Hungary' es: 'Hungría' country_code: 36 example_dial: '(1) 234 5678' is: country_name: en: 'Iceland' es: 'Islandia' country_code: 354 example_dial: '410 1234' in: country_name: en: 'India' es: 'India' country_code: 91 example_dial: '011 2345 6789' id: country_name: en: 'Indonesia' es: 'Indonesia' country_code: 62 example_dial: '(061) 2345678' pn: country_name: en: 'Inmarsat HSD' es: 'Inmarsat HSD' country_code: 870 example_dial: '' ir: country_name: en: 'Iran' es: 'Irán' country_code: 98 example_dial: '021 2345 6789' iq: country_name: en: 'Iraq' es: 'Irak' country_code: 964 example_dial: '01 234 5678' ie: country_name: en: 'Ireland' es: 'Irlanda' country_code: 353 example_dial: '(022) 12345' il: country_name: en: 'Israel' es: 'Israel' country_code: 972 example_dial: '02-123-4567' it: country_name: en: 'Italy' es: 'Italia' country_code: 39 example_dial: '02 1234 5678' jm: country_name: en: 'Jamaica' es: 'Jamaica' country_code: 1876 example_dial: '(876) 512-3456' jp: country_name: en: 'Japan' es: 'Japón' country_code: 81 example_dial: '' jo: country_name: en: 'Jordan' es: 'Jordan' country_code: 962 example_dial: '(06) 200 1234' kz: country_name: en: 'Kazakhstan' es: 'Kazajstán' country_code: 7 example_dial: '8 (712) 345 6789' ke: country_name: en: 'Kenya' es: 'Kenya' country_code: 254 example_dial: '020 2012345' ki: country_name: en: 'Kiribati' es: 'Kiribati' country_code: 686 example_dial: '31234' kp: country_name: en: 'Korea North' es: 'Corea del Norte' country_code: 850 example_dial: '02 123 4567' kr: country_name: en: 'Korea South' es: 'Corea del Sur' country_code: 82 example_dial: '02-212-3456' kw: country_name: en: 'Kuwait' es: 'Kuwait' country_code: 965 example_dial: '2234 5678' kg: country_name: en: 'Kyrgyzstan' es: 'Kirguistán' country_code: 996 example_dial: '0312 123 456' la: country_name: en: 'Laos' es: 'Laos' country_code: 856 example_dial: '021 212 862' lv: country_name: en: 'Latvia' es: 'Letonia' country_code: 371 example_dial: '63 123 456' lb: country_name: en: 'Lebanon' es: 'Líbano' country_code: 961 example_dial: '01 123 456' ls: country_name: en: 'Lesotho' es: 'Lesotho' country_code: 266 example_dial: '2212 3456' lr: country_name: en: 'Liberia' es: 'Liberia' country_code: 231 example_dial: '021 234 567' ly: country_name: en: 'Libya' es: 'Libia' country_code: 218 example_dial: '021-2345678' li: country_name: en: 'Liechtenstein' es: 'Liechtenstein' country_code: 423 example_dial: '234 56 78' lt: country_name: en: 'Lithuania' es: 'Lituania' country_code: 370 example_dial: '(8-312) 34567' lu: country_name: en: 'Luxembourg' es: 'Luxemburgo' country_code: 352 example_dial: '27 12 34 56' mo: country_name: en: 'Macao' es: 'Macao' country_code: 853 example_dial: '2821 2345' mk: country_name: en: 'Macedonia' es: 'Macedonia' country_code: 389 example_dial: '02 221 2345' mg: country_name: en: 'Madagascar' es: 'Madagascar' country_code: 261 example_dial: '020 21 234 56' mw: country_name: en: 'Malawi' es: 'Malawi' country_code: 265 example_dial: '01 234 567' my: country_name: en: 'Malaysia' es: 'Malasia' country_code: 60 example_dial: '03-2345 6789' mv: country_name: en: 'Maldives' es: 'Maldivas' country_code: 960 example_dial: '670-1234' ml: country_name: en: 'Mali' es: 'Malí' country_code: 223 example_dial: '20 21 23 45' mt: country_name: en: 'Malta' es: 'Malta' country_code: 356 example_dial: '2100 1234' mh: country_name: en: 'Marshall Islands' es: 'Islas Marshall' country_code: 692 example_dial: '247-1234' mq: country_name: en: 'Martinique' es: 'Martinica' country_code: 596 example_dial: '0596 30 12 34' mr: country_name: en: 'Mauritania' es: 'Mauritania' country_code: 222 example_dial: '35 12 34 56' mu: country_name: en: 'Mauritius' es: 'Mauricio' country_code: 230 example_dial: '201 2345' yt: country_name: en: 'Mayotte' es: 'Mayotte' country_code: 262 example_dial: '0269 60 12 34' mx: country_name: en: 'Mexico' es: 'México' country_code: 52 example_dial: '55 1234 5678' fm: country_name: en: 'Micronesia' es: 'Micronesia' country_code: 691 example_dial: '320 1234' md: country_name: en: 'Moldova' es: 'Moldavia' country_code: 373 example_dial: '022 212 345' mc: country_name: en: 'Monaco' es: 'Mónaco' country_code: 377 example_dial: '99 12 34 56' mn: country_name: en: 'Mongolia' es: 'Mongolia' country_code: 976 example_dial: '5012 3456' ms: country_name: en: 'Montserrat' es: 'Montserrat' country_code: 1664 example_dial: '(664) 491-2345' ma: country_name: en: 'Morocco' es: 'Marruecos' country_code: 212 example_dial: '0520-123456' mz: country_name: en: 'Mozambique' es: 'Mozambique' country_code: 258 example_dial: '21 123 456' mm: country_name: en: 'Myanmar' es: 'Myanmar' country_code: 95 example_dial: '01 234 567' na: country_name: en: 'Namibia' es: 'Namibia' country_code: 264 example_dial: '061 201 2345' nr: country_name: en: 'Nauru' es: 'Nauru' country_code: 674 example_dial: '444 1234' np: country_name: en: 'Nepal' es: 'Nepal' country_code: 977 example_dial: '01-4567890' nl: country_name: en: 'Netherlands' es: 'Países Bajos' country_code: 31 example_dial: '010 123 4567' nc: country_name: en: 'New Caledonia' es: 'Nueva Caledonia' country_code: 687 example_dial: '20.12.34' nz: country_name: en: 'New Zealand' es: 'Nueva Zelanda' country_code: 64 example_dial: '03-234 5678' ni: country_name: en: 'Nicaragua' es: 'Nicaragua' country_code: 505 example_dial: '2123 4567' ne: country_name: en: 'Niger' es: 'Níger' country_code: 227 example_dial: '20 20 12 34' nu: country_name: en: 'Niue' es: 'Niue' country_code: 683 example_dial: '4002' nf: country_name: en: 'Norfolk Islands' es: 'Islas Norfolk' country_code: 6723 example_dial: '10 6609' mp: country_name: en: 'Northern Marianas' es: 'Islas Marianas del Norte' country_code: 1670 example_dial: '(670) 234-5678' no: country_name: en: 'Norway' es: 'Noruega' country_code: 47 example_dial: '21 23 45 67' om: country_name: en: 'Oman' es: 'Omán' country_code: 968 example_dial: '23 123456' pk: country_name: en: 'Pakistan' es: 'Pakistán' country_code: 92 example_dial: '(021) 23456789' pw: country_name: en: 'Palau' es: 'Palau' country_code: 680 example_dial: '277 1234' ps: country_name: en: 'Palestine' es: 'Palestina' country_code: 970 example_dial: '02 223 4567' pa: country_name: en: 'Panama' es: 'Panamá' country_code: 507 example_dial: '200-1234' pg: country_name: en: 'Papua New Guinea' es: 'Papúa Nueva Guinea' country_code: 675 example_dial: '312 3456' py: country_name: en: 'Paraguay' es: 'Paraguay' country_code: 595 example_dial: '(21) 2345678' pe: country_name: en: 'Peru' es: 'Perú' country_code: 51 example_dial: '(01) 1234567' ph: country_name: en: 'Philippines' es: 'Filipinas' country_code: 63 example_dial: '(02) 123 4567' pl: country_name: en: 'Poland' es: 'Polonia' country_code: 48 example_dial: '12 345 67 89' pt: country_name: en: 'Portugal' es: 'Portugal' country_code: 351 example_dial: '212 345 678' 'pr-1': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1939 example_dial: '(939) 234-5678' 'pr-2': country_name: en: 'Puerto Rico' es: 'Puerto Rico' country_code: 1787 example_dial: '(787) 234-5678' qa: country_name: en: 'Qatar' es: 'Qatar' country_code: 974 example_dial: '4412 3456' re: country_name: en: 'Reunion' es: 'Reunion' country_code: 262 example_dial: '0262 16 12 34' ro: country_name: en: 'Romania' es: 'Rumania' country_code: 40 example_dial: '021 123 4567' ru: country_name: en: 'Russia' es: 'Rusia' country_code: 7 example_dial: '8 (301) 123-45-67' rw: country_name: en: 'Rwanda' es: 'Rwanda' country_code: 250 example_dial: '250 123 456' sm: country_name: en: 'San Marino' es: 'San Marino' country_code: 378 example_dial: '0549 886377' st: country_name: en: 'Sao Tome & Principe' es: 'Sao Tome & Principe' country_code: 239 example_dial: '222 1234' sa: country_name: en: 'Saudi Arabia' es: 'Arabia Saudita' country_code: 966 example_dial: '01 234 5678' sn: country_name: en: 'Senegal' es: 'Senegal' country_code: 221 example_dial: '30 101 23 45' rs: country_name: en: 'Serbia' es: 'Serbia' country_code: 381 example_dial: '010 234567' sc: country_name: en: 'Seychelles' es: 'Seychelles' country_code: 248 example_dial: '4 217 123' sl: country_name: en: 'Sierra Leone' es: 'Sierra Leona' country_code: 232 example_dial: '(022) 221234' sg: country_name: en: 'Singapore' es: 'Singapur' country_code: 65 example_dial: '6123 4567' sk: country_name: en: 'Slovak Rep' es: 'República Eslovaca' country_code: 421 example_dial: '02x2F123 456 78' si: country_name: en: 'Slovenia' es: 'Eslovenia' country_code: 386 example_dial: '(01) 123 45 67' sb: country_name: en: 'Solomon Islands' es: 'Islas Salomón' country_code: 677 example_dial: '40123' so: country_name: en: 'Somalia' es: 'Somalia' country_code: 252 example_dial: '5 522010' za: country_name: en: 'South Africa' es: 'Sudáfrica' country_code: 27 example_dial: '010 123 4567' es: country_name: en: 'Spain' es: 'España' country_code: 34 example_dial: '810 12 34 56' lk: country_name: en: 'Sri Lanka' es: 'Sri Lanka' country_code: 94 example_dial: '011 2 345678' sh: country_name: en: 'St. Helena' es: 'St. Helena' country_code: 290 example_dial: '2158' kn: country_name: en: 'St. Kitts & Nevis' es: 'St. Kitts & Nieves' country_code: 1869 example_dial: '(869) 236-1234' lc: country_name: en: 'St. Lucia' es: 'Santa Lucía' country_code: 1758 example_dial: '(758) 234-5678' pm: country_name: en: 'St. Pierre & Miquelon' es: 'St. Pierre & Miquelón' country_code: 508 example_dial: '041 12 34' vc: country_name: en: 'St. Vincents' es: 'St. Vincent' country_code: 1784 example_dial: '(784) 266-1234' sd: country_name: en: 'Sudan' es: 'Sudán' country_code: 249 example_dial: '012 123 1234' sr: country_name: en: 'Suriname' es: 'Suriname' country_code: 597 example_dial: '211-234' sz: country_name: en: 'Swaziland' es: 'Swazilandia' country_code: 268 example_dial: '2217 1234' se: country_name: en: 'Sweden' es: 'Suecia' country_code: 46 example_dial: '08-12 34 56' ch: country_name: en: 'Switzerland' es: 'Suiza' country_code: 41 example_dial: '021 234 56 78' sy: country_name: en: 'Syria' es: 'Siria' country_code: 963 example_dial: '011 234 5678' tw: country_name: en: 'Taiwan' es: 'Taiwan' country_code: 886 example_dial: '02 123 4567' tj: country_name: en: 'Tajikstan' es: 'Tayikistán' country_code: 992 example_dial: '(8) 372 12 3456' tz: country_name: en: 'Tanzania' es: 'Tanzania' country_code: 255 example_dial: '022 234 5678' th: country_name: en: 'Thailand' es: 'Tailandia' country_code: 66 example_dial: '02 123 4567' tg: country_name: en: 'Togo' es: 'Togo' country_code: 228 example_dial: '22 21 23 45' tk: country_name: en: 'Tokelau' es: 'Tokelau' country_code: 690 example_dial: '3010' to: country_name: en: 'Tonga' es: 'Tonga' country_code: 676 example_dial: '20-123' tt: country_name: en: 'Trinidad & Tobago' es: 'Trinidad & amp; Tobago' country_code: 1868 example_dial: '(868) 221-1234' tn: country_name: en: 'Tunisia' es: 'Túnez' country_code: 216 example_dial: '71 234 567' tr: country_name: en: 'Turkey' es: 'pavo' country_code: 90 example_dial: '(0212) 345 6789' tm: country_name: en: 'Turkmenistan' es: 'Turkmenistán' country_code: 993 example_dial: '(8 12) 34-56-78' tc: country_name: en: 'Turks & Caicos' es: 'Turks & amp; Caicos' country_code: 1649 example_dial: '(649) 712-1234' tv: country_name: en: 'Tuvalu' es: 'Tuvalu' country_code: 688 example_dial: '20123' ug: country_name: en: 'Uganda' es: 'Uganda' country_code: 256 example_dial: '031 2345678' gb: country_name: en: 'United Kingdom' es: 'Reino Unido' country_code: 44 example_dial: '0121 234 5678' ua: country_name: en: 'Ukraine' es: 'Ucrania' country_code: 380 example_dial: '03112 34567' ae: country_name: en: 'United Arab Emirates' es: 'Emiratos Árabes Unidos' country_code: 971 example_dial: '02 234 5678' uy: country_name: en: 'Uruguay' es: 'Uruguay' country_code: 598 example_dial: '2123 1234' us: country_name: en: 'United States' es: 'Estados Unidos' country_code: 1 example_dial: '(201) 555-0123' uz: country_name: en: 'Uzbekistan' es: 'Uzbekistán' country_code: 998 example_dial: '8 66 234 56 78' vu: country_name: en: 'Vanuatu' es: 'Vanuatu' country_code: 678 example_dial: '22123' ve: country_name: en: 'Venezuela' es: 'Venezuela' country_code: 58 example_dial: '0212-1234567' vn: country_name: en: 'Vietnam' es: 'Vietnam' country_code: 84 example_dial: '0210 1234 567' vg: country_name: en: 'Virgin Islands GB' es: 'Islas Vírgenes GB' country_code: 1284 example_dial: '(284) 229-1234' vi: country_name: en: 'Virgin Islands USA' es: 'Islas Vírgenes de EE.UU.' country_code: 1340 example_dial: '(340) 642-1234' wf: country_name: en: 'Wallis & Futuna' es: 'Wallis & Futuna' country_code: 681 example_dial: '50 12 34' ws: country_name: en: 'Western Samoa' es: 'Samoa Occidental' country_code: 685 example_dial: '22123' ye: country_name: en: 'Yemen' es: 'Yemen' country_code: 967 example_dial: '01 234 567' zm: country_name: en: 'Zambia' es: 'Zambia' country_code: 260 example_dial: '021 1234567' zw: country_name: en: 'Zimbabwe' es: 'Zimbabwe' country_code: 263 example_dial: '013 12345' 'do-1': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1849 example_dial: '(849) 234-5678' 'do-2': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1809 example_dial: '(809) 234-5678' 'do-3': country_name: en: 'Dominican Republic' es: 'República Dominicana' country_code: 1829 example_dial: '(829) 234-5678' gw: country_name: en: 'Guinea-Bissau' es: 'Guinea-Bissau' country_code: 245 example_dial: '320 1234' me: country_name: en: 'Montenegro' es: 'Montenegro' country_code: 382 example_dial: '030 234 567' ng: country_name: en: 'Nigeria' es: 'Nigeria' country_code: 234 example_dial: '01 234 5678' mf: country_name: en: 'Saint Martin' es: 'saint Martin' country_code: 1599 example_dial: '0590 27-1234' gp: country_name: en: 'Saint Barthelemy' es: 'San Bartolomé' country_code: 590 example_dial: '0590 20-1234' ss: country_name: en: 'South Sudan' es: 'Sudán del Sur' country_code: 211 example_dial: '' sx: country_name: en: 'Sint Maarten' es: 'Sint Maarten' country_code: 1721 example_dial: ''
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998931288719177, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/loaders/collada/instance_effe", "end": 110, "score": 0.9999256134033203, "start": 86, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/loaders/collada/material.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com #= require new_src/loaders/collada/instance_effect class Material constructor: -> @id = "" @name = "" @instance_effect = null parse: (element) -> @id = element.getAttribute "id" @name = element.getAttribute "name" length = element.childNodes.length for i in [0...length] if element.childNodes[i].nodeName is "instance_effect" @instance_effect = new THREE.Collada.InstanceEffect().parse element.childNodes[i] break this namespace "THREE.Collada", (exports) -> exports.Material = Material
26539
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> #= require new_src/loaders/collada/instance_effect class Material constructor: -> @id = "" @name = "" @instance_effect = null parse: (element) -> @id = element.getAttribute "id" @name = element.getAttribute "name" length = element.childNodes.length for i in [0...length] if element.childNodes[i].nodeName is "instance_effect" @instance_effect = new THREE.Collada.InstanceEffect().parse element.childNodes[i] break this namespace "THREE.Collada", (exports) -> exports.Material = Material
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/loaders/collada/instance_effect class Material constructor: -> @id = "" @name = "" @instance_effect = null parse: (element) -> @id = element.getAttribute "id" @name = element.getAttribute "name" length = element.childNodes.length for i in [0...length] if element.childNodes[i].nodeName is "instance_effect" @instance_effect = new THREE.Collada.InstanceEffect().parse element.childNodes[i] break this namespace "THREE.Collada", (exports) -> exports.Material = Material
[ { "context": "###\n\t(c) 2016 Julian Gonggrijp\n###\n\ndefine [\n\t'handlebars.runtime'\n], (hbsRuntim", "end": 30, "score": 0.9998806715011597, "start": 14, "tag": "NAME", "value": "Julian Gonggrijp" } ]
client/script/handlebars.coffee
NBOCampbellToets/CampbellSoup
0
### (c) 2016 Julian Gonggrijp ### define [ 'handlebars.runtime' ], (hbsRuntime) -> hbsRuntime.default
126790
### (c) 2016 <NAME> ### define [ 'handlebars.runtime' ], (hbsRuntime) -> hbsRuntime.default
true
### (c) 2016 PI:NAME:<NAME>END_PI ### define [ 'handlebars.runtime' ], (hbsRuntime) -> hbsRuntime.default
[ { "context": "/authorization\"\n\nspaceless = \"\"\"\nDigest username=\"Mufasa\",realm=\"testrealm@host.com\",nonce=\"dcd98b7102dd2f", "end": 136, "score": 0.9997264742851257, "start": 130, "tag": "USERNAME", "value": "Mufasa" }, { "context": "\n\nspaceless = \"\"\"\nDigest username=\"Mufasa\",realm=\"testrealm@host.com\",nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\",uri=\"", "end": 163, "score": 0.9999201893806458, "start": 145, "tag": "EMAIL", "value": "testrealm@host.com" }, { "context": "71e9517f40e41\"\n\"\"\"\n\nspaced = \"\"\"\nDigest username=\"Mufasa\",\n realm=\"testrealm@host.com\",\n nonce=\"dcd98b71", "end": 396, "score": 0.9997183680534363, "start": 390, "tag": "USERNAME", "value": "Mufasa" }, { "context": "\n\nspaced = \"\"\"\nDigest username=\"Mufasa\",\n realm=\"testrealm@host.com\",\n nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\",\n ", "end": 426, "score": 0.9999186396598816, "start": 408, "tag": "EMAIL", "value": "testrealm@host.com" }, { "context": "login, \"smurf\"\n assert.equal params.password, \"smurfy\"\n\n context.test \"params with no spaces\", ->\n ", "end": 907, "score": 0.9994229674339294, "start": 901, "tag": "PASSWORD", "value": "smurfy" }, { "context": "\"\n assert.deepEqual params, {\n username: \"Mufasa\"\n realm: \"testrealm@host.com\"\n nonce: \"", "end": 1081, "score": 0.9997335076332092, "start": 1075, "tag": "USERNAME", "value": "Mufasa" }, { "context": " params, {\n username: \"Mufasa\"\n realm: \"testrealm@host.com\"\n nonce: \"dcd98b7102dd2f0e8b11d0f600bfb0c093", "end": 1115, "score": 0.9999184012413025, "start": 1097, "tag": "EMAIL", "value": "testrealm@host.com" }, { "context": "\"\n assert.deepEqual params, {\n username: \"Mufasa\"\n realm: \"testrealm@host.com\"\n nonce: \"", "end": 1525, "score": 0.9997398257255554, "start": 1519, "tag": "USERNAME", "value": "Mufasa" }, { "context": " params, {\n username: \"Mufasa\"\n realm: \"testrealm@host.com\"\n nonce: \"dcd98b7102dd2f0e8b11d0f600bfb0c093", "end": 1559, "score": 0.9999129176139832, "start": 1541, "tag": "EMAIL", "value": "testrealm@host.com" } ]
test/authorization_parsing_test.coffee
patchboard/patchboard
38
assert = require "assert" Testify = require "testify" {parse} = require "../src/authorization" spaceless = """ Digest username="Mufasa",realm="testrealm@host.com",nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",uri="/dir/index.html",qop=auth,nc=00000001,cnonce="0a4f113b",response="6629fae49393a05397450978507c4ef1",opaque="5ccc069c403ebaf9f0171e9517f40e41" """ spaced = """ Digest username="Mufasa", realm="testrealm@host.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", uri="/dir/index.html", qop=auth, nc=00000001, cnonce="0a4f113b", response="6629fae49393a05397450978507c4ef1", opaque="5ccc069c403ebaf9f0171e9517f40e41" """ Testify.test "Parsing Authorization header values", (context) -> context.test "Basic", -> {scheme, params} = parse("Basic c211cmY6c211cmZ5") assert.equal scheme, "Basic" assert.equal params.login, "smurf" assert.equal params.password, "smurfy" context.test "params with no spaces", -> {scheme, params} = parse(spaceless) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "testrealm@host.com" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "with spaces", -> {scheme, params} = parse(spaced) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "testrealm@host.com" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "Invalid", -> assert.throws -> parse "Smurf " assert.throws -> parse "Smurf smurfy" assert.throws -> x = parse "Smurf color=blue hat=white" console.log x
140579
assert = require "assert" Testify = require "testify" {parse} = require "../src/authorization" spaceless = """ Digest username="Mufasa",realm="<EMAIL>",nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",uri="/dir/index.html",qop=auth,nc=00000001,cnonce="0a4f113b",response="6629fae49393a05397450978507c4ef1",opaque="5ccc069c403ebaf9f0171e9517f40e41" """ spaced = """ Digest username="Mufasa", realm="<EMAIL>", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", uri="/dir/index.html", qop=auth, nc=00000001, cnonce="0a4f113b", response="6629fae49393a05397450978507c4ef1", opaque="5ccc069c403ebaf9f0171e9517f40e41" """ Testify.test "Parsing Authorization header values", (context) -> context.test "Basic", -> {scheme, params} = parse("Basic c211cmY6c211cmZ5") assert.equal scheme, "Basic" assert.equal params.login, "smurf" assert.equal params.password, "<PASSWORD>" context.test "params with no spaces", -> {scheme, params} = parse(spaceless) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "<EMAIL>" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "with spaces", -> {scheme, params} = parse(spaced) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "<EMAIL>" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "Invalid", -> assert.throws -> parse "Smurf " assert.throws -> parse "Smurf smurfy" assert.throws -> x = parse "Smurf color=blue hat=white" console.log x
true
assert = require "assert" Testify = require "testify" {parse} = require "../src/authorization" spaceless = """ Digest username="Mufasa",realm="PI:EMAIL:<EMAIL>END_PI",nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",uri="/dir/index.html",qop=auth,nc=00000001,cnonce="0a4f113b",response="6629fae49393a05397450978507c4ef1",opaque="5ccc069c403ebaf9f0171e9517f40e41" """ spaced = """ Digest username="Mufasa", realm="PI:EMAIL:<EMAIL>END_PI", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", uri="/dir/index.html", qop=auth, nc=00000001, cnonce="0a4f113b", response="6629fae49393a05397450978507c4ef1", opaque="5ccc069c403ebaf9f0171e9517f40e41" """ Testify.test "Parsing Authorization header values", (context) -> context.test "Basic", -> {scheme, params} = parse("Basic c211cmY6c211cmZ5") assert.equal scheme, "Basic" assert.equal params.login, "smurf" assert.equal params.password, "PI:PASSWORD:<PASSWORD>END_PI" context.test "params with no spaces", -> {scheme, params} = parse(spaceless) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "PI:EMAIL:<EMAIL>END_PI" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "with spaces", -> {scheme, params} = parse(spaced) assert.equal scheme, "Digest" assert.deepEqual params, { username: "Mufasa" realm: "PI:EMAIL:<EMAIL>END_PI" nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093" uri: "/dir/index.html" qop: "auth" nc: "00000001" cnonce: "0a4f113b" response: "6629fae49393a05397450978507c4ef1" opaque: "5ccc069c403ebaf9f0171e9517f40e41" } context.test "Invalid", -> assert.throws -> parse "Smurf " assert.throws -> parse "Smurf smurfy" assert.throws -> x = parse "Smurf color=blue hat=white" console.log x
[ { "context": " $scope.model = [\n {\n marca: 'Fender'\n nombre: 'Galaxy s7'\n precio: ", "end": 226, "score": 0.9967466592788696, "start": 220, "tag": "NAME", "value": "Fender" }, { "context": "precio: 400\n }\n {\n marca: 'LeoVergara'\n nombre: 'Brandon Vergara Magaña'\n ", "end": 328, "score": 0.9997493624687195, "start": 318, "tag": "NAME", "value": "LeoVergara" }, { "context": "\n marca: 'LeoVergara'\n nombre: 'Brandon Vergara Magaña'\n precio: 400\n }\n {\n ", "end": 371, "score": 0.9998847246170044, "start": 349, "tag": "NAME", "value": "Brandon Vergara Magaña" }, { "context": "precio: 400\n }\n {\n marca: 'Brandon'\n nombre: 'Jugandon a con Angular'\n ", "end": 440, "score": 0.999767005443573, "start": 433, "tag": "NAME", "value": "Brandon" }, { "context": " {\n marca: 'Brandon'\n nombre: 'Jugandon a con Angular'\n precio: 400\n }\n ", "end": 469, "score": 0.9987590312957764, "start": 461, "tag": "NAME", "value": "Jugandon" } ]
coffeeScripts/controllers/indexController.coffee
LeoVergara1/firstAppAngular
0
class IndexController appDemo = angular.module('appDemo', []) sizeList = 0 angularController:() -> appDemo.controller 'InstrumentosListadoCtrl', ($scope) -> $scope.model = [ { marca: 'Fender' nombre: 'Galaxy s7' precio: 400 } { marca: 'LeoVergara' nombre: 'Brandon Vergara Magaña' precio: 400 } { marca: 'Brandon' nombre: 'Jugandon a con Angular' precio: 400 } ] $scope.entero = 8 $scope.sizeList = $scope.model.length $scope.cost = 0 $scope.registrar = -> console.log "Inicia" if $scope.nombre? and $scope.marca? and $scope.precio? console.log "Hay nombre" $scope.model.push marca: $scope.marca nombre: $scope.nombre precio: parseFloat($scope.precio) else alert "Completa los datos porfavor" console.log $scope.nombre console.log $scope.marca console.log $scope.precio $scope.sizeList = $scope.model.length $scope.cost = 0 for iterator in $scope.model $scope.cost = $scope.cost + iterator.precio console.log $scope.model.precio $scope.remove = (index) -> console.log index console.log "Removiendo..." $scope.model.splice(index, 1) hello: () -> console.log("Saludo") start: () -> @angularController() console.log("Start") new IndexController().start()
163675
class IndexController appDemo = angular.module('appDemo', []) sizeList = 0 angularController:() -> appDemo.controller 'InstrumentosListadoCtrl', ($scope) -> $scope.model = [ { marca: '<NAME>' nombre: 'Galaxy s7' precio: 400 } { marca: '<NAME>' nombre: '<NAME>' precio: 400 } { marca: '<NAME>' nombre: '<NAME> a con Angular' precio: 400 } ] $scope.entero = 8 $scope.sizeList = $scope.model.length $scope.cost = 0 $scope.registrar = -> console.log "Inicia" if $scope.nombre? and $scope.marca? and $scope.precio? console.log "Hay nombre" $scope.model.push marca: $scope.marca nombre: $scope.nombre precio: parseFloat($scope.precio) else alert "Completa los datos porfavor" console.log $scope.nombre console.log $scope.marca console.log $scope.precio $scope.sizeList = $scope.model.length $scope.cost = 0 for iterator in $scope.model $scope.cost = $scope.cost + iterator.precio console.log $scope.model.precio $scope.remove = (index) -> console.log index console.log "Removiendo..." $scope.model.splice(index, 1) hello: () -> console.log("Saludo") start: () -> @angularController() console.log("Start") new IndexController().start()
true
class IndexController appDemo = angular.module('appDemo', []) sizeList = 0 angularController:() -> appDemo.controller 'InstrumentosListadoCtrl', ($scope) -> $scope.model = [ { marca: 'PI:NAME:<NAME>END_PI' nombre: 'Galaxy s7' precio: 400 } { marca: 'PI:NAME:<NAME>END_PI' nombre: 'PI:NAME:<NAME>END_PI' precio: 400 } { marca: 'PI:NAME:<NAME>END_PI' nombre: 'PI:NAME:<NAME>END_PI a con Angular' precio: 400 } ] $scope.entero = 8 $scope.sizeList = $scope.model.length $scope.cost = 0 $scope.registrar = -> console.log "Inicia" if $scope.nombre? and $scope.marca? and $scope.precio? console.log "Hay nombre" $scope.model.push marca: $scope.marca nombre: $scope.nombre precio: parseFloat($scope.precio) else alert "Completa los datos porfavor" console.log $scope.nombre console.log $scope.marca console.log $scope.precio $scope.sizeList = $scope.model.length $scope.cost = 0 for iterator in $scope.model $scope.cost = $scope.cost + iterator.precio console.log $scope.model.precio $scope.remove = (index) -> console.log index console.log "Removiendo..." $scope.model.splice(index, 1) hello: () -> console.log("Saludo") start: () -> @angularController() console.log("Start") new IndexController().start()
[ { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'has-text'}).appendToDocumentBody()\n ", "end": 260, "score": 0.9998552799224854, "start": 241, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'success'}).appendToDocumentBody()\n ", "end": 366, "score": 0.9997318983078003, "start": 347, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.', cssClass: 'fail'}).appendToDocumentBody()\n\n n", "end": 467, "score": 0.9650071859359741, "start": 452, "tag": "EMAIL", "value": "fatih@fatihacet" }, { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'big has-text'}).appendToDocumentBody", "end": 712, "score": 0.9997613430023193, "start": 693, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'big success'}).appendToDocumentBody(", "end": 822, "score": 0.9998443126678467, "start": 803, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "umentBody()\n new spark.components.Input({value: 'fatih@fatihacet.', cssClass: 'big fail'}).appendToDocumentBody()\n", "end": 927, "score": 0.9726248979568481, "start": 912, "tag": "EMAIL", "value": "fatih@fatihacet" } ]
src/examples/input/main.coffee
dashersw/spark
1
window.addEventListener 'load', -> new spark.core.View({ tagName: 'h2', template: 'Spark Inputs' }).appendToDocumentBody() new spark.components.Input({placeholder: 'Email'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'has-text'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'success'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.', cssClass: 'fail'}).appendToDocumentBody() new spark.core.View().appendToDocumentBody() new spark.components.Input({placeholder: 'Email', cssClass: 'big'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'big has-text'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.com', cssClass: 'big success'}).appendToDocumentBody() new spark.components.Input({value: 'fatih@fatihacet.', cssClass: 'big fail'}).appendToDocumentBody() , no
122683
window.addEventListener 'load', -> new spark.core.View({ tagName: 'h2', template: 'Spark Inputs' }).appendToDocumentBody() new spark.components.Input({placeholder: 'Email'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>', cssClass: 'has-text'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>', cssClass: 'success'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>.', cssClass: 'fail'}).appendToDocumentBody() new spark.core.View().appendToDocumentBody() new spark.components.Input({placeholder: 'Email', cssClass: 'big'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>', cssClass: 'big has-text'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>', cssClass: 'big success'}).appendToDocumentBody() new spark.components.Input({value: '<EMAIL>.', cssClass: 'big fail'}).appendToDocumentBody() , no
true
window.addEventListener 'load', -> new spark.core.View({ tagName: 'h2', template: 'Spark Inputs' }).appendToDocumentBody() new spark.components.Input({placeholder: 'Email'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI', cssClass: 'has-text'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI', cssClass: 'success'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI.', cssClass: 'fail'}).appendToDocumentBody() new spark.core.View().appendToDocumentBody() new spark.components.Input({placeholder: 'Email', cssClass: 'big'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI', cssClass: 'big has-text'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI', cssClass: 'big success'}).appendToDocumentBody() new spark.components.Input({value: 'PI:EMAIL:<EMAIL>END_PI.', cssClass: 'big fail'}).appendToDocumentBody() , no
[ { "context": " id> reserve - Make a reservation.\n#\n# Author:\n# Shingo Sato <shinsugar@gmail.com>\n\n{ toNumber, head, last, is", "end": 360, "score": 0.999883770942688, "start": 349, "tag": "NAME", "value": "Shingo Sato" }, { "context": " Make a reservation.\n#\n# Author:\n# Shingo Sato <shinsugar@gmail.com>\n\n{ toNumber, head, last, isNull, isUndefined } =", "end": 381, "score": 0.9999237060546875, "start": 362, "tag": "EMAIL", "value": "shinsugar@gmail.com" } ]
src/fass-reservation.coffee
sugarshin/hubot-fass-reservation
1
# Description # A Hubot script for utilities of FaSS reservation # # Configuration: # N/A # # Commands: # hubot fass list - List salons. # hubot fass <salon id> waiting - List all waiting. # hubot fass <salon id> waiting <number> - Start watch the number in waiting. # hubot fass <salon id> reserve - Make a reservation. # # Author: # Shingo Sato <shinsugar@gmail.com> { toNumber, head, last, isNull, isUndefined } = require 'lodash' cheerio = require 'cheerio' createPoll = require './utils/create-poll' getHtml = require './utils/get-html' salonMap = require './utils/salon-map' getWaitingResultPageUrl = (salonId) -> "https://wb.goku.ne.jp/FaSS#{salonId}HtmlResult/WaitingResultPage.htm" selectors = waitingOrder: 'body > div > DIV' outsideHours: ':contains("ただいまの時間は営業時間外です")' closed: 'body' ### @param {String} - text @return {['01', '222']}[] ### parseWaitingOrderText = (text) -> text .split('\n') .filter((t) -> /^\s+(?:\d{2})\)\s+/.test(t)) .map((t) -> t.trim()) .map((t) -> t.split(') ')) getWaitingOrder = (html) -> parseWaitingOrderText cheerio.load(html)(selectors.waitingOrder).text() existsSalon = (msg) -> unless salonMap[msg.match[1].toLowerCase()] msg.send "I don't know such a salon: `#{msg.match[1]}`. You can check with `hubot fass ls`" return false return true module.exports = (robot) -> robot.respond /\s*fass\s+l(?:s|ist)\s*$/i, (msg) -> msg.send Object.keys(salonMap).map((k) -> ["#{salonMap[k]} - #{k}", " e.g., `hubot fass #{k} w`"].join '\n').join '\n\n' robot.respond /\s*fass\s+([a-z0-9]+)\s+r(?:sv|eserve)\s*$/i, (msg) -> return unless existsSalon msg msg.send 'Not implemented yet. Please ask https://sugarshin.net/' robot.respond /\s*fass\s+([a-z0-9]+)\s+w(?:aiting)?(?:\s+(\d+))?\s*$/i, (msg) -> return unless existsSalon msg waitingResultPageUrl = getWaitingResultPageUrl msg.match[1] getHtml(waitingResultPageUrl) .then (html) -> $ = cheerio.load(html) if $(selectors.outsideHours).length > 0 msg.send '営業時間外です' return if isUndefined msg.match[2] $waitingOrder = $ selectors.waitingOrder if $waitingOrder.length > 0 msg.send $waitingOrder.text() return msg.send $(selectors.closed).text() return numberStr = msg.match[2] waitingOrder = getWaitingOrder html if toNumber(last(waitingOrder)[1]) < toNumber(numberStr) msg.send 'その番号では予約されていません' return if toNumber(head(waitingOrder)[1]) > toNumber(numberStr) msg.send 'すでに来店済みです' return prevIndex = null getHtmlPolling = createPoll( getHtml (html) -> currentWaitingOrder = getWaitingOrder html currentIndex = currentWaitingOrder.findIndex (o) -> o[1] is numberStr if (currentIndex is -1) or (toNumber(head(currentWaitingOrder)[1]) > toNumber(numberStr)) msg.send '施術を開始したか、予約が取り消されました' return true if currentIndex is 0 msg.reply '順番がきました' return true if currentIndex is 3 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 3 人で順番がきます' else if currentIndex is 5 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 5 人で順番がきます' prevIndex = currentIndex return false ) msg.send "`#{numberStr}` 番の監視を開始します" getHtmlPolling(waitingResultPageUrl).catch (err) -> msg.send "エラーが発生しました #{err.toString()}" .catch (err) -> msg.send "エラーが発生しました #{err.toString()}"
214065
# Description # A Hubot script for utilities of FaSS reservation # # Configuration: # N/A # # Commands: # hubot fass list - List salons. # hubot fass <salon id> waiting - List all waiting. # hubot fass <salon id> waiting <number> - Start watch the number in waiting. # hubot fass <salon id> reserve - Make a reservation. # # Author: # <NAME> <<EMAIL>> { toNumber, head, last, isNull, isUndefined } = require 'lodash' cheerio = require 'cheerio' createPoll = require './utils/create-poll' getHtml = require './utils/get-html' salonMap = require './utils/salon-map' getWaitingResultPageUrl = (salonId) -> "https://wb.goku.ne.jp/FaSS#{salonId}HtmlResult/WaitingResultPage.htm" selectors = waitingOrder: 'body > div > DIV' outsideHours: ':contains("ただいまの時間は営業時間外です")' closed: 'body' ### @param {String} - text @return {['01', '222']}[] ### parseWaitingOrderText = (text) -> text .split('\n') .filter((t) -> /^\s+(?:\d{2})\)\s+/.test(t)) .map((t) -> t.trim()) .map((t) -> t.split(') ')) getWaitingOrder = (html) -> parseWaitingOrderText cheerio.load(html)(selectors.waitingOrder).text() existsSalon = (msg) -> unless salonMap[msg.match[1].toLowerCase()] msg.send "I don't know such a salon: `#{msg.match[1]}`. You can check with `hubot fass ls`" return false return true module.exports = (robot) -> robot.respond /\s*fass\s+l(?:s|ist)\s*$/i, (msg) -> msg.send Object.keys(salonMap).map((k) -> ["#{salonMap[k]} - #{k}", " e.g., `hubot fass #{k} w`"].join '\n').join '\n\n' robot.respond /\s*fass\s+([a-z0-9]+)\s+r(?:sv|eserve)\s*$/i, (msg) -> return unless existsSalon msg msg.send 'Not implemented yet. Please ask https://sugarshin.net/' robot.respond /\s*fass\s+([a-z0-9]+)\s+w(?:aiting)?(?:\s+(\d+))?\s*$/i, (msg) -> return unless existsSalon msg waitingResultPageUrl = getWaitingResultPageUrl msg.match[1] getHtml(waitingResultPageUrl) .then (html) -> $ = cheerio.load(html) if $(selectors.outsideHours).length > 0 msg.send '営業時間外です' return if isUndefined msg.match[2] $waitingOrder = $ selectors.waitingOrder if $waitingOrder.length > 0 msg.send $waitingOrder.text() return msg.send $(selectors.closed).text() return numberStr = msg.match[2] waitingOrder = getWaitingOrder html if toNumber(last(waitingOrder)[1]) < toNumber(numberStr) msg.send 'その番号では予約されていません' return if toNumber(head(waitingOrder)[1]) > toNumber(numberStr) msg.send 'すでに来店済みです' return prevIndex = null getHtmlPolling = createPoll( getHtml (html) -> currentWaitingOrder = getWaitingOrder html currentIndex = currentWaitingOrder.findIndex (o) -> o[1] is numberStr if (currentIndex is -1) or (toNumber(head(currentWaitingOrder)[1]) > toNumber(numberStr)) msg.send '施術を開始したか、予約が取り消されました' return true if currentIndex is 0 msg.reply '順番がきました' return true if currentIndex is 3 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 3 人で順番がきます' else if currentIndex is 5 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 5 人で順番がきます' prevIndex = currentIndex return false ) msg.send "`#{numberStr}` 番の監視を開始します" getHtmlPolling(waitingResultPageUrl).catch (err) -> msg.send "エラーが発生しました #{err.toString()}" .catch (err) -> msg.send "エラーが発生しました #{err.toString()}"
true
# Description # A Hubot script for utilities of FaSS reservation # # Configuration: # N/A # # Commands: # hubot fass list - List salons. # hubot fass <salon id> waiting - List all waiting. # hubot fass <salon id> waiting <number> - Start watch the number in waiting. # hubot fass <salon id> reserve - Make a reservation. # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> { toNumber, head, last, isNull, isUndefined } = require 'lodash' cheerio = require 'cheerio' createPoll = require './utils/create-poll' getHtml = require './utils/get-html' salonMap = require './utils/salon-map' getWaitingResultPageUrl = (salonId) -> "https://wb.goku.ne.jp/FaSS#{salonId}HtmlResult/WaitingResultPage.htm" selectors = waitingOrder: 'body > div > DIV' outsideHours: ':contains("ただいまの時間は営業時間外です")' closed: 'body' ### @param {String} - text @return {['01', '222']}[] ### parseWaitingOrderText = (text) -> text .split('\n') .filter((t) -> /^\s+(?:\d{2})\)\s+/.test(t)) .map((t) -> t.trim()) .map((t) -> t.split(') ')) getWaitingOrder = (html) -> parseWaitingOrderText cheerio.load(html)(selectors.waitingOrder).text() existsSalon = (msg) -> unless salonMap[msg.match[1].toLowerCase()] msg.send "I don't know such a salon: `#{msg.match[1]}`. You can check with `hubot fass ls`" return false return true module.exports = (robot) -> robot.respond /\s*fass\s+l(?:s|ist)\s*$/i, (msg) -> msg.send Object.keys(salonMap).map((k) -> ["#{salonMap[k]} - #{k}", " e.g., `hubot fass #{k} w`"].join '\n').join '\n\n' robot.respond /\s*fass\s+([a-z0-9]+)\s+r(?:sv|eserve)\s*$/i, (msg) -> return unless existsSalon msg msg.send 'Not implemented yet. Please ask https://sugarshin.net/' robot.respond /\s*fass\s+([a-z0-9]+)\s+w(?:aiting)?(?:\s+(\d+))?\s*$/i, (msg) -> return unless existsSalon msg waitingResultPageUrl = getWaitingResultPageUrl msg.match[1] getHtml(waitingResultPageUrl) .then (html) -> $ = cheerio.load(html) if $(selectors.outsideHours).length > 0 msg.send '営業時間外です' return if isUndefined msg.match[2] $waitingOrder = $ selectors.waitingOrder if $waitingOrder.length > 0 msg.send $waitingOrder.text() return msg.send $(selectors.closed).text() return numberStr = msg.match[2] waitingOrder = getWaitingOrder html if toNumber(last(waitingOrder)[1]) < toNumber(numberStr) msg.send 'その番号では予約されていません' return if toNumber(head(waitingOrder)[1]) > toNumber(numberStr) msg.send 'すでに来店済みです' return prevIndex = null getHtmlPolling = createPoll( getHtml (html) -> currentWaitingOrder = getWaitingOrder html currentIndex = currentWaitingOrder.findIndex (o) -> o[1] is numberStr if (currentIndex is -1) or (toNumber(head(currentWaitingOrder)[1]) > toNumber(numberStr)) msg.send '施術を開始したか、予約が取り消されました' return true if currentIndex is 0 msg.reply '順番がきました' return true if currentIndex is 3 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 3 人で順番がきます' else if currentIndex is 5 and (isNull(prevIndex) or currentIndex < prevIndex) msg.reply 'あと 5 人で順番がきます' prevIndex = currentIndex return false ) msg.send "`#{numberStr}` 番の監視を開始します" getHtmlPolling(waitingResultPageUrl).catch (err) -> msg.send "エラーが発生しました #{err.toString()}" .catch (err) -> msg.send "エラーが発生しました #{err.toString()}"
[ { "context": "accounts: [\n {\n id : \"bd3ec1d3-91b7-4b5a-b6a9-86871f132304\"\n name : \"Personal\"\n ", "end": 223, "score": 0.9935199618339539, "start": 187, "tag": "KEY", "value": "bd3ec1d3-91b7-4b5a-b6a9-86871f132304" }, { "context": "\n },\n {\n id : \"bd33-91b7-4b5a-b6a9-86871f132304\"\n name : \"work\"\n prov", "end": 410, "score": 0.9931016564369202, "start": 378, "tag": "KEY", "value": "bd33-91b7-4b5a-b6a9-86871f132304" }, { "context": "\"AWS\"\n accounts: [\n id : \"iv103n\"\n name : \"main\"\n provider", "end": 1334, "score": 0.9049140214920044, "start": 1328, "tag": "USERNAME", "value": "iv103n" }, { "context": "gine\"\n accounts: [\n id : \"onf49wb\"\n name : \"work\"\n provider", "end": 2710, "score": 0.5719433426856995, "start": 2703, "tag": "USERNAME", "value": "onf49wb" }, { "context": "con\": \"digital-ocean\",\n# \"serverNickName\": \"Droplet\",\ndollarsPerMo : 5\n# \"credentialFields\": [\n", "end": 4363, "score": 0.910758376121521, "start": 4356, "tag": "USERNAME", "value": "Droplet" }, { "context": "},\n# \"accounts\": [\n# {\n# \"id\": \"bd3ec1d3-91b7-4b5a-b6a9-86871f132304\",\n# \"name\": \"test-provider-account\",\n# ", "end": 4893, "score": 0.995500922203064, "start": 4857, "tag": "KEY", "value": "bd3ec1d3-91b7-4b5a-b6a9-86871f132304" } ]
stage/shims/app-launch-shim.coffee
nanobox-io/nanobox-dash-ui-app-launch
0
module.exports = class DataShim constructor: () -> getProviders : () -> [ { id: 'do' name : "Digital Ocean" accounts: [ { id : "bd3ec1d3-91b7-4b5a-b6a9-86871f132304" name : "Personal" provider_id : "do" default_region : "sfo1" }, { id : "bd33-91b7-4b5a-b6a9-86871f132304" name : "work" provider_id : "do" default_region : "am3" } ] meta: icon: "custom" serverNickName: "Droplet" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] }, { id: 'aws' name : "AWS" accounts: [ id : "iv103n" name : "main" provider_id : "aws" default_region : "us-gov-west-1" ] meta: icon: "aws" serverNickName: "EC2 Instance" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"US East", items:[ {name:"N. Virginia", id:"us-east-1"} ]} {group:"US West", items:[ {name:"Oregon", id:"us-west-2"} {name:"N. California", id:"us-west-1"} {name:"AWS GovCloud", id:"us-gov-west-1"} ]} {group:"EU", items:[ {name:"Ireland", id:"eu-west-1"} {name:"Frankfurt", id:"eu-central-1"} ]} {group:"Asia Pacific", items:[ {name:"Singapore", id:"ap-southeast-1"} {name:"Tokyo", id:"ap-northeast-1"} {name:"Seoul", id:"ap-northeast-2"} {name:"Sydney", id:"ap-southeast-2"} ]} {group:"South America", items:[ {name:"São Paulo", id:"sa-east-1"} ]} {group:"China", items:[ {name:"Beijing", id:"cn-north-1"} ]} ] }, { id: 'gc' name : "Google Compute Engine" accounts: [ id : "onf49wb" name : "work" provider_id : "gc" default_region : "us-central1-a" ] meta: icon: "google-compute" serverNickName: "VM" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"Easter United States", items:[ {name:"South Carolina - B", id: "us-east1-b"} {name:"South Carolina - C", id: "us-east1-c"} {name:"South Carolina - D", id: "us-east1-d"} ]} {group:"Central United States", items:[ {name:"Iowa - A", id: "us-central1-a"} {name:"Iowa - B", id: "us-central1-b"} {name:"Iowa - C", id: "us-central1-c"} {name:"Iowa - F", id: "us-central1-f"} ]} {group:"Western Europe", items:[ {name:"Belgium - B", id: "europe-west1-b"} {name:"Belgium - C", id: "europe-west1-c"} {name:"Belgium - D", id: "europe-west1-d"} ]} {group:"East Asia", items:[ {name:"Taiwan - A", id: "asia-east1-a"} {name:"Taiwan - B", id: "asia-east1-b"} {name:"Taiwan - C", id: "asia-east1-c"} ]} ] } ] # [ # { # "id": "do", # "name": "DigitalOcean", # "regions": [ # { # "id": "nyc1", # "name": "New York 1" # }, # { # "id": "sfo1", # "name": "San Francisco 1" # } # ], # "meta": { # "icon": "digital-ocean", # "serverNickName": "Droplet", dollarsPerMo : 5 # "credentialFields": [ # "access_token" # ], # "specs": [ # { # "metric": "memory", # "val": "512" # }, # { # "metric": "vcpus", # "val": "1" # }, # { # "metric": "disk", # "val": "20" # }, # { # "metric": "transfer", # "val": "1.0" # } # ] # }, # "accounts": [ # { # "id": "bd3ec1d3-91b7-4b5a-b6a9-86871f132304", # "name": "test-provider-account", # "provider_id": "do", # "default_region": "sfo1" # } # ] # } # ]
42865
module.exports = class DataShim constructor: () -> getProviders : () -> [ { id: 'do' name : "Digital Ocean" accounts: [ { id : "<KEY>" name : "Personal" provider_id : "do" default_region : "sfo1" }, { id : "<KEY>" name : "work" provider_id : "do" default_region : "am3" } ] meta: icon: "custom" serverNickName: "Droplet" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] }, { id: 'aws' name : "AWS" accounts: [ id : "iv103n" name : "main" provider_id : "aws" default_region : "us-gov-west-1" ] meta: icon: "aws" serverNickName: "EC2 Instance" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"US East", items:[ {name:"N. Virginia", id:"us-east-1"} ]} {group:"US West", items:[ {name:"Oregon", id:"us-west-2"} {name:"N. California", id:"us-west-1"} {name:"AWS GovCloud", id:"us-gov-west-1"} ]} {group:"EU", items:[ {name:"Ireland", id:"eu-west-1"} {name:"Frankfurt", id:"eu-central-1"} ]} {group:"Asia Pacific", items:[ {name:"Singapore", id:"ap-southeast-1"} {name:"Tokyo", id:"ap-northeast-1"} {name:"Seoul", id:"ap-northeast-2"} {name:"Sydney", id:"ap-southeast-2"} ]} {group:"South America", items:[ {name:"São Paulo", id:"sa-east-1"} ]} {group:"China", items:[ {name:"Beijing", id:"cn-north-1"} ]} ] }, { id: 'gc' name : "Google Compute Engine" accounts: [ id : "onf49wb" name : "work" provider_id : "gc" default_region : "us-central1-a" ] meta: icon: "google-compute" serverNickName: "VM" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"Easter United States", items:[ {name:"South Carolina - B", id: "us-east1-b"} {name:"South Carolina - C", id: "us-east1-c"} {name:"South Carolina - D", id: "us-east1-d"} ]} {group:"Central United States", items:[ {name:"Iowa - A", id: "us-central1-a"} {name:"Iowa - B", id: "us-central1-b"} {name:"Iowa - C", id: "us-central1-c"} {name:"Iowa - F", id: "us-central1-f"} ]} {group:"Western Europe", items:[ {name:"Belgium - B", id: "europe-west1-b"} {name:"Belgium - C", id: "europe-west1-c"} {name:"Belgium - D", id: "europe-west1-d"} ]} {group:"East Asia", items:[ {name:"Taiwan - A", id: "asia-east1-a"} {name:"Taiwan - B", id: "asia-east1-b"} {name:"Taiwan - C", id: "asia-east1-c"} ]} ] } ] # [ # { # "id": "do", # "name": "DigitalOcean", # "regions": [ # { # "id": "nyc1", # "name": "New York 1" # }, # { # "id": "sfo1", # "name": "San Francisco 1" # } # ], # "meta": { # "icon": "digital-ocean", # "serverNickName": "Droplet", dollarsPerMo : 5 # "credentialFields": [ # "access_token" # ], # "specs": [ # { # "metric": "memory", # "val": "512" # }, # { # "metric": "vcpus", # "val": "1" # }, # { # "metric": "disk", # "val": "20" # }, # { # "metric": "transfer", # "val": "1.0" # } # ] # }, # "accounts": [ # { # "id": "<KEY>", # "name": "test-provider-account", # "provider_id": "do", # "default_region": "sfo1" # } # ] # } # ]
true
module.exports = class DataShim constructor: () -> getProviders : () -> [ { id: 'do' name : "Digital Ocean" accounts: [ { id : "PI:KEY:<KEY>END_PI" name : "Personal" provider_id : "do" default_region : "sfo1" }, { id : "PI:KEY:<KEY>END_PI" name : "work" provider_id : "do" default_region : "am3" } ] meta: icon: "custom" serverNickName: "Droplet" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {name: "New York 1", id: "nyc1"} {name: "New York 2", id: "nyc2"} {name: "New York 3", id: "nyc3"} {name: "Amsterdam 2", id: "am2"} {name: "Amsterdam 3", id: "am3"} {name: "San Francisco", id: "sfo1"} {name: "Singapore", id: "s1"} {name: "London", id: "l1"} {name: "Frankfurt", id: "f1"} {name: "Toronto", id: "t1"} ] }, { id: 'aws' name : "AWS" accounts: [ id : "iv103n" name : "main" provider_id : "aws" default_region : "us-gov-west-1" ] meta: icon: "aws" serverNickName: "EC2 Instance" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"US East", items:[ {name:"N. Virginia", id:"us-east-1"} ]} {group:"US West", items:[ {name:"Oregon", id:"us-west-2"} {name:"N. California", id:"us-west-1"} {name:"AWS GovCloud", id:"us-gov-west-1"} ]} {group:"EU", items:[ {name:"Ireland", id:"eu-west-1"} {name:"Frankfurt", id:"eu-central-1"} ]} {group:"Asia Pacific", items:[ {name:"Singapore", id:"ap-southeast-1"} {name:"Tokyo", id:"ap-northeast-1"} {name:"Seoul", id:"ap-northeast-2"} {name:"Sydney", id:"ap-southeast-2"} ]} {group:"South America", items:[ {name:"São Paulo", id:"sa-east-1"} ]} {group:"China", items:[ {name:"Beijing", id:"cn-north-1"} ]} ] }, { id: 'gc' name : "Google Compute Engine" accounts: [ id : "onf49wb" name : "work" provider_id : "gc" default_region : "us-central1-a" ] meta: icon: "google-compute" serverNickName: "VM" dollarsPerMo : 5 specs: [ {metric:"ram", val: "512 MB"} {metric:"cpu", val: "0.5 Core"} {metric:"disk",val: "1 GB"} {metric:"transfer", val: "2 TB"} ] regions : [ {group:"Easter United States", items:[ {name:"South Carolina - B", id: "us-east1-b"} {name:"South Carolina - C", id: "us-east1-c"} {name:"South Carolina - D", id: "us-east1-d"} ]} {group:"Central United States", items:[ {name:"Iowa - A", id: "us-central1-a"} {name:"Iowa - B", id: "us-central1-b"} {name:"Iowa - C", id: "us-central1-c"} {name:"Iowa - F", id: "us-central1-f"} ]} {group:"Western Europe", items:[ {name:"Belgium - B", id: "europe-west1-b"} {name:"Belgium - C", id: "europe-west1-c"} {name:"Belgium - D", id: "europe-west1-d"} ]} {group:"East Asia", items:[ {name:"Taiwan - A", id: "asia-east1-a"} {name:"Taiwan - B", id: "asia-east1-b"} {name:"Taiwan - C", id: "asia-east1-c"} ]} ] } ] # [ # { # "id": "do", # "name": "DigitalOcean", # "regions": [ # { # "id": "nyc1", # "name": "New York 1" # }, # { # "id": "sfo1", # "name": "San Francisco 1" # } # ], # "meta": { # "icon": "digital-ocean", # "serverNickName": "Droplet", dollarsPerMo : 5 # "credentialFields": [ # "access_token" # ], # "specs": [ # { # "metric": "memory", # "val": "512" # }, # { # "metric": "vcpus", # "val": "1" # }, # { # "metric": "disk", # "val": "20" # }, # { # "metric": "transfer", # "val": "1.0" # } # ] # }, # "accounts": [ # { # "id": "PI:KEY:<KEY>END_PI", # "name": "test-provider-account", # "provider_id": "do", # "default_region": "sfo1" # } # ] # } # ]
[ { "context": "('.apps.key').toString().trim()\ncatch\n authKey= 'local'\n\ndeploy= (host,sha1,force=no)->\n app= apps[host", "end": 231, "score": 0.9942842125892639, "start": 226, "tag": "KEY", "value": "local" } ]
apps/travis.edgy.black.coffee
59naga/edgy
0
apps= require('yamljs').load 'apps.yml' fs= require 'fs' path= require 'path' pm2= require '../lib/pm2' Repository= require '../lib/repository' try authKey= fs.readFileSync('.apps.key').toString().trim() catch authKey= 'local' deploy= (host,sha1,force=no)-> app= apps[host] repo= new Repository path.resolve(__dirname,host),app return repo.q.reject 'host is undefined' if app is undefined repo.log host,sha1 repo.update sha1,force .then -> pm2.connect() .then -> pm2.delete host .then -> pm2.start {"#{host}":app} .then -> repo.q.resolve 'Update successfully' http= require 'http' http.createServer (req,res)-> res.writeHead 200,'Content-Type':'text/plain' body= '' req.on 'data',(chunk)-> body+= chunk req.on 'end',-> querystring= require 'querystring' {host,sha1,key,force}= querystring.parse body console.log host,sha1,key is authKey,force return res.end "403 Forbidden" if key isnt authKey deploy host,sha1,force .then (result)-> res.statusCode= 200 res.end "200 #{host} #{result}" .catch (error)-> res.statusCode= 500 res.end "500 ERROR #{error.stack}" .listen process.env.PORT,-> console.log "Open #{process.env.HOST} > http://localhost:#{process.env.PORT}/"
82137
apps= require('yamljs').load 'apps.yml' fs= require 'fs' path= require 'path' pm2= require '../lib/pm2' Repository= require '../lib/repository' try authKey= fs.readFileSync('.apps.key').toString().trim() catch authKey= '<KEY>' deploy= (host,sha1,force=no)-> app= apps[host] repo= new Repository path.resolve(__dirname,host),app return repo.q.reject 'host is undefined' if app is undefined repo.log host,sha1 repo.update sha1,force .then -> pm2.connect() .then -> pm2.delete host .then -> pm2.start {"#{host}":app} .then -> repo.q.resolve 'Update successfully' http= require 'http' http.createServer (req,res)-> res.writeHead 200,'Content-Type':'text/plain' body= '' req.on 'data',(chunk)-> body+= chunk req.on 'end',-> querystring= require 'querystring' {host,sha1,key,force}= querystring.parse body console.log host,sha1,key is authKey,force return res.end "403 Forbidden" if key isnt authKey deploy host,sha1,force .then (result)-> res.statusCode= 200 res.end "200 #{host} #{result}" .catch (error)-> res.statusCode= 500 res.end "500 ERROR #{error.stack}" .listen process.env.PORT,-> console.log "Open #{process.env.HOST} > http://localhost:#{process.env.PORT}/"
true
apps= require('yamljs').load 'apps.yml' fs= require 'fs' path= require 'path' pm2= require '../lib/pm2' Repository= require '../lib/repository' try authKey= fs.readFileSync('.apps.key').toString().trim() catch authKey= 'PI:KEY:<KEY>END_PI' deploy= (host,sha1,force=no)-> app= apps[host] repo= new Repository path.resolve(__dirname,host),app return repo.q.reject 'host is undefined' if app is undefined repo.log host,sha1 repo.update sha1,force .then -> pm2.connect() .then -> pm2.delete host .then -> pm2.start {"#{host}":app} .then -> repo.q.resolve 'Update successfully' http= require 'http' http.createServer (req,res)-> res.writeHead 200,'Content-Type':'text/plain' body= '' req.on 'data',(chunk)-> body+= chunk req.on 'end',-> querystring= require 'querystring' {host,sha1,key,force}= querystring.parse body console.log host,sha1,key is authKey,force return res.end "403 Forbidden" if key isnt authKey deploy host,sha1,force .then (result)-> res.statusCode= 200 res.end "200 #{host} #{result}" .catch (error)-> res.statusCode= 500 res.end "500 ERROR #{error.stack}" .listen process.env.PORT,-> console.log "Open #{process.env.HOST} > http://localhost:#{process.env.PORT}/"
[ { "context": "uired\n#\n# credentials: {\n# id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# ", "end": 453, "score": 0.8274643421173096, "start": 441, "tag": "KEY", "value": "dh37fgj492je" }, { "context": " id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# algorithm: 'sha256' ", "end": 494, "score": 0.9996871948242188, "start": 475, "tag": "KEY", "value": "aoijedoaijsdlaksjdl" }, { "context": "uired\n#\n# credentials: {\n# id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# ", "end": 5734, "score": 0.8705859780311584, "start": 5722, "tag": "USERNAME", "value": "dh37fgj492je" }, { "context": " id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# algorithm: 'sha256' ", "end": 5775, "score": 0.9996874928474426, "start": 5756, "tag": "KEY", "value": "aoijedoaijsdlaksjdl" }, { "context": "uired\n#\n# credentials: {\n# id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# ", "end": 7726, "score": 0.9731862545013428, "start": 7714, "tag": "USERNAME", "value": "dh37fgj492je" }, { "context": " id: 'dh37fgj492je',\n# key: 'aoijedoaijsdlaksjdl',\n# algorithm: 'sha256' ", "end": 7767, "score": 0.9995792508125305, "start": 7748, "tag": "KEY", "value": "aoijedoaijsdlaksjdl" } ]
deps/npm/node_modules/request/node_modules/hawk/lib/client.coffee
lxe/io.coffee
0
# Load modules Url = require("url") Hoek = require("hoek") Cryptiles = require("cryptiles") Crypto = require("./crypto") Utils = require("./utils") # Declare internals internals = {} # Generate an Authorization header for a given request # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # method: HTTP verb (e.g. 'GET', 'POST') # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: 'aoijedoaijsdlaksjdl', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) # contentType: 'application/json', // Payload content-type (ignored if hash provided) # hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash # app: '24s23423f34dx', // Oz application id # dlg: '234sz34tww3sd' // Oz delegated-by application id # } # exports.header = (uri, method, options) -> result = field: "" artifacts: {} # Validate inputs if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not method or typeof method isnt "string" or not options or typeof options isnt "object" result.err = "Invalid argument type" return result # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials if not credentials or not credentials.id or not credentials.key or not credentials.algorithm result.err = "Invalid credential object" return result if Crypto.algorithms.indexOf(credentials.algorithm) is -1 result.err = "Unknown algorithm" return result # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) method: method resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) hash: options.hash ext: options.ext app: options.app dlg: options.dlg result.artifacts = artifacts # Calculate payload hash artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType) if not artifacts.hash and options.hasOwnProperty("payload") mac = Crypto.calculateMac("header", credentials, artifacts) # Construct header hasExt = artifacts.ext isnt null and artifacts.ext isnt `undefined` and artifacts.ext isnt "" # Other falsey values allowed header = "Hawk id=\"" + credentials.id + "\", ts=\"" + artifacts.ts + "\", nonce=\"" + artifacts.nonce + ((if artifacts.hash then "\", hash=\"" + artifacts.hash else "")) + ((if hasExt then "\", ext=\"" + Utils.escapeHeaderAttribute(artifacts.ext) else "")) + "\", mac=\"" + mac + "\"" header += ", app=\"" + artifacts.app + ((if artifacts.dlg then "\", dlg=\"" + artifacts.dlg else "")) + "\"" if artifacts.app result.field = header result # Validate server response # # res: node's response object # artifacts: object recieved from header().artifacts # options: { # payload: optional payload received # required: specifies if a Server-Authorization header is required. Defaults to 'false' # } # exports.authenticate = (res, credentials, artifacts, options) -> artifacts = Hoek.clone(artifacts) options = options or {} if res.headers["www-authenticate"] # Parse HTTP WWW-Authenticate header attributes = Utils.parseAuthorizationHeader(res.headers["www-authenticate"], [ "ts" "tsm" "error" ]) return false if attributes instanceof Error # Validate server timestamp (not used to update clock since it is done via the SNPT client) if attributes.ts tsm = Crypto.calculateTsMac(attributes.ts, credentials) return false if tsm isnt attributes.tsm # Parse HTTP Server-Authorization header return true if not res.headers["server-authorization"] and not options.required attributes = Utils.parseAuthorizationHeader(res.headers["server-authorization"], [ "mac" "ext" "hash" ]) return false if attributes instanceof Error artifacts.ext = attributes.ext artifacts.hash = attributes.hash mac = Crypto.calculateMac("response", credentials, artifacts) return false if mac isnt attributes.mac return true unless options.hasOwnProperty("payload") return false unless attributes.hash calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers["content-type"]) calculatedHash is attributes.hash # Generate a bewit value for a given URI # # * credentials is an object with the following keys: 'id, 'key', 'algorithm'. # * options is an object with the following optional keys: 'ext', 'localtimeOffsetMsec' # # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: 'aoijedoaijsdlaksjdl', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # ttlSec: 60 * 60, // TTL in seconds # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # localtimeOffsetMsec: 400 // Time offset to sync with server time # }; # exports.getBewit = (uri, options) -> # Validate inputs return "" if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not options or typeof options isnt "object" or not options.ttlSec options.ext = ((if options.ext is null or options.ext is `undefined` then "" else options.ext)) # Zero is valid value # Application time now = Utils.now() + (options.localtimeOffsetMsec or 0) # Validate credentials credentials = options.credentials return "" if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return "" if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature exp = Math.floor(now / 1000) + options.ttlSec mac = Crypto.calculateMac("bewit", credentials, ts: exp nonce: "" method: "GET" resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) ext: options.ext ) # Construct bewit: id\exp\mac\ext bewit = credentials.id + "\\" + exp + "\\" + mac + "\\" + options.ext Utils.base64urlEncode bewit # Generate an authorization string for a message # # host: 'example.com', # port: 8000, # message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: 'aoijedoaijsdlaksjdl', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # } # exports.message = (host, port, message, options) -> # Validate inputs return null if not host or typeof host isnt "string" or not port or typeof port isnt "number" or message is null or message is `undefined` or typeof message isnt "string" or not options or typeof options isnt "object" # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials # Invalid credential object return null if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return null if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) host: host port: port hash: Crypto.calculatePayloadHash(message, credentials.algorithm) # Construct authorization result = id: credentials.id ts: artifacts.ts nonce: artifacts.nonce hash: artifacts.hash mac: Crypto.calculateMac("message", credentials, artifacts) result
176132
# Load modules Url = require("url") Hoek = require("hoek") Cryptiles = require("cryptiles") Crypto = require("./crypto") Utils = require("./utils") # Declare internals internals = {} # Generate an Authorization header for a given request # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # method: HTTP verb (e.g. 'GET', 'POST') # options: { # # // Required # # credentials: { # id: '<KEY>', # key: '<KEY>', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) # contentType: 'application/json', // Payload content-type (ignored if hash provided) # hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash # app: '24s23423f34dx', // Oz application id # dlg: '234sz34tww3sd' // Oz delegated-by application id # } # exports.header = (uri, method, options) -> result = field: "" artifacts: {} # Validate inputs if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not method or typeof method isnt "string" or not options or typeof options isnt "object" result.err = "Invalid argument type" return result # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials if not credentials or not credentials.id or not credentials.key or not credentials.algorithm result.err = "Invalid credential object" return result if Crypto.algorithms.indexOf(credentials.algorithm) is -1 result.err = "Unknown algorithm" return result # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) method: method resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) hash: options.hash ext: options.ext app: options.app dlg: options.dlg result.artifacts = artifacts # Calculate payload hash artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType) if not artifacts.hash and options.hasOwnProperty("payload") mac = Crypto.calculateMac("header", credentials, artifacts) # Construct header hasExt = artifacts.ext isnt null and artifacts.ext isnt `undefined` and artifacts.ext isnt "" # Other falsey values allowed header = "Hawk id=\"" + credentials.id + "\", ts=\"" + artifacts.ts + "\", nonce=\"" + artifacts.nonce + ((if artifacts.hash then "\", hash=\"" + artifacts.hash else "")) + ((if hasExt then "\", ext=\"" + Utils.escapeHeaderAttribute(artifacts.ext) else "")) + "\", mac=\"" + mac + "\"" header += ", app=\"" + artifacts.app + ((if artifacts.dlg then "\", dlg=\"" + artifacts.dlg else "")) + "\"" if artifacts.app result.field = header result # Validate server response # # res: node's response object # artifacts: object recieved from header().artifacts # options: { # payload: optional payload received # required: specifies if a Server-Authorization header is required. Defaults to 'false' # } # exports.authenticate = (res, credentials, artifacts, options) -> artifacts = Hoek.clone(artifacts) options = options or {} if res.headers["www-authenticate"] # Parse HTTP WWW-Authenticate header attributes = Utils.parseAuthorizationHeader(res.headers["www-authenticate"], [ "ts" "tsm" "error" ]) return false if attributes instanceof Error # Validate server timestamp (not used to update clock since it is done via the SNPT client) if attributes.ts tsm = Crypto.calculateTsMac(attributes.ts, credentials) return false if tsm isnt attributes.tsm # Parse HTTP Server-Authorization header return true if not res.headers["server-authorization"] and not options.required attributes = Utils.parseAuthorizationHeader(res.headers["server-authorization"], [ "mac" "ext" "hash" ]) return false if attributes instanceof Error artifacts.ext = attributes.ext artifacts.hash = attributes.hash mac = Crypto.calculateMac("response", credentials, artifacts) return false if mac isnt attributes.mac return true unless options.hasOwnProperty("payload") return false unless attributes.hash calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers["content-type"]) calculatedHash is attributes.hash # Generate a bewit value for a given URI # # * credentials is an object with the following keys: 'id, 'key', 'algorithm'. # * options is an object with the following optional keys: 'ext', 'localtimeOffsetMsec' # # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: '<KEY>', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # ttlSec: 60 * 60, // TTL in seconds # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # localtimeOffsetMsec: 400 // Time offset to sync with server time # }; # exports.getBewit = (uri, options) -> # Validate inputs return "" if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not options or typeof options isnt "object" or not options.ttlSec options.ext = ((if options.ext is null or options.ext is `undefined` then "" else options.ext)) # Zero is valid value # Application time now = Utils.now() + (options.localtimeOffsetMsec or 0) # Validate credentials credentials = options.credentials return "" if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return "" if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature exp = Math.floor(now / 1000) + options.ttlSec mac = Crypto.calculateMac("bewit", credentials, ts: exp nonce: "" method: "GET" resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) ext: options.ext ) # Construct bewit: id\exp\mac\ext bewit = credentials.id + "\\" + exp + "\\" + mac + "\\" + options.ext Utils.base64urlEncode bewit # Generate an authorization string for a message # # host: 'example.com', # port: 8000, # message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: '<KEY>', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # } # exports.message = (host, port, message, options) -> # Validate inputs return null if not host or typeof host isnt "string" or not port or typeof port isnt "number" or message is null or message is `undefined` or typeof message isnt "string" or not options or typeof options isnt "object" # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials # Invalid credential object return null if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return null if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) host: host port: port hash: Crypto.calculatePayloadHash(message, credentials.algorithm) # Construct authorization result = id: credentials.id ts: artifacts.ts nonce: artifacts.nonce hash: artifacts.hash mac: Crypto.calculateMac("message", credentials, artifacts) result
true
# Load modules Url = require("url") Hoek = require("hoek") Cryptiles = require("cryptiles") Crypto = require("./crypto") Utils = require("./utils") # Declare internals internals = {} # Generate an Authorization header for a given request # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # method: HTTP verb (e.g. 'GET', 'POST') # options: { # # // Required # # credentials: { # id: 'PI:KEY:<KEY>END_PI', # key: 'PI:KEY:<KEY>END_PI', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) # contentType: 'application/json', // Payload content-type (ignored if hash provided) # hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash # app: '24s23423f34dx', // Oz application id # dlg: '234sz34tww3sd' // Oz delegated-by application id # } # exports.header = (uri, method, options) -> result = field: "" artifacts: {} # Validate inputs if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not method or typeof method isnt "string" or not options or typeof options isnt "object" result.err = "Invalid argument type" return result # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials if not credentials or not credentials.id or not credentials.key or not credentials.algorithm result.err = "Invalid credential object" return result if Crypto.algorithms.indexOf(credentials.algorithm) is -1 result.err = "Unknown algorithm" return result # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) method: method resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) hash: options.hash ext: options.ext app: options.app dlg: options.dlg result.artifacts = artifacts # Calculate payload hash artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType) if not artifacts.hash and options.hasOwnProperty("payload") mac = Crypto.calculateMac("header", credentials, artifacts) # Construct header hasExt = artifacts.ext isnt null and artifacts.ext isnt `undefined` and artifacts.ext isnt "" # Other falsey values allowed header = "Hawk id=\"" + credentials.id + "\", ts=\"" + artifacts.ts + "\", nonce=\"" + artifacts.nonce + ((if artifacts.hash then "\", hash=\"" + artifacts.hash else "")) + ((if hasExt then "\", ext=\"" + Utils.escapeHeaderAttribute(artifacts.ext) else "")) + "\", mac=\"" + mac + "\"" header += ", app=\"" + artifacts.app + ((if artifacts.dlg then "\", dlg=\"" + artifacts.dlg else "")) + "\"" if artifacts.app result.field = header result # Validate server response # # res: node's response object # artifacts: object recieved from header().artifacts # options: { # payload: optional payload received # required: specifies if a Server-Authorization header is required. Defaults to 'false' # } # exports.authenticate = (res, credentials, artifacts, options) -> artifacts = Hoek.clone(artifacts) options = options or {} if res.headers["www-authenticate"] # Parse HTTP WWW-Authenticate header attributes = Utils.parseAuthorizationHeader(res.headers["www-authenticate"], [ "ts" "tsm" "error" ]) return false if attributes instanceof Error # Validate server timestamp (not used to update clock since it is done via the SNPT client) if attributes.ts tsm = Crypto.calculateTsMac(attributes.ts, credentials) return false if tsm isnt attributes.tsm # Parse HTTP Server-Authorization header return true if not res.headers["server-authorization"] and not options.required attributes = Utils.parseAuthorizationHeader(res.headers["server-authorization"], [ "mac" "ext" "hash" ]) return false if attributes instanceof Error artifacts.ext = attributes.ext artifacts.hash = attributes.hash mac = Crypto.calculateMac("response", credentials, artifacts) return false if mac isnt attributes.mac return true unless options.hasOwnProperty("payload") return false unless attributes.hash calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers["content-type"]) calculatedHash is attributes.hash # Generate a bewit value for a given URI # # * credentials is an object with the following keys: 'id, 'key', 'algorithm'. # * options is an object with the following optional keys: 'ext', 'localtimeOffsetMsec' # # # uri: 'http://example.com/resource?a=b' or object from Url.parse() # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: 'PI:KEY:<KEY>END_PI', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # ttlSec: 60 * 60, // TTL in seconds # # // Optional # # ext: 'application-specific', // Application specific data sent via the ext attribute # localtimeOffsetMsec: 400 // Time offset to sync with server time # }; # exports.getBewit = (uri, options) -> # Validate inputs return "" if not uri or (typeof uri isnt "string" and typeof uri isnt "object") or not options or typeof options isnt "object" or not options.ttlSec options.ext = ((if options.ext is null or options.ext is `undefined` then "" else options.ext)) # Zero is valid value # Application time now = Utils.now() + (options.localtimeOffsetMsec or 0) # Validate credentials credentials = options.credentials return "" if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return "" if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Parse URI uri = Url.parse(uri) if typeof uri is "string" # Calculate signature exp = Math.floor(now / 1000) + options.ttlSec mac = Crypto.calculateMac("bewit", credentials, ts: exp nonce: "" method: "GET" resource: uri.pathname + (uri.search or "") # Maintain trailing '?' host: uri.hostname port: uri.port or ((if uri.protocol is "http:" then 80 else 443)) ext: options.ext ) # Construct bewit: id\exp\mac\ext bewit = credentials.id + "\\" + exp + "\\" + mac + "\\" + options.ext Utils.base64urlEncode bewit # Generate an authorization string for a message # # host: 'example.com', # port: 8000, # message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation # options: { # # // Required # # credentials: { # id: 'dh37fgj492je', # key: 'PI:KEY:<KEY>END_PI', # algorithm: 'sha256' // 'sha1', 'sha256' # }, # # // Optional # # timestamp: Date.now(), // A pre-calculated timestamp # nonce: '2334f34f', // A pre-generated nonce # localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) # } # exports.message = (host, port, message, options) -> # Validate inputs return null if not host or typeof host isnt "string" or not port or typeof port isnt "number" or message is null or message is `undefined` or typeof message isnt "string" or not options or typeof options isnt "object" # Application time timestamp = options.timestamp or Math.floor((Utils.now() + (options.localtimeOffsetMsec or 0)) / 1000) # Validate credentials credentials = options.credentials # Invalid credential object return null if not credentials or not credentials.id or not credentials.key or not credentials.algorithm return null if Crypto.algorithms.indexOf(credentials.algorithm) is -1 # Calculate signature artifacts = ts: timestamp nonce: options.nonce or Cryptiles.randomString(6) host: host port: port hash: Crypto.calculatePayloadHash(message, credentials.algorithm) # Construct authorization result = id: credentials.id ts: artifacts.ts nonce: artifacts.nonce hash: artifacts.hash mac: Crypto.calculateMac("message", credentials, artifacts) result
[ { "context": "the end where element == to object\", ->\n key = 3\n uno =\n equals: -> throw 'do not go here", "end": 289, "score": 0.8978615999221802, "start": 288, "tag": "KEY", "value": "3" } ]
spec/lib/corelib/array/rindex_spec.coffee
hasclass/core-lib
1
# Modifying a collection while the contents are being iterated # gives undefined behavior. See # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/23633 describe "Array#rindex", -> it "returns the first index backwards from the end where element == to object", -> key = 3 uno = equals: -> throw 'do not go here' dos = equals: -> true tres = equals: -> false ary = R [uno, dos, tres] expect( ary.rindex(key) ).toEqual R(1) it "returns size-1 if last element == to object", -> expect( R([2, 1, 3, 2, 5]).rindex(5) ).toEqual R(4) it "returns 0 if only first element == to object", -> expect( R([2, 1, 3, 1, 5]).rindex(2) ).toEqual R(0) it "returns nil if no element == to object", -> expect( R([1, 1, 3, 2, 1, 3]).rindex(4) ).toEqual null # it "properly handles empty recursive arrays", -> # empty = ArraySpecs.empty_recursive_array # empty.rindex(empty).should == 0 # empty.rindex(1).should be_nil # it "properly handles recursive arrays", -> # array = ArraySpecs.recursive_array # array.rindex(1).should == 0 # array.rindex(array).should == 7 describe 'ruby_version_is "1.8.7"', -> it "accepts a block instead of an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex (x) -> x < 2 ).toEqual R(4) it "ignore the block if there is an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex(5, (x) -> x < 2 ) ).toEqual R(3) xit "rechecks the array size during iteration", -> ary = R([4, 2, 1, 5, 1, 3]) seen = [] ary.rindex (x) -> seen.push(x) ary.clear() false expect( seen ).toEqual [3] describe "given no argument and no block", -> it "produces an Enumerator", -> en = R([4, 2, 1, 5, 1, 3]).rindex() expect( en ).toBeInstanceOf R.Enumerator expect( en.each (x) -> x < 2 ).toEqual R(4)
107463
# Modifying a collection while the contents are being iterated # gives undefined behavior. See # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/23633 describe "Array#rindex", -> it "returns the first index backwards from the end where element == to object", -> key = <KEY> uno = equals: -> throw 'do not go here' dos = equals: -> true tres = equals: -> false ary = R [uno, dos, tres] expect( ary.rindex(key) ).toEqual R(1) it "returns size-1 if last element == to object", -> expect( R([2, 1, 3, 2, 5]).rindex(5) ).toEqual R(4) it "returns 0 if only first element == to object", -> expect( R([2, 1, 3, 1, 5]).rindex(2) ).toEqual R(0) it "returns nil if no element == to object", -> expect( R([1, 1, 3, 2, 1, 3]).rindex(4) ).toEqual null # it "properly handles empty recursive arrays", -> # empty = ArraySpecs.empty_recursive_array # empty.rindex(empty).should == 0 # empty.rindex(1).should be_nil # it "properly handles recursive arrays", -> # array = ArraySpecs.recursive_array # array.rindex(1).should == 0 # array.rindex(array).should == 7 describe 'ruby_version_is "1.8.7"', -> it "accepts a block instead of an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex (x) -> x < 2 ).toEqual R(4) it "ignore the block if there is an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex(5, (x) -> x < 2 ) ).toEqual R(3) xit "rechecks the array size during iteration", -> ary = R([4, 2, 1, 5, 1, 3]) seen = [] ary.rindex (x) -> seen.push(x) ary.clear() false expect( seen ).toEqual [3] describe "given no argument and no block", -> it "produces an Enumerator", -> en = R([4, 2, 1, 5, 1, 3]).rindex() expect( en ).toBeInstanceOf R.Enumerator expect( en.each (x) -> x < 2 ).toEqual R(4)
true
# Modifying a collection while the contents are being iterated # gives undefined behavior. See # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/23633 describe "Array#rindex", -> it "returns the first index backwards from the end where element == to object", -> key = PI:KEY:<KEY>END_PI uno = equals: -> throw 'do not go here' dos = equals: -> true tres = equals: -> false ary = R [uno, dos, tres] expect( ary.rindex(key) ).toEqual R(1) it "returns size-1 if last element == to object", -> expect( R([2, 1, 3, 2, 5]).rindex(5) ).toEqual R(4) it "returns 0 if only first element == to object", -> expect( R([2, 1, 3, 1, 5]).rindex(2) ).toEqual R(0) it "returns nil if no element == to object", -> expect( R([1, 1, 3, 2, 1, 3]).rindex(4) ).toEqual null # it "properly handles empty recursive arrays", -> # empty = ArraySpecs.empty_recursive_array # empty.rindex(empty).should == 0 # empty.rindex(1).should be_nil # it "properly handles recursive arrays", -> # array = ArraySpecs.recursive_array # array.rindex(1).should == 0 # array.rindex(array).should == 7 describe 'ruby_version_is "1.8.7"', -> it "accepts a block instead of an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex (x) -> x < 2 ).toEqual R(4) it "ignore the block if there is an argument", -> expect( R([4, 2, 1, 5, 1, 3]).rindex(5, (x) -> x < 2 ) ).toEqual R(3) xit "rechecks the array size during iteration", -> ary = R([4, 2, 1, 5, 1, 3]) seen = [] ary.rindex (x) -> seen.push(x) ary.clear() false expect( seen ).toEqual [3] describe "given no argument and no block", -> it "produces an Enumerator", -> en = R([4, 2, 1, 5, 1, 3]).rindex() expect( en ).toBeInstanceOf R.Enumerator expect( en.each (x) -> x < 2 ).toEqual R(4)
[ { "context": "/neocotic.com/UndoWikipediaBlackout) \r\n# (c) 2012 Alasdair Mercer \r\n# Freely distributable under the MIT license. ", "end": 100, "score": 0.9998793005943298, "start": 85, "tag": "NAME", "value": "Alasdair Mercer" } ]
src/lib/options.coffee
neocotic/UndoWikipediaBlackout
1
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 Alasdair Mercer # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private constants # ----------------- # Source URL of the user feedback widget script. WIDGET_SOURCE = 'https://widget.uservoice.com/66hVxrEWDUgjuAmIIqPKg.js' # Private variables # ----------------- # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Load functions # -------------- # Bind an event of the specified `type` to the elements included by # `selector` that, when triggered, modifies the underlying `option` with the # value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[0].toLowerCase() + key.substr 1 data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').attr 'checked', 'checked' if store.get 'analytics' loadSaveEvents() loadDeveloperTools() # Update the developer tools section of the options page with the current # settings. loadDeveloperTools = -> log.trace() loadLogger() # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').attr 'checked', 'checked' if logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.attr 'selected', 'selected' if level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").attr 'selected', 'selected' loadLoggerSaveEvents() # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').change -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Miscellaneous functions # ----------------------- # Add the user feedback feature to the page. feedback = -> unless feedbackAdded # Temporary workaround for Content Security Policy issues with UserVoice's # use of inline JavaScript. # This should be removed if/when it's no longer required. uvwDialogClose = $ '#uvw-dialog-close[onclick]' uvwDialogClose.live 'hover', -> $(this).removeAttr 'onclick' uvwDialogClose.die 'hover' $(uvwDialogClose.selector.replace('[onclick]', '')).live 'click', (e) -> UserVoice.hidePopupWidget() e.preventDefault() uvTabLabel = $ '#uvTabLabel[href^="javascript:"]' uvTabLabel.live 'hover', -> $(this).removeAttr 'href' uvTabLabel.die 'hover' # Continue with normal process of loading Widget. window.uvOptions = {} uv = document.createElement 'script' uv.async = 'async' uv.src = WIDGET_SOURCE script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script feedbackAdded = yes # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as # loading the current settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. feedback() # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').click -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() store.set 'options_active_tab', id = nav.attr 'id' unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").click() log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').click -> $('#tools_wizard').modal 'show' $('.tools_close_btn').click -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').submit -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').click -> analytics.track 'Footer', 'Clicked', 'Homepage' $('#donation').submit -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. load() # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this trigger = $this.attr 'data-trigger' trigger = if trigger? then trigger.trim().toLowerCase() else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' trigger: trigger if trigger is 'manual' $this.click -> $this.popover 'toggle' $('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then placement.trim().toLowerCase() else 'top' $this.tooltip placement: placement $('[data-goto]').click -> goto = $ $(this).attr 'data-goto' log.debug "Relocating view to include '#{goto.selector}'" $(window).scrollTop goto.position()?.top or 0 # Initialize `options` when the DOM is ready. utils.ready -> options.init()
52010
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 <NAME> # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private constants # ----------------- # Source URL of the user feedback widget script. WIDGET_SOURCE = 'https://widget.uservoice.com/66hVxrEWDUgjuAmIIqPKg.js' # Private variables # ----------------- # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Load functions # -------------- # Bind an event of the specified `type` to the elements included by # `selector` that, when triggered, modifies the underlying `option` with the # value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[0].toLowerCase() + key.substr 1 data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').attr 'checked', 'checked' if store.get 'analytics' loadSaveEvents() loadDeveloperTools() # Update the developer tools section of the options page with the current # settings. loadDeveloperTools = -> log.trace() loadLogger() # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').attr 'checked', 'checked' if logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.attr 'selected', 'selected' if level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").attr 'selected', 'selected' loadLoggerSaveEvents() # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').change -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Miscellaneous functions # ----------------------- # Add the user feedback feature to the page. feedback = -> unless feedbackAdded # Temporary workaround for Content Security Policy issues with UserVoice's # use of inline JavaScript. # This should be removed if/when it's no longer required. uvwDialogClose = $ '#uvw-dialog-close[onclick]' uvwDialogClose.live 'hover', -> $(this).removeAttr 'onclick' uvwDialogClose.die 'hover' $(uvwDialogClose.selector.replace('[onclick]', '')).live 'click', (e) -> UserVoice.hidePopupWidget() e.preventDefault() uvTabLabel = $ '#uvTabLabel[href^="javascript:"]' uvTabLabel.live 'hover', -> $(this).removeAttr 'href' uvTabLabel.die 'hover' # Continue with normal process of loading Widget. window.uvOptions = {} uv = document.createElement 'script' uv.async = 'async' uv.src = WIDGET_SOURCE script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script feedbackAdded = yes # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as # loading the current settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. feedback() # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').click -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() store.set 'options_active_tab', id = nav.attr 'id' unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").click() log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').click -> $('#tools_wizard').modal 'show' $('.tools_close_btn').click -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').submit -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').click -> analytics.track 'Footer', 'Clicked', 'Homepage' $('#donation').submit -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. load() # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this trigger = $this.attr 'data-trigger' trigger = if trigger? then trigger.trim().toLowerCase() else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' trigger: trigger if trigger is 'manual' $this.click -> $this.popover 'toggle' $('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then placement.trim().toLowerCase() else 'top' $this.tooltip placement: placement $('[data-goto]').click -> goto = $ $(this).attr 'data-goto' log.debug "Relocating view to include '#{goto.selector}'" $(window).scrollTop goto.position()?.top or 0 # Initialize `options` when the DOM is ready. utils.ready -> options.init()
true
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 PI:NAME:<NAME>END_PI # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private constants # ----------------- # Source URL of the user feedback widget script. WIDGET_SOURCE = 'https://widget.uservoice.com/66hVxrEWDUgjuAmIIqPKg.js' # Private variables # ----------------- # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Load functions # -------------- # Bind an event of the specified `type` to the elements included by # `selector` that, when triggered, modifies the underlying `option` with the # value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[0].toLowerCase() + key.substr 1 data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').attr 'checked', 'checked' if store.get 'analytics' loadSaveEvents() loadDeveloperTools() # Update the developer tools section of the options page with the current # settings. loadDeveloperTools = -> log.trace() loadLogger() # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').attr 'checked', 'checked' if logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.attr 'selected', 'selected' if level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").attr 'selected', 'selected' loadLoggerSaveEvents() # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').change -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Miscellaneous functions # ----------------------- # Add the user feedback feature to the page. feedback = -> unless feedbackAdded # Temporary workaround for Content Security Policy issues with UserVoice's # use of inline JavaScript. # This should be removed if/when it's no longer required. uvwDialogClose = $ '#uvw-dialog-close[onclick]' uvwDialogClose.live 'hover', -> $(this).removeAttr 'onclick' uvwDialogClose.die 'hover' $(uvwDialogClose.selector.replace('[onclick]', '')).live 'click', (e) -> UserVoice.hidePopupWidget() e.preventDefault() uvTabLabel = $ '#uvTabLabel[href^="javascript:"]' uvTabLabel.live 'hover', -> $(this).removeAttr 'href' uvTabLabel.die 'hover' # Continue with normal process of loading Widget. window.uvOptions = {} uv = document.createElement 'script' uv.async = 'async' uv.src = WIDGET_SOURCE script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script feedbackAdded = yes # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as # loading the current settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. feedback() # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').click -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() store.set 'options_active_tab', id = nav.attr 'id' unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").click() log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').click -> $('#tools_wizard').modal 'show' $('.tools_close_btn').click -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').submit -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').click -> analytics.track 'Footer', 'Clicked', 'Homepage' $('#donation').submit -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. load() # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this trigger = $this.attr 'data-trigger' trigger = if trigger? then trigger.trim().toLowerCase() else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' trigger: trigger if trigger is 'manual' $this.click -> $this.popover 'toggle' $('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then placement.trim().toLowerCase() else 'top' $this.tooltip placement: placement $('[data-goto]').click -> goto = $ $(this).attr 'data-goto' log.debug "Relocating view to include '#{goto.selector}'" $(window).scrollTop goto.position()?.top or 0 # Initialize `options` when the DOM is ready. utils.ready -> options.init()
[ { "context": "out 12000\n\n\t\tbeforeEach ->\n\t\t\t@driver.get 'http://127.0.0.1/'\n\n\t\tit 'has the title of the application in the ", "end": 400, "score": 0.7324510812759399, "start": 391, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ut 12000\n\n\t\tbeforeEach ->\n\t\t\t@driver.get 'http://127.0.0.1/'\n\n\t\tit 'is the name of the private list after cl", "end": 1256, "score": 0.7102668881416321, "start": 1248, "tag": "IP_ADDRESS", "value": "27.0.0.1" }, { "context": " 12000\n\n\t\tbeforeEach ->\n\t\t\t@driver.get 'http://127.0.0.1/'\n\n\t\tit 'is the length of the completd items", "end": 2254, "score": 0.5693066120147705, "start": 2254, "tag": "IP_ADDRESS", "value": "" }, { "context": "2000\n\n\t\tbeforeEach ->\n\t\t\t@driver.get 'http://127.0.0.1/'\n\n\t\tit 'is the length of the completd items = 1", "end": 2258, "score": 0.6038933396339417, "start": 2257, "tag": "IP_ADDRESS", "value": "0" } ]
test/js/totodoo2.coffee
markomanninen/totodoo
0
selenium = require 'selenium-webdriver' chai = require 'chai' chai.use require 'chai-as-promised' expect = chai.expect before -> @driver = new selenium.Builder() .withCapabilities(selenium.Capabilities.phantomjs()) .build() @driver.getWindowHandle() after -> @driver.quit() describe 'Totodoo App', -> describe 'Init', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'has the title of the application in the window\'s title', (done) -> expect(@driver.getTitle()).to.eventually.contain 'Totodoo App' @timeout 4000, done() it 'is the name of the default list', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> text = drvr.findElement(id: 'listName').getText() expect(text).to.eventually.equal 'Public list 1' done() it 'is the length of the default list items = 2', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> lis = element.all(drvr.findElement(id: 'todo-list').findElements(tagName: 'li')) expect(lis.count()).to.eventually.equal 2 done() describe 'List actions', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'is the name of the private list after click', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'Private list 1' @driver.findElement(linkText: listName).click() text = @driver.findElement(id: 'listName').getText() expect(text).to.eventually.equal listName @timeout 10000, done() it 'is the name of the public list after change', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'PUBLIC LIST 1' el = @driver.findElement(id: 'listName') @driver.executeScript("arguments[0].setAttribute('value', arguments[1])", el, listName) text = @driver.findElement(id: 'id1').findElement(tagName: 'a').getText() expect(text).to.eventually.equal listName @timeout 4000, done() describe 'Create list', -> describe 'Delete list', -> describe 'Item actions', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'is the length of the completd items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Completed').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() it 'is the length of the active items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Active').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() describe 'Add item', -> describe 'Complete item', -> describe 'Uncomplete item', -> describe 'Remove item', -> describe 'Show all items', -> describe 'Swap completed items', -> describe 'User actions', ->
28630
selenium = require 'selenium-webdriver' chai = require 'chai' chai.use require 'chai-as-promised' expect = chai.expect before -> @driver = new selenium.Builder() .withCapabilities(selenium.Capabilities.phantomjs()) .build() @driver.getWindowHandle() after -> @driver.quit() describe 'Totodoo App', -> describe 'Init', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'has the title of the application in the window\'s title', (done) -> expect(@driver.getTitle()).to.eventually.contain 'Totodoo App' @timeout 4000, done() it 'is the name of the default list', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> text = drvr.findElement(id: 'listName').getText() expect(text).to.eventually.equal 'Public list 1' done() it 'is the length of the default list items = 2', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> lis = element.all(drvr.findElement(id: 'todo-list').findElements(tagName: 'li')) expect(lis.count()).to.eventually.equal 2 done() describe 'List actions', -> @timeout 12000 beforeEach -> @driver.get 'http://1172.16.17.32/' it 'is the name of the private list after click', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'Private list 1' @driver.findElement(linkText: listName).click() text = @driver.findElement(id: 'listName').getText() expect(text).to.eventually.equal listName @timeout 10000, done() it 'is the name of the public list after change', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'PUBLIC LIST 1' el = @driver.findElement(id: 'listName') @driver.executeScript("arguments[0].setAttribute('value', arguments[1])", el, listName) text = @driver.findElement(id: 'id1').findElement(tagName: 'a').getText() expect(text).to.eventually.equal listName @timeout 4000, done() describe 'Create list', -> describe 'Delete list', -> describe 'Item actions', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'is the length of the completd items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Completed').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() it 'is the length of the active items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Active').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() describe 'Add item', -> describe 'Complete item', -> describe 'Uncomplete item', -> describe 'Remove item', -> describe 'Show all items', -> describe 'Swap completed items', -> describe 'User actions', ->
true
selenium = require 'selenium-webdriver' chai = require 'chai' chai.use require 'chai-as-promised' expect = chai.expect before -> @driver = new selenium.Builder() .withCapabilities(selenium.Capabilities.phantomjs()) .build() @driver.getWindowHandle() after -> @driver.quit() describe 'Totodoo App', -> describe 'Init', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'has the title of the application in the window\'s title', (done) -> expect(@driver.getTitle()).to.eventually.contain 'Totodoo App' @timeout 4000, done() it 'is the name of the default list', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> text = drvr.findElement(id: 'listName').getText() expect(text).to.eventually.equal 'Public list 1' done() it 'is the length of the default list items = 2', (done) -> drvr = @driver @driver.wait((()-> drvr.executeScript('return document.readyState')), 10000).then ()-> lis = element.all(drvr.findElement(id: 'todo-list').findElements(tagName: 'li')) expect(lis.count()).to.eventually.equal 2 done() describe 'List actions', -> @timeout 12000 beforeEach -> @driver.get 'http://1PI:IP_ADDRESS:172.16.17.32END_PI/' it 'is the name of the private list after click', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'Private list 1' @driver.findElement(linkText: listName).click() text = @driver.findElement(id: 'listName').getText() expect(text).to.eventually.equal listName @timeout 10000, done() it 'is the name of the public list after change', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> listName = 'PUBLIC LIST 1' el = @driver.findElement(id: 'listName') @driver.executeScript("arguments[0].setAttribute('value', arguments[1])", el, listName) text = @driver.findElement(id: 'id1').findElement(tagName: 'a').getText() expect(text).to.eventually.equal listName @timeout 4000, done() describe 'Create list', -> describe 'Delete list', -> describe 'Item actions', -> @timeout 12000 beforeEach -> @driver.get 'http://127.0.0.1/' it 'is the length of the completd items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Completed').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() it 'is the length of the active items = 1', (done) -> @driver.wait((()-> @driver.executeScript('return document.readyState')), 10000).then ()-> @driver.findElement(linkText: 'Active').click() lis = @driver.findElement(id: 'todo-list').findElements(tagName: 'li') expect(lis.size()).to.eventually.equal 1 @timeout 10000, done() describe 'Add item', -> describe 'Complete item', -> describe 'Uncomplete item', -> describe 'Remove item', -> describe 'Show all items', -> describe 'Swap completed items', -> describe 'User actions', ->
[ { "context": "###\nCopyright 2016-2017 Balena\n\nLicensed under the Apache License, Version 2.0 (", "end": 30, "score": 0.988315224647522, "start": 24, "tag": "NAME", "value": "Balena" } ]
lib/actions/help.coffee
eternius/otto-cli
0
### Copyright 2016-2017 Balena 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. ### _ = require('lodash') capitano = require('capitano') columnify = require('columnify') messages = require('../utils/messages') { getManualSortCompareFunction } = require('../utils/helpers') { exitWithExpectedError } = require('../utils/patterns') { getOclifHelpLinePairs } = require('./help_ts') parse = (object) -> return _.map object, (item) -> # Hacky way to determine if an object is # a function or a command if item.alias? signature = item.toString() else signature = item.signature.toString() return [ signature item.description ] indent = (text) -> text = _.map text.split('\n'), (line) -> return ' ' + line return text.join('\n') print = (usageDescriptionPairs) -> console.log indent columnify _.fromPairs(usageDescriptionPairs), showHeaders: false minWidth: 35 manuallySortedPrimaryCommands = [ 'help', 'login', 'push', 'logs', 'ssh', 'apps', 'app', 'devices', 'device', 'tunnel', 'preload', 'build', 'deploy', 'join', 'leave', 'local scan', ] general = (params, options, done) -> console.log('Usage: balena [COMMAND] [OPTIONS]\n') console.log(messages.reachingOut) console.log('\nPrimary commands:\n') # We do not want the wildcard command # to be printed in the help screen. commands = _.reject capitano.state.commands, (command) -> return command.hidden or command.isWildcard() groupedCommands = _.groupBy commands, (command) -> if command.primary return 'primary' return 'secondary' print parse(groupedCommands.primary).sort(getManualSortCompareFunction( manuallySortedPrimaryCommands, ([signature, description], manualItem) -> signature == manualItem or signature.startsWith("#{manualItem} ") )) if options.verbose console.log('\nAdditional commands:\n') print parse(groupedCommands.secondary).concat(getOclifHelpLinePairs()).sort() else console.log('\nRun `balena help --verbose` to list additional commands') if not _.isEmpty(capitano.state.globalOptions) console.log('\nGlobal Options:\n') print parse(capitano.state.globalOptions).sort() return done() command = (params, options, done) -> capitano.state.getMatchCommand params.command, (error, command) -> return done(error) if error? if not command? or command.isWildcard() exitWithExpectedError("Command not found: #{params.command}") console.log("Usage: #{command.signature}") if command.help? console.log("\n#{command.help}") else if command.description? console.log("\n#{_.capitalize(command.description)}") if not _.isEmpty(command.options) console.log('\nOptions:\n') print parse(command.options).sort() return done() exports.help = signature: 'help [command...]' description: 'show help' help: ''' Get detailed help for an specific command. Examples: $ balena help apps $ balena help os download ''' primary: true options: [ signature: 'verbose' description: 'show additional commands' boolean: true alias: 'v' ] action: (params, options, done) -> if params.command? command(params, options, done) else general(params, options, done)
19603
### Copyright 2016-2017 <NAME> 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. ### _ = require('lodash') capitano = require('capitano') columnify = require('columnify') messages = require('../utils/messages') { getManualSortCompareFunction } = require('../utils/helpers') { exitWithExpectedError } = require('../utils/patterns') { getOclifHelpLinePairs } = require('./help_ts') parse = (object) -> return _.map object, (item) -> # Hacky way to determine if an object is # a function or a command if item.alias? signature = item.toString() else signature = item.signature.toString() return [ signature item.description ] indent = (text) -> text = _.map text.split('\n'), (line) -> return ' ' + line return text.join('\n') print = (usageDescriptionPairs) -> console.log indent columnify _.fromPairs(usageDescriptionPairs), showHeaders: false minWidth: 35 manuallySortedPrimaryCommands = [ 'help', 'login', 'push', 'logs', 'ssh', 'apps', 'app', 'devices', 'device', 'tunnel', 'preload', 'build', 'deploy', 'join', 'leave', 'local scan', ] general = (params, options, done) -> console.log('Usage: balena [COMMAND] [OPTIONS]\n') console.log(messages.reachingOut) console.log('\nPrimary commands:\n') # We do not want the wildcard command # to be printed in the help screen. commands = _.reject capitano.state.commands, (command) -> return command.hidden or command.isWildcard() groupedCommands = _.groupBy commands, (command) -> if command.primary return 'primary' return 'secondary' print parse(groupedCommands.primary).sort(getManualSortCompareFunction( manuallySortedPrimaryCommands, ([signature, description], manualItem) -> signature == manualItem or signature.startsWith("#{manualItem} ") )) if options.verbose console.log('\nAdditional commands:\n') print parse(groupedCommands.secondary).concat(getOclifHelpLinePairs()).sort() else console.log('\nRun `balena help --verbose` to list additional commands') if not _.isEmpty(capitano.state.globalOptions) console.log('\nGlobal Options:\n') print parse(capitano.state.globalOptions).sort() return done() command = (params, options, done) -> capitano.state.getMatchCommand params.command, (error, command) -> return done(error) if error? if not command? or command.isWildcard() exitWithExpectedError("Command not found: #{params.command}") console.log("Usage: #{command.signature}") if command.help? console.log("\n#{command.help}") else if command.description? console.log("\n#{_.capitalize(command.description)}") if not _.isEmpty(command.options) console.log('\nOptions:\n') print parse(command.options).sort() return done() exports.help = signature: 'help [command...]' description: 'show help' help: ''' Get detailed help for an specific command. Examples: $ balena help apps $ balena help os download ''' primary: true options: [ signature: 'verbose' description: 'show additional commands' boolean: true alias: 'v' ] action: (params, options, done) -> if params.command? command(params, options, done) else general(params, options, done)
true
### Copyright 2016-2017 PI:NAME:<NAME>END_PI 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. ### _ = require('lodash') capitano = require('capitano') columnify = require('columnify') messages = require('../utils/messages') { getManualSortCompareFunction } = require('../utils/helpers') { exitWithExpectedError } = require('../utils/patterns') { getOclifHelpLinePairs } = require('./help_ts') parse = (object) -> return _.map object, (item) -> # Hacky way to determine if an object is # a function or a command if item.alias? signature = item.toString() else signature = item.signature.toString() return [ signature item.description ] indent = (text) -> text = _.map text.split('\n'), (line) -> return ' ' + line return text.join('\n') print = (usageDescriptionPairs) -> console.log indent columnify _.fromPairs(usageDescriptionPairs), showHeaders: false minWidth: 35 manuallySortedPrimaryCommands = [ 'help', 'login', 'push', 'logs', 'ssh', 'apps', 'app', 'devices', 'device', 'tunnel', 'preload', 'build', 'deploy', 'join', 'leave', 'local scan', ] general = (params, options, done) -> console.log('Usage: balena [COMMAND] [OPTIONS]\n') console.log(messages.reachingOut) console.log('\nPrimary commands:\n') # We do not want the wildcard command # to be printed in the help screen. commands = _.reject capitano.state.commands, (command) -> return command.hidden or command.isWildcard() groupedCommands = _.groupBy commands, (command) -> if command.primary return 'primary' return 'secondary' print parse(groupedCommands.primary).sort(getManualSortCompareFunction( manuallySortedPrimaryCommands, ([signature, description], manualItem) -> signature == manualItem or signature.startsWith("#{manualItem} ") )) if options.verbose console.log('\nAdditional commands:\n') print parse(groupedCommands.secondary).concat(getOclifHelpLinePairs()).sort() else console.log('\nRun `balena help --verbose` to list additional commands') if not _.isEmpty(capitano.state.globalOptions) console.log('\nGlobal Options:\n') print parse(capitano.state.globalOptions).sort() return done() command = (params, options, done) -> capitano.state.getMatchCommand params.command, (error, command) -> return done(error) if error? if not command? or command.isWildcard() exitWithExpectedError("Command not found: #{params.command}") console.log("Usage: #{command.signature}") if command.help? console.log("\n#{command.help}") else if command.description? console.log("\n#{_.capitalize(command.description)}") if not _.isEmpty(command.options) console.log('\nOptions:\n') print parse(command.options).sort() return done() exports.help = signature: 'help [command...]' description: 'show help' help: ''' Get detailed help for an specific command. Examples: $ balena help apps $ balena help os download ''' primary: true options: [ signature: 'verbose' description: 'show additional commands' boolean: true alias: 'v' ] action: (params, options, done) -> if params.command? command(params, options, done) else general(params, options, done)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9985197186470032, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-should-keep-alive.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") http = require("http") net = require("net") SERVER_RESPONSES = [ "HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ] SHOULD_KEEP_ALIVE = [ false # HTTP/1.0, default true # HTTP/1.0, Connection: keep-alive false # HTTP/1.0, Connection: close true # HTTP/1.1, default true # HTTP/1.1, Connection: keep-alive false # HTTP/1.1, Connection: close ] requests = 0 responses = 0 http.globalAgent.maxSockets = 5 server = net.createServer((socket) -> socket.write SERVER_RESPONSES[requests] ++requests return ).listen(common.PORT, -> makeRequest = -> req = http.get( port: common.PORT , (res) -> assert.equal req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], SERVER_RESPONSES[responses] + " should " + ((if SHOULD_KEEP_ALIVE[responses] then "" else "not ")) + "Keep-Alive" ++responses if responses < SHOULD_KEEP_ALIVE.length makeRequest() else server.close() res.resume() return ) return makeRequest() return ) process.on "exit", -> assert.equal requests, SERVER_RESPONSES.length assert.equal responses, SHOULD_KEEP_ALIVE.length return
187091
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") http = require("http") net = require("net") SERVER_RESPONSES = [ "HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ] SHOULD_KEEP_ALIVE = [ false # HTTP/1.0, default true # HTTP/1.0, Connection: keep-alive false # HTTP/1.0, Connection: close true # HTTP/1.1, default true # HTTP/1.1, Connection: keep-alive false # HTTP/1.1, Connection: close ] requests = 0 responses = 0 http.globalAgent.maxSockets = 5 server = net.createServer((socket) -> socket.write SERVER_RESPONSES[requests] ++requests return ).listen(common.PORT, -> makeRequest = -> req = http.get( port: common.PORT , (res) -> assert.equal req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], SERVER_RESPONSES[responses] + " should " + ((if SHOULD_KEEP_ALIVE[responses] then "" else "not ")) + "Keep-Alive" ++responses if responses < SHOULD_KEEP_ALIVE.length makeRequest() else server.close() res.resume() return ) return makeRequest() return ) process.on "exit", -> assert.equal requests, SERVER_RESPONSES.length assert.equal responses, SHOULD_KEEP_ALIVE.length return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") http = require("http") net = require("net") SERVER_RESPONSES = [ "HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n" "HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ] SHOULD_KEEP_ALIVE = [ false # HTTP/1.0, default true # HTTP/1.0, Connection: keep-alive false # HTTP/1.0, Connection: close true # HTTP/1.1, default true # HTTP/1.1, Connection: keep-alive false # HTTP/1.1, Connection: close ] requests = 0 responses = 0 http.globalAgent.maxSockets = 5 server = net.createServer((socket) -> socket.write SERVER_RESPONSES[requests] ++requests return ).listen(common.PORT, -> makeRequest = -> req = http.get( port: common.PORT , (res) -> assert.equal req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], SERVER_RESPONSES[responses] + " should " + ((if SHOULD_KEEP_ALIVE[responses] then "" else "not ")) + "Keep-Alive" ++responses if responses < SHOULD_KEEP_ALIVE.length makeRequest() else server.close() res.resume() return ) return makeRequest() return ) process.on "exit", -> assert.equal requests, SERVER_RESPONSES.length assert.equal responses, SHOULD_KEEP_ALIVE.length return
[ { "context": "\n $scope.labels = [\n \"Alpha\"\n \"Bravo\"\n \"Charlie\"\n ]\n", "end": 115, "score": 0.9989690780639648, "start": 108, "tag": "NAME", "value": "Charlie" } ]
source/javascripts/angular/controllers/basic.coffee
adambutler/angular-js-for-data-driven-applications
0
angular.module('app').controller "BasicCtrl", ($scope) -> $scope.labels = [ "Alpha" "Bravo" "Charlie" ]
119724
angular.module('app').controller "BasicCtrl", ($scope) -> $scope.labels = [ "Alpha" "Bravo" "<NAME>" ]
true
angular.module('app').controller "BasicCtrl", ($scope) -> $scope.labels = [ "Alpha" "Bravo" "PI:NAME:<NAME>END_PI" ]
[ { "context": "\"nonce\" : \"24-byte nonce for xsalsa\"\n \"key\" : \"this is 32-byte key for xsalsa20\"\n \"ciphertext\" : [ 0x", "end": 978, "score": 0.7847883701324463, "start": 971, "tag": "KEY", "value": "this is" }, { "context": ": \"24-byte nonce for xsalsa\"\n \"key\" : \"this is 32-byte key for xsalsa20\"\n \"ciphertext\" : [ 0x48,", "end": 981, "score": 0.6576611399650574, "start": 979, "tag": "KEY", "value": "32" }, { "context": "24-byte nonce for xsalsa\"\n \"key\" : \"this is 32-byte key for xsalsa20\"\n \"ciphertext\" : [ 0x48, 0x48, 0x29, ", "end": 994, "score": 0.6720195412635803, "start": 982, "tag": "KEY", "value": "byte key for" }, { "context": "e for xsalsa\"\n \"key\" : \"this is 32-byte key for xsalsa20\"\n \"ciphertext\" : [ 0x48, 0x48, 0x29, 0x7f, 0xe", "end": 1003, "score": 0.9636411666870117, "start": 995, "tag": "KEY", "value": "xsalsa20" } ]
test/files/salsa20.iced
CyberFlameGO/triplesec
274
data = key128 : require('../data/salsa20_key128').data key256 : require('../data/salsa20_key256').data {Salsa20} = require '../../lib/salsa20' {WordArray} = require '../../lib/wordarray' test_case = (T, i, test) -> key = WordArray.from_hex test.key iv = WordArray.from_hex test.IV stream = new Salsa20 key, iv i = 0 for part in test.stream if i < part.low stream.getBytes(part.low - i) bytes = stream.getBytes(part.hi - part.low + 1) i = part.hi + 1 T.equal bytes.toString('hex'), part.bytes.toLowerCase(), "Case #{i}: #{test.desc}" run_tests = (T, which, cb) -> for test,i in data[which] test_case T, i, test cb() exports.key256 = (T, cb) -> run_tests T, 'key256', cb exports.key128 = (T, cb) -> run_tests T, 'key128', cb exports.nonce192 = (T, cb) -> # From here: # https://code.google.com/p/go/source/browse/salsa20/salsa20_test.go?repo=crypto # v = "nonce" : "24-byte nonce for xsalsa" "key" : "this is 32-byte key for xsalsa20" "ciphertext" : [ 0x48, 0x48, 0x29, 0x7f, 0xeb, 0x1f, 0xb5, 0x2f, 0xb6, 0x6d, 0x81, 0x60, 0x9b, 0xd5, 0x47, 0xfa, 0xbc, 0xbe, 0x70, 0x26, 0xed, 0xc8, 0xb5, 0xe5, 0xe4, 0x49, 0xd0, 0x88, 0xbf, 0xa6, 0x9c, 0x08, 0x8f, 0x5d, 0x8d, 0xa1, 0xd7, 0x91, 0x26, 0x7c, 0x2c, 0x19, 0x5a, 0x7f, 0x8c, 0xae, 0x9c, 0x4b, 0x40, 0x50, 0xd0, 0x8c, 0xe6, 0xd3, 0xa1, 0x51, 0xec, 0x26, 0x5f, 0x3a, 0x58, 0xe4, 0x76, 0x48 ] nonce = WordArray.from_utf8 v.nonce key = WordArray.from_utf8 v.key ctext = Buffer.from(v.ciphertext).toString('hex') stream = new Salsa20 key, nonce bytes = stream.getBytes(v.ciphertext.length).toString('hex') T.equal bytes, ctext, "test from salsa20.go" cb() exports.test_slicing = (T,cb) -> v = data.key256[data.key256.length - 1] key = WordArray.from_hex v.key iv = WordArray.from_hex v.IV n = 64 stream = new Salsa20 key, iv reference = (stream.getBytes().toString('hex') for i in [0...n]).join('') stream = new Salsa20 key, iv big = stream.getBytes(n*n).toString('hex') T.equal big, reference, 'all at once works' stream = new Salsa20 key, iv sz = 8 nibbles = (stream.getBytes(sz).toString('hex') for i in [0...(n*64/sz)]).join('') T.equal big, nibbles, 'works in small nibbles' stream = new Salsa20 key, iv odd = (stream.getBytes(7).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 7" stream = new Salsa20 key, iv odd = (stream.getBytes(17).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 17" randos = [ [56,207,186,128,22,145,254,246,71,12,102,103,91,204,61,143,146,192,80], [252,226,56,65,10,74,108,3,153,154,92,230,195,180,124,146,215,180,170], [202,154,234,221,147,25,114,50,232,160,201,71,146,74,77,153,122,136,241], [106,120,187,8,144,131,101,195,208,146,113,28,124,203,90,39,126,106,181], [143,113,158,148,76,135,91,102,175,112,102,189,148,41,155,197,58,101,142], [5,249,193,54,187,73,62,83,201,127,238,210,118,248,165,112,105,21,136], [2,218,113,183,85,132,159,132,90,181,89,62,185,175,253,38,15,35,149], [126,128,107,160,167,17,239,187,106,42,175,97,49,10,229,150,200,236,227], [224,176,32,105,156,180,238,208,74,24,19,131,29,138,35,244,223,87,232], [221,254,40,17,232,82,246,126,94,18,122,48,66,2,223,117,85,97,20] ] for seq in randos stream = new Salsa20 key, iv rand = (stream.getBytes(i).toString('hex') for i in seq).join('') T.equal rand, reference[0...(rand.length)], "on random boundaries" cb()
39598
data = key128 : require('../data/salsa20_key128').data key256 : require('../data/salsa20_key256').data {Salsa20} = require '../../lib/salsa20' {WordArray} = require '../../lib/wordarray' test_case = (T, i, test) -> key = WordArray.from_hex test.key iv = WordArray.from_hex test.IV stream = new Salsa20 key, iv i = 0 for part in test.stream if i < part.low stream.getBytes(part.low - i) bytes = stream.getBytes(part.hi - part.low + 1) i = part.hi + 1 T.equal bytes.toString('hex'), part.bytes.toLowerCase(), "Case #{i}: #{test.desc}" run_tests = (T, which, cb) -> for test,i in data[which] test_case T, i, test cb() exports.key256 = (T, cb) -> run_tests T, 'key256', cb exports.key128 = (T, cb) -> run_tests T, 'key128', cb exports.nonce192 = (T, cb) -> # From here: # https://code.google.com/p/go/source/browse/salsa20/salsa20_test.go?repo=crypto # v = "nonce" : "24-byte nonce for xsalsa" "key" : "<KEY> <KEY>-<KEY> <KEY>" "ciphertext" : [ 0x48, 0x48, 0x29, 0x7f, 0xeb, 0x1f, 0xb5, 0x2f, 0xb6, 0x6d, 0x81, 0x60, 0x9b, 0xd5, 0x47, 0xfa, 0xbc, 0xbe, 0x70, 0x26, 0xed, 0xc8, 0xb5, 0xe5, 0xe4, 0x49, 0xd0, 0x88, 0xbf, 0xa6, 0x9c, 0x08, 0x8f, 0x5d, 0x8d, 0xa1, 0xd7, 0x91, 0x26, 0x7c, 0x2c, 0x19, 0x5a, 0x7f, 0x8c, 0xae, 0x9c, 0x4b, 0x40, 0x50, 0xd0, 0x8c, 0xe6, 0xd3, 0xa1, 0x51, 0xec, 0x26, 0x5f, 0x3a, 0x58, 0xe4, 0x76, 0x48 ] nonce = WordArray.from_utf8 v.nonce key = WordArray.from_utf8 v.key ctext = Buffer.from(v.ciphertext).toString('hex') stream = new Salsa20 key, nonce bytes = stream.getBytes(v.ciphertext.length).toString('hex') T.equal bytes, ctext, "test from salsa20.go" cb() exports.test_slicing = (T,cb) -> v = data.key256[data.key256.length - 1] key = WordArray.from_hex v.key iv = WordArray.from_hex v.IV n = 64 stream = new Salsa20 key, iv reference = (stream.getBytes().toString('hex') for i in [0...n]).join('') stream = new Salsa20 key, iv big = stream.getBytes(n*n).toString('hex') T.equal big, reference, 'all at once works' stream = new Salsa20 key, iv sz = 8 nibbles = (stream.getBytes(sz).toString('hex') for i in [0...(n*64/sz)]).join('') T.equal big, nibbles, 'works in small nibbles' stream = new Salsa20 key, iv odd = (stream.getBytes(7).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 7" stream = new Salsa20 key, iv odd = (stream.getBytes(17).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 17" randos = [ [56,207,186,128,22,145,254,246,71,12,102,103,91,204,61,143,146,192,80], [252,226,56,65,10,74,108,3,153,154,92,230,195,180,124,146,215,180,170], [202,154,234,221,147,25,114,50,232,160,201,71,146,74,77,153,122,136,241], [106,120,187,8,144,131,101,195,208,146,113,28,124,203,90,39,126,106,181], [143,113,158,148,76,135,91,102,175,112,102,189,148,41,155,197,58,101,142], [5,249,193,54,187,73,62,83,201,127,238,210,118,248,165,112,105,21,136], [2,218,113,183,85,132,159,132,90,181,89,62,185,175,253,38,15,35,149], [126,128,107,160,167,17,239,187,106,42,175,97,49,10,229,150,200,236,227], [224,176,32,105,156,180,238,208,74,24,19,131,29,138,35,244,223,87,232], [221,254,40,17,232,82,246,126,94,18,122,48,66,2,223,117,85,97,20] ] for seq in randos stream = new Salsa20 key, iv rand = (stream.getBytes(i).toString('hex') for i in seq).join('') T.equal rand, reference[0...(rand.length)], "on random boundaries" cb()
true
data = key128 : require('../data/salsa20_key128').data key256 : require('../data/salsa20_key256').data {Salsa20} = require '../../lib/salsa20' {WordArray} = require '../../lib/wordarray' test_case = (T, i, test) -> key = WordArray.from_hex test.key iv = WordArray.from_hex test.IV stream = new Salsa20 key, iv i = 0 for part in test.stream if i < part.low stream.getBytes(part.low - i) bytes = stream.getBytes(part.hi - part.low + 1) i = part.hi + 1 T.equal bytes.toString('hex'), part.bytes.toLowerCase(), "Case #{i}: #{test.desc}" run_tests = (T, which, cb) -> for test,i in data[which] test_case T, i, test cb() exports.key256 = (T, cb) -> run_tests T, 'key256', cb exports.key128 = (T, cb) -> run_tests T, 'key128', cb exports.nonce192 = (T, cb) -> # From here: # https://code.google.com/p/go/source/browse/salsa20/salsa20_test.go?repo=crypto # v = "nonce" : "24-byte nonce for xsalsa" "key" : "PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI-PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI" "ciphertext" : [ 0x48, 0x48, 0x29, 0x7f, 0xeb, 0x1f, 0xb5, 0x2f, 0xb6, 0x6d, 0x81, 0x60, 0x9b, 0xd5, 0x47, 0xfa, 0xbc, 0xbe, 0x70, 0x26, 0xed, 0xc8, 0xb5, 0xe5, 0xe4, 0x49, 0xd0, 0x88, 0xbf, 0xa6, 0x9c, 0x08, 0x8f, 0x5d, 0x8d, 0xa1, 0xd7, 0x91, 0x26, 0x7c, 0x2c, 0x19, 0x5a, 0x7f, 0x8c, 0xae, 0x9c, 0x4b, 0x40, 0x50, 0xd0, 0x8c, 0xe6, 0xd3, 0xa1, 0x51, 0xec, 0x26, 0x5f, 0x3a, 0x58, 0xe4, 0x76, 0x48 ] nonce = WordArray.from_utf8 v.nonce key = WordArray.from_utf8 v.key ctext = Buffer.from(v.ciphertext).toString('hex') stream = new Salsa20 key, nonce bytes = stream.getBytes(v.ciphertext.length).toString('hex') T.equal bytes, ctext, "test from salsa20.go" cb() exports.test_slicing = (T,cb) -> v = data.key256[data.key256.length - 1] key = WordArray.from_hex v.key iv = WordArray.from_hex v.IV n = 64 stream = new Salsa20 key, iv reference = (stream.getBytes().toString('hex') for i in [0...n]).join('') stream = new Salsa20 key, iv big = stream.getBytes(n*n).toString('hex') T.equal big, reference, 'all at once works' stream = new Salsa20 key, iv sz = 8 nibbles = (stream.getBytes(sz).toString('hex') for i in [0...(n*64/sz)]).join('') T.equal big, nibbles, 'works in small nibbles' stream = new Salsa20 key, iv odd = (stream.getBytes(7).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 7" stream = new Salsa20 key, iv odd = (stream.getBytes(17).toString('hex') for i in [0...100]).join('') T.equal odd, reference[0...(odd.length)], "on odd boundaries of 17" randos = [ [56,207,186,128,22,145,254,246,71,12,102,103,91,204,61,143,146,192,80], [252,226,56,65,10,74,108,3,153,154,92,230,195,180,124,146,215,180,170], [202,154,234,221,147,25,114,50,232,160,201,71,146,74,77,153,122,136,241], [106,120,187,8,144,131,101,195,208,146,113,28,124,203,90,39,126,106,181], [143,113,158,148,76,135,91,102,175,112,102,189,148,41,155,197,58,101,142], [5,249,193,54,187,73,62,83,201,127,238,210,118,248,165,112,105,21,136], [2,218,113,183,85,132,159,132,90,181,89,62,185,175,253,38,15,35,149], [126,128,107,160,167,17,239,187,106,42,175,97,49,10,229,150,200,236,227], [224,176,32,105,156,180,238,208,74,24,19,131,29,138,35,244,223,87,232], [221,254,40,17,232,82,246,126,94,18,122,48,66,2,223,117,85,97,20] ] for seq in randos stream = new Salsa20 key, iv rand = (stream.getBytes(i).toString('hex') for i in seq).join('') T.equal rand, reference[0...(rand.length)], "on random boundaries" cb()
[ { "context": "ould have a name', ->\n @foo.name.should.equal 'Acute Pharyngitis'\n\n it 'should execute to the defined value set',", "end": 1019, "score": 0.9992696642875671, "start": 1002, "tag": "NAME", "value": "Acute Pharyngitis" }, { "context": " setup @, data, [], vsets\n\n it 'should find that John is not female', ->\n @ctx.patient = new Patien", "end": 2355, "score": 0.9675527215003967, "start": 2351, "tag": "NAME", "value": "John" }, { "context": "ec(@ctx).should.be.false()\n\n it 'should find that Sally is female', ->\n @ctx.patient = new PatientSou", "end": 2510, "score": 0.9708786010742188, "start": 2505, "tag": "NAME", "value": "Sally" } ]
Src/coffeescript/cql-execution/test/elm/clinical/test.coffee
MeasureAuthoringTool/clinical_quality_language
2
should = require 'should' setup = require '../../setup' data = require './data' vsets = require './valuesets' { p1, p2 } = require './patients' { PatientSource} = require '../../../lib/cql-patient' describe 'ValueSetDef', -> @beforeEach -> setup @, data, [], vsets it 'should return a resolved value set when the codeService knows about it', -> vs = @known.exec(@ctx) vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061' vs.version.should.equal '20140501' vs.codes.length.should.equal 3 it 'should execute one-arg to ValueSet with ID', -> vs = @['unknown One Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' should.not.exist vs.version it 'should execute two-arg to ValueSet with ID and version', -> vs = @['unknown Two Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' vs.version.should.equal '1' describe 'ValueSetRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Acute Pharyngitis' it 'should execute to the defined value set', -> @foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001' describe 'InValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find string code in value set', -> @string.exec(@ctx).should.be.true() it 'should find string code in versioned value set', -> @stringInVersionedValueSet.exec(@ctx).should.be.true() it 'should find short code in value set', -> @shortCode.exec(@ctx).should.be.true() it 'should find medium code in value set', -> @mediumCode.exec(@ctx).should.be.true() it 'should find long code in value set', -> @longCode.exec(@ctx).should.be.true() it 'should not find string code in value set', -> @wrongString.exec(@ctx).should.be.false() it 'should not find string code in versioned value set', -> @wrongStringInVersionedValueSet.exec(@ctx).should.be.false() it 'should not find short code in value set', -> @wrongShortCode.exec(@ctx).should.be.false() it 'should not find medium code in value set', -> @wrongMediumCode.exec(@ctx).should.be.false() it 'should not find long code in value set', -> @wrongLongCode.exec(@ctx).should.be.false() describe 'Patient Property In ValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find that John is not female', -> @ctx.patient = new PatientSource([ p1 ]).currentPatient() @isFemale.exec(@ctx).should.be.false() it 'should find that Sally is female', -> @ctx.patient = new PatientSource([ p2 ]).currentPatient() @isFemale.exec(@ctx).should.be.true() describe 'CodeDef', -> @beforeEach -> setup @, data, [] it 'should return a CodeDef', -> codeDef = @lib.getCode('Tobacco smoking status code') codeDef.constructor.name.should.equal 'CodeDef' codeDef.name.should.equal 'Tobacco smoking status code' it 'should execute to a Code datatype', -> codeDef = @lib.getCode('Tobacco smoking status code') code = codeDef.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'CodeRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status code' it 'should execute to the defined code', -> code = @foo.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'ConceptDef', -> @beforeEach -> setup @, data, [] it 'should return a ConceptDef', -> conceptDef = @lib.getConcept('Tobacco smoking status') conceptDef.constructor.name.should.equal 'ConceptDef' conceptDef.name.should.equal 'Tobacco smoking status' it 'should execute to a Concept datatype', -> conceptDef = @lib.getConcept('Tobacco smoking status') concept = conceptDef.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'ConceptRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status' it 'should execute to the defined concept', -> concept = @foo.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'CalculateAge', -> @beforeEach -> setup @, data, [ p1 ] # Note, tests are inexact (otherwise test needs to repeat exact logic we're testing) # p1 birth date is 1980-06-17 @bday = new Date(1980, 5, 17) @today = new Date() # according to spec, dates without timezones are in *current* time offset, so need to adjust offsetDiff = @today.getTimezoneOffset() - @bday.getTimezoneOffset() @bday.setMinutes(@bday.getMinutes() + offsetDiff) # this is getting the possible number of months in years with the addtion of an offset # to get the correct number of months month_offset = if @today.getMonth() == 5 && @today.getDate() < 17 then 6 else 5 @full_months = ((@today.getFullYear() - 1980) * 12) + (@today.getMonth() - month_offset) @timediff = @today - @bday # diff in milliseconds it 'should execute age in years', -> @years.exec(@ctx).should.equal @full_months // 12 it 'should execute age in months', -> @months.exec(@ctx).should.equal @full_months it 'should execute age in days', -> @days.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 // 24 it 'should execute age in hours', -> # a little strange since the qicore data model specified birthDate as a date (no time) @hours.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 it 'should execute age in minutes', -> # a little strange since the qicore data model specified birthDate as a date (no time) @minutes.exec(@ctx).should.equal @timediff // 1000 // 60 it 'should execute age in seconds', -> # a little strange since the qicore data model specified birthDate as a date (no time) @seconds.exec(@ctx).should.equal @timediff // 1000 describe 'CalculateAgeAt', -> @beforeEach -> setup @, data, [ p1 ] it 'should execute age at 2012 as 31', -> @ageAt2012.exec(@ctx).should.equal 31 it 'should execute age at 19810216 as 0', -> @ageAt19810216.exec(@ctx).should.equal 0 it 'should execute age at 1975 as -5', -> @ageAt19810216.exec(@ctx).should.equal 0
125050
should = require 'should' setup = require '../../setup' data = require './data' vsets = require './valuesets' { p1, p2 } = require './patients' { PatientSource} = require '../../../lib/cql-patient' describe 'ValueSetDef', -> @beforeEach -> setup @, data, [], vsets it 'should return a resolved value set when the codeService knows about it', -> vs = @known.exec(@ctx) vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061' vs.version.should.equal '20140501' vs.codes.length.should.equal 3 it 'should execute one-arg to ValueSet with ID', -> vs = @['unknown One Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' should.not.exist vs.version it 'should execute two-arg to ValueSet with ID and version', -> vs = @['unknown Two Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' vs.version.should.equal '1' describe 'ValueSetRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal '<NAME>' it 'should execute to the defined value set', -> @foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001' describe 'InValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find string code in value set', -> @string.exec(@ctx).should.be.true() it 'should find string code in versioned value set', -> @stringInVersionedValueSet.exec(@ctx).should.be.true() it 'should find short code in value set', -> @shortCode.exec(@ctx).should.be.true() it 'should find medium code in value set', -> @mediumCode.exec(@ctx).should.be.true() it 'should find long code in value set', -> @longCode.exec(@ctx).should.be.true() it 'should not find string code in value set', -> @wrongString.exec(@ctx).should.be.false() it 'should not find string code in versioned value set', -> @wrongStringInVersionedValueSet.exec(@ctx).should.be.false() it 'should not find short code in value set', -> @wrongShortCode.exec(@ctx).should.be.false() it 'should not find medium code in value set', -> @wrongMediumCode.exec(@ctx).should.be.false() it 'should not find long code in value set', -> @wrongLongCode.exec(@ctx).should.be.false() describe 'Patient Property In ValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find that <NAME> is not female', -> @ctx.patient = new PatientSource([ p1 ]).currentPatient() @isFemale.exec(@ctx).should.be.false() it 'should find that <NAME> is female', -> @ctx.patient = new PatientSource([ p2 ]).currentPatient() @isFemale.exec(@ctx).should.be.true() describe 'CodeDef', -> @beforeEach -> setup @, data, [] it 'should return a CodeDef', -> codeDef = @lib.getCode('Tobacco smoking status code') codeDef.constructor.name.should.equal 'CodeDef' codeDef.name.should.equal 'Tobacco smoking status code' it 'should execute to a Code datatype', -> codeDef = @lib.getCode('Tobacco smoking status code') code = codeDef.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'CodeRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status code' it 'should execute to the defined code', -> code = @foo.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'ConceptDef', -> @beforeEach -> setup @, data, [] it 'should return a ConceptDef', -> conceptDef = @lib.getConcept('Tobacco smoking status') conceptDef.constructor.name.should.equal 'ConceptDef' conceptDef.name.should.equal 'Tobacco smoking status' it 'should execute to a Concept datatype', -> conceptDef = @lib.getConcept('Tobacco smoking status') concept = conceptDef.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'ConceptRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status' it 'should execute to the defined concept', -> concept = @foo.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'CalculateAge', -> @beforeEach -> setup @, data, [ p1 ] # Note, tests are inexact (otherwise test needs to repeat exact logic we're testing) # p1 birth date is 1980-06-17 @bday = new Date(1980, 5, 17) @today = new Date() # according to spec, dates without timezones are in *current* time offset, so need to adjust offsetDiff = @today.getTimezoneOffset() - @bday.getTimezoneOffset() @bday.setMinutes(@bday.getMinutes() + offsetDiff) # this is getting the possible number of months in years with the addtion of an offset # to get the correct number of months month_offset = if @today.getMonth() == 5 && @today.getDate() < 17 then 6 else 5 @full_months = ((@today.getFullYear() - 1980) * 12) + (@today.getMonth() - month_offset) @timediff = @today - @bday # diff in milliseconds it 'should execute age in years', -> @years.exec(@ctx).should.equal @full_months // 12 it 'should execute age in months', -> @months.exec(@ctx).should.equal @full_months it 'should execute age in days', -> @days.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 // 24 it 'should execute age in hours', -> # a little strange since the qicore data model specified birthDate as a date (no time) @hours.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 it 'should execute age in minutes', -> # a little strange since the qicore data model specified birthDate as a date (no time) @minutes.exec(@ctx).should.equal @timediff // 1000 // 60 it 'should execute age in seconds', -> # a little strange since the qicore data model specified birthDate as a date (no time) @seconds.exec(@ctx).should.equal @timediff // 1000 describe 'CalculateAgeAt', -> @beforeEach -> setup @, data, [ p1 ] it 'should execute age at 2012 as 31', -> @ageAt2012.exec(@ctx).should.equal 31 it 'should execute age at 19810216 as 0', -> @ageAt19810216.exec(@ctx).should.equal 0 it 'should execute age at 1975 as -5', -> @ageAt19810216.exec(@ctx).should.equal 0
true
should = require 'should' setup = require '../../setup' data = require './data' vsets = require './valuesets' { p1, p2 } = require './patients' { PatientSource} = require '../../../lib/cql-patient' describe 'ValueSetDef', -> @beforeEach -> setup @, data, [], vsets it 'should return a resolved value set when the codeService knows about it', -> vs = @known.exec(@ctx) vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061' vs.version.should.equal '20140501' vs.codes.length.should.equal 3 it 'should execute one-arg to ValueSet with ID', -> vs = @['unknown One Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' should.not.exist vs.version it 'should execute two-arg to ValueSet with ID and version', -> vs = @['unknown Two Arg'].exec(@ctx) vs.oid.should.equal '1.2.3.4.5.6.7.8.9' vs.version.should.equal '1' describe 'ValueSetRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'PI:NAME:<NAME>END_PI' it 'should execute to the defined value set', -> @foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001' describe 'InValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find string code in value set', -> @string.exec(@ctx).should.be.true() it 'should find string code in versioned value set', -> @stringInVersionedValueSet.exec(@ctx).should.be.true() it 'should find short code in value set', -> @shortCode.exec(@ctx).should.be.true() it 'should find medium code in value set', -> @mediumCode.exec(@ctx).should.be.true() it 'should find long code in value set', -> @longCode.exec(@ctx).should.be.true() it 'should not find string code in value set', -> @wrongString.exec(@ctx).should.be.false() it 'should not find string code in versioned value set', -> @wrongStringInVersionedValueSet.exec(@ctx).should.be.false() it 'should not find short code in value set', -> @wrongShortCode.exec(@ctx).should.be.false() it 'should not find medium code in value set', -> @wrongMediumCode.exec(@ctx).should.be.false() it 'should not find long code in value set', -> @wrongLongCode.exec(@ctx).should.be.false() describe 'Patient Property In ValueSet', -> @beforeEach -> setup @, data, [], vsets it 'should find that PI:NAME:<NAME>END_PI is not female', -> @ctx.patient = new PatientSource([ p1 ]).currentPatient() @isFemale.exec(@ctx).should.be.false() it 'should find that PI:NAME:<NAME>END_PI is female', -> @ctx.patient = new PatientSource([ p2 ]).currentPatient() @isFemale.exec(@ctx).should.be.true() describe 'CodeDef', -> @beforeEach -> setup @, data, [] it 'should return a CodeDef', -> codeDef = @lib.getCode('Tobacco smoking status code') codeDef.constructor.name.should.equal 'CodeDef' codeDef.name.should.equal 'Tobacco smoking status code' it 'should execute to a Code datatype', -> codeDef = @lib.getCode('Tobacco smoking status code') code = codeDef.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'CodeRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status code' it 'should execute to the defined code', -> code = @foo.exec(@ctx) code.code.should.equal('72166-2') code.system.should.equal('http://loinc.org') should.not.exist(code.version) code.display.should.equal('Tobacco smoking status') describe 'ConceptDef', -> @beforeEach -> setup @, data, [] it 'should return a ConceptDef', -> conceptDef = @lib.getConcept('Tobacco smoking status') conceptDef.constructor.name.should.equal 'ConceptDef' conceptDef.name.should.equal 'Tobacco smoking status' it 'should execute to a Concept datatype', -> conceptDef = @lib.getConcept('Tobacco smoking status') concept = conceptDef.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'ConceptRef', -> @beforeEach -> setup @, data it 'should have a name', -> @foo.name.should.equal 'Tobacco smoking status' it 'should execute to the defined concept', -> concept = @foo.exec(@ctx) concept.text.should.equal('Tobacco smoking status') concept.codes.should.have.length(1) concept.codes[0].code.should.equal('72166-2') concept.codes[0].system.should.equal('http://loinc.org') should.not.exist(concept.codes[0].version) concept.codes[0].display.should.equal('Tobacco smoking status') describe 'CalculateAge', -> @beforeEach -> setup @, data, [ p1 ] # Note, tests are inexact (otherwise test needs to repeat exact logic we're testing) # p1 birth date is 1980-06-17 @bday = new Date(1980, 5, 17) @today = new Date() # according to spec, dates without timezones are in *current* time offset, so need to adjust offsetDiff = @today.getTimezoneOffset() - @bday.getTimezoneOffset() @bday.setMinutes(@bday.getMinutes() + offsetDiff) # this is getting the possible number of months in years with the addtion of an offset # to get the correct number of months month_offset = if @today.getMonth() == 5 && @today.getDate() < 17 then 6 else 5 @full_months = ((@today.getFullYear() - 1980) * 12) + (@today.getMonth() - month_offset) @timediff = @today - @bday # diff in milliseconds it 'should execute age in years', -> @years.exec(@ctx).should.equal @full_months // 12 it 'should execute age in months', -> @months.exec(@ctx).should.equal @full_months it 'should execute age in days', -> @days.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 // 24 it 'should execute age in hours', -> # a little strange since the qicore data model specified birthDate as a date (no time) @hours.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 it 'should execute age in minutes', -> # a little strange since the qicore data model specified birthDate as a date (no time) @minutes.exec(@ctx).should.equal @timediff // 1000 // 60 it 'should execute age in seconds', -> # a little strange since the qicore data model specified birthDate as a date (no time) @seconds.exec(@ctx).should.equal @timediff // 1000 describe 'CalculateAgeAt', -> @beforeEach -> setup @, data, [ p1 ] it 'should execute age at 2012 as 31', -> @ageAt2012.exec(@ctx).should.equal 31 it 'should execute age at 19810216 as 0', -> @ageAt19810216.exec(@ctx).should.equal 0 it 'should execute age at 1975 as -5', -> @ageAt19810216.exec(@ctx).should.equal 0
[ { "context": "ubot ignore me\n#\n# Notes:\n# None\n#\n# Author:\n# Brian Shumate <brian@couchbase.com>\n\nignore = [\n \"http://3.bp.", "end": 196, "score": 0.9998812675476074, "start": 183, "tag": "NAME", "value": "Brian Shumate" }, { "context": "\n# Notes:\n# None\n#\n# Author:\n# Brian Shumate <brian@couchbase.com>\n\nignore = [\n \"http://3.bp.blogspot.com/-DFLMK7f", "end": 217, "score": 0.9999278783798218, "start": 198, "tag": "EMAIL", "value": "brian@couchbase.com" } ]
files/scripts/ignoreme.coffee
AAROC/the-boss-role
0
# Description: # Displays Venture Bros IGNORE ME! image # # Dependencies: # None # # Configuration: # None # # Commands: # hubot ignore me # # Notes: # None # # Author: # Brian Shumate <brian@couchbase.com> ignore = [ "http://3.bp.blogspot.com/-DFLMK7ffcJM/Tbjn752gOFI/AAAAAAAAAsk/qa7D5ZdQDgM/s1600/1301856749331.jpg", "http://venturebrosblog.com/wp-content/uploads/2011/02/venture-bros-ignore-me1.jpg", "http://memedepot.com/uploads/2000/2159_1272950412470.jpg" ] module.exports = (robot) -> robot.hear /ignore me/i, (msg)-> msg.send msg.random ignore
12964
# Description: # Displays Venture Bros IGNORE ME! image # # Dependencies: # None # # Configuration: # None # # Commands: # hubot ignore me # # Notes: # None # # Author: # <NAME> <<EMAIL>> ignore = [ "http://3.bp.blogspot.com/-DFLMK7ffcJM/Tbjn752gOFI/AAAAAAAAAsk/qa7D5ZdQDgM/s1600/1301856749331.jpg", "http://venturebrosblog.com/wp-content/uploads/2011/02/venture-bros-ignore-me1.jpg", "http://memedepot.com/uploads/2000/2159_1272950412470.jpg" ] module.exports = (robot) -> robot.hear /ignore me/i, (msg)-> msg.send msg.random ignore
true
# Description: # Displays Venture Bros IGNORE ME! image # # Dependencies: # None # # Configuration: # None # # Commands: # hubot ignore me # # Notes: # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ignore = [ "http://3.bp.blogspot.com/-DFLMK7ffcJM/Tbjn752gOFI/AAAAAAAAAsk/qa7D5ZdQDgM/s1600/1301856749331.jpg", "http://venturebrosblog.com/wp-content/uploads/2011/02/venture-bros-ignore-me1.jpg", "http://memedepot.com/uploads/2000/2159_1272950412470.jpg" ] module.exports = (robot) -> robot.hear /ignore me/i, (msg)-> msg.send msg.random ignore
[ { "context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################", "end": 99, "score": 0.9990456700325012, "start": 93, "tag": "NAME", "value": "Markus" } ]
server/publications/challenge.coffee
agottschalk10/worklearn
0
####################################################### # # Moocita collections # Created by Markus on 26/10/2015. # ####################################################### ####################################################### # item header ####################################################### ####################################################### _challenge_fields = fields: title: 1 content: 1 material: 1 owner_id: 1 published: 1 num_reviews: 1 ####################################################### # helper ####################################################### ####################################################### _get_solution_data = (solution_id) -> solution = Solutions.findOne solution_id entry = _get_profile_data solution.owner_id, {} entry.content = solution.content entry.material = solution.material entry.published = solution.published entry = _get_reviews_data solution_id, entry return entry ####################################################### _get_reviews_data = (solution_id, entry) -> filter = solution_id: solution_id published: true options = fields: rating: 1 content: 1 owner_id: 1 review_cursor = Reviews.find filter, options reviews = [] avg = 0 nt = 0 review_cursor.forEach (review) -> r = _get_profile_data review.owner_id, {} r = _get_feedback_data review._id, r r.content = review.content r.rating = review.rating reviews.push r avg += parseInt(r.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["reviews"] = reviews entry["average_rating"] = avg return entry ####################################################### _get_feedback_data = (review_id, entry) -> filter = review_id: review_id published: true options = fields: rating: 1 content: 1 owner_id: 1 feedback_cursor = Feedback.find filter, options feedback = [] avg = 0 nt = 0 feedback_cursor.forEach (fdb) -> f = _get_profile_data fdb.owner_id, {} f.content = fdb.content f.rating = fdb.rating feedback.push f avg += parseInt(f.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["feedback"] = feedback entry["average_rating"] = avg return entry ####################################################### _get_profile_data = (user_id, entry) -> filter = owner_id: user_id profile = Profiles.findOne filter if profile entry["name"] = get_profile_name profile, false, false entry["avatar"] = get_avatar profile return entry ####################################################### # challenges ####################################################### ####################################################### Meteor.publish "challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId filter = filter_visible_documents user_id crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "challenges", user_id return crs ####################################################### Meteor.publish "my_challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId restrict = owner_id: user_id filter = filter_visible_documents user_id, restrict crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "my_challenges", user_id return crs ####################################################### Meteor.publish "challenge_by_id", (challenge_id) -> check challenge_id, String user_id = this.userId restrict = _id: challenge_id published: true filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "challenge_by_id", user_id return crs ####################################################### Meteor.publish "my_challenge_by_id", (challenge_id) -> user_id = this.userId restrict = _id:challenge_id owner_id: user_id filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "my_challenge_by_id", user_id return crs ####################################################### Meteor.publish "challenge_summaries", (parameter) -> pattern = challenge_id: String published: Match.Optional(Boolean) query: Match.Optional(String) page: Number size: Number check parameter, pattern if parameter.size>50 throw Meteor.Error("Size values larger than 50 are not allowed.") user_id = this.userId challenge = Challenges.findOne parameter.challenge_id if challenge.owner_id != user_id throw Meteor.Error("Not permitted.") filter = challenge_id: parameter.challenge_id if parameter.published filter.published = parameter.published mod = fields: content: 1 material: 1 owner_id: 1 published: 1 challenge_id: 1 solution_ids = new Set() profile_ids = new Set() ############################################## # retrieving solutions ############################################## ############################################## solution_cursor = find_documents_paged_unprotected Solutions, filter, mod, parameter solution_cursor.forEach (solution) -> solution_ids.add solution._id profile_ids.add solution.owner_id ############################################## # retrieving reviews ############################################## # resetting the filter solution_ids = Array.from(solution_ids) filter = solution_id: $in: solution_ids mod = fields: rating: 1 content: 1 owner_id: 1 published: 1 challenge_id: 1 solution_id: 1 review_id: 1 owner_id: 1 ############################################## review_cursor = Reviews.find(filter, mod) review_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving feedback ############################################## ############################################## feedback_cursor = Feedback.find(filter, mod) feedback_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving profiles ############################################## # resetting the filter profile_ids = Array.from(profile_ids) filter = owner_id: $in: profile_ids mod = fields: resume: 1 published: 1 given_name: 1 middle_name: 1 family_name: 1 owner_id: 1 avatar: 1 ############################################## profile_cursor = Profiles.find(filter, mod) log_publication "Multiple Cursor", null, {}, {}, "challenge_summaries", user_id return [solution_cursor, review_cursor, feedback_cursor, profile_cursor]
213437
####################################################### # # Moocita collections # Created by <NAME> on 26/10/2015. # ####################################################### ####################################################### # item header ####################################################### ####################################################### _challenge_fields = fields: title: 1 content: 1 material: 1 owner_id: 1 published: 1 num_reviews: 1 ####################################################### # helper ####################################################### ####################################################### _get_solution_data = (solution_id) -> solution = Solutions.findOne solution_id entry = _get_profile_data solution.owner_id, {} entry.content = solution.content entry.material = solution.material entry.published = solution.published entry = _get_reviews_data solution_id, entry return entry ####################################################### _get_reviews_data = (solution_id, entry) -> filter = solution_id: solution_id published: true options = fields: rating: 1 content: 1 owner_id: 1 review_cursor = Reviews.find filter, options reviews = [] avg = 0 nt = 0 review_cursor.forEach (review) -> r = _get_profile_data review.owner_id, {} r = _get_feedback_data review._id, r r.content = review.content r.rating = review.rating reviews.push r avg += parseInt(r.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["reviews"] = reviews entry["average_rating"] = avg return entry ####################################################### _get_feedback_data = (review_id, entry) -> filter = review_id: review_id published: true options = fields: rating: 1 content: 1 owner_id: 1 feedback_cursor = Feedback.find filter, options feedback = [] avg = 0 nt = 0 feedback_cursor.forEach (fdb) -> f = _get_profile_data fdb.owner_id, {} f.content = fdb.content f.rating = fdb.rating feedback.push f avg += parseInt(f.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["feedback"] = feedback entry["average_rating"] = avg return entry ####################################################### _get_profile_data = (user_id, entry) -> filter = owner_id: user_id profile = Profiles.findOne filter if profile entry["name"] = get_profile_name profile, false, false entry["avatar"] = get_avatar profile return entry ####################################################### # challenges ####################################################### ####################################################### Meteor.publish "challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId filter = filter_visible_documents user_id crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "challenges", user_id return crs ####################################################### Meteor.publish "my_challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId restrict = owner_id: user_id filter = filter_visible_documents user_id, restrict crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "my_challenges", user_id return crs ####################################################### Meteor.publish "challenge_by_id", (challenge_id) -> check challenge_id, String user_id = this.userId restrict = _id: challenge_id published: true filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "challenge_by_id", user_id return crs ####################################################### Meteor.publish "my_challenge_by_id", (challenge_id) -> user_id = this.userId restrict = _id:challenge_id owner_id: user_id filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "my_challenge_by_id", user_id return crs ####################################################### Meteor.publish "challenge_summaries", (parameter) -> pattern = challenge_id: String published: Match.Optional(Boolean) query: Match.Optional(String) page: Number size: Number check parameter, pattern if parameter.size>50 throw Meteor.Error("Size values larger than 50 are not allowed.") user_id = this.userId challenge = Challenges.findOne parameter.challenge_id if challenge.owner_id != user_id throw Meteor.Error("Not permitted.") filter = challenge_id: parameter.challenge_id if parameter.published filter.published = parameter.published mod = fields: content: 1 material: 1 owner_id: 1 published: 1 challenge_id: 1 solution_ids = new Set() profile_ids = new Set() ############################################## # retrieving solutions ############################################## ############################################## solution_cursor = find_documents_paged_unprotected Solutions, filter, mod, parameter solution_cursor.forEach (solution) -> solution_ids.add solution._id profile_ids.add solution.owner_id ############################################## # retrieving reviews ############################################## # resetting the filter solution_ids = Array.from(solution_ids) filter = solution_id: $in: solution_ids mod = fields: rating: 1 content: 1 owner_id: 1 published: 1 challenge_id: 1 solution_id: 1 review_id: 1 owner_id: 1 ############################################## review_cursor = Reviews.find(filter, mod) review_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving feedback ############################################## ############################################## feedback_cursor = Feedback.find(filter, mod) feedback_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving profiles ############################################## # resetting the filter profile_ids = Array.from(profile_ids) filter = owner_id: $in: profile_ids mod = fields: resume: 1 published: 1 given_name: 1 middle_name: 1 family_name: 1 owner_id: 1 avatar: 1 ############################################## profile_cursor = Profiles.find(filter, mod) log_publication "Multiple Cursor", null, {}, {}, "challenge_summaries", user_id return [solution_cursor, review_cursor, feedback_cursor, profile_cursor]
true
####################################################### # # Moocita collections # Created by PI:NAME:<NAME>END_PI on 26/10/2015. # ####################################################### ####################################################### # item header ####################################################### ####################################################### _challenge_fields = fields: title: 1 content: 1 material: 1 owner_id: 1 published: 1 num_reviews: 1 ####################################################### # helper ####################################################### ####################################################### _get_solution_data = (solution_id) -> solution = Solutions.findOne solution_id entry = _get_profile_data solution.owner_id, {} entry.content = solution.content entry.material = solution.material entry.published = solution.published entry = _get_reviews_data solution_id, entry return entry ####################################################### _get_reviews_data = (solution_id, entry) -> filter = solution_id: solution_id published: true options = fields: rating: 1 content: 1 owner_id: 1 review_cursor = Reviews.find filter, options reviews = [] avg = 0 nt = 0 review_cursor.forEach (review) -> r = _get_profile_data review.owner_id, {} r = _get_feedback_data review._id, r r.content = review.content r.rating = review.rating reviews.push r avg += parseInt(r.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["reviews"] = reviews entry["average_rating"] = avg return entry ####################################################### _get_feedback_data = (review_id, entry) -> filter = review_id: review_id published: true options = fields: rating: 1 content: 1 owner_id: 1 feedback_cursor = Feedback.find filter, options feedback = [] avg = 0 nt = 0 feedback_cursor.forEach (fdb) -> f = _get_profile_data fdb.owner_id, {} f.content = fdb.content f.rating = fdb.rating feedback.push f avg += parseInt(f.rating) nt += 1 avg = if nt then avg / nt else "no reviews yet" entry["feedback"] = feedback entry["average_rating"] = avg return entry ####################################################### _get_profile_data = (user_id, entry) -> filter = owner_id: user_id profile = Profiles.findOne filter if profile entry["name"] = get_profile_name profile, false, false entry["avatar"] = get_avatar profile return entry ####################################################### # challenges ####################################################### ####################################################### Meteor.publish "challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId filter = filter_visible_documents user_id crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "challenges", user_id return crs ####################################################### Meteor.publish "my_challenges", (parameter) -> pattern = query: Match.Optional(String) page: Number size: Number check parameter, pattern user_id = this.userId restrict = owner_id: user_id filter = filter_visible_documents user_id, restrict crs = find_documents_paged_unprotected Challenges, filter, _challenge_fields, parameter log_publication "Challenges", crs, filter, _challenge_fields, "my_challenges", user_id return crs ####################################################### Meteor.publish "challenge_by_id", (challenge_id) -> check challenge_id, String user_id = this.userId restrict = _id: challenge_id published: true filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "challenge_by_id", user_id return crs ####################################################### Meteor.publish "my_challenge_by_id", (challenge_id) -> user_id = this.userId restrict = _id:challenge_id owner_id: user_id filter = filter_visible_documents user_id, restrict crs = Challenges.find filter, _challenge_fields log_publication "Challenges", crs, filter, _challenge_fields, "my_challenge_by_id", user_id return crs ####################################################### Meteor.publish "challenge_summaries", (parameter) -> pattern = challenge_id: String published: Match.Optional(Boolean) query: Match.Optional(String) page: Number size: Number check parameter, pattern if parameter.size>50 throw Meteor.Error("Size values larger than 50 are not allowed.") user_id = this.userId challenge = Challenges.findOne parameter.challenge_id if challenge.owner_id != user_id throw Meteor.Error("Not permitted.") filter = challenge_id: parameter.challenge_id if parameter.published filter.published = parameter.published mod = fields: content: 1 material: 1 owner_id: 1 published: 1 challenge_id: 1 solution_ids = new Set() profile_ids = new Set() ############################################## # retrieving solutions ############################################## ############################################## solution_cursor = find_documents_paged_unprotected Solutions, filter, mod, parameter solution_cursor.forEach (solution) -> solution_ids.add solution._id profile_ids.add solution.owner_id ############################################## # retrieving reviews ############################################## # resetting the filter solution_ids = Array.from(solution_ids) filter = solution_id: $in: solution_ids mod = fields: rating: 1 content: 1 owner_id: 1 published: 1 challenge_id: 1 solution_id: 1 review_id: 1 owner_id: 1 ############################################## review_cursor = Reviews.find(filter, mod) review_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving feedback ############################################## ############################################## feedback_cursor = Feedback.find(filter, mod) feedback_cursor.forEach (entry) -> profile_ids.add entry.owner_id ############################################## # retrieving profiles ############################################## # resetting the filter profile_ids = Array.from(profile_ids) filter = owner_id: $in: profile_ids mod = fields: resume: 1 published: 1 given_name: 1 middle_name: 1 family_name: 1 owner_id: 1 avatar: 1 ############################################## profile_cursor = Profiles.find(filter, mod) log_publication "Multiple Cursor", null, {}, {}, "challenge_summaries", user_id return [solution_cursor, review_cursor, feedback_cursor, profile_cursor]
[ { "context": "-4de7-4b7f-9a5e-002b1c5c4a0f\"\n gist:\n token: \"b158678ac60c921d45424b53d41dce1e8459a8ee\"\n kite:\n showWelcomeNotificationOnStartup: fa", "end": 1331, "score": 0.9920809268951416, "start": 1291, "tag": "KEY", "value": "b158678ac60c921d45424b53d41dce1e8459a8ee" } ]
.atom/config.cson
chuckxD/dotfiles
1
"*": "atom-clock": showUTC: true "atom-terminal": {} core: disabledPackages: [ "sync-settings" "Sublime-Style-Column-Selection" "atom-transpose" "autoclose-html" "case-keep-replace" "change-case" "duplicate-line-or-selection" "editorconfig" "multi-cursor" "es6-javascript" "terminal-plus" "atom-ide-debugger-node" "atom-ide-debugger-python" "atom-ide-ui" "ide-json" "ide-yaml" "linter-csslint" "Hydrogen" "hydrogen-launcher" "vim-surround" "atom-react" "vim-mode-visual-block" "vim-mode-plus-ex-mode" "nvim-mode" "move-cursor-improved" "vim-mode-clipboard-plus" "vim-mode-plus-duplicate" "vim-mode-plus-exchange" "vim-mode-plus-keymaps-for-tree-view" "vim-mode-zz" "vim-mode-plus-replace-with-execution" "vim-mode-plus-move-selected-text" "vim-mode-plus-macros" ] telemetryConsent: "no" themes: [ "atom-black-ui" "ir-black-k-syntax" ] uriHandlerRegistration: "always" useTreeSitterParsers: false editor: fontSize: 12 scrollPastEnd: true "exception-reporting": userId: "7167d68a-4de7-4b7f-9a5e-002b1c5c4a0f" gist: token: "b158678ac60c921d45424b53d41dce1e8459a8ee" kite: showWelcomeNotificationOnStartup: false linter: {} "linter-ui-default": panelHeight: 233.1428985595703 "prettier-atom": formatOnSaveOptions: enabled: true isDisabledIfNoConfigFile: true isDisabledIfNotInPackageJson: true respectEslintignore: false showInStatusBar: true prettierEslintOptions: {} useEslint: true "terminal-plus": core: {} style: theme: "pro" "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true "vim-mode": {} "vim-mode-plus": useClipboardAsDefaultRegister: true welcome: showOnStartup: false core: ignoredNames: [ ".git" ".svn" ".DS_Store" ] "exception-reporting": userId: "750db657-913b-52ea-512d-dea57c560caf" metrics: userId: "6d7958e72f635b2868a2e1b862219e92281e2fb7" "release-notes": viewedVersion: "0.69.0" welcome: showOnStartup: false
189151
"*": "atom-clock": showUTC: true "atom-terminal": {} core: disabledPackages: [ "sync-settings" "Sublime-Style-Column-Selection" "atom-transpose" "autoclose-html" "case-keep-replace" "change-case" "duplicate-line-or-selection" "editorconfig" "multi-cursor" "es6-javascript" "terminal-plus" "atom-ide-debugger-node" "atom-ide-debugger-python" "atom-ide-ui" "ide-json" "ide-yaml" "linter-csslint" "Hydrogen" "hydrogen-launcher" "vim-surround" "atom-react" "vim-mode-visual-block" "vim-mode-plus-ex-mode" "nvim-mode" "move-cursor-improved" "vim-mode-clipboard-plus" "vim-mode-plus-duplicate" "vim-mode-plus-exchange" "vim-mode-plus-keymaps-for-tree-view" "vim-mode-zz" "vim-mode-plus-replace-with-execution" "vim-mode-plus-move-selected-text" "vim-mode-plus-macros" ] telemetryConsent: "no" themes: [ "atom-black-ui" "ir-black-k-syntax" ] uriHandlerRegistration: "always" useTreeSitterParsers: false editor: fontSize: 12 scrollPastEnd: true "exception-reporting": userId: "7167d68a-4de7-4b7f-9a5e-002b1c5c4a0f" gist: token: "<KEY>" kite: showWelcomeNotificationOnStartup: false linter: {} "linter-ui-default": panelHeight: 233.1428985595703 "prettier-atom": formatOnSaveOptions: enabled: true isDisabledIfNoConfigFile: true isDisabledIfNotInPackageJson: true respectEslintignore: false showInStatusBar: true prettierEslintOptions: {} useEslint: true "terminal-plus": core: {} style: theme: "pro" "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true "vim-mode": {} "vim-mode-plus": useClipboardAsDefaultRegister: true welcome: showOnStartup: false core: ignoredNames: [ ".git" ".svn" ".DS_Store" ] "exception-reporting": userId: "750db657-913b-52ea-512d-dea57c560caf" metrics: userId: "6d7958e72f635b2868a2e1b862219e92281e2fb7" "release-notes": viewedVersion: "0.69.0" welcome: showOnStartup: false
true
"*": "atom-clock": showUTC: true "atom-terminal": {} core: disabledPackages: [ "sync-settings" "Sublime-Style-Column-Selection" "atom-transpose" "autoclose-html" "case-keep-replace" "change-case" "duplicate-line-or-selection" "editorconfig" "multi-cursor" "es6-javascript" "terminal-plus" "atom-ide-debugger-node" "atom-ide-debugger-python" "atom-ide-ui" "ide-json" "ide-yaml" "linter-csslint" "Hydrogen" "hydrogen-launcher" "vim-surround" "atom-react" "vim-mode-visual-block" "vim-mode-plus-ex-mode" "nvim-mode" "move-cursor-improved" "vim-mode-clipboard-plus" "vim-mode-plus-duplicate" "vim-mode-plus-exchange" "vim-mode-plus-keymaps-for-tree-view" "vim-mode-zz" "vim-mode-plus-replace-with-execution" "vim-mode-plus-move-selected-text" "vim-mode-plus-macros" ] telemetryConsent: "no" themes: [ "atom-black-ui" "ir-black-k-syntax" ] uriHandlerRegistration: "always" useTreeSitterParsers: false editor: fontSize: 12 scrollPastEnd: true "exception-reporting": userId: "7167d68a-4de7-4b7f-9a5e-002b1c5c4a0f" gist: token: "PI:KEY:<KEY>END_PI" kite: showWelcomeNotificationOnStartup: false linter: {} "linter-ui-default": panelHeight: 233.1428985595703 "prettier-atom": formatOnSaveOptions: enabled: true isDisabledIfNoConfigFile: true isDisabledIfNotInPackageJson: true respectEslintignore: false showInStatusBar: true prettierEslintOptions: {} useEslint: true "terminal-plus": core: {} style: theme: "pro" "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true "vim-mode": {} "vim-mode-plus": useClipboardAsDefaultRegister: true welcome: showOnStartup: false core: ignoredNames: [ ".git" ".svn" ".DS_Store" ] "exception-reporting": userId: "750db657-913b-52ea-512d-dea57c560caf" metrics: userId: "6d7958e72f635b2868a2e1b862219e92281e2fb7" "release-notes": viewedVersion: "0.69.0" welcome: showOnStartup: false
[ { "context": "lStore.exists()\n LocalStore.store.first = \"John\"\n $scope.first = LocalStore.store.first\n ", "end": 625, "score": 0.9998478293418884, "start": 621, "tag": "NAME", "value": "John" }, { "context": "Store.store.first\n LocalStore.set('last', \"Smith\")\n $scope.last = LocalStore.get('last')\n ", "end": 710, "score": 0.9996375441551208, "start": 705, "tag": "NAME", "value": "Smith" } ]
halite/lattice/app/util/appStoreSrvc.coffee
CARFAX/halite
212
### Persistent Data Service using Web Storage LocalStorage and SessionStorage Each is given a different factory. Provides shared global application persistent data .set applys JSON.stringify to its val so that objects can be stored .get applys JSON.parse to to its return to inverse set If the value is a string then the other forms .store.keystring .store['keystring'] to get an set values usage: mainApp = angular.module("MainApp", [... 'appStoreSrvc']) mainApp.controller 'MyCtlr', ['$scope', ...,'LocalStore', ($scope,...,LocalStore) -> if LocalStore.exists() LocalStore.store.first = "John" $scope.first = LocalStore.store.first LocalStore.set('last', "Smith") $scope.last = LocalStore.get('last') Simailarly for SessionStore ### angular.module("appStoreSrvc", []) .factory "LocalStore", () -> servicer = store: localStorage exists: () -> return localStorage? clear: () -> return localStorage.clear() len: () -> return localStorage.length key: (index) -> return localStorage.key(index) get: (key) -> return angular.fromJson localStorage.getItem(key) set: (key,val) -> return localStorage.setItem key, angular.toJson(val) remove: (key) -> return localStorage.removeItem(key) return servicer .factory "SessionStore", () -> servicer = store: sessionStorage exists: () -> return sessionStorage? clear: () -> return sessionStorage.clear() len: () -> return sessionStorage.length key: (index) -> return sessionStorage.key(index) get: (key) -> return angular.fromJson sessionStorage.getItem(key) set: (key,val) -> return sessionStorage.setItem key, angular.toJson(val) remove: (key) -> return sessionStorage.removeItem(key) return servicer
69828
### Persistent Data Service using Web Storage LocalStorage and SessionStorage Each is given a different factory. Provides shared global application persistent data .set applys JSON.stringify to its val so that objects can be stored .get applys JSON.parse to to its return to inverse set If the value is a string then the other forms .store.keystring .store['keystring'] to get an set values usage: mainApp = angular.module("MainApp", [... 'appStoreSrvc']) mainApp.controller 'MyCtlr', ['$scope', ...,'LocalStore', ($scope,...,LocalStore) -> if LocalStore.exists() LocalStore.store.first = "<NAME>" $scope.first = LocalStore.store.first LocalStore.set('last', "<NAME>") $scope.last = LocalStore.get('last') Simailarly for SessionStore ### angular.module("appStoreSrvc", []) .factory "LocalStore", () -> servicer = store: localStorage exists: () -> return localStorage? clear: () -> return localStorage.clear() len: () -> return localStorage.length key: (index) -> return localStorage.key(index) get: (key) -> return angular.fromJson localStorage.getItem(key) set: (key,val) -> return localStorage.setItem key, angular.toJson(val) remove: (key) -> return localStorage.removeItem(key) return servicer .factory "SessionStore", () -> servicer = store: sessionStorage exists: () -> return sessionStorage? clear: () -> return sessionStorage.clear() len: () -> return sessionStorage.length key: (index) -> return sessionStorage.key(index) get: (key) -> return angular.fromJson sessionStorage.getItem(key) set: (key,val) -> return sessionStorage.setItem key, angular.toJson(val) remove: (key) -> return sessionStorage.removeItem(key) return servicer
true
### Persistent Data Service using Web Storage LocalStorage and SessionStorage Each is given a different factory. Provides shared global application persistent data .set applys JSON.stringify to its val so that objects can be stored .get applys JSON.parse to to its return to inverse set If the value is a string then the other forms .store.keystring .store['keystring'] to get an set values usage: mainApp = angular.module("MainApp", [... 'appStoreSrvc']) mainApp.controller 'MyCtlr', ['$scope', ...,'LocalStore', ($scope,...,LocalStore) -> if LocalStore.exists() LocalStore.store.first = "PI:NAME:<NAME>END_PI" $scope.first = LocalStore.store.first LocalStore.set('last', "PI:NAME:<NAME>END_PI") $scope.last = LocalStore.get('last') Simailarly for SessionStore ### angular.module("appStoreSrvc", []) .factory "LocalStore", () -> servicer = store: localStorage exists: () -> return localStorage? clear: () -> return localStorage.clear() len: () -> return localStorage.length key: (index) -> return localStorage.key(index) get: (key) -> return angular.fromJson localStorage.getItem(key) set: (key,val) -> return localStorage.setItem key, angular.toJson(val) remove: (key) -> return localStorage.removeItem(key) return servicer .factory "SessionStore", () -> servicer = store: sessionStorage exists: () -> return sessionStorage? clear: () -> return sessionStorage.clear() len: () -> return sessionStorage.length key: (index) -> return sessionStorage.key(index) get: (key) -> return angular.fromJson sessionStorage.getItem(key) set: (key,val) -> return sessionStorage.setItem key, angular.toJson(val) remove: (key) -> return sessionStorage.removeItem(key) return servicer
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.99988853931427, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.9999317526817322, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998799562454224, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.999934732913971, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998822808265686, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.9999352693557739, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/common/components.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/components.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce module = angular.module("taigaCommon") ############################################################################# ## Date Range Directive (used mainly for sprint date range) ############################################################################# DateRangeDirective = -> renderRange = ($el, first, second) -> initDate = moment(first).format("DD MMM YYYY") endDate = moment(second).format("DD MMM YYYY") $el.html("#{initDate}-#{endDate}") link = ($scope, $el, $attrs) -> [first, second] = $attrs.tgDateRange.split(",") bindOnce $scope, first, (valFirst) -> bindOnce $scope, second, (valSecond) -> renderRange($el, valFirst, valSecond) return {link:link} module.directive("tgDateRange", DateRangeDirective) ############################################################################# ## Date Selector Directive (using pikaday) ############################################################################# DateSelectorDirective =-> link = ($scope, $el, $attrs, $model) -> selectedDate = null $el.picker = new Pikaday({ field: $el[0] format: "DD MMM YYYY" onSelect: (date) => selectedDate = date onOpen: => $el.picker.setDate(selectedDate) if selectedDate? }) $scope.$watch $attrs.ngModel, (val) -> $el.picker.setDate(val) if val? return { link: link require: "ngModel" } module.directive("tgDateSelector", DateSelectorDirective) ############################################################################# ## Sprint Progress Bar Directive ############################################################################# SprintProgressBarDirective = -> renderProgress = ($el, percentage, visual_percentage) -> if $el.hasClass(".current-progress") $el.css("width", "#{percentage}%") else $el.find(".current-progress").css("width", "#{visual_percentage}%") $el.find(".number").html("#{percentage} %") link = ($scope, $el, $attrs) -> bindOnce $scope, $attrs.tgSprintProgressbar, (sprint) -> closedPoints = sprint.closed_points totalPoints = sprint.total_points percentage = 0 percentage = Math.round(100 * (closedPoints/totalPoints)) if totalPoints != 0 visual_percentage = 0 #Visual hack for .current-progress bar visual_percentage = Math.round(98 * (closedPoints/totalPoints)) if totalPoints != 0 renderProgress($el, percentage, visual_percentage) return {link: link} module.directive("tgSprintProgressbar", SprintProgressBarDirective) ############################################################################# ## Created-by display directive ############################################################################# CreatedByDisplayDirective = -> # Display the owner information (full name and photo) and the date of # creation of an object (like USs, tasks and issues). # # Example: # div.us-created-by(tg-created-by-display, ng-model="us") # # Requirements: # - model object must have the attributes 'created_date' and # 'owner'(ng-model) # - scope.usersById object is required. template = _.template(""" <div class="user-avatar"> <img src="<%- owner.photo %>" alt="<%- owner.full_name_display %>" /> </div> <div class="created-by"> <span class="created-title">Created by <%- owner.full_name_display %></span> <span class="created-date"><%- date %></span> </div> """) # TODO: i18n link = ($scope, $el, $attrs) -> render = (model) -> owner = $scope.usersById?[model.owner] or { full_name_display: "external user" photo: "/images/unnamed.png" } html = template({ owner: owner date: moment(model.created_date).format("DD MMM YYYY HH:mm") }) $el.html(html) bindOnce $scope, $attrs.ngModel, (model) -> render(model) if model? $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgCreatedByDisplay", CreatedByDisplayDirective) ############################################################################# ## Watchers directive ############################################################################# WatchersDirective = ($rootscope, $confirm, $repo, $qqueue) -> # You have to include a div with the tg-lb-watchers directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if(isEditable){ %> <div class="watchers-header"> <span class="title">watchers</span> <a href="" title="Add watcher" class="icon icon-plus add-watcher"></a> </div> <% } else if(watchers.length > 0){ %> <div class="watchers-header"> <span class="title">watchers</span> </div> <% }; %> <% _.each(watchers, function(watcher) { %> <% if(watcher) { %> <div class="watcher-single"> <div class="watcher-avatar"> <span class="avatar" href="" title="<%- watcher.full_name_display %>"> <img src="<%- watcher.photo %>" alt="<%- watcher.full_name_display %>"> </span> </div> <div class="watcher-name"> <span><%- watcher.full_name_display %></span> <% if(isEditable){ %> <a class="icon icon-delete" data-watcher-id="<%- watcher.id %>" href="" title="delete-watcher"> </a> <% }; %> </div> </div> <% } %> <% }); %> """) link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (watchers) => item = $model.$modelValue.clone() item.watchers = watchers $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() deleteWatcher = $qqueue.bindAdd (watcherIds) => item = $model.$modelValue.clone() item.watchers = watcherIds $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> item.revert() $confirm.notify("error") renderWatchers = (watchers) -> ctx = { watchers: watchers isEditable: isEditable() } html = template(ctx) $el.html(html) if isEditable() and watchers.length == 0 $el.find(".title").text("Add watchers") $el.find(".watchers-header").addClass("no-watchers") $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() target = angular.element(event.currentTarget) watcherId = target.data("watcher-id") title = "Delete watcher" message = $scope.usersById[watcherId].full_name_display $confirm.askOnDelete(title, message).then (finish) => finish() watcherIds = _.clone($model.$modelValue.watchers, false) watcherIds = _.pull(watcherIds, watcherId) deleteWatcher(watcherIds) $el.on "click", ".add-watcher", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("watcher:add", $model.$modelValue) $scope.$on "watcher:added", (ctx, watcherId) -> watchers = _.clone($model.$modelValue.watchers, false) watchers.push(watcherId) watchers = _.uniq(watchers) save(watchers) $scope.$watch $attrs.ngModel, (item) -> return if not item? watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $scope.$on "$destroy", -> $el.off() return {link:link, require:"ngModel"} module.directive("tgWatchers", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgQqueue", WatchersDirective]) ############################################################################# ## Assigned to directive ############################################################################# AssignedToDirective = ($rootscope, $confirm, $repo, $loading, $qqueue) -> # You have to include a div with the tg-lb-assignedto directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if (assignedTo) { %> <div class="user-avatar"> <img src="<%- assignedTo.photo %>" alt="<%- assignedTo.full_name_display %>" /> </div> <% } %> <div class="assigned-to"> <span class="assigned-title">Assigned to</span> <a href="" title="edit assignment" class="user-assigned <% if(isEditable){ %>editable<% }; %>"> <span class="assigned-name"> <% if (assignedTo) { %> <%- assignedTo.full_name_display %> <% } else { %> Not assigned <% } %> </span> <% if(isEditable){ %><span class="icon icon-arrow-bottom"></span><% }; %> </a> <% if (assignedTo!==null && isEditable) { %> <a href="" title="delete assignment" class="icon icon-delete"></a> <% } %> </div> """) # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (userId) => $model.$modelValue.assigned_to = userId $loading.start($el) promise = $repo.save($model.$modelValue) promise.then -> $loading.finish($el) $confirm.notify("success") renderAssignedTo($model.$modelValue) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() $confirm.notify("error") $loading.finish($el) return promise renderAssignedTo = (issue) -> assignedToId = issue?.assigned_to assignedTo = if assignedToId? then $scope.usersById[assignedToId] else null ctx = { assignedTo: assignedTo isEditable: isEditable() } html = template(ctx) $el.html(html) $el.on "click", ".user-assigned", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("assigned-to:add", $model.$modelValue) $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() title = "Are you sure you want to leave it unassigned?" # TODO: i18n $confirm.ask(title).then (finish) => finish() $model.$modelValue.assigned_to = null save(null) $scope.$on "assigned-to:added", (ctx, userId, item) -> return if item.id != $model.$modelValue.id save(userId) $scope.$watch $attrs.ngModel, (instance) -> renderAssignedTo(instance) $scope.$on "$destroy", -> $el.off() return { link:link, require:"ngModel" } module.directive("tgAssignedTo", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgLoading", "$tgQqueue", AssignedToDirective]) ############################################################################# ## Block Button directive ############################################################################# BlockButtonDirective = ($rootscope, $loading) -> template = """ <a href="#" class="button button-gray item-block">Block</a> <a href="#" class="button button-red item-unblock">Unblock</a> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_us") != -1 $scope.$watch $attrs.ngModel, (item) -> return if not item if isEditable() $el.find('.item-block').addClass('editable') if item.is_blocked $el.find('.item-block').hide() $el.find('.item-unblock').show() else $el.find('.item-block').show() $el.find('.item-unblock').hide() $el.on "click", ".item-block", (event) -> event.preventDefault() $rootscope.$broadcast("block", $model.$modelValue) $el.on "click", ".item-unblock", (event) -> event.preventDefault() $loading.start($el.find(".item-unblock")) finish = -> $loading.finish($el.find(".item-unblock")) $rootscope.$broadcast("unblock", $model.$modelValue, finish) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgBlockButton", ["$rootScope", "$tgLoading", BlockButtonDirective]) ############################################################################# ## Delete Button directive ############################################################################# DeleteButtonDirective = ($log, $repo, $confirm, $location) -> template = """ <a href="" class="button button-red">Delete</a> """ #TODO: i18n link = ($scope, $el, $attrs, $model) -> if not $attrs.onDeleteGoToUrl return $log.error "DeleteButtonDirective requires on-delete-go-to-url set in scope." if not $attrs.onDeleteTitle return $log.error "DeleteButtonDirective requires on-delete-title set in scope." $el.on "click", ".button", (event) -> title = $scope.$eval($attrs.onDeleteTitle) subtitle = $model.$modelValue.subject $confirm.askOnDelete(title, subtitle).then (finish) => promise = $repo.remove($model.$modelValue) promise.then => finish() url = $scope.$eval($attrs.onDeleteGoToUrl) $location.path(url) promise.then null, => finish(false) $confirm.notify("error") $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgDeleteButton", ["$log", "$tgRepo", "$tgConfirm", "$tgLocation", DeleteButtonDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableSubjectDirective = ($rootscope, $repo, $confirm, $loading, $qqueue) -> template = """ <div class="view-subject"> {{ item.subject }} <a class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-subject"> <input type="text" ng-model="item.subject" data-required="true" data-maxlength="500"/> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (subject) => $model.$modelValue.subject = subject $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-subject').hide() $el.find('.view-subject').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) return promise $el.click -> return if not isEditable() $el.find('.edit-subject').show() $el.find('.view-subject').hide() $el.find('input').focus() $el.on "click", ".save", -> subject = $scope.item.subject save(subject) $el.on "keyup", "input", (event) -> if event.keyCode == 13 subject = $scope.item.subject save(subject) else if event.keyCode == 27 $scope.$apply () => $model.$modelValue.revert() $el.find('div.edit-subject').hide() $el.find('div.view-subject').show() $el.find('div.edit-subject').hide() $el.find('div.view-subject span.edit').hide() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if not isEditable() $el.find('.view-subject .edit').remove() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableSubject", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", EditableSubjectDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableDescriptionDirective = ($rootscope, $repo, $confirm, $compile, $loading, $selectedText, $qqueue) -> template = """ <div class="view-description"> <section class="us-content wysiwyg" tg-bind-html="item.description_html || noDescriptionMsg"></section> <span class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-description"> <textarea placeholder="Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet..." ng-model="item.description" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ # TODO: i18n noDescriptionMegEditMode = """ <p class="no-description editable"> Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet... </p> """ # TODO: i18n noDescriptionMegReadMode = """ <p class="no-description"> No description yet. </p> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> $el.find('.edit-description').hide() $el.find('.view-description .edit').hide() isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (description) => $model.$modelValue.description = description $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-description').hide() $el.find('.view-description').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-description", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if $selectedText.get().length $el.find('.edit-description').show() $el.find('.view-description').hide() $el.find('textarea').focus() $el.on "click", ".save", -> description = $scope.item.description save(description) $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 $scope.$apply () => $scope.item.revert() $el.find('.edit-description').hide() $el.find('.view-description').show() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if isEditable() $el.find('.view-description .edit').show() $el.find('.view-description .us-content').addClass('editable') $scope.noDescriptionMsg = noDescriptionMegEditMode else $scope.noDescriptionMsg = noDescriptionMegReadMode $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableDescription", ["$rootScope", "$tgRepo", "$tgConfirm", "$compile", "$tgLoading", "$selectedText", "$tgQqueue", EditableDescriptionDirective]) ############################################################################# ## Common list directives ############################################################################# ## NOTE: These directives are used in issues and search and are ## completely bindonce, they only serves for visualization of data. ############################################################################# ListItemIssueStatusDirective = -> link = ($scope, $el, $attrs) -> issue = $scope.$eval($attrs.tgListitemIssueStatus) bindOnce $scope, "issueStatusById", (issueStatusById) -> $el.html(issueStatusById[issue.status].name) return {link:link} ListItemTaskStatusDirective = -> link = ($scope, $el, $attrs) -> task = $scope.$eval($attrs.tgListitemTaskStatus) bindOnce $scope, "taskStatusById", (taskStatusById) -> $el.html(taskStatusById[task.status].name) return {link:link} ListItemUsStatusDirective = -> link = ($scope, $el, $attrs) -> us = $scope.$eval($attrs.tgListitemUsStatus) bindOnce $scope, "usStatusById", (usStatusById) -> $el.html(usStatusById[us.status].name) return {link:link} ListItemAssignedtoDirective = -> template = _.template(""" <figure class="avatar"> <img src="<%- imgurl %>" alt="<%- name %>"/> <figcaption><%- name %></figcaption> </figure> """) link = ($scope, $el, $attrs) -> bindOnce $scope, "membersById", (membersById) -> item = $scope.$eval($attrs.tgListitemAssignedto) ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"} member = membersById[item.assigned_to] if member ctx.imgurl = member.photo ctx.name = member.full_name $el.html(template(ctx)) return {link:link} ListItemPriorityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (priorityById, issue) -> priority = priorityById[issue.priority] domNode = $el.find(".level") domNode.css("background-color", priority.color) domNode.attr("title", priority.name) bindOnce $scope, "priorityById", (priorityById) -> issue = $scope.$eval($attrs.tgListitemPriority) render(priorityById, issue) $scope.$watch $attrs.tgListitemPriority, (issue) -> render($scope.priorityById, issue) return { link: link template: template } ListItemSeverityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (severityById, issue) -> severity = severityById[issue.severity] domNode = $el.find(".level") domNode.css("background-color", severity.color) domNode.attr("title", severity.name) bindOnce $scope, "severityById", (severityById) -> issue = $scope.$eval($attrs.tgListitemSeverity) render(severityById, issue) $scope.$watch $attrs.tgListitemSeverity, (issue) -> render($scope.severityById, issue) return { link: link template: template } ListItemTypeDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (issueTypeById, issue) -> type = issueTypeById[issue.type] domNode = $el.find(".level") domNode.css("background-color", type.color) domNode.attr("title", type.name) bindOnce $scope, "issueTypeById", (issueTypeById) -> issue = $scope.$eval($attrs.tgListitemType) render(issueTypeById, issue) $scope.$watch $attrs.tgListitemType, (issue) -> render($scope.issueTypeById, issue) return { link: link template: template } ############################################################################# ## Progress bar directive ############################################################################# TgProgressBarDirective = -> template = _.template(""" <div class="current-progress" style="width: <%- percentage %>%"></div> """) render = (el, percentage) -> el.html(template({percentage: percentage})) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch $attrs.tgProgressBar, (percentage) -> percentage = _.max([0 , percentage]) percentage = _.min([100, percentage]) render($el, percentage) $scope.$on "$destroy", -> $el.off() return {link: link} ############################################################################# ## Main title directive ############################################################################# TgMainTitleDirective = -> template = _.template(""" <span class="project-name"><%- projectName %></span> <span class="green"><%- sectionName %></span> """) render = (el, projectName, sectionName) -> el.html(template({ projectName: projectName sectionName: sectionName })) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch "project", (project) -> render($el, project.name, $scope.sectionName) if project $scope.$on "project:loaded", (ctx, project) => render($el, project.name, $scope.sectionName) $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgListitemType", ListItemTypeDirective) module.directive("tgListitemIssueStatus", ListItemIssueStatusDirective) module.directive("tgListitemAssignedto", ListItemAssignedtoDirective) module.directive("tgListitemPriority", ListItemPriorityDirective) module.directive("tgListitemSeverity", ListItemSeverityDirective) module.directive("tgListitemTaskStatus", ListItemTaskStatusDirective) module.directive("tgListitemUsStatus", ListItemUsStatusDirective) module.directive("tgProgressBar", TgProgressBarDirective) module.directive("tgMainTitle", TgMainTitleDirective)
138295
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/components.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce module = angular.module("taigaCommon") ############################################################################# ## Date Range Directive (used mainly for sprint date range) ############################################################################# DateRangeDirective = -> renderRange = ($el, first, second) -> initDate = moment(first).format("DD MMM YYYY") endDate = moment(second).format("DD MMM YYYY") $el.html("#{initDate}-#{endDate}") link = ($scope, $el, $attrs) -> [first, second] = $attrs.tgDateRange.split(",") bindOnce $scope, first, (valFirst) -> bindOnce $scope, second, (valSecond) -> renderRange($el, valFirst, valSecond) return {link:link} module.directive("tgDateRange", DateRangeDirective) ############################################################################# ## Date Selector Directive (using pikaday) ############################################################################# DateSelectorDirective =-> link = ($scope, $el, $attrs, $model) -> selectedDate = null $el.picker = new Pikaday({ field: $el[0] format: "DD MMM YYYY" onSelect: (date) => selectedDate = date onOpen: => $el.picker.setDate(selectedDate) if selectedDate? }) $scope.$watch $attrs.ngModel, (val) -> $el.picker.setDate(val) if val? return { link: link require: "ngModel" } module.directive("tgDateSelector", DateSelectorDirective) ############################################################################# ## Sprint Progress Bar Directive ############################################################################# SprintProgressBarDirective = -> renderProgress = ($el, percentage, visual_percentage) -> if $el.hasClass(".current-progress") $el.css("width", "#{percentage}%") else $el.find(".current-progress").css("width", "#{visual_percentage}%") $el.find(".number").html("#{percentage} %") link = ($scope, $el, $attrs) -> bindOnce $scope, $attrs.tgSprintProgressbar, (sprint) -> closedPoints = sprint.closed_points totalPoints = sprint.total_points percentage = 0 percentage = Math.round(100 * (closedPoints/totalPoints)) if totalPoints != 0 visual_percentage = 0 #Visual hack for .current-progress bar visual_percentage = Math.round(98 * (closedPoints/totalPoints)) if totalPoints != 0 renderProgress($el, percentage, visual_percentage) return {link: link} module.directive("tgSprintProgressbar", SprintProgressBarDirective) ############################################################################# ## Created-by display directive ############################################################################# CreatedByDisplayDirective = -> # Display the owner information (full name and photo) and the date of # creation of an object (like USs, tasks and issues). # # Example: # div.us-created-by(tg-created-by-display, ng-model="us") # # Requirements: # - model object must have the attributes 'created_date' and # 'owner'(ng-model) # - scope.usersById object is required. template = _.template(""" <div class="user-avatar"> <img src="<%- owner.photo %>" alt="<%- owner.full_name_display %>" /> </div> <div class="created-by"> <span class="created-title">Created by <%- owner.full_name_display %></span> <span class="created-date"><%- date %></span> </div> """) # TODO: i18n link = ($scope, $el, $attrs) -> render = (model) -> owner = $scope.usersById?[model.owner] or { full_name_display: "external user" photo: "/images/unnamed.png" } html = template({ owner: owner date: moment(model.created_date).format("DD MMM YYYY HH:mm") }) $el.html(html) bindOnce $scope, $attrs.ngModel, (model) -> render(model) if model? $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgCreatedByDisplay", CreatedByDisplayDirective) ############################################################################# ## Watchers directive ############################################################################# WatchersDirective = ($rootscope, $confirm, $repo, $qqueue) -> # You have to include a div with the tg-lb-watchers directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if(isEditable){ %> <div class="watchers-header"> <span class="title">watchers</span> <a href="" title="Add watcher" class="icon icon-plus add-watcher"></a> </div> <% } else if(watchers.length > 0){ %> <div class="watchers-header"> <span class="title">watchers</span> </div> <% }; %> <% _.each(watchers, function(watcher) { %> <% if(watcher) { %> <div class="watcher-single"> <div class="watcher-avatar"> <span class="avatar" href="" title="<%- watcher.full_name_display %>"> <img src="<%- watcher.photo %>" alt="<%- watcher.full_name_display %>"> </span> </div> <div class="watcher-name"> <span><%- watcher.full_name_display %></span> <% if(isEditable){ %> <a class="icon icon-delete" data-watcher-id="<%- watcher.id %>" href="" title="delete-watcher"> </a> <% }; %> </div> </div> <% } %> <% }); %> """) link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (watchers) => item = $model.$modelValue.clone() item.watchers = watchers $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() deleteWatcher = $qqueue.bindAdd (watcherIds) => item = $model.$modelValue.clone() item.watchers = watcherIds $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> item.revert() $confirm.notify("error") renderWatchers = (watchers) -> ctx = { watchers: watchers isEditable: isEditable() } html = template(ctx) $el.html(html) if isEditable() and watchers.length == 0 $el.find(".title").text("Add watchers") $el.find(".watchers-header").addClass("no-watchers") $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() target = angular.element(event.currentTarget) watcherId = target.data("watcher-id") title = "Delete watcher" message = $scope.usersById[watcherId].full_name_display $confirm.askOnDelete(title, message).then (finish) => finish() watcherIds = _.clone($model.$modelValue.watchers, false) watcherIds = _.pull(watcherIds, watcherId) deleteWatcher(watcherIds) $el.on "click", ".add-watcher", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("watcher:add", $model.$modelValue) $scope.$on "watcher:added", (ctx, watcherId) -> watchers = _.clone($model.$modelValue.watchers, false) watchers.push(watcherId) watchers = _.uniq(watchers) save(watchers) $scope.$watch $attrs.ngModel, (item) -> return if not item? watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $scope.$on "$destroy", -> $el.off() return {link:link, require:"ngModel"} module.directive("tgWatchers", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgQqueue", WatchersDirective]) ############################################################################# ## Assigned to directive ############################################################################# AssignedToDirective = ($rootscope, $confirm, $repo, $loading, $qqueue) -> # You have to include a div with the tg-lb-assignedto directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if (assignedTo) { %> <div class="user-avatar"> <img src="<%- assignedTo.photo %>" alt="<%- assignedTo.full_name_display %>" /> </div> <% } %> <div class="assigned-to"> <span class="assigned-title">Assigned to</span> <a href="" title="edit assignment" class="user-assigned <% if(isEditable){ %>editable<% }; %>"> <span class="assigned-name"> <% if (assignedTo) { %> <%- assignedTo.full_name_display %> <% } else { %> Not assigned <% } %> </span> <% if(isEditable){ %><span class="icon icon-arrow-bottom"></span><% }; %> </a> <% if (assignedTo!==null && isEditable) { %> <a href="" title="delete assignment" class="icon icon-delete"></a> <% } %> </div> """) # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (userId) => $model.$modelValue.assigned_to = userId $loading.start($el) promise = $repo.save($model.$modelValue) promise.then -> $loading.finish($el) $confirm.notify("success") renderAssignedTo($model.$modelValue) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() $confirm.notify("error") $loading.finish($el) return promise renderAssignedTo = (issue) -> assignedToId = issue?.assigned_to assignedTo = if assignedToId? then $scope.usersById[assignedToId] else null ctx = { assignedTo: assignedTo isEditable: isEditable() } html = template(ctx) $el.html(html) $el.on "click", ".user-assigned", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("assigned-to:add", $model.$modelValue) $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() title = "Are you sure you want to leave it unassigned?" # TODO: i18n $confirm.ask(title).then (finish) => finish() $model.$modelValue.assigned_to = null save(null) $scope.$on "assigned-to:added", (ctx, userId, item) -> return if item.id != $model.$modelValue.id save(userId) $scope.$watch $attrs.ngModel, (instance) -> renderAssignedTo(instance) $scope.$on "$destroy", -> $el.off() return { link:link, require:"ngModel" } module.directive("tgAssignedTo", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgLoading", "$tgQqueue", AssignedToDirective]) ############################################################################# ## Block Button directive ############################################################################# BlockButtonDirective = ($rootscope, $loading) -> template = """ <a href="#" class="button button-gray item-block">Block</a> <a href="#" class="button button-red item-unblock">Unblock</a> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_us") != -1 $scope.$watch $attrs.ngModel, (item) -> return if not item if isEditable() $el.find('.item-block').addClass('editable') if item.is_blocked $el.find('.item-block').hide() $el.find('.item-unblock').show() else $el.find('.item-block').show() $el.find('.item-unblock').hide() $el.on "click", ".item-block", (event) -> event.preventDefault() $rootscope.$broadcast("block", $model.$modelValue) $el.on "click", ".item-unblock", (event) -> event.preventDefault() $loading.start($el.find(".item-unblock")) finish = -> $loading.finish($el.find(".item-unblock")) $rootscope.$broadcast("unblock", $model.$modelValue, finish) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgBlockButton", ["$rootScope", "$tgLoading", BlockButtonDirective]) ############################################################################# ## Delete Button directive ############################################################################# DeleteButtonDirective = ($log, $repo, $confirm, $location) -> template = """ <a href="" class="button button-red">Delete</a> """ #TODO: i18n link = ($scope, $el, $attrs, $model) -> if not $attrs.onDeleteGoToUrl return $log.error "DeleteButtonDirective requires on-delete-go-to-url set in scope." if not $attrs.onDeleteTitle return $log.error "DeleteButtonDirective requires on-delete-title set in scope." $el.on "click", ".button", (event) -> title = $scope.$eval($attrs.onDeleteTitle) subtitle = $model.$modelValue.subject $confirm.askOnDelete(title, subtitle).then (finish) => promise = $repo.remove($model.$modelValue) promise.then => finish() url = $scope.$eval($attrs.onDeleteGoToUrl) $location.path(url) promise.then null, => finish(false) $confirm.notify("error") $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgDeleteButton", ["$log", "$tgRepo", "$tgConfirm", "$tgLocation", DeleteButtonDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableSubjectDirective = ($rootscope, $repo, $confirm, $loading, $qqueue) -> template = """ <div class="view-subject"> {{ item.subject }} <a class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-subject"> <input type="text" ng-model="item.subject" data-required="true" data-maxlength="500"/> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (subject) => $model.$modelValue.subject = subject $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-subject').hide() $el.find('.view-subject').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) return promise $el.click -> return if not isEditable() $el.find('.edit-subject').show() $el.find('.view-subject').hide() $el.find('input').focus() $el.on "click", ".save", -> subject = $scope.item.subject save(subject) $el.on "keyup", "input", (event) -> if event.keyCode == 13 subject = $scope.item.subject save(subject) else if event.keyCode == 27 $scope.$apply () => $model.$modelValue.revert() $el.find('div.edit-subject').hide() $el.find('div.view-subject').show() $el.find('div.edit-subject').hide() $el.find('div.view-subject span.edit').hide() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if not isEditable() $el.find('.view-subject .edit').remove() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableSubject", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", EditableSubjectDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableDescriptionDirective = ($rootscope, $repo, $confirm, $compile, $loading, $selectedText, $qqueue) -> template = """ <div class="view-description"> <section class="us-content wysiwyg" tg-bind-html="item.description_html || noDescriptionMsg"></section> <span class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-description"> <textarea placeholder="Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet..." ng-model="item.description" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ # TODO: i18n noDescriptionMegEditMode = """ <p class="no-description editable"> Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet... </p> """ # TODO: i18n noDescriptionMegReadMode = """ <p class="no-description"> No description yet. </p> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> $el.find('.edit-description').hide() $el.find('.view-description .edit').hide() isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (description) => $model.$modelValue.description = description $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-description').hide() $el.find('.view-description').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-description", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if $selectedText.get().length $el.find('.edit-description').show() $el.find('.view-description').hide() $el.find('textarea').focus() $el.on "click", ".save", -> description = $scope.item.description save(description) $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 $scope.$apply () => $scope.item.revert() $el.find('.edit-description').hide() $el.find('.view-description').show() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if isEditable() $el.find('.view-description .edit').show() $el.find('.view-description .us-content').addClass('editable') $scope.noDescriptionMsg = noDescriptionMegEditMode else $scope.noDescriptionMsg = noDescriptionMegReadMode $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableDescription", ["$rootScope", "$tgRepo", "$tgConfirm", "$compile", "$tgLoading", "$selectedText", "$tgQqueue", EditableDescriptionDirective]) ############################################################################# ## Common list directives ############################################################################# ## NOTE: These directives are used in issues and search and are ## completely bindonce, they only serves for visualization of data. ############################################################################# ListItemIssueStatusDirective = -> link = ($scope, $el, $attrs) -> issue = $scope.$eval($attrs.tgListitemIssueStatus) bindOnce $scope, "issueStatusById", (issueStatusById) -> $el.html(issueStatusById[issue.status].name) return {link:link} ListItemTaskStatusDirective = -> link = ($scope, $el, $attrs) -> task = $scope.$eval($attrs.tgListitemTaskStatus) bindOnce $scope, "taskStatusById", (taskStatusById) -> $el.html(taskStatusById[task.status].name) return {link:link} ListItemUsStatusDirective = -> link = ($scope, $el, $attrs) -> us = $scope.$eval($attrs.tgListitemUsStatus) bindOnce $scope, "usStatusById", (usStatusById) -> $el.html(usStatusById[us.status].name) return {link:link} ListItemAssignedtoDirective = -> template = _.template(""" <figure class="avatar"> <img src="<%- imgurl %>" alt="<%- name %>"/> <figcaption><%- name %></figcaption> </figure> """) link = ($scope, $el, $attrs) -> bindOnce $scope, "membersById", (membersById) -> item = $scope.$eval($attrs.tgListitemAssignedto) ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"} member = membersById[item.assigned_to] if member ctx.imgurl = member.photo ctx.name = member.full_name $el.html(template(ctx)) return {link:link} ListItemPriorityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (priorityById, issue) -> priority = priorityById[issue.priority] domNode = $el.find(".level") domNode.css("background-color", priority.color) domNode.attr("title", priority.name) bindOnce $scope, "priorityById", (priorityById) -> issue = $scope.$eval($attrs.tgListitemPriority) render(priorityById, issue) $scope.$watch $attrs.tgListitemPriority, (issue) -> render($scope.priorityById, issue) return { link: link template: template } ListItemSeverityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (severityById, issue) -> severity = severityById[issue.severity] domNode = $el.find(".level") domNode.css("background-color", severity.color) domNode.attr("title", severity.name) bindOnce $scope, "severityById", (severityById) -> issue = $scope.$eval($attrs.tgListitemSeverity) render(severityById, issue) $scope.$watch $attrs.tgListitemSeverity, (issue) -> render($scope.severityById, issue) return { link: link template: template } ListItemTypeDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (issueTypeById, issue) -> type = issueTypeById[issue.type] domNode = $el.find(".level") domNode.css("background-color", type.color) domNode.attr("title", type.name) bindOnce $scope, "issueTypeById", (issueTypeById) -> issue = $scope.$eval($attrs.tgListitemType) render(issueTypeById, issue) $scope.$watch $attrs.tgListitemType, (issue) -> render($scope.issueTypeById, issue) return { link: link template: template } ############################################################################# ## Progress bar directive ############################################################################# TgProgressBarDirective = -> template = _.template(""" <div class="current-progress" style="width: <%- percentage %>%"></div> """) render = (el, percentage) -> el.html(template({percentage: percentage})) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch $attrs.tgProgressBar, (percentage) -> percentage = _.max([0 , percentage]) percentage = _.min([100, percentage]) render($el, percentage) $scope.$on "$destroy", -> $el.off() return {link: link} ############################################################################# ## Main title directive ############################################################################# TgMainTitleDirective = -> template = _.template(""" <span class="project-name"><%- projectName %></span> <span class="green"><%- sectionName %></span> """) render = (el, projectName, sectionName) -> el.html(template({ projectName: projectName sectionName: sectionName })) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch "project", (project) -> render($el, project.name, $scope.sectionName) if project $scope.$on "project:loaded", (ctx, project) => render($el, project.name, $scope.sectionName) $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgListitemType", ListItemTypeDirective) module.directive("tgListitemIssueStatus", ListItemIssueStatusDirective) module.directive("tgListitemAssignedto", ListItemAssignedtoDirective) module.directive("tgListitemPriority", ListItemPriorityDirective) module.directive("tgListitemSeverity", ListItemSeverityDirective) module.directive("tgListitemTaskStatus", ListItemTaskStatusDirective) module.directive("tgListitemUsStatus", ListItemUsStatusDirective) module.directive("tgProgressBar", TgProgressBarDirective) module.directive("tgMainTitle", TgMainTitleDirective)
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/components.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce module = angular.module("taigaCommon") ############################################################################# ## Date Range Directive (used mainly for sprint date range) ############################################################################# DateRangeDirective = -> renderRange = ($el, first, second) -> initDate = moment(first).format("DD MMM YYYY") endDate = moment(second).format("DD MMM YYYY") $el.html("#{initDate}-#{endDate}") link = ($scope, $el, $attrs) -> [first, second] = $attrs.tgDateRange.split(",") bindOnce $scope, first, (valFirst) -> bindOnce $scope, second, (valSecond) -> renderRange($el, valFirst, valSecond) return {link:link} module.directive("tgDateRange", DateRangeDirective) ############################################################################# ## Date Selector Directive (using pikaday) ############################################################################# DateSelectorDirective =-> link = ($scope, $el, $attrs, $model) -> selectedDate = null $el.picker = new Pikaday({ field: $el[0] format: "DD MMM YYYY" onSelect: (date) => selectedDate = date onOpen: => $el.picker.setDate(selectedDate) if selectedDate? }) $scope.$watch $attrs.ngModel, (val) -> $el.picker.setDate(val) if val? return { link: link require: "ngModel" } module.directive("tgDateSelector", DateSelectorDirective) ############################################################################# ## Sprint Progress Bar Directive ############################################################################# SprintProgressBarDirective = -> renderProgress = ($el, percentage, visual_percentage) -> if $el.hasClass(".current-progress") $el.css("width", "#{percentage}%") else $el.find(".current-progress").css("width", "#{visual_percentage}%") $el.find(".number").html("#{percentage} %") link = ($scope, $el, $attrs) -> bindOnce $scope, $attrs.tgSprintProgressbar, (sprint) -> closedPoints = sprint.closed_points totalPoints = sprint.total_points percentage = 0 percentage = Math.round(100 * (closedPoints/totalPoints)) if totalPoints != 0 visual_percentage = 0 #Visual hack for .current-progress bar visual_percentage = Math.round(98 * (closedPoints/totalPoints)) if totalPoints != 0 renderProgress($el, percentage, visual_percentage) return {link: link} module.directive("tgSprintProgressbar", SprintProgressBarDirective) ############################################################################# ## Created-by display directive ############################################################################# CreatedByDisplayDirective = -> # Display the owner information (full name and photo) and the date of # creation of an object (like USs, tasks and issues). # # Example: # div.us-created-by(tg-created-by-display, ng-model="us") # # Requirements: # - model object must have the attributes 'created_date' and # 'owner'(ng-model) # - scope.usersById object is required. template = _.template(""" <div class="user-avatar"> <img src="<%- owner.photo %>" alt="<%- owner.full_name_display %>" /> </div> <div class="created-by"> <span class="created-title">Created by <%- owner.full_name_display %></span> <span class="created-date"><%- date %></span> </div> """) # TODO: i18n link = ($scope, $el, $attrs) -> render = (model) -> owner = $scope.usersById?[model.owner] or { full_name_display: "external user" photo: "/images/unnamed.png" } html = template({ owner: owner date: moment(model.created_date).format("DD MMM YYYY HH:mm") }) $el.html(html) bindOnce $scope, $attrs.ngModel, (model) -> render(model) if model? $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgCreatedByDisplay", CreatedByDisplayDirective) ############################################################################# ## Watchers directive ############################################################################# WatchersDirective = ($rootscope, $confirm, $repo, $qqueue) -> # You have to include a div with the tg-lb-watchers directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if(isEditable){ %> <div class="watchers-header"> <span class="title">watchers</span> <a href="" title="Add watcher" class="icon icon-plus add-watcher"></a> </div> <% } else if(watchers.length > 0){ %> <div class="watchers-header"> <span class="title">watchers</span> </div> <% }; %> <% _.each(watchers, function(watcher) { %> <% if(watcher) { %> <div class="watcher-single"> <div class="watcher-avatar"> <span class="avatar" href="" title="<%- watcher.full_name_display %>"> <img src="<%- watcher.photo %>" alt="<%- watcher.full_name_display %>"> </span> </div> <div class="watcher-name"> <span><%- watcher.full_name_display %></span> <% if(isEditable){ %> <a class="icon icon-delete" data-watcher-id="<%- watcher.id %>" href="" title="delete-watcher"> </a> <% }; %> </div> </div> <% } %> <% }); %> """) link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (watchers) => item = $model.$modelValue.clone() item.watchers = watchers $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() deleteWatcher = $qqueue.bindAdd (watcherIds) => item = $model.$modelValue.clone() item.watchers = watcherIds $model.$setViewValue(item) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $rootscope.$broadcast("history:reload") promise.then null, -> item.revert() $confirm.notify("error") renderWatchers = (watchers) -> ctx = { watchers: watchers isEditable: isEditable() } html = template(ctx) $el.html(html) if isEditable() and watchers.length == 0 $el.find(".title").text("Add watchers") $el.find(".watchers-header").addClass("no-watchers") $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() target = angular.element(event.currentTarget) watcherId = target.data("watcher-id") title = "Delete watcher" message = $scope.usersById[watcherId].full_name_display $confirm.askOnDelete(title, message).then (finish) => finish() watcherIds = _.clone($model.$modelValue.watchers, false) watcherIds = _.pull(watcherIds, watcherId) deleteWatcher(watcherIds) $el.on "click", ".add-watcher", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("watcher:add", $model.$modelValue) $scope.$on "watcher:added", (ctx, watcherId) -> watchers = _.clone($model.$modelValue.watchers, false) watchers.push(watcherId) watchers = _.uniq(watchers) save(watchers) $scope.$watch $attrs.ngModel, (item) -> return if not item? watchers = _.map(item.watchers, (watcherId) -> $scope.usersById[watcherId]) renderWatchers(watchers) $scope.$on "$destroy", -> $el.off() return {link:link, require:"ngModel"} module.directive("tgWatchers", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgQqueue", WatchersDirective]) ############################################################################# ## Assigned to directive ############################################################################# AssignedToDirective = ($rootscope, $confirm, $repo, $loading, $qqueue) -> # You have to include a div with the tg-lb-assignedto directive in the page # where use this directive # # TODO: i18n template = _.template(""" <% if (assignedTo) { %> <div class="user-avatar"> <img src="<%- assignedTo.photo %>" alt="<%- assignedTo.full_name_display %>" /> </div> <% } %> <div class="assigned-to"> <span class="assigned-title">Assigned to</span> <a href="" title="edit assignment" class="user-assigned <% if(isEditable){ %>editable<% }; %>"> <span class="assigned-name"> <% if (assignedTo) { %> <%- assignedTo.full_name_display %> <% } else { %> Not assigned <% } %> </span> <% if(isEditable){ %><span class="icon icon-arrow-bottom"></span><% }; %> </a> <% if (assignedTo!==null && isEditable) { %> <a href="" title="delete assignment" class="icon icon-delete"></a> <% } %> </div> """) # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project?.my_permissions?.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (userId) => $model.$modelValue.assigned_to = userId $loading.start($el) promise = $repo.save($model.$modelValue) promise.then -> $loading.finish($el) $confirm.notify("success") renderAssignedTo($model.$modelValue) $rootscope.$broadcast("history:reload") promise.then null, -> $model.$modelValue.revert() $confirm.notify("error") $loading.finish($el) return promise renderAssignedTo = (issue) -> assignedToId = issue?.assigned_to assignedTo = if assignedToId? then $scope.usersById[assignedToId] else null ctx = { assignedTo: assignedTo isEditable: isEditable() } html = template(ctx) $el.html(html) $el.on "click", ".user-assigned", (event) -> event.preventDefault() return if not isEditable() $scope.$apply -> $rootscope.$broadcast("assigned-to:add", $model.$modelValue) $el.on "click", ".icon-delete", (event) -> event.preventDefault() return if not isEditable() title = "Are you sure you want to leave it unassigned?" # TODO: i18n $confirm.ask(title).then (finish) => finish() $model.$modelValue.assigned_to = null save(null) $scope.$on "assigned-to:added", (ctx, userId, item) -> return if item.id != $model.$modelValue.id save(userId) $scope.$watch $attrs.ngModel, (instance) -> renderAssignedTo(instance) $scope.$on "$destroy", -> $el.off() return { link:link, require:"ngModel" } module.directive("tgAssignedTo", ["$rootScope", "$tgConfirm", "$tgRepo", "$tgLoading", "$tgQqueue", AssignedToDirective]) ############################################################################# ## Block Button directive ############################################################################# BlockButtonDirective = ($rootscope, $loading) -> template = """ <a href="#" class="button button-gray item-block">Block</a> <a href="#" class="button button-red item-unblock">Unblock</a> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_us") != -1 $scope.$watch $attrs.ngModel, (item) -> return if not item if isEditable() $el.find('.item-block').addClass('editable') if item.is_blocked $el.find('.item-block').hide() $el.find('.item-unblock').show() else $el.find('.item-block').show() $el.find('.item-unblock').hide() $el.on "click", ".item-block", (event) -> event.preventDefault() $rootscope.$broadcast("block", $model.$modelValue) $el.on "click", ".item-unblock", (event) -> event.preventDefault() $loading.start($el.find(".item-unblock")) finish = -> $loading.finish($el.find(".item-unblock")) $rootscope.$broadcast("unblock", $model.$modelValue, finish) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgBlockButton", ["$rootScope", "$tgLoading", BlockButtonDirective]) ############################################################################# ## Delete Button directive ############################################################################# DeleteButtonDirective = ($log, $repo, $confirm, $location) -> template = """ <a href="" class="button button-red">Delete</a> """ #TODO: i18n link = ($scope, $el, $attrs, $model) -> if not $attrs.onDeleteGoToUrl return $log.error "DeleteButtonDirective requires on-delete-go-to-url set in scope." if not $attrs.onDeleteTitle return $log.error "DeleteButtonDirective requires on-delete-title set in scope." $el.on "click", ".button", (event) -> title = $scope.$eval($attrs.onDeleteTitle) subtitle = $model.$modelValue.subject $confirm.askOnDelete(title, subtitle).then (finish) => promise = $repo.remove($model.$modelValue) promise.then => finish() url = $scope.$eval($attrs.onDeleteGoToUrl) $location.path(url) promise.then null, => finish(false) $confirm.notify("error") $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgDeleteButton", ["$log", "$tgRepo", "$tgConfirm", "$tgLocation", DeleteButtonDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableSubjectDirective = ($rootscope, $repo, $confirm, $loading, $qqueue) -> template = """ <div class="view-subject"> {{ item.subject }} <a class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-subject"> <input type="text" ng-model="item.subject" data-required="true" data-maxlength="500"/> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (subject) => $model.$modelValue.subject = subject $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-subject').hide() $el.find('.view-subject').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) return promise $el.click -> return if not isEditable() $el.find('.edit-subject').show() $el.find('.view-subject').hide() $el.find('input').focus() $el.on "click", ".save", -> subject = $scope.item.subject save(subject) $el.on "keyup", "input", (event) -> if event.keyCode == 13 subject = $scope.item.subject save(subject) else if event.keyCode == 27 $scope.$apply () => $model.$modelValue.revert() $el.find('div.edit-subject').hide() $el.find('div.view-subject').show() $el.find('div.edit-subject').hide() $el.find('div.view-subject span.edit').hide() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if not isEditable() $el.find('.view-subject .edit').remove() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableSubject", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", EditableSubjectDirective]) ############################################################################# ## Editable subject directive ############################################################################# EditableDescriptionDirective = ($rootscope, $repo, $confirm, $compile, $loading, $selectedText, $qqueue) -> template = """ <div class="view-description"> <section class="us-content wysiwyg" tg-bind-html="item.description_html || noDescriptionMsg"></section> <span class="edit icon icon-edit" href="" title="Edit" /> </div> <div class="edit-description"> <textarea placeholder="Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet..." ng-model="item.description" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="save-container"> <a class="save icon icon-floppy" href="" title="Save" /> </span> </div> """ # TODO: i18n noDescriptionMegEditMode = """ <p class="no-description editable"> Empty space is so boring... go on be descriptive... A rose by any other name would smell as sweet... </p> """ # TODO: i18n noDescriptionMegReadMode = """ <p class="no-description"> No description yet. </p> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> $el.find('.edit-description').hide() $el.find('.view-description .edit').hide() isEditable = -> return $scope.project.my_permissions.indexOf($attrs.requiredPerm) != -1 save = $qqueue.bindAdd (description) => $model.$modelValue.description = description $loading.start($el.find('.save-container')) promise = $repo.save($model.$modelValue) promise.then -> $confirm.notify("success") $rootscope.$broadcast("history:reload") $el.find('.edit-description').hide() $el.find('.view-description').show() promise.then null, -> $confirm.notify("error") promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-description", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if $selectedText.get().length $el.find('.edit-description').show() $el.find('.view-description').hide() $el.find('textarea').focus() $el.on "click", ".save", -> description = $scope.item.description save(description) $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 $scope.$apply () => $scope.item.revert() $el.find('.edit-description').hide() $el.find('.view-description').show() $scope.$watch $attrs.ngModel, (value) -> return if not value $scope.item = value if isEditable() $el.find('.view-description .edit').show() $el.find('.view-description .us-content').addClass('editable') $scope.noDescriptionMsg = noDescriptionMegEditMode else $scope.noDescriptionMsg = noDescriptionMegReadMode $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableDescription", ["$rootScope", "$tgRepo", "$tgConfirm", "$compile", "$tgLoading", "$selectedText", "$tgQqueue", EditableDescriptionDirective]) ############################################################################# ## Common list directives ############################################################################# ## NOTE: These directives are used in issues and search and are ## completely bindonce, they only serves for visualization of data. ############################################################################# ListItemIssueStatusDirective = -> link = ($scope, $el, $attrs) -> issue = $scope.$eval($attrs.tgListitemIssueStatus) bindOnce $scope, "issueStatusById", (issueStatusById) -> $el.html(issueStatusById[issue.status].name) return {link:link} ListItemTaskStatusDirective = -> link = ($scope, $el, $attrs) -> task = $scope.$eval($attrs.tgListitemTaskStatus) bindOnce $scope, "taskStatusById", (taskStatusById) -> $el.html(taskStatusById[task.status].name) return {link:link} ListItemUsStatusDirective = -> link = ($scope, $el, $attrs) -> us = $scope.$eval($attrs.tgListitemUsStatus) bindOnce $scope, "usStatusById", (usStatusById) -> $el.html(usStatusById[us.status].name) return {link:link} ListItemAssignedtoDirective = -> template = _.template(""" <figure class="avatar"> <img src="<%- imgurl %>" alt="<%- name %>"/> <figcaption><%- name %></figcaption> </figure> """) link = ($scope, $el, $attrs) -> bindOnce $scope, "membersById", (membersById) -> item = $scope.$eval($attrs.tgListitemAssignedto) ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"} member = membersById[item.assigned_to] if member ctx.imgurl = member.photo ctx.name = member.full_name $el.html(template(ctx)) return {link:link} ListItemPriorityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (priorityById, issue) -> priority = priorityById[issue.priority] domNode = $el.find(".level") domNode.css("background-color", priority.color) domNode.attr("title", priority.name) bindOnce $scope, "priorityById", (priorityById) -> issue = $scope.$eval($attrs.tgListitemPriority) render(priorityById, issue) $scope.$watch $attrs.tgListitemPriority, (issue) -> render($scope.priorityById, issue) return { link: link template: template } ListItemSeverityDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (severityById, issue) -> severity = severityById[issue.severity] domNode = $el.find(".level") domNode.css("background-color", severity.color) domNode.attr("title", severity.name) bindOnce $scope, "severityById", (severityById) -> issue = $scope.$eval($attrs.tgListitemSeverity) render(severityById, issue) $scope.$watch $attrs.tgListitemSeverity, (issue) -> render($scope.severityById, issue) return { link: link template: template } ListItemTypeDirective = -> template = """ <div class="level"></div> """ link = ($scope, $el, $attrs) -> render = (issueTypeById, issue) -> type = issueTypeById[issue.type] domNode = $el.find(".level") domNode.css("background-color", type.color) domNode.attr("title", type.name) bindOnce $scope, "issueTypeById", (issueTypeById) -> issue = $scope.$eval($attrs.tgListitemType) render(issueTypeById, issue) $scope.$watch $attrs.tgListitemType, (issue) -> render($scope.issueTypeById, issue) return { link: link template: template } ############################################################################# ## Progress bar directive ############################################################################# TgProgressBarDirective = -> template = _.template(""" <div class="current-progress" style="width: <%- percentage %>%"></div> """) render = (el, percentage) -> el.html(template({percentage: percentage})) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch $attrs.tgProgressBar, (percentage) -> percentage = _.max([0 , percentage]) percentage = _.min([100, percentage]) render($el, percentage) $scope.$on "$destroy", -> $el.off() return {link: link} ############################################################################# ## Main title directive ############################################################################# TgMainTitleDirective = -> template = _.template(""" <span class="project-name"><%- projectName %></span> <span class="green"><%- sectionName %></span> """) render = (el, projectName, sectionName) -> el.html(template({ projectName: projectName sectionName: sectionName })) link = ($scope, $el, $attrs) -> element = angular.element($el) $scope.$watch "project", (project) -> render($el, project.name, $scope.sectionName) if project $scope.$on "project:loaded", (ctx, project) => render($el, project.name, $scope.sectionName) $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgListitemType", ListItemTypeDirective) module.directive("tgListitemIssueStatus", ListItemIssueStatusDirective) module.directive("tgListitemAssignedto", ListItemAssignedtoDirective) module.directive("tgListitemPriority", ListItemPriorityDirective) module.directive("tgListitemSeverity", ListItemSeverityDirective) module.directive("tgListitemTaskStatus", ListItemTaskStatusDirective) module.directive("tgListitemUsStatus", ListItemUsStatusDirective) module.directive("tgProgressBar", TgProgressBarDirective) module.directive("tgMainTitle", TgMainTitleDirective)
[ { "context": "top|disable>\n# Hubot relay state\n#\n# Author:\n# clicia scarlet <yuyuvn@icloud.com>\n\nmodule.exports = (robot) ->\n", "end": 621, "score": 0.99969482421875, "start": 607, "tag": "NAME", "value": "clicia scarlet" }, { "context": "Hubot relay state\n#\n# Author:\n# clicia scarlet <yuyuvn@icloud.com>\n\nmodule.exports = (robot) ->\n robot.catchAll (m", "end": 640, "score": 0.9999103546142578, "start": 623, "tag": "EMAIL", "value": "yuyuvn@icloud.com" } ]
src/relay.coffee
yuyuvn/hubot-relay
0
# Description: # Relay message to another chatbox via http # # Dependencies: # "coffee-script": "~1.6" # # Configuration: # RELAY_EVERYTHING - Relay message that didn't call bot name # RELAY_URL - URL relay to # RELAY_RESPONSE - Bot will respond even when relay successfully # RELAY_ENABLE_COMMAND - Support command # RELAY_ENABLE_RECEIVE - Enable receive relay message # # Commands: # Hubot relay add <url> # Hubot relay delete <url> # Hubot relay delete all # Hubot relay list <url> # Hubot relay <start|enable> # Hubot relay <stop|disable> # Hubot relay state # # Author: # clicia scarlet <yuyuvn@icloud.com> module.exports = (robot) -> robot.catchAll (msg) -> # Message class doesn't have text property so we need to check it before relay return if !msg.message.text r = new RegExp "^(?:#{robot.alias}|#{robot.name}) ([^]+)", "i" matches = msg.message.text.match(r) if matches != null && matches.length > 1 message = matches[1] else return if !process.env.RELAY_EVERYTHING message = msg.message.text message = if robot.adapter.removeFormatting then robot.adapter.removeFormatting(message) else message if process.env.RELAY_ENABLE_COMMAND return if !robot.brain.get(msg.message.user.name + "_relay_enable") urls = robot.brain.get(msg.message.user.name + "_relay_url") || (if process.env.RELAY_URL then process.env.RELAY_URL.split("|") else null) msg.send "Relay Error! Use '#{robot.name} relay add <relay_url>' to add relay url" if !urls else return if !process.env.RELAY_URL urls = process.env.RELAY_URL.split "|" urls.forEach (url) -> data = JSON.stringify({msg: message}) robot.http(url) .header('Content-Type', 'application/json') .post(data) (err, res, body) -> if err msg.send "Relay failed :(\n #{err}" else if process.env.RELAY_RESPONSE msg.send "Relay completed '#{message}'" if process.env.RELAY_ENABLE_COMMAND robot.respond /relay add (.+)/, (msg) -> url = msg.match[1] brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key list = [] if !list list.push url robot.brain.set brain_key, list robot.brain.save msg.send "Added '#{url}' to relay list" robot.respond /relay delete (.+)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND url = msg.match[1] return if url == "all" brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key if list index = list.indexOf(url) list.splice(index, 1) if index >= 0 robot.brain.set brain_key, list robot.brain.save msg.send "Deleted '#{url}' from relay list" robot.respond /relay list/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND urls = robot.brain.get(msg.message.user.name + "_relay_url") || [] msg.send "Relay list:\n" + urls.join("\n") robot.respond /relay delete all/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_url"), [] robot.brain.save msg.send "Deleted all urls from relay list" robot.respond /relay (start|enable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), true robot.brain.save msg.send "Relay is enabled" robot.respond /relay (stop|disable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), false robot.brain.save msg.send "Relay is disabled" robot.respond /relay state/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND state = robot.brain.get (msg.message.user.name + "_relay_enable"), false state_mes = if state then "enabled" else "disabled" msg.send "Relay is #{state_mes}" if process.env.RELAY_ENABLE_RECEIVE robot.router.post "/hubot/relay/:room", (req, res) -> room = req.params.room msg = req.body.msg robot.messageRoom room, msg res.send 'OK'
22332
# Description: # Relay message to another chatbox via http # # Dependencies: # "coffee-script": "~1.6" # # Configuration: # RELAY_EVERYTHING - Relay message that didn't call bot name # RELAY_URL - URL relay to # RELAY_RESPONSE - Bot will respond even when relay successfully # RELAY_ENABLE_COMMAND - Support command # RELAY_ENABLE_RECEIVE - Enable receive relay message # # Commands: # Hubot relay add <url> # Hubot relay delete <url> # Hubot relay delete all # Hubot relay list <url> # Hubot relay <start|enable> # Hubot relay <stop|disable> # Hubot relay state # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> robot.catchAll (msg) -> # Message class doesn't have text property so we need to check it before relay return if !msg.message.text r = new RegExp "^(?:#{robot.alias}|#{robot.name}) ([^]+)", "i" matches = msg.message.text.match(r) if matches != null && matches.length > 1 message = matches[1] else return if !process.env.RELAY_EVERYTHING message = msg.message.text message = if robot.adapter.removeFormatting then robot.adapter.removeFormatting(message) else message if process.env.RELAY_ENABLE_COMMAND return if !robot.brain.get(msg.message.user.name + "_relay_enable") urls = robot.brain.get(msg.message.user.name + "_relay_url") || (if process.env.RELAY_URL then process.env.RELAY_URL.split("|") else null) msg.send "Relay Error! Use '#{robot.name} relay add <relay_url>' to add relay url" if !urls else return if !process.env.RELAY_URL urls = process.env.RELAY_URL.split "|" urls.forEach (url) -> data = JSON.stringify({msg: message}) robot.http(url) .header('Content-Type', 'application/json') .post(data) (err, res, body) -> if err msg.send "Relay failed :(\n #{err}" else if process.env.RELAY_RESPONSE msg.send "Relay completed '#{message}'" if process.env.RELAY_ENABLE_COMMAND robot.respond /relay add (.+)/, (msg) -> url = msg.match[1] brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key list = [] if !list list.push url robot.brain.set brain_key, list robot.brain.save msg.send "Added '#{url}' to relay list" robot.respond /relay delete (.+)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND url = msg.match[1] return if url == "all" brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key if list index = list.indexOf(url) list.splice(index, 1) if index >= 0 robot.brain.set brain_key, list robot.brain.save msg.send "Deleted '#{url}' from relay list" robot.respond /relay list/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND urls = robot.brain.get(msg.message.user.name + "_relay_url") || [] msg.send "Relay list:\n" + urls.join("\n") robot.respond /relay delete all/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_url"), [] robot.brain.save msg.send "Deleted all urls from relay list" robot.respond /relay (start|enable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), true robot.brain.save msg.send "Relay is enabled" robot.respond /relay (stop|disable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), false robot.brain.save msg.send "Relay is disabled" robot.respond /relay state/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND state = robot.brain.get (msg.message.user.name + "_relay_enable"), false state_mes = if state then "enabled" else "disabled" msg.send "Relay is #{state_mes}" if process.env.RELAY_ENABLE_RECEIVE robot.router.post "/hubot/relay/:room", (req, res) -> room = req.params.room msg = req.body.msg robot.messageRoom room, msg res.send 'OK'
true
# Description: # Relay message to another chatbox via http # # Dependencies: # "coffee-script": "~1.6" # # Configuration: # RELAY_EVERYTHING - Relay message that didn't call bot name # RELAY_URL - URL relay to # RELAY_RESPONSE - Bot will respond even when relay successfully # RELAY_ENABLE_COMMAND - Support command # RELAY_ENABLE_RECEIVE - Enable receive relay message # # Commands: # Hubot relay add <url> # Hubot relay delete <url> # Hubot relay delete all # Hubot relay list <url> # Hubot relay <start|enable> # Hubot relay <stop|disable> # Hubot relay state # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> robot.catchAll (msg) -> # Message class doesn't have text property so we need to check it before relay return if !msg.message.text r = new RegExp "^(?:#{robot.alias}|#{robot.name}) ([^]+)", "i" matches = msg.message.text.match(r) if matches != null && matches.length > 1 message = matches[1] else return if !process.env.RELAY_EVERYTHING message = msg.message.text message = if robot.adapter.removeFormatting then robot.adapter.removeFormatting(message) else message if process.env.RELAY_ENABLE_COMMAND return if !robot.brain.get(msg.message.user.name + "_relay_enable") urls = robot.brain.get(msg.message.user.name + "_relay_url") || (if process.env.RELAY_URL then process.env.RELAY_URL.split("|") else null) msg.send "Relay Error! Use '#{robot.name} relay add <relay_url>' to add relay url" if !urls else return if !process.env.RELAY_URL urls = process.env.RELAY_URL.split "|" urls.forEach (url) -> data = JSON.stringify({msg: message}) robot.http(url) .header('Content-Type', 'application/json') .post(data) (err, res, body) -> if err msg.send "Relay failed :(\n #{err}" else if process.env.RELAY_RESPONSE msg.send "Relay completed '#{message}'" if process.env.RELAY_ENABLE_COMMAND robot.respond /relay add (.+)/, (msg) -> url = msg.match[1] brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key list = [] if !list list.push url robot.brain.set brain_key, list robot.brain.save msg.send "Added '#{url}' to relay list" robot.respond /relay delete (.+)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND url = msg.match[1] return if url == "all" brain_key = msg.message.user.name + "_relay_url" list = robot.brain.get brain_key if list index = list.indexOf(url) list.splice(index, 1) if index >= 0 robot.brain.set brain_key, list robot.brain.save msg.send "Deleted '#{url}' from relay list" robot.respond /relay list/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND urls = robot.brain.get(msg.message.user.name + "_relay_url") || [] msg.send "Relay list:\n" + urls.join("\n") robot.respond /relay delete all/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_url"), [] robot.brain.save msg.send "Deleted all urls from relay list" robot.respond /relay (start|enable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), true robot.brain.save msg.send "Relay is enabled" robot.respond /relay (stop|disable)/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND robot.brain.set (msg.message.user.name + "_relay_enable"), false robot.brain.save msg.send "Relay is disabled" robot.respond /relay state/, (msg) -> return if !process.env.RELAY_ENABLE_COMMAND state = robot.brain.get (msg.message.user.name + "_relay_enable"), false state_mes = if state then "enabled" else "disabled" msg.send "Relay is #{state_mes}" if process.env.RELAY_ENABLE_RECEIVE robot.router.post "/hubot/relay/:room", (req, res) -> room = req.params.room msg = req.body.msg robot.messageRoom room, msg res.send 'OK'
[ { "context": ", value) ->\n d = new Date(value.time)\n key = \"#{d.getFullYear()}-#{d.getMonth() + 1}-#{d.getDate()}\"\n arr[key] = [] unless arr[key]\n arr[key].pu", "end": 1109, "score": 0.7758246660232544, "start": 1054, "tag": "KEY", "value": "\"#{d.getFullYear()}-#{d.getMonth() + 1}-#{d.getDate()}\"" } ]
src/iced/archivist.iced
stampery/trailbot-vault
0
app = document.app vault = document.vault archivist = -> @after 'initialize', -> vault.on 'synced', @globalArchive @globalArchive = => window.mkdir "archive" app.settings.watchers.forEach @watcherArchive @watcherArchive = (watcher) => for path, file of watcher.settings.files @fileArchive path, file, watcher.events @fileArchive = (path, file, events) => if events[path] events[path].sort @sortBy limit = @getLimit file.archive || 30 # index of the first event older than the limit indexOlder = undefined for i, ev of events[path] if ev.ref < limit indexOlder = i break if indexOlder archivable = events[path].slice indexOlder events[path] = events[path].slice 0, indexOlder app.save() archivable = archivable.reduce @groupByDay, [] for date, lines of archivable @writeToFile "#{@getBaseName path}-#{date}", lines.join "\n" @groupByDay = (arr, value) -> d = new Date(value.time) key = "#{d.getFullYear()}-#{d.getMonth() + 1}-#{d.getDate()}" arr[key] = [] unless arr[key] arr[key].push JSON.stringify value arr @writeToFile = (prefix, txt) -> window.fs.writeFile "archive/#{prefix}-archive", txt, (err) -> if err console.log "Error creating the archiving file #{prefix} #{err}" else console.log "Archive for date #{prefix} succesfully saved" @sortBy = (a, b, field = "ref") -> if a[field] < b[field] return 1 if a[field] > b[field] return -1 return 0 # current date minus the number of days , return epoch @getLimit = (days) -> now = new Date() limit = new Date() limit.setDate(now.getDate() - (days)) limit.setHours(23) limit.setMinutes(59) limit.setSeconds(59) Date.parse limit @getBaseName = (path) -> path.split(/[\\/]/).reverse()[0].split(".")[0] Archivist = flight.component archivist Archivist.attachTo document module.exports = Archivist
32630
app = document.app vault = document.vault archivist = -> @after 'initialize', -> vault.on 'synced', @globalArchive @globalArchive = => window.mkdir "archive" app.settings.watchers.forEach @watcherArchive @watcherArchive = (watcher) => for path, file of watcher.settings.files @fileArchive path, file, watcher.events @fileArchive = (path, file, events) => if events[path] events[path].sort @sortBy limit = @getLimit file.archive || 30 # index of the first event older than the limit indexOlder = undefined for i, ev of events[path] if ev.ref < limit indexOlder = i break if indexOlder archivable = events[path].slice indexOlder events[path] = events[path].slice 0, indexOlder app.save() archivable = archivable.reduce @groupByDay, [] for date, lines of archivable @writeToFile "#{@getBaseName path}-#{date}", lines.join "\n" @groupByDay = (arr, value) -> d = new Date(value.time) key = <KEY> arr[key] = [] unless arr[key] arr[key].push JSON.stringify value arr @writeToFile = (prefix, txt) -> window.fs.writeFile "archive/#{prefix}-archive", txt, (err) -> if err console.log "Error creating the archiving file #{prefix} #{err}" else console.log "Archive for date #{prefix} succesfully saved" @sortBy = (a, b, field = "ref") -> if a[field] < b[field] return 1 if a[field] > b[field] return -1 return 0 # current date minus the number of days , return epoch @getLimit = (days) -> now = new Date() limit = new Date() limit.setDate(now.getDate() - (days)) limit.setHours(23) limit.setMinutes(59) limit.setSeconds(59) Date.parse limit @getBaseName = (path) -> path.split(/[\\/]/).reverse()[0].split(".")[0] Archivist = flight.component archivist Archivist.attachTo document module.exports = Archivist
true
app = document.app vault = document.vault archivist = -> @after 'initialize', -> vault.on 'synced', @globalArchive @globalArchive = => window.mkdir "archive" app.settings.watchers.forEach @watcherArchive @watcherArchive = (watcher) => for path, file of watcher.settings.files @fileArchive path, file, watcher.events @fileArchive = (path, file, events) => if events[path] events[path].sort @sortBy limit = @getLimit file.archive || 30 # index of the first event older than the limit indexOlder = undefined for i, ev of events[path] if ev.ref < limit indexOlder = i break if indexOlder archivable = events[path].slice indexOlder events[path] = events[path].slice 0, indexOlder app.save() archivable = archivable.reduce @groupByDay, [] for date, lines of archivable @writeToFile "#{@getBaseName path}-#{date}", lines.join "\n" @groupByDay = (arr, value) -> d = new Date(value.time) key = PI:KEY:<KEY>END_PI arr[key] = [] unless arr[key] arr[key].push JSON.stringify value arr @writeToFile = (prefix, txt) -> window.fs.writeFile "archive/#{prefix}-archive", txt, (err) -> if err console.log "Error creating the archiving file #{prefix} #{err}" else console.log "Archive for date #{prefix} succesfully saved" @sortBy = (a, b, field = "ref") -> if a[field] < b[field] return 1 if a[field] > b[field] return -1 return 0 # current date minus the number of days , return epoch @getLimit = (days) -> now = new Date() limit = new Date() limit.setDate(now.getDate() - (days)) limit.setHours(23) limit.setMinutes(59) limit.setSeconds(59) Date.parse limit @getBaseName = (path) -> path.split(/[\\/]/).reverse()[0].split(".")[0] Archivist = flight.component archivist Archivist.attachTo document module.exports = Archivist
[ { "context": ".then (element) =>\n return element.sendKeys('admin@example.com')\n .then =>\n return @driver.findElement(@", "end": 489, "score": 0.9998733401298523, "start": 472, "tag": "EMAIL", "value": "admin@example.com" }, { "context": ".then (element) =>\n return element.sendKeys('admin')\n .then =>\n return @driver.findElement(@", "end": 831, "score": 0.9307329654693604, "start": 826, "tag": "USERNAME", "value": "admin" } ]
features/step_definitions/authentication_steps.coffee
grappendorf/caretaker-webapp
0
module.exports = -> @World = require('webapp-tester').World @When /^I am authenticated as adminiatrator$/, (next) -> @driver.visit('#').then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Email']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('admin@example.com') .then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Password']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('admin') .then => return @driver.findElement(@webdriver.By.xpath("//*[normalize-space()='Sign in']")) .then (element) => return element.click() .then => next() , (x) => next.fail x
127250
module.exports = -> @World = require('webapp-tester').World @When /^I am authenticated as adminiatrator$/, (next) -> @driver.visit('#').then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Email']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('<EMAIL>') .then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Password']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('admin') .then => return @driver.findElement(@webdriver.By.xpath("//*[normalize-space()='Sign in']")) .then (element) => return element.click() .then => next() , (x) => next.fail x
true
module.exports = -> @World = require('webapp-tester').World @When /^I am authenticated as adminiatrator$/, (next) -> @driver.visit('#').then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Email']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('PI:EMAIL:<EMAIL>END_PI') .then => return @driver.findElement(@webdriver.By.xpath("//label[normalize-space()='Password']")) .then (element) => return element.getAttribute('id') .then (id) => return @driver.findElement(@webdriver.By.xpath("//input[@aria-labelledby='#{id}']")) .then (element) => return element.sendKeys('admin') .then => return @driver.findElement(@webdriver.By.xpath("//*[normalize-space()='Sign in']")) .then (element) => return element.click() .then => next() , (x) => next.fail x
[ { "context": "\n - on enter should validation fire by default??? Sinan - 6/6/2012\n\n###\n\n\nKDInputView = require './inpu", "end": 64, "score": 0.6342931389808655, "start": 61, "tag": "NAME", "value": "Sin" } ]
src/components/inputs/hitenterinputview.coffee
burakcan/kd
0
### todo: - on enter should validation fire by default??? Sinan - 6/6/2012 ### KDInputView = require './inputview.coffee' module.exports = class KDHitEnterInputView extends KDInputView constructor:(options = {}, data)-> options.type or= "textarea" options.button or= null options.showButton ?= no options.label or= null options.placeholder or= "" options.callback or= null options.togglerPartials or= ["quick update disabled","quick update enabled"] super options,data @setClass "hitenterview" @button = @getOptions().button ? null @enableEnterKey() @setToggler() if options.label? @disableEnterKey() if @getOptions().showButton @on "ValidationPassed", => @blur() @getOptions().callback?.call @,@getValue() enableEnterKey:-> @setClass "active" @hideButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[1]) if @inputEnterToggler? @enterKeyEnabled = yes disableEnterKey:-> @unsetClass "active" @showButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[0]) if @inputEnterToggler? @enterKeyEnabled = no setToggler:-> o = @getOptions() @inputEnterToggler = new KDCustomHTMLView tagName : "a" cssClass : "hitenterview-toggle" partial : if o.showButton then o.togglerPartials[0] else o.togglerPartials[1] click : @bound "toggleEnterKey" @inputLabel.addSubView @inputEnterToggler hideButton:-> @button.hide() showButton:-> @button.show() toggleEnterKey:-> if @enterKeyEnabled then @disableEnterKey() else @enableEnterKey() keyDown:(event)-> if event.which is 13 and (event.altKey or event.shiftKey) isnt true and @enterKeyEnabled @emit "EnterPerformed" @validate() no else if event.which is 27 # escape @emit "EscapePerformed"
59507
### todo: - on enter should validation fire by default??? <NAME>an - 6/6/2012 ### KDInputView = require './inputview.coffee' module.exports = class KDHitEnterInputView extends KDInputView constructor:(options = {}, data)-> options.type or= "textarea" options.button or= null options.showButton ?= no options.label or= null options.placeholder or= "" options.callback or= null options.togglerPartials or= ["quick update disabled","quick update enabled"] super options,data @setClass "hitenterview" @button = @getOptions().button ? null @enableEnterKey() @setToggler() if options.label? @disableEnterKey() if @getOptions().showButton @on "ValidationPassed", => @blur() @getOptions().callback?.call @,@getValue() enableEnterKey:-> @setClass "active" @hideButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[1]) if @inputEnterToggler? @enterKeyEnabled = yes disableEnterKey:-> @unsetClass "active" @showButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[0]) if @inputEnterToggler? @enterKeyEnabled = no setToggler:-> o = @getOptions() @inputEnterToggler = new KDCustomHTMLView tagName : "a" cssClass : "hitenterview-toggle" partial : if o.showButton then o.togglerPartials[0] else o.togglerPartials[1] click : @bound "toggleEnterKey" @inputLabel.addSubView @inputEnterToggler hideButton:-> @button.hide() showButton:-> @button.show() toggleEnterKey:-> if @enterKeyEnabled then @disableEnterKey() else @enableEnterKey() keyDown:(event)-> if event.which is 13 and (event.altKey or event.shiftKey) isnt true and @enterKeyEnabled @emit "EnterPerformed" @validate() no else if event.which is 27 # escape @emit "EscapePerformed"
true
### todo: - on enter should validation fire by default??? PI:NAME:<NAME>END_PIan - 6/6/2012 ### KDInputView = require './inputview.coffee' module.exports = class KDHitEnterInputView extends KDInputView constructor:(options = {}, data)-> options.type or= "textarea" options.button or= null options.showButton ?= no options.label or= null options.placeholder or= "" options.callback or= null options.togglerPartials or= ["quick update disabled","quick update enabled"] super options,data @setClass "hitenterview" @button = @getOptions().button ? null @enableEnterKey() @setToggler() if options.label? @disableEnterKey() if @getOptions().showButton @on "ValidationPassed", => @blur() @getOptions().callback?.call @,@getValue() enableEnterKey:-> @setClass "active" @hideButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[1]) if @inputEnterToggler? @enterKeyEnabled = yes disableEnterKey:-> @unsetClass "active" @showButton() if @button @inputEnterToggler.$().html(@getOptions().togglerPartials[0]) if @inputEnterToggler? @enterKeyEnabled = no setToggler:-> o = @getOptions() @inputEnterToggler = new KDCustomHTMLView tagName : "a" cssClass : "hitenterview-toggle" partial : if o.showButton then o.togglerPartials[0] else o.togglerPartials[1] click : @bound "toggleEnterKey" @inputLabel.addSubView @inputEnterToggler hideButton:-> @button.hide() showButton:-> @button.show() toggleEnterKey:-> if @enterKeyEnabled then @disableEnterKey() else @enableEnterKey() keyDown:(event)-> if event.which is 13 and (event.altKey or event.shiftKey) isnt true and @enterKeyEnabled @emit "EnterPerformed" @validate() no else if event.which is 27 # escape @emit "EscapePerformed"
[ { "context": "# Author: Thinh Pham\n# Email: nhim175@gmail.com\n\nScorpion = require '.", "end": 20, "score": 0.999853253364563, "start": 10, "tag": "NAME", "value": "Thinh Pham" }, { "context": "# Author: Thinh Pham\n# Email: nhim175@gmail.com\n\nScorpion = require './scorpion.coffee'\n\nclass Bo", "end": 47, "score": 0.9999228715896606, "start": 30, "tag": "EMAIL", "value": "nhim175@gmail.com" } ]
src/lib/boss.coffee
nhim175/scorpionsmasher
0
# Author: Thinh Pham # Email: nhim175@gmail.com Scorpion = require './scorpion.coffee' class Boss extends Scorpion runFrames: Phaser.Animation.generateFrameNames('b', 1, 5, '.png', 0) dieFrames: ['b6.png'] speed: 5 bonus: 5 health: 10 module.exports = Boss
68158
# Author: <NAME> # Email: <EMAIL> Scorpion = require './scorpion.coffee' class Boss extends Scorpion runFrames: Phaser.Animation.generateFrameNames('b', 1, 5, '.png', 0) dieFrames: ['b6.png'] speed: 5 bonus: 5 health: 10 module.exports = Boss
true
# Author: PI:NAME:<NAME>END_PI # Email: PI:EMAIL:<EMAIL>END_PI Scorpion = require './scorpion.coffee' class Boss extends Scorpion runFrames: Phaser.Animation.generateFrameNames('b', 1, 5, '.png', 0) dieFrames: ['b6.png'] speed: 5 bonus: 5 health: 10 module.exports = Boss
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998464584350586, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999295473098755, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/gearbox/navigate.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" asciify = require "asciify" connect = require "connect" request = require "request" logger = require "winston" colors = require "colors" async = require "async" nconf = require "nconf" https = require "https" http = require "http" util = require "util" {external} = require "../membrane/remote" {Barebones} = require "../membrane/skeleton" {Preflight} = require "../membrane/preflight" # This abstract compound provides the hash navigation functionality. # It is basically and advanced hash router to be deployed to client # site. It is well fitted within the framework architecture and is # the fusion of the server and client site environments, exposing a # convenient server API that that defined the client routing logic. module.exports.Navigate = class Navigate extends Preflight # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block here defines a set of Bower dependencies that are # required by the client site part of the code that constitutes # this service or compound. Dependencies can be restricted to a # certain version and also they can have customized entrypoint. # Refer to `BowerSupport` class implementation for information. @bower "crossroads.js", "dist/crossroads.min.js" @bower "hasher#1.1.4", "dist/js/hasher.min.js" # Mount the supplied implementation as the hash location route # hanlder. The implementation is assumed to be the client site # coded and therefore is automatically externalized by use of # `external` tool and the gets transferred to a client by the # usual mechanisms defined in the `Screenplay` implementation. @mount: (xendpoint, xoptions, ximplement) -> endpoint = _.find(arguments, _.isString) or 0 implement = _.find(arguments, _.isFunction) or 0 options = _.find(arguments, _.isPlainObject) or {} m = "Mounting client site navigation path %s to %s" assert identify = try @identify().underline or null assert _.isString(endpoint), "got invalid endpoint" assert _.isFunction(implement), "no implementation" assert not implement.remote?, "is already external" assert /[\w\/-_]+/.test(endpoint), "dirty endpoint" assert _.isFunction externed = external implement assert _.isObject externed.remote.meta ?= Object() assert ptr = endpoint: endpoint, options: options assert _.isString uid = _.uniqueId "__hash_nav_mnt_" assert _.isFunction this.prototype[uid] = externed logger.silly m.grey, endpoint.underline, identify _.extend externed.remote.meta, ptr; externed # This is an external autocall routine that when invoked on the # client site - it creates, initializes, and sets up the hashing # navigation solution. This is a subsystem that features fully # fledged router for the hash (#) style navigation within single # page-ish environment. Should be used in the top level service! navigation: @autocall z: +103, -> router = "no crossroads router is detected" attaching = "no hasher library has been found" assert m = "Install hashing navigation at %s" assert _.isObject(hasher or null), attaching assert _.isObject(crossroads or null), router e = "Mounting frontend endpoint %s to %s method" assert crossroads.ignoreState = yes # multiparse logger.info m.magenta, @service.magenta.underline parser = (landed, old) -> crossroads.parse landed begin = _.find @, (x) -> x?.meta?.options?.default hasher.setHash begin.meta.endpoint if begin?.meta assert _.isObject hasher.initialized.add parser assert _.isObject hasher.changed.add parser setupAndExecute = (fx) -> hasher.init(); fx setupAndExecute _.forIn this, (value, name) -> return unless _.isFunction value or null return unless value?.meta?.endpoint or 0 assert endpoint = try value.meta.endpoint assert method = try name.toString().bold logger.debug e, endpoint.underline, method crossroads.addRoute endpoint, value
203356
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" asciify = require "asciify" connect = require "connect" request = require "request" logger = require "winston" colors = require "colors" async = require "async" nconf = require "nconf" https = require "https" http = require "http" util = require "util" {external} = require "../membrane/remote" {Barebones} = require "../membrane/skeleton" {Preflight} = require "../membrane/preflight" # This abstract compound provides the hash navigation functionality. # It is basically and advanced hash router to be deployed to client # site. It is well fitted within the framework architecture and is # the fusion of the server and client site environments, exposing a # convenient server API that that defined the client routing logic. module.exports.Navigate = class Navigate extends Preflight # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block here defines a set of Bower dependencies that are # required by the client site part of the code that constitutes # this service or compound. Dependencies can be restricted to a # certain version and also they can have customized entrypoint. # Refer to `BowerSupport` class implementation for information. @bower "crossroads.js", "dist/crossroads.min.js" @bower "hasher#1.1.4", "dist/js/hasher.min.js" # Mount the supplied implementation as the hash location route # hanlder. The implementation is assumed to be the client site # coded and therefore is automatically externalized by use of # `external` tool and the gets transferred to a client by the # usual mechanisms defined in the `Screenplay` implementation. @mount: (xendpoint, xoptions, ximplement) -> endpoint = _.find(arguments, _.isString) or 0 implement = _.find(arguments, _.isFunction) or 0 options = _.find(arguments, _.isPlainObject) or {} m = "Mounting client site navigation path %s to %s" assert identify = try @identify().underline or null assert _.isString(endpoint), "got invalid endpoint" assert _.isFunction(implement), "no implementation" assert not implement.remote?, "is already external" assert /[\w\/-_]+/.test(endpoint), "dirty endpoint" assert _.isFunction externed = external implement assert _.isObject externed.remote.meta ?= Object() assert ptr = endpoint: endpoint, options: options assert _.isString uid = _.uniqueId "__hash_nav_mnt_" assert _.isFunction this.prototype[uid] = externed logger.silly m.grey, endpoint.underline, identify _.extend externed.remote.meta, ptr; externed # This is an external autocall routine that when invoked on the # client site - it creates, initializes, and sets up the hashing # navigation solution. This is a subsystem that features fully # fledged router for the hash (#) style navigation within single # page-ish environment. Should be used in the top level service! navigation: @autocall z: +103, -> router = "no crossroads router is detected" attaching = "no hasher library has been found" assert m = "Install hashing navigation at %s" assert _.isObject(hasher or null), attaching assert _.isObject(crossroads or null), router e = "Mounting frontend endpoint %s to %s method" assert crossroads.ignoreState = yes # multiparse logger.info m.magenta, @service.magenta.underline parser = (landed, old) -> crossroads.parse landed begin = _.find @, (x) -> x?.meta?.options?.default hasher.setHash begin.meta.endpoint if begin?.meta assert _.isObject hasher.initialized.add parser assert _.isObject hasher.changed.add parser setupAndExecute = (fx) -> hasher.init(); fx setupAndExecute _.forIn this, (value, name) -> return unless _.isFunction value or null return unless value?.meta?.endpoint or 0 assert endpoint = try value.meta.endpoint assert method = try name.toString().bold logger.debug e, endpoint.underline, method crossroads.addRoute endpoint, value
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" asciify = require "asciify" connect = require "connect" request = require "request" logger = require "winston" colors = require "colors" async = require "async" nconf = require "nconf" https = require "https" http = require "http" util = require "util" {external} = require "../membrane/remote" {Barebones} = require "../membrane/skeleton" {Preflight} = require "../membrane/preflight" # This abstract compound provides the hash navigation functionality. # It is basically and advanced hash router to be deployed to client # site. It is well fitted within the framework architecture and is # the fusion of the server and client site environments, exposing a # convenient server API that that defined the client routing logic. module.exports.Navigate = class Navigate extends Preflight # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block here defines a set of Bower dependencies that are # required by the client site part of the code that constitutes # this service or compound. Dependencies can be restricted to a # certain version and also they can have customized entrypoint. # Refer to `BowerSupport` class implementation for information. @bower "crossroads.js", "dist/crossroads.min.js" @bower "hasher#1.1.4", "dist/js/hasher.min.js" # Mount the supplied implementation as the hash location route # hanlder. The implementation is assumed to be the client site # coded and therefore is automatically externalized by use of # `external` tool and the gets transferred to a client by the # usual mechanisms defined in the `Screenplay` implementation. @mount: (xendpoint, xoptions, ximplement) -> endpoint = _.find(arguments, _.isString) or 0 implement = _.find(arguments, _.isFunction) or 0 options = _.find(arguments, _.isPlainObject) or {} m = "Mounting client site navigation path %s to %s" assert identify = try @identify().underline or null assert _.isString(endpoint), "got invalid endpoint" assert _.isFunction(implement), "no implementation" assert not implement.remote?, "is already external" assert /[\w\/-_]+/.test(endpoint), "dirty endpoint" assert _.isFunction externed = external implement assert _.isObject externed.remote.meta ?= Object() assert ptr = endpoint: endpoint, options: options assert _.isString uid = _.uniqueId "__hash_nav_mnt_" assert _.isFunction this.prototype[uid] = externed logger.silly m.grey, endpoint.underline, identify _.extend externed.remote.meta, ptr; externed # This is an external autocall routine that when invoked on the # client site - it creates, initializes, and sets up the hashing # navigation solution. This is a subsystem that features fully # fledged router for the hash (#) style navigation within single # page-ish environment. Should be used in the top level service! navigation: @autocall z: +103, -> router = "no crossroads router is detected" attaching = "no hasher library has been found" assert m = "Install hashing navigation at %s" assert _.isObject(hasher or null), attaching assert _.isObject(crossroads or null), router e = "Mounting frontend endpoint %s to %s method" assert crossroads.ignoreState = yes # multiparse logger.info m.magenta, @service.magenta.underline parser = (landed, old) -> crossroads.parse landed begin = _.find @, (x) -> x?.meta?.options?.default hasher.setHash begin.meta.endpoint if begin?.meta assert _.isObject hasher.initialized.add parser assert _.isObject hasher.changed.add parser setupAndExecute = (fx) -> hasher.init(); fx setupAndExecute _.forIn this, (value, name) -> return unless _.isFunction value or null return unless value?.meta?.endpoint or 0 assert endpoint = try value.meta.endpoint assert method = try name.toString().bold logger.debug e, endpoint.underline, method crossroads.addRoute endpoint, value
[ { "context": "nt_in_cents: 999\n\t\taccount:\n\t\t\taccount_code: \"user-123\"\n\t\t\t\ndescribe \"SubscriptionHandler\", ->\n\n\tbeforeE", "end": 471, "score": 0.8762991428375244, "start": 468, "tag": "KEY", "value": "123" }, { "context": "ecurlySubscriptions[\"subscription-123-active\"]\n\t\t@User = {}\n\t\t@user =\n\t\t\t_id: @user_id = \"user_id_here_\"", "end": 830, "score": 0.5335913896560669, "start": 826, "tag": "USERNAME", "value": "User" }, { "context": "iptions[\"subscription-123-active\"]\n\t\t@User = {}\n\t\t@user =\n\t\t\t_id: @user_id = \"user_id_here_\"\n\t\t@subscript", "end": 843, "score": 0.5113010406494141, "start": 838, "tag": "USERNAME", "value": "@user" }, { "context": "{}\n\t\t@user =\n\t\t\t_id: @user_id = \"user_id_here_\"\n\t\t@subscription = \n\t\t\trecurlySubscription_id: @activeRecurlySubsc", "end": 896, "score": 0.6678273677825928, "start": 883, "tag": "USERNAME", "value": "@subscription" }, { "context": "ubscription_id: @activeRecurlySubscription.uuid\n\t\t@RecurlyWrapper = \n\t\t\tgetSubscription: sinon.stub().callsArgWith(", "end": 976, "score": 0.834668755531311, "start": 961, "tag": "USERNAME", "value": "@RecurlyWrapper" }, { "context": "h(3, null, @activeRecurlySubscription)\n\n\t\t@DropboxHandler =\n\t\t\tunlinkAccount:sinon.stub().callsArgWith(1)\n\n", "end": 1406, "score": 0.5458938479423523, "start": 1399, "tag": "USERNAME", "value": "Handler" }, { "context": "\t\t\tunlinkAccount:sinon.stub().callsArgWith(1)\n\n\t\t@SubscriptionUpdater = \n\t\t\tsyncSubscription: sinon.stub().callsArgWith", "end": 1478, "score": 0.8152714967727661, "start": 1459, "tag": "USERNAME", "value": "SubscriptionUpdater" }, { "context": "tFreeTrial: sinon.stub().callsArgWith(1)\n\n\t\t@LimitationsManager =\n\t\t\tuserHasV2Subscription: sinon.stub()\n\n", "end": 1595, "score": 0.5305210947990417, "start": 1589, "tag": "USERNAME", "value": "ations" }, { "context": "relatex\": @Settings\n\t\t\t'../../models/User': User:@User\n\t\t\t'./SubscriptionUpdater': @SubscriptionUpdater\n", "end": 1925, "score": 0.5039998292922974, "start": 1921, "tag": "USERNAME", "value": "User" }, { "context": ":\"123\"\n\t\t\t\tnumber:\"12345\"\n\t\t\t@recurly_token_id = \"45555666\"\n\t\t\t@SubscriptionHandler.validateNoSubscri", "end": 2504, "score": 0.5286152362823486, "start": 2503, "tag": "KEY", "value": "4" }, { "context": "\"123\"\n\t\t\t\tnumber:\"12345\"\n\t\t\t@recurly_token_id = \"45555666\"\n\t\t\t@SubscriptionHandler.validateNoSubscriptionIn", "end": 2511, "score": 0.7166553139686584, "start": 2504, "tag": "PASSWORD", "value": "5555666" }, { "context": "ach ->\n\t\t\t\t@SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callba", "end": 2700, "score": 0.9101478457450867, "start": 2695, "tag": "USERNAME", "value": "@user" }, { "context": "\t\t\t@RecurlyWrapper.createSubscription.calledWith(@user, @subscriptionDetails, @recurly_token_id).should.", "end": 2870, "score": 0.8479141592979431, "start": 2866, "tag": "USERNAME", "value": "user" }, { "context": "lse)\n\t\t\t\t@SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callba", "end": 3459, "score": 0.8182054758071899, "start": 3455, "tag": "USERNAME", "value": "user" }, { "context": "tion)\n\t\t\t\t\t@SubscriptionHandler.updateSubscription(@user, @plan_code, null, done)\n\n\t\t\t\tit \"should update t", "end": 3956, "score": 0.966968297958374, "start": 3951, "tag": "USERNAME", "value": "@user" }, { "context": "false)\n\t\t\t\t@SubscriptionHandler.updateSubscription(@user, @plan_code, null, done)\n\n\t\t\tit \"should redirect ", "end": 4925, "score": 0.9846317768096924, "start": 4920, "tag": "USERNAME", "value": "@user" }, { "context": "ption)\n\t\t\t\t@SubscriptionHandler.updateSubscription(@user, @plan_code, @coupon_code, done)\n\n\t\t\tit \"should g", "end": 5409, "score": 0.9819983243942261, "start": 5404, "tag": "USERNAME", "value": "@user" } ]
test/unit/coffee/Subscription/SubscriptionHandlerTests.coffee
davidmehren/web-sharelatex
1
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/SubscriptionHandler" mockRecurlySubscriptions = "subscription-123-active": uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "user-123" describe "SubscriptionHandler", -> beforeEach -> @Settings = plans : [{ planCode: "collaborator" name: "Collaborator" features: collaborators: -1 versioning: true }] defaultPlanCode : collaborators: 0 versioning: false @activeRecurlySubscription = mockRecurlySubscriptions["subscription-123-active"] @User = {} @user = _id: @user_id = "user_id_here_" @subscription = recurlySubscription_id: @activeRecurlySubscription.uuid @RecurlyWrapper = getSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) updateSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) cancelSubscription: sinon.stub().callsArgWith(1) reactivateSubscription: sinon.stub().callsArgWith(1) redeemCoupon:sinon.stub().callsArgWith(2) createSubscription: sinon.stub().callsArgWith(3, null, @activeRecurlySubscription) @DropboxHandler = unlinkAccount:sinon.stub().callsArgWith(1) @SubscriptionUpdater = syncSubscription: sinon.stub().callsArgWith(2) startFreeTrial: sinon.stub().callsArgWith(1) @LimitationsManager = userHasV2Subscription: sinon.stub() @EmailHandler = sendEmail:sinon.stub() @AnalyticsManager = recordEvent:sinon.stub() @SubscriptionHandler = SandboxedModule.require modulePath, requires: "./RecurlyWrapper": @RecurlyWrapper "settings-sharelatex": @Settings '../../models/User': User:@User './SubscriptionUpdater': @SubscriptionUpdater "logger-sharelatex":{log:->} './LimitationsManager':@LimitationsManager "../Email/EmailHandler":@EmailHandler "../Dropbox/DropboxHandler":@DropboxHandler "../../infrastructure/Events": @Events = {emit: sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager @SubscriptionHandler.syncSubscriptionToUser = sinon.stub().callsArgWith(2) describe "createSubscription", -> beforeEach -> @callback = sinon.stub() @subscriptionDetails = cvv:"123" number:"12345" @recurly_token_id = "45555666" @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, true) describe "successfully", -> beforeEach -> @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should create the subscription with the wrapper", -> @RecurlyWrapper.createSubscription.calledWith(@user, @subscriptionDetails, @recurly_token_id).should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "when there is already a subscription in Recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, false) @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should return an error", -> @callback.calledWith(new Error("user already has subscription in recurly")) describe "updateSubscription", -> describe "with a user with a subscription", -> describe "with a valid plan code", -> beforeEach (done) -> @plan_code = "collaborator" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code it "should update immediately", -> updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.timeframe.should.equal "now" it "should sync the new subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should redirect to the subscription dashboard", -> @RecurlyWrapper.updateSubscription.called.should.equal false @SubscriptionHandler.syncSubscriptionToUser.called.should.equal false describe "with a coupon code", -> beforeEach (done) -> @plan_code = "collaborator" @coupon_code = "1231312" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, @coupon_code, done) it "should get the users account", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should redeme the coupon", (done)-> @RecurlyWrapper.redeemCoupon.calledWith(@activeRecurlySubscription.account.account_code, @coupon_code).should.equal true done() it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code describe "cancelSubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.cancelSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should cancel the subscription", -> @RecurlyWrapper.cancelSubscription.called.should.equal true @RecurlyWrapper.cancelSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true it "should trigger the cancel subscription event", -> @Events.emit.calledWith("cancelSubscription", @user._id).should.equal true describe "reactiveRecurlySubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.reactivateSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should reactivate the subscription", -> @RecurlyWrapper.reactivateSubscription.called.should.equal true @RecurlyWrapper.reactivateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true describe "recurlyCallback", -> describe "with an actionable request", -> beforeEach (done) -> @user.id = @activeRecurlySubscription.account.account_code @User.findById = (userId, callback) => userId.should.equal @user.id callback null, @user @SubscriptionHandler.recurlyCallback(@activeRecurlySubscription, done) it "should request the affected subscription from the API", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should request the account details of the subscription", -> options = @RecurlyWrapper.getSubscription.args[0][1] options.includeAccount.should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "validateNoSubscriptionInRecurly", -> beforeEach -> @subscriptions = [] @RecurlyWrapper.listAccountActiveSubscriptions = sinon.stub().yields(null, @subscriptions) @SubscriptionUpdater.syncSubscription = sinon.stub().yields() @callback = sinon.stub() describe "with no subscription in recurly", -> beforeEach -> @subscriptions.push @subscription = { "mock": "subscription" } @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should call RecurlyWrapper.listAccountActiveSubscriptions with the user id", -> @RecurlyWrapper.listAccountActiveSubscriptions .calledWith(@user_id) .should.equal true it "should sync the subscription", -> @SubscriptionUpdater.syncSubscription .calledWith(@subscription, @user_id) .should.equal true it "should call the callback with valid == false", -> @callback.calledWith(null, false).should.equal true describe "with a subscription in recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should not sync the subscription", -> @SubscriptionUpdater.syncSubscription .called .should.equal false it "should call the callback with valid == true", -> @callback.calledWith(null, true).should.equal true
136753
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/SubscriptionHandler" mockRecurlySubscriptions = "subscription-123-active": uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "user-<KEY>" describe "SubscriptionHandler", -> beforeEach -> @Settings = plans : [{ planCode: "collaborator" name: "Collaborator" features: collaborators: -1 versioning: true }] defaultPlanCode : collaborators: 0 versioning: false @activeRecurlySubscription = mockRecurlySubscriptions["subscription-123-active"] @User = {} @user = _id: @user_id = "user_id_here_" @subscription = recurlySubscription_id: @activeRecurlySubscription.uuid @RecurlyWrapper = getSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) updateSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) cancelSubscription: sinon.stub().callsArgWith(1) reactivateSubscription: sinon.stub().callsArgWith(1) redeemCoupon:sinon.stub().callsArgWith(2) createSubscription: sinon.stub().callsArgWith(3, null, @activeRecurlySubscription) @DropboxHandler = unlinkAccount:sinon.stub().callsArgWith(1) @SubscriptionUpdater = syncSubscription: sinon.stub().callsArgWith(2) startFreeTrial: sinon.stub().callsArgWith(1) @LimitationsManager = userHasV2Subscription: sinon.stub() @EmailHandler = sendEmail:sinon.stub() @AnalyticsManager = recordEvent:sinon.stub() @SubscriptionHandler = SandboxedModule.require modulePath, requires: "./RecurlyWrapper": @RecurlyWrapper "settings-sharelatex": @Settings '../../models/User': User:@User './SubscriptionUpdater': @SubscriptionUpdater "logger-sharelatex":{log:->} './LimitationsManager':@LimitationsManager "../Email/EmailHandler":@EmailHandler "../Dropbox/DropboxHandler":@DropboxHandler "../../infrastructure/Events": @Events = {emit: sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager @SubscriptionHandler.syncSubscriptionToUser = sinon.stub().callsArgWith(2) describe "createSubscription", -> beforeEach -> @callback = sinon.stub() @subscriptionDetails = cvv:"123" number:"12345" @recurly_token_id = "<KEY> <PASSWORD>" @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, true) describe "successfully", -> beforeEach -> @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should create the subscription with the wrapper", -> @RecurlyWrapper.createSubscription.calledWith(@user, @subscriptionDetails, @recurly_token_id).should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "when there is already a subscription in Recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, false) @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should return an error", -> @callback.calledWith(new Error("user already has subscription in recurly")) describe "updateSubscription", -> describe "with a user with a subscription", -> describe "with a valid plan code", -> beforeEach (done) -> @plan_code = "collaborator" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code it "should update immediately", -> updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.timeframe.should.equal "now" it "should sync the new subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should redirect to the subscription dashboard", -> @RecurlyWrapper.updateSubscription.called.should.equal false @SubscriptionHandler.syncSubscriptionToUser.called.should.equal false describe "with a coupon code", -> beforeEach (done) -> @plan_code = "collaborator" @coupon_code = "1231312" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, @coupon_code, done) it "should get the users account", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should redeme the coupon", (done)-> @RecurlyWrapper.redeemCoupon.calledWith(@activeRecurlySubscription.account.account_code, @coupon_code).should.equal true done() it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code describe "cancelSubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.cancelSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should cancel the subscription", -> @RecurlyWrapper.cancelSubscription.called.should.equal true @RecurlyWrapper.cancelSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true it "should trigger the cancel subscription event", -> @Events.emit.calledWith("cancelSubscription", @user._id).should.equal true describe "reactiveRecurlySubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.reactivateSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should reactivate the subscription", -> @RecurlyWrapper.reactivateSubscription.called.should.equal true @RecurlyWrapper.reactivateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true describe "recurlyCallback", -> describe "with an actionable request", -> beforeEach (done) -> @user.id = @activeRecurlySubscription.account.account_code @User.findById = (userId, callback) => userId.should.equal @user.id callback null, @user @SubscriptionHandler.recurlyCallback(@activeRecurlySubscription, done) it "should request the affected subscription from the API", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should request the account details of the subscription", -> options = @RecurlyWrapper.getSubscription.args[0][1] options.includeAccount.should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "validateNoSubscriptionInRecurly", -> beforeEach -> @subscriptions = [] @RecurlyWrapper.listAccountActiveSubscriptions = sinon.stub().yields(null, @subscriptions) @SubscriptionUpdater.syncSubscription = sinon.stub().yields() @callback = sinon.stub() describe "with no subscription in recurly", -> beforeEach -> @subscriptions.push @subscription = { "mock": "subscription" } @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should call RecurlyWrapper.listAccountActiveSubscriptions with the user id", -> @RecurlyWrapper.listAccountActiveSubscriptions .calledWith(@user_id) .should.equal true it "should sync the subscription", -> @SubscriptionUpdater.syncSubscription .calledWith(@subscription, @user_id) .should.equal true it "should call the callback with valid == false", -> @callback.calledWith(null, false).should.equal true describe "with a subscription in recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should not sync the subscription", -> @SubscriptionUpdater.syncSubscription .called .should.equal false it "should call the callback with valid == true", -> @callback.calledWith(null, true).should.equal true
true
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/SubscriptionHandler" mockRecurlySubscriptions = "subscription-123-active": uuid: "subscription-123-active" plan: name: "Gold" plan_code: "gold" current_period_ends_at: new Date() state: "active" unit_amount_in_cents: 999 account: account_code: "user-PI:KEY:<KEY>END_PI" describe "SubscriptionHandler", -> beforeEach -> @Settings = plans : [{ planCode: "collaborator" name: "Collaborator" features: collaborators: -1 versioning: true }] defaultPlanCode : collaborators: 0 versioning: false @activeRecurlySubscription = mockRecurlySubscriptions["subscription-123-active"] @User = {} @user = _id: @user_id = "user_id_here_" @subscription = recurlySubscription_id: @activeRecurlySubscription.uuid @RecurlyWrapper = getSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) updateSubscription: sinon.stub().callsArgWith(2, null, @activeRecurlySubscription) cancelSubscription: sinon.stub().callsArgWith(1) reactivateSubscription: sinon.stub().callsArgWith(1) redeemCoupon:sinon.stub().callsArgWith(2) createSubscription: sinon.stub().callsArgWith(3, null, @activeRecurlySubscription) @DropboxHandler = unlinkAccount:sinon.stub().callsArgWith(1) @SubscriptionUpdater = syncSubscription: sinon.stub().callsArgWith(2) startFreeTrial: sinon.stub().callsArgWith(1) @LimitationsManager = userHasV2Subscription: sinon.stub() @EmailHandler = sendEmail:sinon.stub() @AnalyticsManager = recordEvent:sinon.stub() @SubscriptionHandler = SandboxedModule.require modulePath, requires: "./RecurlyWrapper": @RecurlyWrapper "settings-sharelatex": @Settings '../../models/User': User:@User './SubscriptionUpdater': @SubscriptionUpdater "logger-sharelatex":{log:->} './LimitationsManager':@LimitationsManager "../Email/EmailHandler":@EmailHandler "../Dropbox/DropboxHandler":@DropboxHandler "../../infrastructure/Events": @Events = {emit: sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager @SubscriptionHandler.syncSubscriptionToUser = sinon.stub().callsArgWith(2) describe "createSubscription", -> beforeEach -> @callback = sinon.stub() @subscriptionDetails = cvv:"123" number:"12345" @recurly_token_id = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, true) describe "successfully", -> beforeEach -> @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should create the subscription with the wrapper", -> @RecurlyWrapper.createSubscription.calledWith(@user, @subscriptionDetails, @recurly_token_id).should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "when there is already a subscription in Recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly = sinon.stub().yields(null, false) @SubscriptionHandler.createSubscription(@user, @subscriptionDetails, @recurly_token_id, @callback) it "should return an error", -> @callback.calledWith(new Error("user already has subscription in recurly")) describe "updateSubscription", -> describe "with a user with a subscription", -> describe "with a valid plan code", -> beforeEach (done) -> @plan_code = "collaborator" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code it "should update immediately", -> updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.timeframe.should.equal "now" it "should sync the new subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false) @SubscriptionHandler.updateSubscription(@user, @plan_code, null, done) it "should redirect to the subscription dashboard", -> @RecurlyWrapper.updateSubscription.called.should.equal false @SubscriptionHandler.syncSubscriptionToUser.called.should.equal false describe "with a coupon code", -> beforeEach (done) -> @plan_code = "collaborator" @coupon_code = "1231312" @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.updateSubscription(@user, @plan_code, @coupon_code, done) it "should get the users account", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should redeme the coupon", (done)-> @RecurlyWrapper.redeemCoupon.calledWith(@activeRecurlySubscription.account.account_code, @coupon_code).should.equal true done() it "should update the subscription", -> @RecurlyWrapper.updateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true updateOptions = @RecurlyWrapper.updateSubscription.args[0][1] updateOptions.plan_code.should.equal @plan_code describe "cancelSubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.cancelSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.cancelSubscription @user, done it "should cancel the subscription", -> @RecurlyWrapper.cancelSubscription.called.should.equal true @RecurlyWrapper.cancelSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true it "should trigger the cancel subscription event", -> @Events.emit.calledWith("cancelSubscription", @user._id).should.equal true describe "reactiveRecurlySubscription", -> describe "with a user without a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should redirect to the subscription dashboard", -> @RecurlyWrapper.reactivateSubscription.called.should.equal false describe "with a user with a subscription", -> beforeEach (done) -> @LimitationsManager.userHasV2Subscription.callsArgWith(1, null, true, @subscription) @SubscriptionHandler.reactivateSubscription @user, done it "should reactivate the subscription", -> @RecurlyWrapper.reactivateSubscription.called.should.equal true @RecurlyWrapper.reactivateSubscription.calledWith(@subscription.recurlySubscription_id).should.equal true describe "recurlyCallback", -> describe "with an actionable request", -> beforeEach (done) -> @user.id = @activeRecurlySubscription.account.account_code @User.findById = (userId, callback) => userId.should.equal @user.id callback null, @user @SubscriptionHandler.recurlyCallback(@activeRecurlySubscription, done) it "should request the affected subscription from the API", -> @RecurlyWrapper.getSubscription.calledWith(@activeRecurlySubscription.uuid).should.equal true it "should request the account details of the subscription", -> options = @RecurlyWrapper.getSubscription.args[0][1] options.includeAccount.should.equal true it "should sync the subscription to the user", -> @SubscriptionUpdater.syncSubscription.calledOnce.should.equal true @SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal @activeRecurlySubscription @SubscriptionUpdater.syncSubscription.args[0][1].should.deep.equal @user._id describe "validateNoSubscriptionInRecurly", -> beforeEach -> @subscriptions = [] @RecurlyWrapper.listAccountActiveSubscriptions = sinon.stub().yields(null, @subscriptions) @SubscriptionUpdater.syncSubscription = sinon.stub().yields() @callback = sinon.stub() describe "with no subscription in recurly", -> beforeEach -> @subscriptions.push @subscription = { "mock": "subscription" } @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should call RecurlyWrapper.listAccountActiveSubscriptions with the user id", -> @RecurlyWrapper.listAccountActiveSubscriptions .calledWith(@user_id) .should.equal true it "should sync the subscription", -> @SubscriptionUpdater.syncSubscription .calledWith(@subscription, @user_id) .should.equal true it "should call the callback with valid == false", -> @callback.calledWith(null, false).should.equal true describe "with a subscription in recurly", -> beforeEach -> @SubscriptionHandler.validateNoSubscriptionInRecurly @user_id, @callback it "should not sync the subscription", -> @SubscriptionUpdater.syncSubscription .called .should.equal false it "should call the callback with valid == true", -> @callback.calledWith(null, true).should.equal true
[ { "context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s", "end": 61, "score": 0.9998396635055542, "start": 48, "tag": "NAME", "value": "Stephan Jorek" } ]
src/misc/gulp/gulp-jison.coffee
sjorek/goatee-script.js
0
### ^ BSD 3-Clause License Copyright (c) 2017, Stephan Jorek All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### fs = require('fs') path = require('path') map = require 'map-stream' util = require('gulp-util') PluginError = util.PluginError cli = require('jison/lib/cli') ### # # Gulp Jison # ------------ # ### PLUGIN_NAME = 'gulp-jison' module.exports = (options) -> # getting raw files lex = null if options.lexfile? lex = fs.readFileSync path.normalize(options.lexfile), 'utf8' processFile = (file, options) -> opts = {} opts[key] = value for own key, value of options if options? opts.file = file.path raw = file.contents.toString() # making best guess at json mode opts.json = path.extname(opts.file) is '.json' unless opts.json # setting output file name and module name based on input file name # if they aren't specified. name = path.basename(opts.outfile ? opts.file).replace /\..*$/g, '' opts.outfile = "#{name}.js" unless opts.outfile? if not opts.moduleName? and name opts.moduleName = name.replace /-\w/g, (match) -> match.charAt(1).toUpperCase() grammar = cli.processGrammars raw, lex, opts.json cli.generateParserString opts, grammar jison = (file, cb) -> contents = processFile(file, options) return cb contents if contents instanceof Error file.contents = new Buffer contents file.path = util.replaceExtension '.js' callback null, file map jison
147181
### ^ BSD 3-Clause License Copyright (c) 2017, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### fs = require('fs') path = require('path') map = require 'map-stream' util = require('gulp-util') PluginError = util.PluginError cli = require('jison/lib/cli') ### # # Gulp Jison # ------------ # ### PLUGIN_NAME = 'gulp-jison' module.exports = (options) -> # getting raw files lex = null if options.lexfile? lex = fs.readFileSync path.normalize(options.lexfile), 'utf8' processFile = (file, options) -> opts = {} opts[key] = value for own key, value of options if options? opts.file = file.path raw = file.contents.toString() # making best guess at json mode opts.json = path.extname(opts.file) is '.json' unless opts.json # setting output file name and module name based on input file name # if they aren't specified. name = path.basename(opts.outfile ? opts.file).replace /\..*$/g, '' opts.outfile = "#{name}.js" unless opts.outfile? if not opts.moduleName? and name opts.moduleName = name.replace /-\w/g, (match) -> match.charAt(1).toUpperCase() grammar = cli.processGrammars raw, lex, opts.json cli.generateParserString opts, grammar jison = (file, cb) -> contents = processFile(file, options) return cb contents if contents instanceof Error file.contents = new Buffer contents file.path = util.replaceExtension '.js' callback null, file map jison
true
### ^ BSD 3-Clause License Copyright (c) 2017, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### fs = require('fs') path = require('path') map = require 'map-stream' util = require('gulp-util') PluginError = util.PluginError cli = require('jison/lib/cli') ### # # Gulp Jison # ------------ # ### PLUGIN_NAME = 'gulp-jison' module.exports = (options) -> # getting raw files lex = null if options.lexfile? lex = fs.readFileSync path.normalize(options.lexfile), 'utf8' processFile = (file, options) -> opts = {} opts[key] = value for own key, value of options if options? opts.file = file.path raw = file.contents.toString() # making best guess at json mode opts.json = path.extname(opts.file) is '.json' unless opts.json # setting output file name and module name based on input file name # if they aren't specified. name = path.basename(opts.outfile ? opts.file).replace /\..*$/g, '' opts.outfile = "#{name}.js" unless opts.outfile? if not opts.moduleName? and name opts.moduleName = name.replace /-\w/g, (match) -> match.charAt(1).toUpperCase() grammar = cli.processGrammars raw, lex, opts.json cli.generateParserString opts, grammar jison = (file, cb) -> contents = processFile(file, options) return cb contents if contents instanceof Error file.contents = new Buffer contents file.path = util.replaceExtension '.js' callback null, file map jison
[ { "context": "eenTea_\", temp: \"75 - 80\", time: 90},\n {name: \"oolong\", title: \"_OolongTea_\", temp: \"80 - 85\", time: 15", "end": 243, "score": 0.5822856426239014, "start": 237, "tag": "NAME", "value": "oolong" }, { "context": "\"_BlackTea_\", temp: \"99\", time: 150},\n {name: \"herbal\", title: \"_HerbalTea_\", temp: \"99\", time: 300},\n ", "end": 380, "score": 0.555867612361908, "start": 374, "tag": "NAME", "value": "herbal" }, { "context": "99\", time: 480}\n]\n\nwindow.degrees = [\n {name: \"celsius\", title: \"Celsius\", symbol: \"C\", formula: (val) -", "end": 534, "score": 0.9862699508666992, "start": 527, "tag": "NAME", "value": "celsius" }, { "context": "\nwindow.degrees = [\n {name: \"celsius\", title: \"Celsius\", symbol: \"C\", formula: (val) -> return val},\n ", "end": 552, "score": 0.957033634185791, "start": 545, "tag": "NAME", "value": "Celsius" }, { "context": ": \"C\", formula: (val) -> return val},\n {name: \"fahrenheit\", title: \"Fahrenheit\", symbol: \"F\", formula: (val", "end": 621, "score": 0.9795145988464355, "start": 611, "tag": "NAME", "value": "fahrenheit" }, { "context": " -> return val},\n {name: \"fahrenheit\", title: \"Fahrenheit\", symbol: \"F\", formula: (val) -> return val * 9 /", "end": 642, "score": 0.9701744318008423, "start": 632, "tag": "NAME", "value": "Fahrenheit" }, { "context": "a: (val) -> return val * 9 / 5 + 32},\n {name: \"kelvin\", title: \"Kelvin\", symbol: \"K\", formula: (val) ->", "end": 720, "score": 0.9961973428726196, "start": 714, "tag": "NAME", "value": "kelvin" }, { "context": "n val * 9 / 5 + 32},\n {name: \"kelvin\", title: \"Kelvin\", symbol: \"K\", formula: (val) -> return val + 273", "end": 737, "score": 0.9980292320251465, "start": 731, "tag": "NAME", "value": "Kelvin" }, { "context": "rmula: (val) -> return val + 273.15},\n {name: \"reaumur\", title: \"Réaumur\", symbol: \"Ré\", formula: (val) ", "end": 812, "score": 0.9837172627449036, "start": 805, "tag": "NAME", "value": "reaumur" }, { "context": "turn val + 273.15},\n {name: \"reaumur\", title: \"Réaumur\", symbol: \"Ré\", formula: (val) -> return val * 4 ", "end": 830, "score": 0.9959245920181274, "start": 823, "tag": "NAME", "value": "Réaumur" }, { "context": "ormula: (val) -> return val * 4 / 5},\n {name: \"rankine\", title: \"Rankine\", symbol: \"R\", formula: (val) -", "end": 905, "score": 0.9825836420059204, "start": 898, "tag": "NAME", "value": "rankine" }, { "context": "eturn val * 4 / 5},\n {name: \"rankine\", title: \"Rankine\", symbol: \"R\", formula: (val) -> return (val + 27", "end": 923, "score": 0.9464186429977417, "start": 916, "tag": "NAME", "value": "Rankine" }, { "context": "l) -> return (val + 273.15) * 9 / 5},\n {name: \"delisle\", title: \"Delisle\", symbol: \"De\", formula: (val) ", "end": 1008, "score": 0.9469351768493652, "start": 1001, "tag": "NAME", "value": "delisle" }, { "context": "+ 273.15) * 9 / 5},\n {name: \"delisle\", title: \"Delisle\", symbol: \"De\", formula: (val) -> return (100 - v", "end": 1026, "score": 0.960004985332489, "start": 1019, "tag": "NAME", "value": "Delisle" }, { "context": "(val) -> return (100 - val) * 3 / 2},\n {name: \"romer\", title: \"Rømer\", symbol: \"Rø\", formula: (val) ->", "end": 1107, "score": 0.9845827221870422, "start": 1102, "tag": "NAME", "value": "romer" }, { "context": "(100 - val) * 3 / 2},\n {name: \"romer\", title: \"Rømer\", symbol: \"Rø\", formula: (val) -> return val * 21", "end": 1123, "score": 0.9948479533195496, "start": 1118, "tag": "NAME", "value": "Rømer" } ]
coffee/teas.coffee
rain0r/Tea-clock
14
window.teas = [ {name: "white", title: "_WhiteTea_", temp: "65 - 70", time: 90}, {name: "yellow", title: "_YellowTea_", temp: "70 - 75", time: 90}, {name: "green", title: "_GreenTea_", temp: "75 - 80", time: 90}, {name: "oolong", title: "_OolongTea_", temp: "80 - 85", time: 150}, {name: "black", title: "_BlackTea_", temp: "99", time: 150}, {name: "herbal", title: "_HerbalTea_", temp: "99", time: 300}, {name: "fruit", title: "_FruitTea_", temp: "99", time: 480} ] window.degrees = [ {name: "celsius", title: "Celsius", symbol: "C", formula: (val) -> return val}, {name: "fahrenheit", title: "Fahrenheit", symbol: "F", formula: (val) -> return val * 9 / 5 + 32}, {name: "kelvin", title: "Kelvin", symbol: "K", formula: (val) -> return val + 273.15}, {name: "reaumur", title: "Réaumur", symbol: "Ré", formula: (val) -> return val * 4 / 5}, {name: "rankine", title: "Rankine", symbol: "R", formula: (val) -> return (val + 273.15) * 9 / 5}, {name: "delisle", title: "Delisle", symbol: "De", formula: (val) -> return (100 - val) * 3 / 2}, {name: "romer", title: "Rømer", symbol: "Rø", formula: (val) -> return val * 21 / 40 + 7.5} ] window.notificationTemplate = {title: "_AppTitle_", body: "_NotificationMessage_" }
181148
window.teas = [ {name: "white", title: "_WhiteTea_", temp: "65 - 70", time: 90}, {name: "yellow", title: "_YellowTea_", temp: "70 - 75", time: 90}, {name: "green", title: "_GreenTea_", temp: "75 - 80", time: 90}, {name: "<NAME>", title: "_OolongTea_", temp: "80 - 85", time: 150}, {name: "black", title: "_BlackTea_", temp: "99", time: 150}, {name: "<NAME>", title: "_HerbalTea_", temp: "99", time: 300}, {name: "fruit", title: "_FruitTea_", temp: "99", time: 480} ] window.degrees = [ {name: "<NAME>", title: "<NAME>", symbol: "C", formula: (val) -> return val}, {name: "<NAME>", title: "<NAME>", symbol: "F", formula: (val) -> return val * 9 / 5 + 32}, {name: "<NAME>", title: "<NAME>", symbol: "K", formula: (val) -> return val + 273.15}, {name: "<NAME>", title: "<NAME>", symbol: "Ré", formula: (val) -> return val * 4 / 5}, {name: "<NAME>", title: "<NAME>", symbol: "R", formula: (val) -> return (val + 273.15) * 9 / 5}, {name: "<NAME>", title: "<NAME>", symbol: "De", formula: (val) -> return (100 - val) * 3 / 2}, {name: "<NAME>", title: "<NAME>", symbol: "Rø", formula: (val) -> return val * 21 / 40 + 7.5} ] window.notificationTemplate = {title: "_AppTitle_", body: "_NotificationMessage_" }
true
window.teas = [ {name: "white", title: "_WhiteTea_", temp: "65 - 70", time: 90}, {name: "yellow", title: "_YellowTea_", temp: "70 - 75", time: 90}, {name: "green", title: "_GreenTea_", temp: "75 - 80", time: 90}, {name: "PI:NAME:<NAME>END_PI", title: "_OolongTea_", temp: "80 - 85", time: 150}, {name: "black", title: "_BlackTea_", temp: "99", time: 150}, {name: "PI:NAME:<NAME>END_PI", title: "_HerbalTea_", temp: "99", time: 300}, {name: "fruit", title: "_FruitTea_", temp: "99", time: 480} ] window.degrees = [ {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "C", formula: (val) -> return val}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "F", formula: (val) -> return val * 9 / 5 + 32}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "K", formula: (val) -> return val + 273.15}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "Ré", formula: (val) -> return val * 4 / 5}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "R", formula: (val) -> return (val + 273.15) * 9 / 5}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "De", formula: (val) -> return (100 - val) * 3 / 2}, {name: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI", symbol: "Rø", formula: (val) -> return val * 21 / 40 + 7.5} ] window.notificationTemplate = {title: "_AppTitle_", body: "_NotificationMessage_" }
[ { "context": "e': process.env.MAIL_USERNAME\n 'mail_password': process.env.MAIL_PASSWORD\n 'mongo_db': process.env.MONGODB or 'mong", "end": 1555, "score": 0.9891115427017212, "start": 1530, "tag": "PASSWORD", "value": "process.env.MAIL_PASSWORD" }, { "context": "mongo_db': process.env.MONGODB or 'mongodb://192.168.99.100:27017/mean-coffee-starter'\n 'redis_host': p", "end": 1625, "score": 0.9997555613517761, "start": 1611, "tag": "IP_ADDRESS", "value": "192.168.99.100" }, { "context": "'\n 'redis_host': process.env.REDISHOST or '192.168.99.100'\n 'redis_port': process.env.REDISPORT or 63", "end": 1715, "score": 0.9997111558914185, "start": 1701, "tag": "IP_ADDRESS", "value": "192.168.99.100" } ]
config/globals.coffee
crueber/mean-coffee-starter
0
path = require "path" Emitter = require('events').EventEmitter ### # Application Globals Setup ### module.exports = (app) -> global.app = app global._ = require 'lodash' global.moment = require 'moment' global.logger = require('./logger')() global.events = new Emitter() global.empty_fn = -> null global.constant = {} global.constant.one_ms = 1 global.constant.one_second = constant.one_ms * 1000 global.constant.one_minute = constant.one_second * 60 global.constant.one_hour = constant.one_minute * 60 global.constant.one_day = constant.one_hour * 24 global.constant.one_week = constant.one_hour * 7 global.constant.one_month = constant.one_day * 30 # approx global.constant.one_year = constant.one_week * 52 # approx global.constant.one_byte = 1 global.constant.one_kb = 1024 * global.constant.one_byte global.constant.one_mb = 1024 * global.constant.one_kb global.constant.one_gb = 1024 * global.constant.one_mb application_globals = 'dev': app.get('env') isnt 'production' 'views': path.join(__dirname, "/../views") 'view engine': 'jade' 'title': 'MEAN Coffee Baseline' 'port': process.env.PORT 'sessionSecret': process.env.SESSION_SECRET 'mail_host': process.env.MAIL_HOST 'mail_port': process.env.MAIL_PORT 'mail_username': process.env.MAIL_USERNAME 'mail_password': process.env.MAIL_PASSWORD 'mongo_db': process.env.MONGODB or 'mongodb://192.168.99.100:27017/mean-coffee-starter' 'redis_host': process.env.REDISHOST or '192.168.99.100' 'redis_port': process.env.REDISPORT or 6379 # 'redis_auth': process.env.REDISAUTH # 'redis_opts': {} # 'postgres_db': process.env.POSTGRESDB app.set key, value for key, value of application_globals app.locals.title = application_globals['title'] app.locals.dev = application_globals['dev']
185007
path = require "path" Emitter = require('events').EventEmitter ### # Application Globals Setup ### module.exports = (app) -> global.app = app global._ = require 'lodash' global.moment = require 'moment' global.logger = require('./logger')() global.events = new Emitter() global.empty_fn = -> null global.constant = {} global.constant.one_ms = 1 global.constant.one_second = constant.one_ms * 1000 global.constant.one_minute = constant.one_second * 60 global.constant.one_hour = constant.one_minute * 60 global.constant.one_day = constant.one_hour * 24 global.constant.one_week = constant.one_hour * 7 global.constant.one_month = constant.one_day * 30 # approx global.constant.one_year = constant.one_week * 52 # approx global.constant.one_byte = 1 global.constant.one_kb = 1024 * global.constant.one_byte global.constant.one_mb = 1024 * global.constant.one_kb global.constant.one_gb = 1024 * global.constant.one_mb application_globals = 'dev': app.get('env') isnt 'production' 'views': path.join(__dirname, "/../views") 'view engine': 'jade' 'title': 'MEAN Coffee Baseline' 'port': process.env.PORT 'sessionSecret': process.env.SESSION_SECRET 'mail_host': process.env.MAIL_HOST 'mail_port': process.env.MAIL_PORT 'mail_username': process.env.MAIL_USERNAME 'mail_password': <PASSWORD> 'mongo_db': process.env.MONGODB or 'mongodb://192.168.99.100:27017/mean-coffee-starter' 'redis_host': process.env.REDISHOST or '192.168.99.100' 'redis_port': process.env.REDISPORT or 6379 # 'redis_auth': process.env.REDISAUTH # 'redis_opts': {} # 'postgres_db': process.env.POSTGRESDB app.set key, value for key, value of application_globals app.locals.title = application_globals['title'] app.locals.dev = application_globals['dev']
true
path = require "path" Emitter = require('events').EventEmitter ### # Application Globals Setup ### module.exports = (app) -> global.app = app global._ = require 'lodash' global.moment = require 'moment' global.logger = require('./logger')() global.events = new Emitter() global.empty_fn = -> null global.constant = {} global.constant.one_ms = 1 global.constant.one_second = constant.one_ms * 1000 global.constant.one_minute = constant.one_second * 60 global.constant.one_hour = constant.one_minute * 60 global.constant.one_day = constant.one_hour * 24 global.constant.one_week = constant.one_hour * 7 global.constant.one_month = constant.one_day * 30 # approx global.constant.one_year = constant.one_week * 52 # approx global.constant.one_byte = 1 global.constant.one_kb = 1024 * global.constant.one_byte global.constant.one_mb = 1024 * global.constant.one_kb global.constant.one_gb = 1024 * global.constant.one_mb application_globals = 'dev': app.get('env') isnt 'production' 'views': path.join(__dirname, "/../views") 'view engine': 'jade' 'title': 'MEAN Coffee Baseline' 'port': process.env.PORT 'sessionSecret': process.env.SESSION_SECRET 'mail_host': process.env.MAIL_HOST 'mail_port': process.env.MAIL_PORT 'mail_username': process.env.MAIL_USERNAME 'mail_password': PI:PASSWORD:<PASSWORD>END_PI 'mongo_db': process.env.MONGODB or 'mongodb://192.168.99.100:27017/mean-coffee-starter' 'redis_host': process.env.REDISHOST or '192.168.99.100' 'redis_port': process.env.REDISPORT or 6379 # 'redis_auth': process.env.REDISAUTH # 'redis_opts': {} # 'postgres_db': process.env.POSTGRESDB app.set key, value for key, value of application_globals app.locals.title = application_globals['title'] app.locals.dev = application_globals['dev']
[ { "context": "port}\"\n\n Accounts.emailTemplates.from = \"CoLabs <no-reply@CoLabs.biz>\"\n Accounts.emailTemplates.siteName = \"CoLabs\"\n ", "end": 850, "score": 0.99989914894104, "start": 831, "tag": "EMAIL", "value": "no-reply@CoLabs.biz" }, { "context": ".verifyEmail.text = (user, url) ->\n \"Welcome, #{user.username}!\n \n Clicking on the following lin", "end": 1084, "score": 0.8408426642417908, "start": 1080, "tag": "USERNAME", "value": "user" }, { "context": "fyEmail.text = (user, url) ->\n \"Welcome, #{user.username}!\n \n Clicking on the following link will ve", "end": 1093, "score": 0.9219821691513062, "start": 1085, "tag": "USERNAME", "value": "username" } ]
app/server/init.coffee
eribeiro9/CoLabs
0
### # TODO: Google Analytics process.env.METEOR_SETTINGS = { public: { ga: { account: "UA-65362043-1" } } } ### if Meteor.settings?.env? rootUrl = '' if Meteor.settings.env.type isnt 'development' {port, rootUrl, mongoUrl, bindIp, velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 process.env.PORT = port process.env.ROOT_URL = rootUrl process.env.MONGO_URL = mongoUrl process.env.BIND_IP = bindIp else do Logger.enable {velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 smtp = Meteor.settings.smtp (smtp[prop] = encodeURIComponent val) for prop, val of smtp process.env.MAIL_URL = "smtp://#{smtp.username}:#{smtp.password}@#{smtp.server}:#{smtp.port}" Accounts.emailTemplates.from = "CoLabs <no-reply@CoLabs.biz>" Accounts.emailTemplates.siteName = "CoLabs" Accounts.emailTemplates.verifyEmail.subject = (user) -> "Confirm Your Email Address at CoLabs" Accounts.emailTemplates.verifyEmail.text = (user, url) -> "Welcome, #{user.username}! Clicking on the following link will verify your email address: #{ rootUrl + "#/" + (url.split '/#/').pop() }. After verifying, you will unlock the full capabilities of interacting with users and projects! Sincerely, The CoLabs Community"
102303
### # TODO: Google Analytics process.env.METEOR_SETTINGS = { public: { ga: { account: "UA-65362043-1" } } } ### if Meteor.settings?.env? rootUrl = '' if Meteor.settings.env.type isnt 'development' {port, rootUrl, mongoUrl, bindIp, velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 process.env.PORT = port process.env.ROOT_URL = rootUrl process.env.MONGO_URL = mongoUrl process.env.BIND_IP = bindIp else do Logger.enable {velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 smtp = Meteor.settings.smtp (smtp[prop] = encodeURIComponent val) for prop, val of smtp process.env.MAIL_URL = "smtp://#{smtp.username}:#{smtp.password}@#{smtp.server}:#{smtp.port}" Accounts.emailTemplates.from = "CoLabs <<EMAIL>>" Accounts.emailTemplates.siteName = "CoLabs" Accounts.emailTemplates.verifyEmail.subject = (user) -> "Confirm Your Email Address at CoLabs" Accounts.emailTemplates.verifyEmail.text = (user, url) -> "Welcome, #{user.username}! Clicking on the following link will verify your email address: #{ rootUrl + "#/" + (url.split '/#/').pop() }. After verifying, you will unlock the full capabilities of interacting with users and projects! Sincerely, The CoLabs Community"
true
### # TODO: Google Analytics process.env.METEOR_SETTINGS = { public: { ga: { account: "UA-65362043-1" } } } ### if Meteor.settings?.env? rootUrl = '' if Meteor.settings.env.type isnt 'development' {port, rootUrl, mongoUrl, bindIp, velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 process.env.PORT = port process.env.ROOT_URL = rootUrl process.env.MONGO_URL = mongoUrl process.env.BIND_IP = bindIp else do Logger.enable {velocity} = Meteor.settings.env process.env.VELOCITY = velocity or 0 smtp = Meteor.settings.smtp (smtp[prop] = encodeURIComponent val) for prop, val of smtp process.env.MAIL_URL = "smtp://#{smtp.username}:#{smtp.password}@#{smtp.server}:#{smtp.port}" Accounts.emailTemplates.from = "CoLabs <PI:EMAIL:<EMAIL>END_PI>" Accounts.emailTemplates.siteName = "CoLabs" Accounts.emailTemplates.verifyEmail.subject = (user) -> "Confirm Your Email Address at CoLabs" Accounts.emailTemplates.verifyEmail.text = (user, url) -> "Welcome, #{user.username}! Clicking on the following link will verify your email address: #{ rootUrl + "#/" + (url.split '/#/').pop() }. After verifying, you will unlock the full capabilities of interacting with users and projects! Sincerely, The CoLabs Community"
[ { "context": " @database.devices.insert uuid: 'uuid1', token: 'token1', configureWhitelist: ['*'], done\n\n beforeEac", "end": 554, "score": 0.6817396879196167, "start": 549, "tag": "KEY", "value": "token" }, { "context": "tabase.devices.insert uuid: 'uuid1', token: 'token1', configureWhitelist: ['*'], done\n\n beforeEach", "end": 555, "score": 0.6519724130630493, "start": 554, "tag": "PASSWORD", "value": "1" }, { "context": " @database.devices.insert uuid: 'uuid2', token: 'token2', configureWhitelist: [], done\n\n describe 'wh", "end": 736, "score": 0.5759169459342957, "start": 731, "tag": "KEY", "value": "token" }, { "context": "tabase.devices.insert uuid: 'uuid2', token: 'token2', configureWhitelist: [], done\n\n describe 'whe", "end": 737, "score": 0.8311790227890015, "start": 736, "tag": "PASSWORD", "value": "2" } ]
test/lib/deleteSubscriptionIfAuthorized-spec.coffee
CESARBR/knot-cloud-source
4
_ = require 'lodash' TestDatabase = require '../test-database' describe 'deleteSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/deleteSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when there is a closed device and an open device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: 'token1', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: 'token2', configureWhitelist: [], done describe 'when the devices are subscribed to each other', -> beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'event', done beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @closed_device.uuid, emitterUuid: @open_device.uuid, type: 'event', done describe 'when the open device tries to remove a subscription from itself to the closed device', -> beforeEach (done) -> params = { uuid: @open_device.uuid targetUuid: @closed_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should remove exactly one subscription from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else tries to remove the subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { uuid: @closed_device.uuid targetUuid: @open_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should remove no subscriptions from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 2 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to remove subscription on behalf of that device'
5061
_ = require 'lodash' TestDatabase = require '../test-database' describe 'deleteSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/deleteSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when there is a closed device and an open device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: '<KEY> <PASSWORD>', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: '<KEY> <PASSWORD>', configureWhitelist: [], done describe 'when the devices are subscribed to each other', -> beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'event', done beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @closed_device.uuid, emitterUuid: @open_device.uuid, type: 'event', done describe 'when the open device tries to remove a subscription from itself to the closed device', -> beforeEach (done) -> params = { uuid: @open_device.uuid targetUuid: @closed_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should remove exactly one subscription from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else tries to remove the subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { uuid: @closed_device.uuid targetUuid: @open_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should remove no subscriptions from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 2 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to remove subscription on behalf of that device'
true
_ = require 'lodash' TestDatabase = require '../test-database' describe 'deleteSubscriptionIfAuthorized', -> beforeEach -> @sut = require '../../lib/deleteSubscriptionIfAuthorized' beforeEach (done) -> TestDatabase.open (error, database) => @database = database @dependencies = database: @database done error describe 'when there is a closed device and an open device', -> beforeEach (done) -> @open_device = uuid: 'uuid1', configureWhitelist: ['*'] @database.devices.insert uuid: 'uuid1', token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', configureWhitelist: ['*'], done beforeEach (done) -> @closed_device = uuid: 'uuid2', configureWhitelist: [] @database.devices.insert uuid: 'uuid2', token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', configureWhitelist: [], done describe 'when the devices are subscribed to each other', -> beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @open_device.uuid, emitterUuid: @closed_device.uuid, type: 'event', done beforeEach (done) -> @database.subscriptions.insert subscriberUuid: @closed_device.uuid, emitterUuid: @open_device.uuid, type: 'event', done describe 'when the open device tries to remove a subscription from itself to the closed device', -> beforeEach (done) -> params = { uuid: @open_device.uuid targetUuid: @closed_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @open_device @sut @open_device, params, done, @dependencies it 'should remove exactly one subscription from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 1 done() describe 'when someone else tries to remove the subscription from the closed device to the open device', -> beforeEach (done) -> @other_device = {uuid: 'uuid3'} params = { uuid: @closed_device.uuid targetUuid: @open_device.uuid type: 'event' } @dependencies.getDevice = sinon.stub().yields null, @closed_device storeError = (@error) => done() @sut @other_device, params, storeError, @dependencies it 'should remove no subscriptions from the database', (done) -> @database.subscriptions.count {}, (error, subscriptionCount) => return done error if error? expect(subscriptionCount).to.equal 2 done() it 'should yield an error', -> expect(@error).to.be.an.instanceOf Error expect(@error.message).to.deep.equal 'Insufficient permissions to remove subscription on behalf of that device'
[ { "context": "window.Furatto =\n name: 'Furatto'\n version: '1.0.0'\n\n$('.alert .close').each ->", "end": 31, "score": 0.5823742151260376, "start": 27, "tag": "NAME", "value": "urat" } ]
coffee/furatto.coffee
IcaliaLabs/furatto
133
window.Furatto = name: 'Furatto' version: '1.0.0' $('.alert .close').each -> $(@).click (e) -> e.preventDefault() $(@).parent().fadeOut()
16866
window.Furatto = name: 'F<NAME>to' version: '1.0.0' $('.alert .close').each -> $(@).click (e) -> e.preventDefault() $(@).parent().fadeOut()
true
window.Furatto = name: 'FPI:NAME:<NAME>END_PIto' version: '1.0.0' $('.alert .close').each -> $(@).click (e) -> e.preventDefault() $(@).parent().fadeOut()
[ { "context": "text: this\n data:\n name: name\n success: (data) ->\n @l", "end": 4718, "score": 0.9973024725914001, "start": 4714, "tag": "NAME", "value": "name" } ]
samples/scala/zentasks/app/assets/javascripts/main.coffee
adriaanm/playframework
22
# ----------------------------------------------- # MAIN # ----------------------------------------------- # DISCLAMER : # If you're used to Backbone.js, you may be # confused by the absence of models, but the goal # of this sample is to demonstrate some features # of Play including the template engine. # I'm not using client-side templating nor models # for this purpose, and I do not recommend this # behavior for real life projects. # ----------------------------------------------- # Just a log helper log = (args...) -> console.log.apply console, args if console.log? # ------------------------------- DROP DOWN MENUS $(".options dt, .users dt").live "click", (e) -> e.preventDefault() if $(e.target).parent().hasClass("opened") $(e.target).parent().removeClass("opened") else $(e.target).parent().addClass("opened") $(document).one "click", -> $(e.target).parent().removeClass("opened") false # --------------------------------- EDIT IN PLACE $.fn.editInPlace = (method, options...) -> this.each -> methods = # public methods init: (options) -> valid = (e) => newValue = @input.val() options.onChange.call(options.context, newValue) cancel = (e) => @el.show() @input.hide() @el = $(this).dblclick(methods.edit) @input = $("<input type='text' />") .insertBefore(@el) .keyup (e) -> switch(e.keyCode) # Enter key when 13 then $(this).blur() # Escape key when 27 then cancel(e) .blur(valid) .hide() edit: -> @input .val(@el.text()) .show() .focus() .select() @el.hide() close: (newName) -> @el.text(newName).show() @input.hide() # jQuery approach: http://docs.jquery.com/Plugins/Authoring if ( methods[method] ) return methods[ method ].apply(this, options) else if (typeof method == 'object') return methods.init.call(this, method) else $.error("Method " + method + " does not exist.") # ---------------------------------------- DRAWER class Drawer extends Backbone.View initialize: -> $("#newGroup").click @addGroup # HTML is our model @el.children("li").each (i,group) -> new Group el: $(group) $("li",group).each (i,project) -> new Project el: $(project) addGroup: -> jsRoutes.controllers.Projects.addGroup().ajax success: (data) -> _view = new Group el: $(data).appendTo("#projects") _view.el.find(".groupName").editInPlace("edit") error: (err) -> # TODO: Deal with # ---------------------------------------- GROUPS class Group extends Backbone.View events: "click .toggle" : "toggle" "click .newProject" : "newProject" "click .deleteGroup" : "deleteGroup" initialize: -> @id = @el.attr("data-group") @name = $(".groupName", @el).editInPlace context: this onChange: @renameGroup newProject: (e) -> e.preventDefault() @el.removeClass("closed") jsRoutes.controllers.Projects.add().ajax context: this data: group: @el.attr("data-group") success: (tpl) -> _list = $("ul",@el) _view = new Project el: $(tpl).appendTo(_list) _view.el.find(".name").editInPlace("edit") error: (err) -> $.error("Error: " + err) deleteGroup: (e) -> e.preventDefault() false if (!confirm "Remove group and projects inside?") id = @el.attr("data-group-id") @loading(true) jsRoutes.controllers.Projects.deleteGroup(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) renameGroup: (name) => @loading(true) jsRoutes.controllers.Projects.renameGroup(@id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-group", data) @id = @el.attr("data-group") error: (err) -> @loading(false) $.error("Error: " + err) toggle: (e) -> e.preventDefault() @el.toggleClass("closed") false loading: (display) -> if (display) @el.children(".options").hide() @el.children(".loader").show() else @el.children(".options").show() @el.children(".loader").hide() # --------------------------------------- PROJECT class Project extends Backbone.View events: "click .delete" : "deleteProject" initialize: -> @id = @el.attr("data-project") @name = $(".name", @el).editInPlace context: this onChange: @renameProject renameProject: (name) -> @loading(true) jsRoutes.controllers.Projects.rename(@id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) error: (err) -> @loading(false) $.error("Error: " + err) deleteProject: (e) -> e.preventDefault() @loading(true) jsRoutes.controllers.Projects.delete(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) false loading: (display) -> if (display) @el.children(".delete").hide() @el.children(".loader").show() else @el.children(".delete").show() @el.children(".loader").hide() # ---------------------------------------- ROUTER class AppRouter extends Backbone.Router initialize: -> @currentApp = new Tasks el: $("#main") routes: "" : "index" "/projects/:project/tasks" : "tasks" index: -> # show dashboard $("#main").load "/ #main" tasks: (project) -> # load project || display app currentApp = @currentApp $("#main").load "/projects/" + project + "/tasks", (tpl) -> currentApp.render(project) # ----------------------------------------- TASKS class Tasks extends Backbone.View events: "click .newFolder" : "newFolder" "click .list .action" : "removeUser" "click .addUserList .action" : "addUser" render: (project) -> @project = project # HTML is our model @folders = $.map $(".folder", @el), (folder) => new TaskFolder el: $(folder) project: @project newFolder: (e) -> e.preventDefault() jsRoutes.controllers.Tasks.addFolder(@project).ajax context: this success: (tpl) -> newFolder = new TaskFolder el: $(tpl).insertBefore(".newFolder") project: @project newFolder.el.find("header > h3").editInPlace("edit") error: (err) -> $.error("Error: " + err) false removeUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.removeUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".addUserList") error: (err) -> $.error("Error: " + err) false addUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.addUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".users .list") error: (err) -> $.error("Error: " + err) false # ---------------------------------- TASKS FOLDER class TaskFolder extends Backbone.View events: "click .deleteCompleteTasks" : "deleteCompleteTasks" "click .deleteAllTasks" : "deleteAllTasks" "click .deleteFolder" : "deleteFolder" "change header>input" : "toggleAll" "submit .addTask" : "newTask" initialize: (options) => @project = options.project @tasks = $.map $(".list li",@el), (item)=> newTask = new TaskItem el: $(item) folder: @ newTask.bind("change", @refreshCount) newTask.bind("delete", @deleteTask) @counter = @el.find(".counter") @id = @el.attr("data-folder-id") @name = $("header > h3", @el).editInPlace context: this onChange: @renameFolder @refreshCount() newTask: (e) => e.preventDefault() $(document).focus() # temporary disable form form = $(e.target) taskBody = $("input[name=taskBody]", form).val() url = form.attr("action") jsRoutes.controllers.Tasks.add(@project, @id).ajax url: url type: "POST" context: this data: title: $("input[name=taskBody]", form).val() dueDate: $("input[name=dueDate]", form).val() assignedTo: $("input[name=assignedTo]", form).val() success: (tpl) -> newTask = new TaskItem(el: $(tpl), folder: @) @el.find("ul").append(newTask.el) @tasks.push(newTask) form.find("input[type=text]").val("").first().focus() error: (err) -> alert "Something went wrong:" + err false renameFolder: (name) => @loading(true) jsRoutes.controllers.Tasks.renameFolder(@project, @id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-folder-id", data) @id = @el.attr("data-folder-id") error: (err) -> @loading(false) $.error("Error: " + err) deleteCompleteTasks: (e) => e.preventDefault() $.each @tasks, (i, item) -> item.deleteTask() if item.el.find(".done:checked").length > 0 true false deleteAllTasks: (e) => e.preventDefault() $.each @tasks, (i, item)-> item.deleteTask() true false deleteFolder: (e) => e.preventDefault() @el.remove() false toggleAll: (e) => val = $(e.target).is(":checked") $.each @tasks, (i, item) -> item.toggle(val) true refreshCount: => count = @tasks.filter((item)-> item.el.find(".done:checked").length == 0 ).length @counter.text(count) deleteTask: (task) => @tasks = _.without @tasks, tasks @refreshCount() loading: (display) -> if (display) @el.find("header .options").hide() @el.find("header .loader").show() else @el.find("header .options").show() @el.find("header .loader").hide() # ------------------------------------- TASK ITEM class TaskItem extends Backbone.View events: "change .done" : "onToggle" "click .deleteTask" : "deleteTask" "dblclick h4" : "editTask" initialize: (options) -> @check = @el.find(".done") @id = @el.attr("data-task-id") @folder = options.folder deleteTask: (e) => e.preventDefault() if e? @loading(false) jsRoutes.controllers.Tasks.delete(@id).ajax context: this data: name: name success: (data) -> @loading(false) @el.remove() @trigger("delete", @) error: (err) -> @loading(false) $.error("Error: " + err) false editTask: (e) => e.preventDefault() # TODO alert "not implemented yet." false toggle: (val) => @loading(true) jsRoutes.controllers.Tasks.update(@id).ajax context: this data: done: val success: (data) -> @loading(false) @check.attr("checked",val) @trigger("change", @) error: (err) -> @loading(false) $.error("Error: " + err) onToggle: (e) => e.preventDefault() val = @check.is(":checked") log val @toggle(val) false loading: (display) -> if (display) @el.find(".delete").hide() @el.find(".loader").show() else @el.find(".delete").show() @el.find(".loader").hide() # ------------------------------------- INIT APP $ -> # document is ready! app = new AppRouter() drawer = new Drawer el: $("#projects") Backbone.history.start pushHistory: true
141328
# ----------------------------------------------- # MAIN # ----------------------------------------------- # DISCLAMER : # If you're used to Backbone.js, you may be # confused by the absence of models, but the goal # of this sample is to demonstrate some features # of Play including the template engine. # I'm not using client-side templating nor models # for this purpose, and I do not recommend this # behavior for real life projects. # ----------------------------------------------- # Just a log helper log = (args...) -> console.log.apply console, args if console.log? # ------------------------------- DROP DOWN MENUS $(".options dt, .users dt").live "click", (e) -> e.preventDefault() if $(e.target).parent().hasClass("opened") $(e.target).parent().removeClass("opened") else $(e.target).parent().addClass("opened") $(document).one "click", -> $(e.target).parent().removeClass("opened") false # --------------------------------- EDIT IN PLACE $.fn.editInPlace = (method, options...) -> this.each -> methods = # public methods init: (options) -> valid = (e) => newValue = @input.val() options.onChange.call(options.context, newValue) cancel = (e) => @el.show() @input.hide() @el = $(this).dblclick(methods.edit) @input = $("<input type='text' />") .insertBefore(@el) .keyup (e) -> switch(e.keyCode) # Enter key when 13 then $(this).blur() # Escape key when 27 then cancel(e) .blur(valid) .hide() edit: -> @input .val(@el.text()) .show() .focus() .select() @el.hide() close: (newName) -> @el.text(newName).show() @input.hide() # jQuery approach: http://docs.jquery.com/Plugins/Authoring if ( methods[method] ) return methods[ method ].apply(this, options) else if (typeof method == 'object') return methods.init.call(this, method) else $.error("Method " + method + " does not exist.") # ---------------------------------------- DRAWER class Drawer extends Backbone.View initialize: -> $("#newGroup").click @addGroup # HTML is our model @el.children("li").each (i,group) -> new Group el: $(group) $("li",group).each (i,project) -> new Project el: $(project) addGroup: -> jsRoutes.controllers.Projects.addGroup().ajax success: (data) -> _view = new Group el: $(data).appendTo("#projects") _view.el.find(".groupName").editInPlace("edit") error: (err) -> # TODO: Deal with # ---------------------------------------- GROUPS class Group extends Backbone.View events: "click .toggle" : "toggle" "click .newProject" : "newProject" "click .deleteGroup" : "deleteGroup" initialize: -> @id = @el.attr("data-group") @name = $(".groupName", @el).editInPlace context: this onChange: @renameGroup newProject: (e) -> e.preventDefault() @el.removeClass("closed") jsRoutes.controllers.Projects.add().ajax context: this data: group: @el.attr("data-group") success: (tpl) -> _list = $("ul",@el) _view = new Project el: $(tpl).appendTo(_list) _view.el.find(".name").editInPlace("edit") error: (err) -> $.error("Error: " + err) deleteGroup: (e) -> e.preventDefault() false if (!confirm "Remove group and projects inside?") id = @el.attr("data-group-id") @loading(true) jsRoutes.controllers.Projects.deleteGroup(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) renameGroup: (name) => @loading(true) jsRoutes.controllers.Projects.renameGroup(@id).ajax context: this data: name: <NAME> success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-group", data) @id = @el.attr("data-group") error: (err) -> @loading(false) $.error("Error: " + err) toggle: (e) -> e.preventDefault() @el.toggleClass("closed") false loading: (display) -> if (display) @el.children(".options").hide() @el.children(".loader").show() else @el.children(".options").show() @el.children(".loader").hide() # --------------------------------------- PROJECT class Project extends Backbone.View events: "click .delete" : "deleteProject" initialize: -> @id = @el.attr("data-project") @name = $(".name", @el).editInPlace context: this onChange: @renameProject renameProject: (name) -> @loading(true) jsRoutes.controllers.Projects.rename(@id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) error: (err) -> @loading(false) $.error("Error: " + err) deleteProject: (e) -> e.preventDefault() @loading(true) jsRoutes.controllers.Projects.delete(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) false loading: (display) -> if (display) @el.children(".delete").hide() @el.children(".loader").show() else @el.children(".delete").show() @el.children(".loader").hide() # ---------------------------------------- ROUTER class AppRouter extends Backbone.Router initialize: -> @currentApp = new Tasks el: $("#main") routes: "" : "index" "/projects/:project/tasks" : "tasks" index: -> # show dashboard $("#main").load "/ #main" tasks: (project) -> # load project || display app currentApp = @currentApp $("#main").load "/projects/" + project + "/tasks", (tpl) -> currentApp.render(project) # ----------------------------------------- TASKS class Tasks extends Backbone.View events: "click .newFolder" : "newFolder" "click .list .action" : "removeUser" "click .addUserList .action" : "addUser" render: (project) -> @project = project # HTML is our model @folders = $.map $(".folder", @el), (folder) => new TaskFolder el: $(folder) project: @project newFolder: (e) -> e.preventDefault() jsRoutes.controllers.Tasks.addFolder(@project).ajax context: this success: (tpl) -> newFolder = new TaskFolder el: $(tpl).insertBefore(".newFolder") project: @project newFolder.el.find("header > h3").editInPlace("edit") error: (err) -> $.error("Error: " + err) false removeUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.removeUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".addUserList") error: (err) -> $.error("Error: " + err) false addUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.addUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".users .list") error: (err) -> $.error("Error: " + err) false # ---------------------------------- TASKS FOLDER class TaskFolder extends Backbone.View events: "click .deleteCompleteTasks" : "deleteCompleteTasks" "click .deleteAllTasks" : "deleteAllTasks" "click .deleteFolder" : "deleteFolder" "change header>input" : "toggleAll" "submit .addTask" : "newTask" initialize: (options) => @project = options.project @tasks = $.map $(".list li",@el), (item)=> newTask = new TaskItem el: $(item) folder: @ newTask.bind("change", @refreshCount) newTask.bind("delete", @deleteTask) @counter = @el.find(".counter") @id = @el.attr("data-folder-id") @name = $("header > h3", @el).editInPlace context: this onChange: @renameFolder @refreshCount() newTask: (e) => e.preventDefault() $(document).focus() # temporary disable form form = $(e.target) taskBody = $("input[name=taskBody]", form).val() url = form.attr("action") jsRoutes.controllers.Tasks.add(@project, @id).ajax url: url type: "POST" context: this data: title: $("input[name=taskBody]", form).val() dueDate: $("input[name=dueDate]", form).val() assignedTo: $("input[name=assignedTo]", form).val() success: (tpl) -> newTask = new TaskItem(el: $(tpl), folder: @) @el.find("ul").append(newTask.el) @tasks.push(newTask) form.find("input[type=text]").val("").first().focus() error: (err) -> alert "Something went wrong:" + err false renameFolder: (name) => @loading(true) jsRoutes.controllers.Tasks.renameFolder(@project, @id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-folder-id", data) @id = @el.attr("data-folder-id") error: (err) -> @loading(false) $.error("Error: " + err) deleteCompleteTasks: (e) => e.preventDefault() $.each @tasks, (i, item) -> item.deleteTask() if item.el.find(".done:checked").length > 0 true false deleteAllTasks: (e) => e.preventDefault() $.each @tasks, (i, item)-> item.deleteTask() true false deleteFolder: (e) => e.preventDefault() @el.remove() false toggleAll: (e) => val = $(e.target).is(":checked") $.each @tasks, (i, item) -> item.toggle(val) true refreshCount: => count = @tasks.filter((item)-> item.el.find(".done:checked").length == 0 ).length @counter.text(count) deleteTask: (task) => @tasks = _.without @tasks, tasks @refreshCount() loading: (display) -> if (display) @el.find("header .options").hide() @el.find("header .loader").show() else @el.find("header .options").show() @el.find("header .loader").hide() # ------------------------------------- TASK ITEM class TaskItem extends Backbone.View events: "change .done" : "onToggle" "click .deleteTask" : "deleteTask" "dblclick h4" : "editTask" initialize: (options) -> @check = @el.find(".done") @id = @el.attr("data-task-id") @folder = options.folder deleteTask: (e) => e.preventDefault() if e? @loading(false) jsRoutes.controllers.Tasks.delete(@id).ajax context: this data: name: name success: (data) -> @loading(false) @el.remove() @trigger("delete", @) error: (err) -> @loading(false) $.error("Error: " + err) false editTask: (e) => e.preventDefault() # TODO alert "not implemented yet." false toggle: (val) => @loading(true) jsRoutes.controllers.Tasks.update(@id).ajax context: this data: done: val success: (data) -> @loading(false) @check.attr("checked",val) @trigger("change", @) error: (err) -> @loading(false) $.error("Error: " + err) onToggle: (e) => e.preventDefault() val = @check.is(":checked") log val @toggle(val) false loading: (display) -> if (display) @el.find(".delete").hide() @el.find(".loader").show() else @el.find(".delete").show() @el.find(".loader").hide() # ------------------------------------- INIT APP $ -> # document is ready! app = new AppRouter() drawer = new Drawer el: $("#projects") Backbone.history.start pushHistory: true
true
# ----------------------------------------------- # MAIN # ----------------------------------------------- # DISCLAMER : # If you're used to Backbone.js, you may be # confused by the absence of models, but the goal # of this sample is to demonstrate some features # of Play including the template engine. # I'm not using client-side templating nor models # for this purpose, and I do not recommend this # behavior for real life projects. # ----------------------------------------------- # Just a log helper log = (args...) -> console.log.apply console, args if console.log? # ------------------------------- DROP DOWN MENUS $(".options dt, .users dt").live "click", (e) -> e.preventDefault() if $(e.target).parent().hasClass("opened") $(e.target).parent().removeClass("opened") else $(e.target).parent().addClass("opened") $(document).one "click", -> $(e.target).parent().removeClass("opened") false # --------------------------------- EDIT IN PLACE $.fn.editInPlace = (method, options...) -> this.each -> methods = # public methods init: (options) -> valid = (e) => newValue = @input.val() options.onChange.call(options.context, newValue) cancel = (e) => @el.show() @input.hide() @el = $(this).dblclick(methods.edit) @input = $("<input type='text' />") .insertBefore(@el) .keyup (e) -> switch(e.keyCode) # Enter key when 13 then $(this).blur() # Escape key when 27 then cancel(e) .blur(valid) .hide() edit: -> @input .val(@el.text()) .show() .focus() .select() @el.hide() close: (newName) -> @el.text(newName).show() @input.hide() # jQuery approach: http://docs.jquery.com/Plugins/Authoring if ( methods[method] ) return methods[ method ].apply(this, options) else if (typeof method == 'object') return methods.init.call(this, method) else $.error("Method " + method + " does not exist.") # ---------------------------------------- DRAWER class Drawer extends Backbone.View initialize: -> $("#newGroup").click @addGroup # HTML is our model @el.children("li").each (i,group) -> new Group el: $(group) $("li",group).each (i,project) -> new Project el: $(project) addGroup: -> jsRoutes.controllers.Projects.addGroup().ajax success: (data) -> _view = new Group el: $(data).appendTo("#projects") _view.el.find(".groupName").editInPlace("edit") error: (err) -> # TODO: Deal with # ---------------------------------------- GROUPS class Group extends Backbone.View events: "click .toggle" : "toggle" "click .newProject" : "newProject" "click .deleteGroup" : "deleteGroup" initialize: -> @id = @el.attr("data-group") @name = $(".groupName", @el).editInPlace context: this onChange: @renameGroup newProject: (e) -> e.preventDefault() @el.removeClass("closed") jsRoutes.controllers.Projects.add().ajax context: this data: group: @el.attr("data-group") success: (tpl) -> _list = $("ul",@el) _view = new Project el: $(tpl).appendTo(_list) _view.el.find(".name").editInPlace("edit") error: (err) -> $.error("Error: " + err) deleteGroup: (e) -> e.preventDefault() false if (!confirm "Remove group and projects inside?") id = @el.attr("data-group-id") @loading(true) jsRoutes.controllers.Projects.deleteGroup(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) renameGroup: (name) => @loading(true) jsRoutes.controllers.Projects.renameGroup(@id).ajax context: this data: name: PI:NAME:<NAME>END_PI success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-group", data) @id = @el.attr("data-group") error: (err) -> @loading(false) $.error("Error: " + err) toggle: (e) -> e.preventDefault() @el.toggleClass("closed") false loading: (display) -> if (display) @el.children(".options").hide() @el.children(".loader").show() else @el.children(".options").show() @el.children(".loader").hide() # --------------------------------------- PROJECT class Project extends Backbone.View events: "click .delete" : "deleteProject" initialize: -> @id = @el.attr("data-project") @name = $(".name", @el).editInPlace context: this onChange: @renameProject renameProject: (name) -> @loading(true) jsRoutes.controllers.Projects.rename(@id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) error: (err) -> @loading(false) $.error("Error: " + err) deleteProject: (e) -> e.preventDefault() @loading(true) jsRoutes.controllers.Projects.delete(@id).ajax context: this success: -> @el.remove() @loading(false) error: (err) -> @loading(false) $.error("Error: " + err) false loading: (display) -> if (display) @el.children(".delete").hide() @el.children(".loader").show() else @el.children(".delete").show() @el.children(".loader").hide() # ---------------------------------------- ROUTER class AppRouter extends Backbone.Router initialize: -> @currentApp = new Tasks el: $("#main") routes: "" : "index" "/projects/:project/tasks" : "tasks" index: -> # show dashboard $("#main").load "/ #main" tasks: (project) -> # load project || display app currentApp = @currentApp $("#main").load "/projects/" + project + "/tasks", (tpl) -> currentApp.render(project) # ----------------------------------------- TASKS class Tasks extends Backbone.View events: "click .newFolder" : "newFolder" "click .list .action" : "removeUser" "click .addUserList .action" : "addUser" render: (project) -> @project = project # HTML is our model @folders = $.map $(".folder", @el), (folder) => new TaskFolder el: $(folder) project: @project newFolder: (e) -> e.preventDefault() jsRoutes.controllers.Tasks.addFolder(@project).ajax context: this success: (tpl) -> newFolder = new TaskFolder el: $(tpl).insertBefore(".newFolder") project: @project newFolder.el.find("header > h3").editInPlace("edit") error: (err) -> $.error("Error: " + err) false removeUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.removeUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".addUserList") error: (err) -> $.error("Error: " + err) false addUser: (e) -> e.preventDefault() jsRoutes.controllers.Projects.addUser(@project).ajax context: this data: user: $(e.target).parent().data('user-id') success: -> $(e.target).parent().appendTo(".users .list") error: (err) -> $.error("Error: " + err) false # ---------------------------------- TASKS FOLDER class TaskFolder extends Backbone.View events: "click .deleteCompleteTasks" : "deleteCompleteTasks" "click .deleteAllTasks" : "deleteAllTasks" "click .deleteFolder" : "deleteFolder" "change header>input" : "toggleAll" "submit .addTask" : "newTask" initialize: (options) => @project = options.project @tasks = $.map $(".list li",@el), (item)=> newTask = new TaskItem el: $(item) folder: @ newTask.bind("change", @refreshCount) newTask.bind("delete", @deleteTask) @counter = @el.find(".counter") @id = @el.attr("data-folder-id") @name = $("header > h3", @el).editInPlace context: this onChange: @renameFolder @refreshCount() newTask: (e) => e.preventDefault() $(document).focus() # temporary disable form form = $(e.target) taskBody = $("input[name=taskBody]", form).val() url = form.attr("action") jsRoutes.controllers.Tasks.add(@project, @id).ajax url: url type: "POST" context: this data: title: $("input[name=taskBody]", form).val() dueDate: $("input[name=dueDate]", form).val() assignedTo: $("input[name=assignedTo]", form).val() success: (tpl) -> newTask = new TaskItem(el: $(tpl), folder: @) @el.find("ul").append(newTask.el) @tasks.push(newTask) form.find("input[type=text]").val("").first().focus() error: (err) -> alert "Something went wrong:" + err false renameFolder: (name) => @loading(true) jsRoutes.controllers.Tasks.renameFolder(@project, @id).ajax context: this data: name: name success: (data) -> @loading(false) @name.editInPlace("close", data) @el.attr("data-folder-id", data) @id = @el.attr("data-folder-id") error: (err) -> @loading(false) $.error("Error: " + err) deleteCompleteTasks: (e) => e.preventDefault() $.each @tasks, (i, item) -> item.deleteTask() if item.el.find(".done:checked").length > 0 true false deleteAllTasks: (e) => e.preventDefault() $.each @tasks, (i, item)-> item.deleteTask() true false deleteFolder: (e) => e.preventDefault() @el.remove() false toggleAll: (e) => val = $(e.target).is(":checked") $.each @tasks, (i, item) -> item.toggle(val) true refreshCount: => count = @tasks.filter((item)-> item.el.find(".done:checked").length == 0 ).length @counter.text(count) deleteTask: (task) => @tasks = _.without @tasks, tasks @refreshCount() loading: (display) -> if (display) @el.find("header .options").hide() @el.find("header .loader").show() else @el.find("header .options").show() @el.find("header .loader").hide() # ------------------------------------- TASK ITEM class TaskItem extends Backbone.View events: "change .done" : "onToggle" "click .deleteTask" : "deleteTask" "dblclick h4" : "editTask" initialize: (options) -> @check = @el.find(".done") @id = @el.attr("data-task-id") @folder = options.folder deleteTask: (e) => e.preventDefault() if e? @loading(false) jsRoutes.controllers.Tasks.delete(@id).ajax context: this data: name: name success: (data) -> @loading(false) @el.remove() @trigger("delete", @) error: (err) -> @loading(false) $.error("Error: " + err) false editTask: (e) => e.preventDefault() # TODO alert "not implemented yet." false toggle: (val) => @loading(true) jsRoutes.controllers.Tasks.update(@id).ajax context: this data: done: val success: (data) -> @loading(false) @check.attr("checked",val) @trigger("change", @) error: (err) -> @loading(false) $.error("Error: " + err) onToggle: (e) => e.preventDefault() val = @check.is(":checked") log val @toggle(val) false loading: (display) -> if (display) @el.find(".delete").hide() @el.find(".loader").show() else @el.find(".delete").show() @el.find(".loader").hide() # ------------------------------------- INIT APP $ -> # document is ready! app = new AppRouter() drawer = new Drawer el: $("#projects") Backbone.history.start pushHistory: true
[ { "context": "\" \n else if d.name is \"Storage\"\n return \"assets/i", "end": 17504, "score": 0.8343694806098938, "start": 17497, "tag": "NAME", "value": "Storage" } ]
v2.5/src/app/controllers/rsaController.coffee
sharonlucong/compass-intel-rsa-dist
0
define(['./baseController'], ()-> 'use strict'; angular.module('compass.controllers') .controller 'rsaCtrl', ['$scope', 'rsaService','$timeout', 'rsaFactory', '$rootScope' ($scope, rsaService, $timeout, rsaFactory, $rootScope) -> $scope.selectPod = (podid) -> $scope.showRacks = false $scope.type = "" $scope.noRacks = false $scope.show = false $scope.showPieChart = false $scope.podID = podid rsaFactory.setPodId(podid) $scope.podpromisecompleted = false rsaService.getPodRacks($scope, podid).then(-> $scope.podpromisecompleted = true if !$scope.racks[0] $scope.noRacks = true else $scope.rackid = $scope.racks[0].id $scope.noRacks = false $rootScope.$broadcast('setActiveTab', $scope.rackid) rsaService.getRackDrawers($scope, $scope.racks[0].id) rsaService.getRackThermalZones($scope, $scope.racks[0].id) rsaService.getRackPowerZones($scope, $scope.racks[0].id) rsaService.getAllChartsData($scope, $scope.racks[0].id).then(-> $scope.showPieChart = true )) $timeout(()-> if !$scope.racks[0] $scope.showRacks = false $scope.noRacks = true else $scope.showRacks = true $scope.noRacks = false , 3000) #initialization rsaService.getRSAManagers($scope).then(-> $scope.selectPod(1) $scope.rackid = 1 ) ] .controller 'rackCtrl', ['$scope', 'rsaService','rsaFactory', '$timeout' ($scope, rsaService, rsaFactory, $timeout) -> tabClasses = [] $scope.pieStorageData = [ {key: "One",y: 3}, {key: "Two",y: 7} ] $scope.pieCPUData = [ {key: "One",y: 4}, {key: "Two",y: 6} ] $scope.pieMemoryData = [ {key: "One",y: 5}, {key: "Two",y: 5} ] $scope.getTabClass = (tabNum) -> return tabClasses[tabNum] $scope.getTabPaneClass = (tabNum) -> return "tab-pane " + tabClasses[tabNum] #initialization tabClasses[1] = "active" $scope.getTabClass(1) $scope.getTabPaneClass(1) $scope.showRackDetails = true $scope.$on('setActiveTab', (event, arg)-> $scope.setActiveTab(arg) ) $scope.setActiveTab = (tabNum) -> $scope.type = "" $scope.showRackDetails = false $scope.show = false $scope.showPieChart = false $scope.rackid = tabNum rsaService.getRackDrawers($scope, tabNum) rsaService.getRackThermalZones($scope, tabNum) rsaService.getRackPowerZones($scope, tabNum) rsaService.getAllChartsData($scope, tabNum).then(-> $scope.showPieChart = true ) tabClasses = [] tabClasses[tabNum] = "active" $timeout(()-> $scope.showRackDetails = true , 3000) $scope.width = 500 $scope.height = 500 $scope.pieColor = ['#6898ce', '#73b9e6'] $scope.xFunction = ()-> return (d)-> return d.key $scope.yFunction = ()-> return (d)-> return d.y $scope.descriptionFunction = ()-> return (d)-> return d.key $scope.colors = () -> return $scope.pieColor $scope.show = false $scope.showChart = (showType, id)-> $scope.isFinishLoading = false $scope.type = showType $scope.show = !$scope.show if $scope.show is false $scope.$apply() if showType is "drawer" $scope.drawerid = id else if showType is "thermal" $scope.thermalid = id else if showType is "power" $scope.powerid = id ] .controller 'chartCtrl', ['$scope','rsaService', '$timeout', 'rsaFactory', '$window' ($scope, rsaService, $timeout, rsaFactory, $window) -> $scope.render = (data) -> d3.selectAll('.chart').selectAll("*").remove() svg = d3.selectAll('.chart') .append("svg") .attr("width", '650px') .style("margin-left", '130px') w = 650; h = 600; x = d3.scale.linear().range([0, w]) y = d3.scale.linear().range([0, h]) color = d3.scale.ordinal().range(["#0D3A6E", "#045A8D", "#0570B0","#3690C0", "#74A9CF","#4586B6","#68A9D4"]) vis = svg.attr("height", h) partition = d3.layout.partition() .value((d)-> return d.size ) kx = w / data.dx ky = h / 1 dataset = [] clickChild = false click = (d) -> if !d.children return if !d.parent and !clickChild $scope.$parent.showChart() clickChild = true if !d.parent clickChild = false if d.y then kx = (w-40) / (1-d.y) else kx = w/(1-d.y) ky = h / d.dx if d.y then l=40 else l=0 x.domain([d.y, 1]).range([l, w]) y.domain([d.x, d.x + d.dx]) if d3.event.altKey then dur = 7500 else dur = 750 t = g.transition() .duration(dur) .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) t.select("rect") .attr("width", d.dy * kx) .attr("height", (d)-> return d.dx * ky ) t.selectAll("image") .style("opacity", (d)-> if d.dx*ky >37 return 1 else return 0 ) t.selectAll("text") .attr("dy", (d)-> if d.dx*ky > 50 if d.name is "Processors" return "1em" else if d.name is "Memories" return "2%" else return ".35em" else return ".35em" ) .style("opacity", (d)-> if d.dx*ky > 30 return 1 else return 0 ) d3.selectAll('.helper').remove() g.append('foreignObject') .attr('x', 10) .attr('y', (d)-> if d.name in ["Processors","Memories"] return 80 else return 20 ) .attr('width', (d)-> if d.name in ["Processors","Memories"] return 200 else return 180 ) .attr('height', (d)-> if d.name in ["Processors","Memories"] if d.dx*ky > 30 return 300 if !d.children if d.dx * ky > 30 return 100 ) .attr('class','helper') .append("xhtml:div") .style("opacity", (d)-> if !d.children if d.dx * ky > 50 return 1 else return 0 else if d.dx*ky > 130 return 1 else return 0 ) .html((d,i)-> str = "" if !d.children if d.details if d.details.component_uuid str = "<div style='color:white;font-size:12px'><span>"+"uuid: </span><p>" + d.details.component_uuid+"</p></div>" if d.name in ["Processors", "Memories"] if d.children[0] for commonkey, commonval of d.children[0].details if commonkey in ["processor_model", "processor_family", "processor_architecture", "processor_manufacture", "processor_cores", "processor_frequency", "memory_module_type", "memory_module_capacity"] str += "<div style='color:white; font-size:12px;'>"+ commonkey+ ": "+ commonval+"</div>" return str ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) d3.event.stopPropagation() g = vis.selectAll("g") .data(partition.nodes(data)) .enter().append("g") .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) .on("click", click) kx = w / data.dx ky = h / 1 g.append("rect") .attr("width", data.dy * kx) .attr("height", (d)-> return d.dx * ky ) .attr("rx", 5) .attr("ry", 5) .style("fill", (d,i)-> if d.children return color(d.name) else return d.parent.name ) .attr("class", (d)-> if d.children return "parent" else return "child" ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) .on("mouseout", (d)-> if !d.parent d3.select(this) .style("fill", "#0D3A6E") d3.selectAll("#tooltip li").remove() d3.select("#tooltip").classed("hidden", true) ) g.append("image") .attr("xlink:href", (d)-> if !d.name return "" else if d.name is "Processors" return "assets/img/processor_icon.png" else if d.name is "Memories" return "assets/img/memory_icon.png" else if d.name.match(/Disc-([0-9]|[1-9][0-9])/) return "assets/img/storage_icon.png" else if d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/thermal_icon.png" else if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/power_icon.png" else if d.name is "Storage" return "assets/img/storage_icon.png" else if !d.child if d.name.match(/fan\s([0-9]|[1-9][0-9])/) return "assets/img/fan_icon.png" else if d.name.match(/psu\s([0-9]|[1-9][0-9])/) return "assets/img/powerunit_icon.png" else return "" else return "" ) .attr("transform", (d)-> if !d.name return "translate(0,0)" if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) or d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "translate(8," + d.dx * ky / 2.2 + ")" else return "translate(8," + d.dx * ky / 3 + ")" ) .attr("width", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .attr("height", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .style("opacity", (d)-> if d.dx * ky > 37 return 1 else return 0 ) g.append("text") .attr("transform", (d)-> return "translate(60," + d.dx * ky / 2 + ")" ) .attr("dy", ".35em") .attr("fill", "white") .style("opacity", (d)-> if d.dx * ky > 12 return 1 else return 0 ) .text((d)-> if !d.parent return d.name + " " + "\u21D0" else return d.name ) if $scope.$parent.type is "drawer" rsaService.getRackDrawerDetails($scope, $scope.$parent.drawerid).then(-> $scope.$parent.isFinishLoading = true return $scope.render($scope.drawerData)) else if $scope.$parent.type is "power" rsaService.getRackPowerZonesSupplyUnits($scope, $scope.$parent.rackid, $scope.$parent.powerid).then(-> return $scope.render($scope.powerData)) else if $scope.$parent.type is "thermal" rsaService.getRackThermalZonesFans($scope, $scope.$parent.rackid, $scope.$parent.thermalid).then(-> return $scope.render($scope.thermalData)) ] )
10335
define(['./baseController'], ()-> 'use strict'; angular.module('compass.controllers') .controller 'rsaCtrl', ['$scope', 'rsaService','$timeout', 'rsaFactory', '$rootScope' ($scope, rsaService, $timeout, rsaFactory, $rootScope) -> $scope.selectPod = (podid) -> $scope.showRacks = false $scope.type = "" $scope.noRacks = false $scope.show = false $scope.showPieChart = false $scope.podID = podid rsaFactory.setPodId(podid) $scope.podpromisecompleted = false rsaService.getPodRacks($scope, podid).then(-> $scope.podpromisecompleted = true if !$scope.racks[0] $scope.noRacks = true else $scope.rackid = $scope.racks[0].id $scope.noRacks = false $rootScope.$broadcast('setActiveTab', $scope.rackid) rsaService.getRackDrawers($scope, $scope.racks[0].id) rsaService.getRackThermalZones($scope, $scope.racks[0].id) rsaService.getRackPowerZones($scope, $scope.racks[0].id) rsaService.getAllChartsData($scope, $scope.racks[0].id).then(-> $scope.showPieChart = true )) $timeout(()-> if !$scope.racks[0] $scope.showRacks = false $scope.noRacks = true else $scope.showRacks = true $scope.noRacks = false , 3000) #initialization rsaService.getRSAManagers($scope).then(-> $scope.selectPod(1) $scope.rackid = 1 ) ] .controller 'rackCtrl', ['$scope', 'rsaService','rsaFactory', '$timeout' ($scope, rsaService, rsaFactory, $timeout) -> tabClasses = [] $scope.pieStorageData = [ {key: "One",y: 3}, {key: "Two",y: 7} ] $scope.pieCPUData = [ {key: "One",y: 4}, {key: "Two",y: 6} ] $scope.pieMemoryData = [ {key: "One",y: 5}, {key: "Two",y: 5} ] $scope.getTabClass = (tabNum) -> return tabClasses[tabNum] $scope.getTabPaneClass = (tabNum) -> return "tab-pane " + tabClasses[tabNum] #initialization tabClasses[1] = "active" $scope.getTabClass(1) $scope.getTabPaneClass(1) $scope.showRackDetails = true $scope.$on('setActiveTab', (event, arg)-> $scope.setActiveTab(arg) ) $scope.setActiveTab = (tabNum) -> $scope.type = "" $scope.showRackDetails = false $scope.show = false $scope.showPieChart = false $scope.rackid = tabNum rsaService.getRackDrawers($scope, tabNum) rsaService.getRackThermalZones($scope, tabNum) rsaService.getRackPowerZones($scope, tabNum) rsaService.getAllChartsData($scope, tabNum).then(-> $scope.showPieChart = true ) tabClasses = [] tabClasses[tabNum] = "active" $timeout(()-> $scope.showRackDetails = true , 3000) $scope.width = 500 $scope.height = 500 $scope.pieColor = ['#6898ce', '#73b9e6'] $scope.xFunction = ()-> return (d)-> return d.key $scope.yFunction = ()-> return (d)-> return d.y $scope.descriptionFunction = ()-> return (d)-> return d.key $scope.colors = () -> return $scope.pieColor $scope.show = false $scope.showChart = (showType, id)-> $scope.isFinishLoading = false $scope.type = showType $scope.show = !$scope.show if $scope.show is false $scope.$apply() if showType is "drawer" $scope.drawerid = id else if showType is "thermal" $scope.thermalid = id else if showType is "power" $scope.powerid = id ] .controller 'chartCtrl', ['$scope','rsaService', '$timeout', 'rsaFactory', '$window' ($scope, rsaService, $timeout, rsaFactory, $window) -> $scope.render = (data) -> d3.selectAll('.chart').selectAll("*").remove() svg = d3.selectAll('.chart') .append("svg") .attr("width", '650px') .style("margin-left", '130px') w = 650; h = 600; x = d3.scale.linear().range([0, w]) y = d3.scale.linear().range([0, h]) color = d3.scale.ordinal().range(["#0D3A6E", "#045A8D", "#0570B0","#3690C0", "#74A9CF","#4586B6","#68A9D4"]) vis = svg.attr("height", h) partition = d3.layout.partition() .value((d)-> return d.size ) kx = w / data.dx ky = h / 1 dataset = [] clickChild = false click = (d) -> if !d.children return if !d.parent and !clickChild $scope.$parent.showChart() clickChild = true if !d.parent clickChild = false if d.y then kx = (w-40) / (1-d.y) else kx = w/(1-d.y) ky = h / d.dx if d.y then l=40 else l=0 x.domain([d.y, 1]).range([l, w]) y.domain([d.x, d.x + d.dx]) if d3.event.altKey then dur = 7500 else dur = 750 t = g.transition() .duration(dur) .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) t.select("rect") .attr("width", d.dy * kx) .attr("height", (d)-> return d.dx * ky ) t.selectAll("image") .style("opacity", (d)-> if d.dx*ky >37 return 1 else return 0 ) t.selectAll("text") .attr("dy", (d)-> if d.dx*ky > 50 if d.name is "Processors" return "1em" else if d.name is "Memories" return "2%" else return ".35em" else return ".35em" ) .style("opacity", (d)-> if d.dx*ky > 30 return 1 else return 0 ) d3.selectAll('.helper').remove() g.append('foreignObject') .attr('x', 10) .attr('y', (d)-> if d.name in ["Processors","Memories"] return 80 else return 20 ) .attr('width', (d)-> if d.name in ["Processors","Memories"] return 200 else return 180 ) .attr('height', (d)-> if d.name in ["Processors","Memories"] if d.dx*ky > 30 return 300 if !d.children if d.dx * ky > 30 return 100 ) .attr('class','helper') .append("xhtml:div") .style("opacity", (d)-> if !d.children if d.dx * ky > 50 return 1 else return 0 else if d.dx*ky > 130 return 1 else return 0 ) .html((d,i)-> str = "" if !d.children if d.details if d.details.component_uuid str = "<div style='color:white;font-size:12px'><span>"+"uuid: </span><p>" + d.details.component_uuid+"</p></div>" if d.name in ["Processors", "Memories"] if d.children[0] for commonkey, commonval of d.children[0].details if commonkey in ["processor_model", "processor_family", "processor_architecture", "processor_manufacture", "processor_cores", "processor_frequency", "memory_module_type", "memory_module_capacity"] str += "<div style='color:white; font-size:12px;'>"+ commonkey+ ": "+ commonval+"</div>" return str ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) d3.event.stopPropagation() g = vis.selectAll("g") .data(partition.nodes(data)) .enter().append("g") .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) .on("click", click) kx = w / data.dx ky = h / 1 g.append("rect") .attr("width", data.dy * kx) .attr("height", (d)-> return d.dx * ky ) .attr("rx", 5) .attr("ry", 5) .style("fill", (d,i)-> if d.children return color(d.name) else return d.parent.name ) .attr("class", (d)-> if d.children return "parent" else return "child" ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) .on("mouseout", (d)-> if !d.parent d3.select(this) .style("fill", "#0D3A6E") d3.selectAll("#tooltip li").remove() d3.select("#tooltip").classed("hidden", true) ) g.append("image") .attr("xlink:href", (d)-> if !d.name return "" else if d.name is "Processors" return "assets/img/processor_icon.png" else if d.name is "Memories" return "assets/img/memory_icon.png" else if d.name.match(/Disc-([0-9]|[1-9][0-9])/) return "assets/img/storage_icon.png" else if d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/thermal_icon.png" else if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/power_icon.png" else if d.name is "<NAME>" return "assets/img/storage_icon.png" else if !d.child if d.name.match(/fan\s([0-9]|[1-9][0-9])/) return "assets/img/fan_icon.png" else if d.name.match(/psu\s([0-9]|[1-9][0-9])/) return "assets/img/powerunit_icon.png" else return "" else return "" ) .attr("transform", (d)-> if !d.name return "translate(0,0)" if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) or d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "translate(8," + d.dx * ky / 2.2 + ")" else return "translate(8," + d.dx * ky / 3 + ")" ) .attr("width", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .attr("height", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .style("opacity", (d)-> if d.dx * ky > 37 return 1 else return 0 ) g.append("text") .attr("transform", (d)-> return "translate(60," + d.dx * ky / 2 + ")" ) .attr("dy", ".35em") .attr("fill", "white") .style("opacity", (d)-> if d.dx * ky > 12 return 1 else return 0 ) .text((d)-> if !d.parent return d.name + " " + "\u21D0" else return d.name ) if $scope.$parent.type is "drawer" rsaService.getRackDrawerDetails($scope, $scope.$parent.drawerid).then(-> $scope.$parent.isFinishLoading = true return $scope.render($scope.drawerData)) else if $scope.$parent.type is "power" rsaService.getRackPowerZonesSupplyUnits($scope, $scope.$parent.rackid, $scope.$parent.powerid).then(-> return $scope.render($scope.powerData)) else if $scope.$parent.type is "thermal" rsaService.getRackThermalZonesFans($scope, $scope.$parent.rackid, $scope.$parent.thermalid).then(-> return $scope.render($scope.thermalData)) ] )
true
define(['./baseController'], ()-> 'use strict'; angular.module('compass.controllers') .controller 'rsaCtrl', ['$scope', 'rsaService','$timeout', 'rsaFactory', '$rootScope' ($scope, rsaService, $timeout, rsaFactory, $rootScope) -> $scope.selectPod = (podid) -> $scope.showRacks = false $scope.type = "" $scope.noRacks = false $scope.show = false $scope.showPieChart = false $scope.podID = podid rsaFactory.setPodId(podid) $scope.podpromisecompleted = false rsaService.getPodRacks($scope, podid).then(-> $scope.podpromisecompleted = true if !$scope.racks[0] $scope.noRacks = true else $scope.rackid = $scope.racks[0].id $scope.noRacks = false $rootScope.$broadcast('setActiveTab', $scope.rackid) rsaService.getRackDrawers($scope, $scope.racks[0].id) rsaService.getRackThermalZones($scope, $scope.racks[0].id) rsaService.getRackPowerZones($scope, $scope.racks[0].id) rsaService.getAllChartsData($scope, $scope.racks[0].id).then(-> $scope.showPieChart = true )) $timeout(()-> if !$scope.racks[0] $scope.showRacks = false $scope.noRacks = true else $scope.showRacks = true $scope.noRacks = false , 3000) #initialization rsaService.getRSAManagers($scope).then(-> $scope.selectPod(1) $scope.rackid = 1 ) ] .controller 'rackCtrl', ['$scope', 'rsaService','rsaFactory', '$timeout' ($scope, rsaService, rsaFactory, $timeout) -> tabClasses = [] $scope.pieStorageData = [ {key: "One",y: 3}, {key: "Two",y: 7} ] $scope.pieCPUData = [ {key: "One",y: 4}, {key: "Two",y: 6} ] $scope.pieMemoryData = [ {key: "One",y: 5}, {key: "Two",y: 5} ] $scope.getTabClass = (tabNum) -> return tabClasses[tabNum] $scope.getTabPaneClass = (tabNum) -> return "tab-pane " + tabClasses[tabNum] #initialization tabClasses[1] = "active" $scope.getTabClass(1) $scope.getTabPaneClass(1) $scope.showRackDetails = true $scope.$on('setActiveTab', (event, arg)-> $scope.setActiveTab(arg) ) $scope.setActiveTab = (tabNum) -> $scope.type = "" $scope.showRackDetails = false $scope.show = false $scope.showPieChart = false $scope.rackid = tabNum rsaService.getRackDrawers($scope, tabNum) rsaService.getRackThermalZones($scope, tabNum) rsaService.getRackPowerZones($scope, tabNum) rsaService.getAllChartsData($scope, tabNum).then(-> $scope.showPieChart = true ) tabClasses = [] tabClasses[tabNum] = "active" $timeout(()-> $scope.showRackDetails = true , 3000) $scope.width = 500 $scope.height = 500 $scope.pieColor = ['#6898ce', '#73b9e6'] $scope.xFunction = ()-> return (d)-> return d.key $scope.yFunction = ()-> return (d)-> return d.y $scope.descriptionFunction = ()-> return (d)-> return d.key $scope.colors = () -> return $scope.pieColor $scope.show = false $scope.showChart = (showType, id)-> $scope.isFinishLoading = false $scope.type = showType $scope.show = !$scope.show if $scope.show is false $scope.$apply() if showType is "drawer" $scope.drawerid = id else if showType is "thermal" $scope.thermalid = id else if showType is "power" $scope.powerid = id ] .controller 'chartCtrl', ['$scope','rsaService', '$timeout', 'rsaFactory', '$window' ($scope, rsaService, $timeout, rsaFactory, $window) -> $scope.render = (data) -> d3.selectAll('.chart').selectAll("*").remove() svg = d3.selectAll('.chart') .append("svg") .attr("width", '650px') .style("margin-left", '130px') w = 650; h = 600; x = d3.scale.linear().range([0, w]) y = d3.scale.linear().range([0, h]) color = d3.scale.ordinal().range(["#0D3A6E", "#045A8D", "#0570B0","#3690C0", "#74A9CF","#4586B6","#68A9D4"]) vis = svg.attr("height", h) partition = d3.layout.partition() .value((d)-> return d.size ) kx = w / data.dx ky = h / 1 dataset = [] clickChild = false click = (d) -> if !d.children return if !d.parent and !clickChild $scope.$parent.showChart() clickChild = true if !d.parent clickChild = false if d.y then kx = (w-40) / (1-d.y) else kx = w/(1-d.y) ky = h / d.dx if d.y then l=40 else l=0 x.domain([d.y, 1]).range([l, w]) y.domain([d.x, d.x + d.dx]) if d3.event.altKey then dur = 7500 else dur = 750 t = g.transition() .duration(dur) .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) t.select("rect") .attr("width", d.dy * kx) .attr("height", (d)-> return d.dx * ky ) t.selectAll("image") .style("opacity", (d)-> if d.dx*ky >37 return 1 else return 0 ) t.selectAll("text") .attr("dy", (d)-> if d.dx*ky > 50 if d.name is "Processors" return "1em" else if d.name is "Memories" return "2%" else return ".35em" else return ".35em" ) .style("opacity", (d)-> if d.dx*ky > 30 return 1 else return 0 ) d3.selectAll('.helper').remove() g.append('foreignObject') .attr('x', 10) .attr('y', (d)-> if d.name in ["Processors","Memories"] return 80 else return 20 ) .attr('width', (d)-> if d.name in ["Processors","Memories"] return 200 else return 180 ) .attr('height', (d)-> if d.name in ["Processors","Memories"] if d.dx*ky > 30 return 300 if !d.children if d.dx * ky > 30 return 100 ) .attr('class','helper') .append("xhtml:div") .style("opacity", (d)-> if !d.children if d.dx * ky > 50 return 1 else return 0 else if d.dx*ky > 130 return 1 else return 0 ) .html((d,i)-> str = "" if !d.children if d.details if d.details.component_uuid str = "<div style='color:white;font-size:12px'><span>"+"uuid: </span><p>" + d.details.component_uuid+"</p></div>" if d.name in ["Processors", "Memories"] if d.children[0] for commonkey, commonval of d.children[0].details if commonkey in ["processor_model", "processor_family", "processor_architecture", "processor_manufacture", "processor_cores", "processor_frequency", "memory_module_type", "memory_module_capacity"] str += "<div style='color:white; font-size:12px;'>"+ commonkey+ ": "+ commonval+"</div>" return str ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) d3.event.stopPropagation() g = vis.selectAll("g") .data(partition.nodes(data)) .enter().append("g") .attr("transform", (d)-> return "translate(" + x(d.y) + "," + y(d.x) + ")" ) .on("click", click) kx = w / data.dx ky = h / 1 g.append("rect") .attr("width", data.dy * kx) .attr("height", (d)-> return d.dx * ky ) .attr("rx", 5) .attr("ry", 5) .style("fill", (d,i)-> if d.children return color(d.name) else return d.parent.name ) .attr("class", (d)-> if d.children return "parent" else return "child" ) .on("mouseover", (d)-> if !d.parent d3.select(this) .style("fill", "#048D7E") if !d.children xPos = 0 yPos = 0 dataset = [] dataset.push("name: " + d.name) for key of d.details if d.details.hasOwnProperty(key) dataset.push(key + ": " + d.details[key]) d3.select('#tooltip') .style("top", 200 + "px") .select("#tooltip ul") .selectAll("li") .data(dataset) .enter() .append("li") .text((dt)-> return dt ) d3.select("#tooltip").classed("hidden", false) ) .on("mouseout", (d)-> if !d.parent d3.select(this) .style("fill", "#0D3A6E") d3.selectAll("#tooltip li").remove() d3.select("#tooltip").classed("hidden", true) ) g.append("image") .attr("xlink:href", (d)-> if !d.name return "" else if d.name is "Processors" return "assets/img/processor_icon.png" else if d.name is "Memories" return "assets/img/memory_icon.png" else if d.name.match(/Disc-([0-9]|[1-9][0-9])/) return "assets/img/storage_icon.png" else if d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/thermal_icon.png" else if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) return "assets/img/power_icon.png" else if d.name is "PI:NAME:<NAME>END_PI" return "assets/img/storage_icon.png" else if !d.child if d.name.match(/fan\s([0-9]|[1-9][0-9])/) return "assets/img/fan_icon.png" else if d.name.match(/psu\s([0-9]|[1-9][0-9])/) return "assets/img/powerunit_icon.png" else return "" else return "" ) .attr("transform", (d)-> if !d.name return "translate(0,0)" if d.name.match(/Power\sZone\s([0-9]|[1-9][0-9])/) or d.name.match(/Thermal\sZone\s([0-9]|[1-9][0-9])/) return "translate(8," + d.dx * ky / 2.2 + ")" else return "translate(8," + d.dx * ky / 3 + ")" ) .attr("width", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .attr("height", (d)-> if d.name is "Memories" or "Processors" or "Storage" return 30 else return 40 ) .style("opacity", (d)-> if d.dx * ky > 37 return 1 else return 0 ) g.append("text") .attr("transform", (d)-> return "translate(60," + d.dx * ky / 2 + ")" ) .attr("dy", ".35em") .attr("fill", "white") .style("opacity", (d)-> if d.dx * ky > 12 return 1 else return 0 ) .text((d)-> if !d.parent return d.name + " " + "\u21D0" else return d.name ) if $scope.$parent.type is "drawer" rsaService.getRackDrawerDetails($scope, $scope.$parent.drawerid).then(-> $scope.$parent.isFinishLoading = true return $scope.render($scope.drawerData)) else if $scope.$parent.type is "power" rsaService.getRackPowerZonesSupplyUnits($scope, $scope.$parent.rackid, $scope.$parent.powerid).then(-> return $scope.render($scope.powerData)) else if $scope.$parent.type is "thermal" rsaService.getRackThermalZonesFans($scope, $scope.$parent.rackid, $scope.$parent.thermalid).then(-> return $scope.render($scope.thermalData)) ] )
[ { "context": "data structure based on a Red-Black Tree\n @author Mads Hartmann Jensen (mads379@gmail.com)\n###\n\nmugs.provide('mugs.TreeS", "end": 131, "score": 0.9998659491539001, "start": 111, "tag": "NAME", "value": "Mads Hartmann Jensen" }, { "context": " a Red-Black Tree\n @author Mads Hartmann Jensen (mads379@gmail.com)\n###\n\nmugs.provide('mugs.TreeSet')\n\nmugs.require(", "end": 150, "score": 0.9999312162399292, "start": 133, "tag": "EMAIL", "value": "mads379@gmail.com" } ]
src/TreeSet.coffee
mads-hartmann/mugs
1
###* @fileoverview Contains the implementation of the Set data structure based on a Red-Black Tree @author Mads Hartmann Jensen (mads379@gmail.com) ### mugs.provide('mugs.TreeSet') mugs.require('mugs.RedBlackLeaf') mugs.require('mugs.RedBlackNode') mugs.require("mugs.Indexed") ###* mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree. The TreeSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.TreeSet = (items,comparator) -> treeUnderConstruction = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK,comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction else this.tree = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK) this.tree.comparator = comparator if comparator? this mugs.TreeSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.TreeSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.TreeSet.prototype.buildFromTree = (tree) -> set = new mugs.TreeSet([], this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.TreeSet.prototype.buildFromArray = (arr) -> new mugs.TreeSet(arr, this.comparator) ###* Applies function 'f' on each value in the set. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the set. @see mugs.Collection ### mugs.TreeSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.TreeSet.prototype.isEmpty = () -> this.tree.isEmpty() ###* Tests if the set contains the element @param element The element to check for ### mugs.TreeSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Insert an element in the set. If the set already contains an element equal to the given value, it is replaced with the new value. @param item The element to insert into the set ### mugs.TreeSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Delete an element from the set @param item The element to remove from the set ### mugs.TreeSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.TreeSet.prototype.get = ( index ) -> this.tree.atIndex(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.TreeSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.TreeSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.TreeSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
173723
###* @fileoverview Contains the implementation of the Set data structure based on a Red-Black Tree @author <NAME> (<EMAIL>) ### mugs.provide('mugs.TreeSet') mugs.require('mugs.RedBlackLeaf') mugs.require('mugs.RedBlackNode') mugs.require("mugs.Indexed") ###* mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree. The TreeSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.TreeSet = (items,comparator) -> treeUnderConstruction = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK,comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction else this.tree = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK) this.tree.comparator = comparator if comparator? this mugs.TreeSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.TreeSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.TreeSet.prototype.buildFromTree = (tree) -> set = new mugs.TreeSet([], this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.TreeSet.prototype.buildFromArray = (arr) -> new mugs.TreeSet(arr, this.comparator) ###* Applies function 'f' on each value in the set. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the set. @see mugs.Collection ### mugs.TreeSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.TreeSet.prototype.isEmpty = () -> this.tree.isEmpty() ###* Tests if the set contains the element @param element The element to check for ### mugs.TreeSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Insert an element in the set. If the set already contains an element equal to the given value, it is replaced with the new value. @param item The element to insert into the set ### mugs.TreeSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Delete an element from the set @param item The element to remove from the set ### mugs.TreeSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.TreeSet.prototype.get = ( index ) -> this.tree.atIndex(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.TreeSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.TreeSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.TreeSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
true
###* @fileoverview Contains the implementation of the Set data structure based on a Red-Black Tree @author PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ### mugs.provide('mugs.TreeSet') mugs.require('mugs.RedBlackLeaf') mugs.require('mugs.RedBlackNode') mugs.require("mugs.Indexed") ###* mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree. The TreeSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.TreeSet provides the implementation of the abstract data type Set based on a Red Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.TreeSet = (items,comparator) -> treeUnderConstruction = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK,comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction else this.tree = new mugs.RedBlackLeaf(mugs.RedBlack.BLACK) this.tree.comparator = comparator if comparator? this mugs.TreeSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.TreeSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.TreeSet.prototype.buildFromTree = (tree) -> set = new mugs.TreeSet([], this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.TreeSet.prototype.buildFromArray = (arr) -> new mugs.TreeSet(arr, this.comparator) ###* Applies function 'f' on each value in the set. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the set. @see mugs.Collection ### mugs.TreeSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.TreeSet.prototype.isEmpty = () -> this.tree.isEmpty() ###* Tests if the set contains the element @param element The element to check for ### mugs.TreeSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Insert an element in the set. If the set already contains an element equal to the given value, it is replaced with the new value. @param item The element to insert into the set ### mugs.TreeSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Delete an element from the set @param item The element to remove from the set ### mugs.TreeSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.TreeSet.prototype.get = ( index ) -> this.tree.atIndex(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.TreeSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.TreeSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.TreeSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.TreeSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.TreeSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
[ { "context": "before ->\n @skip() if __globalTest.offline\n\n [Alice, Bob] = [null, null]\n # run this one as blocking", "end": 597, "score": 0.9982975125312805, "start": 592, "tag": "NAME", "value": "Alice" }, { "context": " ->\n @skip() if __globalTest.offline\n\n [Alice, Bob] = [null, null]\n # run this one as blocking asyn", "end": 602, "score": 0.9971160888671875, "start": 599, "tag": "NAME", "value": "Bob" }, { "context": "sts\n it 'get Server Token', ->\n\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.ne", "end": 749, "score": 0.9995631575584412, "start": 744, "tag": "NAME", "value": "Alice" }, { "context": "', ->\n\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n ", "end": 776, "score": 0.9995189905166626, "start": 771, "tag": "NAME", "value": "Alice" }, { "context": "then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n\n r = new", "end": 805, "score": 0.9995959401130676, "start": 802, "tag": "NAME", "value": "Bob" }, { "context": " ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n\n r = new Relay(__globalTest.host)\n ", "end": 832, "score": 0.9990566372871399, "start": 829, "tag": "NAME", "value": "Bob" }, { "context": "r.openConnection()\n\n it 'clear mailboxes', ->\n Alice.selfDestruct(true).then ->\n Bob.selfDestruct", "end": 2224, "score": 0.7592359781265259, "start": 2219, "tag": "NAME", "value": "Alice" }, { "context": "es', ->\n Alice.selfDestruct(true).then ->\n Bob.selfDestruct(true)\n", "end": 2261, "score": 0.7861824631690979, "start": 2258, "tag": "NAME", "value": "Bob" } ]
tests/specs/05.relay.coffee
vault12/glow
14
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT __CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Config = require 'config' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Utils = require 'utils' # ----- Communication Relay: Start session ----- describe 'Relay Session', -> return unless window.__globalTest.runTests['relay session'] @slow(window.__globalTest.slow) @timeout(window.__globalTest.timeouts.long) before -> @skip() if __globalTest.offline [Alice, Bob] = [null, null] # run this one as blocking async to see if the relay is online for the tests it 'get Server Token', -> MailBox.new('Alice').then (ret)-> Alice = ret MailBox.new('Bob').then (ret)-> Bob = ret r = new Relay(__globalTest.host) tm = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 2 r.getServerToken().then -> unless r.relayToken window.__globalTest.offline = true console.log "Local server offline: start relay at #{r.url}" r.online.should.be.false r.relayToken.should.not.be.null r.clientToken.should.not.be.null expect(r.relayKey).is.null Utils.delay Config.RELAY_TOKEN_TIMEOUT + 5, -> Config.RELAY_TOKEN_TIMEOUT = tm r.online.should.be.false expect(r.relayToken).is.null expect(r.clientToken).is.null it 'get session key', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.online.should.be.true r.relayToken.should.not.be.null r.clientToken.should.not.be.null r.relayKey.should.not.be.null it 'prove mailbox :hpk', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.connectMailbox(Alice).then -> expect(Alice.sessionKeys).not.empty it 'emits token timeout event', -> rt = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 10 r = new Relay(__globalTest.host) r.on 'relaytokentimeout', -> Config.RELAY_TOKEN_TIMEOUT = rt r.openConnection() it 'clear mailboxes', -> Alice.selfDestruct(true).then -> Bob.selfDestruct(true)
49183
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT __CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Config = require 'config' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Utils = require 'utils' # ----- Communication Relay: Start session ----- describe 'Relay Session', -> return unless window.__globalTest.runTests['relay session'] @slow(window.__globalTest.slow) @timeout(window.__globalTest.timeouts.long) before -> @skip() if __globalTest.offline [<NAME>, <NAME>] = [null, null] # run this one as blocking async to see if the relay is online for the tests it 'get Server Token', -> MailBox.new('<NAME>').then (ret)-> <NAME> = ret MailBox.new('<NAME>').then (ret)-> <NAME> = ret r = new Relay(__globalTest.host) tm = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 2 r.getServerToken().then -> unless r.relayToken window.__globalTest.offline = true console.log "Local server offline: start relay at #{r.url}" r.online.should.be.false r.relayToken.should.not.be.null r.clientToken.should.not.be.null expect(r.relayKey).is.null Utils.delay Config.RELAY_TOKEN_TIMEOUT + 5, -> Config.RELAY_TOKEN_TIMEOUT = tm r.online.should.be.false expect(r.relayToken).is.null expect(r.clientToken).is.null it 'get session key', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.online.should.be.true r.relayToken.should.not.be.null r.clientToken.should.not.be.null r.relayKey.should.not.be.null it 'prove mailbox :hpk', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.connectMailbox(Alice).then -> expect(Alice.sessionKeys).not.empty it 'emits token timeout event', -> rt = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 10 r = new Relay(__globalTest.host) r.on 'relaytokentimeout', -> Config.RELAY_TOKEN_TIMEOUT = rt r.openConnection() it 'clear mailboxes', -> <NAME>.selfDestruct(true).then -> <NAME>.selfDestruct(true)
true
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT __CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Config = require 'config' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Utils = require 'utils' # ----- Communication Relay: Start session ----- describe 'Relay Session', -> return unless window.__globalTest.runTests['relay session'] @slow(window.__globalTest.slow) @timeout(window.__globalTest.timeouts.long) before -> @skip() if __globalTest.offline [PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI] = [null, null] # run this one as blocking async to see if the relay is online for the tests it 'get Server Token', -> MailBox.new('PI:NAME:<NAME>END_PI').then (ret)-> PI:NAME:<NAME>END_PI = ret MailBox.new('PI:NAME:<NAME>END_PI').then (ret)-> PI:NAME:<NAME>END_PI = ret r = new Relay(__globalTest.host) tm = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 2 r.getServerToken().then -> unless r.relayToken window.__globalTest.offline = true console.log "Local server offline: start relay at #{r.url}" r.online.should.be.false r.relayToken.should.not.be.null r.clientToken.should.not.be.null expect(r.relayKey).is.null Utils.delay Config.RELAY_TOKEN_TIMEOUT + 5, -> Config.RELAY_TOKEN_TIMEOUT = tm r.online.should.be.false expect(r.relayToken).is.null expect(r.clientToken).is.null it 'get session key', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.online.should.be.true r.relayToken.should.not.be.null r.clientToken.should.not.be.null r.relayKey.should.not.be.null it 'prove mailbox :hpk', -> r = new Relay(__globalTest.host) r.openConnection().then -> r.connectMailbox(Alice).then -> expect(Alice.sessionKeys).not.empty it 'emits token timeout event', -> rt = Config.RELAY_TOKEN_TIMEOUT Config.RELAY_TOKEN_TIMEOUT = 10 r = new Relay(__globalTest.host) r.on 'relaytokentimeout', -> Config.RELAY_TOKEN_TIMEOUT = rt r.openConnection() it 'clear mailboxes', -> PI:NAME:<NAME>END_PI.selfDestruct(true).then -> PI:NAME:<NAME>END_PI.selfDestruct(true)
[ { "context": "window.nameData = [\n 'Bill Stevens',\n 'Bob Johnson',\n 'Steve Smith',\n 'Kevin Smit", "end": 35, "score": 0.9998796582221985, "start": 23, "tag": "NAME", "value": "Bill Stevens" }, { "context": "window.nameData = [\n 'Bill Stevens',\n 'Bob Johnson',\n 'Steve Smith',\n 'Kevin Smith',\n 'Barry O\\'D", "end": 52, "score": 0.9998807907104492, "start": 41, "tag": "NAME", "value": "Bob Johnson" }, { "context": "ameData = [\n 'Bill Stevens',\n 'Bob Johnson',\n 'Steve Smith',\n 'Kevin Smith',\n 'Barry O\\'Donnell',\n 'Kate ", "end": 69, "score": 0.9998624920845032, "start": 58, "tag": "NAME", "value": "Steve Smith" }, { "context": "ll Stevens',\n 'Bob Johnson',\n 'Steve Smith',\n 'Kevin Smith',\n 'Barry O\\'Donnell',\n 'Kate Vera',\n 'Kelly M", "end": 86, "score": 0.9998669624328613, "start": 75, "tag": "NAME", "value": "Kevin Smith" }, { "context": "ob Johnson',\n 'Steve Smith',\n 'Kevin Smith',\n 'Barry O\\'Donnell',\n 'Kate Vera',\n 'Kelly Mars',\n 'Susan Child',", "end": 108, "score": 0.9998863935470581, "start": 92, "tag": "NAME", "value": "Barry O\\'Donnell" }, { "context": "Smith',\n 'Kevin Smith',\n 'Barry O\\'Donnell',\n 'Kate Vera',\n 'Kelly Mars',\n 'Susan Child',\n 'Karen Moore", "end": 123, "score": 0.9998910427093506, "start": 114, "tag": "NAME", "value": "Kate Vera" }, { "context": "n Smith',\n 'Barry O\\'Donnell',\n 'Kate Vera',\n 'Kelly Mars',\n 'Susan Child',\n 'Karen Moore',\n 'Natalie Re", "end": 139, "score": 0.9998812675476074, "start": 129, "tag": "NAME", "value": "Kelly Mars" }, { "context": "ry O\\'Donnell',\n 'Kate Vera',\n 'Kelly Mars',\n 'Susan Child',\n 'Karen Moore',\n 'Natalie Reynolds'\n]\nwindow.", "end": 156, "score": 0.9998855590820312, "start": 145, "tag": "NAME", "value": "Susan Child" }, { "context": " 'Kate Vera',\n 'Kelly Mars',\n 'Susan Child',\n 'Karen Moore',\n 'Natalie Reynolds'\n]\nwindow.nameAndLocationDa", "end": 173, "score": 0.9998904466629028, "start": 162, "tag": "NAME", "value": "Karen Moore" }, { "context": "Kelly Mars',\n 'Susan Child',\n 'Karen Moore',\n 'Natalie Reynolds'\n]\nwindow.nameAndLocationData = [\n {name: 'Bill ", "end": 195, "score": 0.9999001622200012, "start": 179, "tag": "NAME", "value": "Natalie Reynolds" }, { "context": "nolds'\n]\nwindow.nameAndLocationData = [\n {name: 'Bill Stevens', location: 'New York'},\n {name: 'Bob Johnson', ", "end": 252, "score": 0.9998767971992493, "start": 240, "tag": "NAME", "value": "Bill Stevens" }, { "context": " 'Bill Stevens', location: 'New York'},\n {name: 'Bob Johnson', location: 'London'},\n {name: 'Steve Smith', lo", "end": 299, "score": 0.9998648166656494, "start": 288, "tag": "NAME", "value": "Bob Johnson" }, { "context": "me: 'Bob Johnson', location: 'London'},\n {name: 'Steve Smith', location: 'Cairo'},\n {name: 'Kevin Smith', loc", "end": 344, "score": 0.9998629689216614, "start": 333, "tag": "NAME", "value": "Steve Smith" }, { "context": "ame: 'Steve Smith', location: 'Cairo'},\n {name: 'Kevin Smith', location: 'Moscow'},\n {name: 'Barry O\\'Donnell", "end": 388, "score": 0.9998674392700195, "start": 377, "tag": "NAME", "value": "Kevin Smith" }, { "context": "me: 'Kevin Smith', location: 'Moscow'},\n {name: 'Barry O\\'Donnell', location: 'Tokyo'},\n {name: 'Kate Vera', locat", "end": 438, "score": 0.9998689293861389, "start": 422, "tag": "NAME", "value": "Barry O\\'Donnell" }, { "context": "'Barry O\\'Donnell', location: 'Tokyo'},\n {name: 'Kate Vera', location: 'Paris'},\n {name: 'Kelly Mars', loca", "end": 480, "score": 0.9998661279678345, "start": 471, "tag": "NAME", "value": "Kate Vera" }, { "context": "{name: 'Kate Vera', location: 'Paris'},\n {name: 'Kelly Mars', location: 'Barcelona'},\n {name: 'Susan Child',", "end": 523, "score": 0.9998792409896851, "start": 513, "tag": "NAME", "value": "Kelly Mars" }, { "context": ": 'Kelly Mars', location: 'Barcelona'},\n {name: 'Susan Child', location: 'Sardinia'},\n {name: 'Karen Moore', ", "end": 571, "score": 0.9998626708984375, "start": 560, "tag": "NAME", "value": "Susan Child" }, { "context": ": 'Susan Child', location: 'Sardinia'},\n {name: 'Karen Moore', location: 'Los Angeles'},\n {name: 'Natalie Rey", "end": 618, "score": 0.9998876452445984, "start": 607, "tag": "NAME", "value": "Karen Moore" }, { "context": "Karen Moore', location: 'Los Angeles'},\n {name: 'Natalie Reynolds', location: 'Brazil'}\n]", "end": 673, "score": 0.9998936057090759, "start": 657, "tag": "NAME", "value": "Natalie Reynolds" } ]
docs/content/examples/auto-complete/examples/data.coffee
p-koscielniak/hexagonjs
61
window.nameData = [ 'Bill Stevens', 'Bob Johnson', 'Steve Smith', 'Kevin Smith', 'Barry O\'Donnell', 'Kate Vera', 'Kelly Mars', 'Susan Child', 'Karen Moore', 'Natalie Reynolds' ] window.nameAndLocationData = [ {name: 'Bill Stevens', location: 'New York'}, {name: 'Bob Johnson', location: 'London'}, {name: 'Steve Smith', location: 'Cairo'}, {name: 'Kevin Smith', location: 'Moscow'}, {name: 'Barry O\'Donnell', location: 'Tokyo'}, {name: 'Kate Vera', location: 'Paris'}, {name: 'Kelly Mars', location: 'Barcelona'}, {name: 'Susan Child', location: 'Sardinia'}, {name: 'Karen Moore', location: 'Los Angeles'}, {name: 'Natalie Reynolds', location: 'Brazil'} ]
107205
window.nameData = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>' ] window.nameAndLocationData = [ {name: '<NAME>', location: 'New York'}, {name: '<NAME>', location: 'London'}, {name: '<NAME>', location: 'Cairo'}, {name: '<NAME>', location: 'Moscow'}, {name: '<NAME>', location: 'Tokyo'}, {name: '<NAME>', location: 'Paris'}, {name: '<NAME>', location: 'Barcelona'}, {name: '<NAME>', location: 'Sardinia'}, {name: '<NAME>', location: 'Los Angeles'}, {name: '<NAME>', location: 'Brazil'} ]
true
window.nameData = [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] window.nameAndLocationData = [ {name: 'PI:NAME:<NAME>END_PI', location: 'New York'}, {name: 'PI:NAME:<NAME>END_PI', location: 'London'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Cairo'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Moscow'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Tokyo'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Paris'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Barcelona'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Sardinia'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Los Angeles'}, {name: 'PI:NAME:<NAME>END_PI', location: 'Brazil'} ]
[ { "context": ": false # see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacemen", "end": 4968, "score": 0.9408020973205566, "start": 4966, "tag": "USERNAME", "value": "it" }, { "context": "........\n e = { d..., }\n e.$key = '^rawtext'\n e.syntax = null\n delete e", "end": 7233, "score": 0.7888504266738892, "start": 7231, "tag": "KEY", "value": "'^" }, { "context": ".....\n e = { d..., }\n e.$key = '^rawtext'\n e.syntax = null\n delete e.atrs\n ", "end": 7240, "score": 0.9537687301635742, "start": 7233, "tag": "KEY", "value": "rawtext" }, { "context": "en, ref, code, message ) ->\n token.$key = '^error'\n token.origin = 'htmlish'\n token.code ", "end": 15568, "score": 0.8338679075241089, "start": 15563, "tag": "KEY", "value": "error" } ]
src/htmlish-parser.coffee
loveencounterflow/dbay-mirage
0
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'DBAY-MIRAGE/HTMLISH-PARSER' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #........................................................................................................... types = new ( require 'intertype' ).Intertype() { isa type_of validate validate_list_of } = types.export() GUY = require 'guy' _HTMLISH = ( require 'paragate/lib/htmlish.grammar' ).new_grammar { bare: true, } { lets freeze thaw } = GUY.lft TIMETUNNEL = require 'timetunnel' { Moonriver } = require 'moonriver' { $ } = Moonriver #=========================================================================================================== ### TAINT use more relaxed syntax for names ### # G: grouped # O: optional xncr = {} xncr.nameG = ( /// (?<name> [a-z][a-z0-9]* ) /// ).source xncr.nameOG = ( /// (?: (?<csg> (?: [a-z][a-z0-9]* ) ) | ) /// ).source xncr.hexG = ( /// (?: x (?<hex> [a-fA-F0-9]+ ) ) /// ).source xncr.decG = ( /// (?<dec> [ 0-9]+ ) /// ).source xncr.matcher = /// ^ & #{xncr.nameG} ; | & #{xncr.nameOG} \# (?: #{xncr.hexG} | #{xncr.decG} ) ; $ /// xncr.splitter = /// ( & [^\s;]+ ; ) /// #=========================================================================================================== class @Htmlish #--------------------------------------------------------------------------------------------------------- @C: GUY.lft.freeze xncr: xncr # #--------------------------------------------------------------------------------------------------------- # constructor: -> # return undefined #--------------------------------------------------------------------------------------------------------- _tunnel: ( text ) -> ### TAINT do not reconstruct tunnel for each call ### # guards = 'äöüßp' # guards = '①②③④⑤' guards = '¥₽₨฿₮' intalph = '0123456789' tnl = new TIMETUNNEL.Timetunnel { guards, intalph, } tnl.add_tunnel TIMETUNNEL.tunnels.keep_backslash # tnl.add_tunnel TIMETUNNEL.tunnels.remove_backslash text = tnl.hide text return { text, reveal: ( tnl.reveal.bind tnl ), } #--------------------------------------------------------------------------------------------------------- _entity_token_from_match: ( d, start, stop, match ) -> g = match.groups R = { d..., } R.$key = '^entity' R.text = match[ 0 ] R.start = start R.stop = stop if g.name? R.type = 'named' R.name = g.name else R.type = if g.csg? then 'xncr' else 'ncr' R.csg = g.csg if g.csg? R.$value = parseInt g.hex ? g.dec, ( if g.hex? then 16 else 10 ) return R #--------------------------------------------------------------------------------------------------------- _text_token_from_part: ( d, start, stop, part ) -> R = { d..., } R.text = part R.start = start R.stop = stop return R #========================================================================================================= # #--------------------------------------------------------------------------------------------------------- $tunnel: ( tunnel_wrap ) -> ( text, send ) => { text reveal } = @_tunnel text tunnel_wrap.reveal = reveal send text return null #--------------------------------------------------------------------------------------------------------- $reveal_tunneled_text: ( tunnel_wrap ) -> ( d, send ) => return send d unless ( d.$key is '^text' ) or ( d.$key is '^rawtext' ) d.text = tunnel_wrap.reveal d.text send d #--------------------------------------------------------------------------------------------------------- $transpile_markdownish: -> mdit_cfg = html: true # Enable HTML tags in source xhtmlOut: false # Use '/' to close single tags (<br />). breaks: false # Convert '\n' in paragraphs into <br> langPrefix: 'language-' # CSS language prefix for fenced blocks. linkify: false # Autoconvert URL-like text to links typographer: false # see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js quotes: '“”‘’' # '„“‚‘' for German, ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French highlight: null # function (/*str, lang*/) { return ''; } # md = ( require 'markdown-it' ) 'zero' md = ( require 'markdown-it' ) mdit_cfg md.enable 'emphasis' # md.enable 'autolink' md.enable 'backticks' md.disable 'entity' # md.enable 'escape' # md.enable 'html_inline' # md.enable 'image' md.enable 'link' # md.enable 'newline' # md.enable 'text' # md.enable 'balance_pairs' # md.enable 'text_collapse' md.disable 'smartquotes' return ( text, send ) => text = md.renderInline text ### TAINT didn't find a way to keep markdown-it from escaping `<`, `&`; as a hotfix, undo these: ### text = text.replace /&lt;/g, '<' text = text.replace /&amp;/g, '&' send text #--------------------------------------------------------------------------------------------------------- $parse_htmlish: -> ( text, send ) => send d for d in thaw _HTMLISH.parse text #--------------------------------------------------------------------------------------------------------- $add_location: -> ( d, send ) => [ lnr col ] = d.$vnr ? [ null, null, ] d.delta_lnr = lnr - 1 d.col = col send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_otag: ( tag_catalog ) -> ( d, send ) => return send d unless ( d.$key is '<tag' ) d.syntax = tag_catalog[ d.name ]?.syntax ? 'html' send d #--------------------------------------------------------------------------------------------------------- $convert_nonhtml_syntax: -> wait_for_name = null return ( d, send ) => if wait_for_name? #................................................................................................... if ( d.$key is '>tag' ) and ( d.name is wait_for_name ) wait_for_name = null return send d #................................................................................................... e = { d..., } e.$key = '^rawtext' e.syntax = null delete e.atrs return send e #..................................................................................................... if ( d.$key is '<tag' ) and ( d.syntax isnt 'html' ) wait_for_name = d.name #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_other_tokens: ( tag_catalog ) -> stack = [ 'html', ] return ( d, send ) => if ( d.$key is '<tag' ) then stack.push d.syntax ? 'html' else if ( d.$key is '>tag' ) then stack.pop() d.syntax = stack[ stack.length - 1 ] ? 'html' send d #--------------------------------------------------------------------------------------------------------- $parse_ncrs: -> xncr_matcher = @constructor.C.xncr.matcher xncr_splitter = @constructor.C.xncr.splitter return ( d, send ) => return send d unless ( d.$key is '^text' ) parts = d.text.split xncr_splitter return send d unless parts.length > 1 is_entity = true start = 0 #..................................................................................................... for part in parts is_entity = not is_entity continue if part is '' stop = start + part.length #................................................................................................... if is_entity and ( match = part.match xncr_matcher )? send @_entity_token_from_match d, start, stop, match else send @_text_token_from_part d, start, stop, part #................................................................................................... start = stop return null #--------------------------------------------------------------------------------------------------------- $complain_about_bareachrs: -> ( d, send ) => return send d unless ( d.$key is '^text' ) #..................................................................................................... if ( d.$key is '^text' ) if ( /(?<!\\)[<&]/.test d.text ) @_as_error d, '^ð1^', 'bareachrs', "bare active characters" #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $remove_backslashes: -> ( d, send ) => return send d unless ( d.$key is '^text' ) d.text = d.text.replace /\\</g, '&lt;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\&/g, '&amp;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\\n/ugs, '' ### replace escaped newlines with empty string ### d.text = d.text.replace /\\(.)/ugs, '$1' ### obliterate remaining backslashes (exc. escaped ones) ### send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_opening_tags: -> ( d, send ) => return send d unless ( d.$key is '<tag' ) if ( d.type is 'otag' ) and ( /^<\s+/.test d.text ) @_as_error d, '^ð1^', 'xtraows', "extraneous whitespace before tag name" send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_closing_tags: -> ( d, send ) => return send d unless ( d.$key is '>tag' ) if ( d.type is 'ctag' ) and ( ( /^<\s*\/\s+/.test d.text ) or ( /^<\s+\/\s*/.test d.text ) ) @_as_error d, '^ð2^', 'xtracws', "extraneous whitespace in closing tag" send d #--------------------------------------------------------------------------------------------------------- $validate_paired_tags: -> stack = [] return ( d, send ) => if ( d.$key is '<tag' ) stack.push d send d #..................................................................................................... else if ( d.$key is '>tag' ) #................................................................................................... if stack.length is 0 return send @_as_error d, '^ð2^', 'xtractag', "extraneous closing tag </#{d.name}>" #................................................................................................... matching_d = stack.pop() if d.name? if ( d.name != matching_d.name ) return send @_as_error d, '^ð2^', 'nomatch', "expected </#{matching_d.name}>, got </#{d.name}>" #................................................................................................... else d.name = matching_d.name send d #..................................................................................................... else send d #..................................................................................................... return null #--------------------------------------------------------------------------------------------------------- $relabel_rawtexts: -> ( d, send ) -> d.$key = '^text' if d.$key is '^rawtext' send d #--------------------------------------------------------------------------------------------------------- $consolidate_texts: -> last = Symbol 'last' # prv_was_text = false send = null collector = [] #....................................................................................................... flush = -> # prv_was_text = false return if collector.length is 0 d = collector[ 0 ] if collector.length > 1 d.text = ( e.text for e in collector ).join '' d.stop = collector[ collector.length - 1 ].stop send d collector.length = 0 #....................................................................................................... return $ { last, }, ( d, _send ) -> send = _send return flush() if d is last unless d.$key is '^text' flush() return send d collector.push d #--------------------------------------------------------------------------------------------------------- $split_lines: -> ( d, send ) => return send d unless ( d.$key is '^text' ) return send d unless ( lines = d.text.split '\n' ).length > 1 e = d ### TAINT makes `start`, `stop` invalid (but are thery still needed?) ### for line, idx in lines e = { e..., } e.oln += idx e.col = 1 unless idx is 0 e.text = line send e return null #--------------------------------------------------------------------------------------------------------- parse: ( text, tag_catalog = null ) -> ### TAINT use `cfg` pattern ### ### TAINT do not reconstruct pipeline on each run ### tunnel_wrap = {} R = [] mr = new Moonriver() #------------------------------------------------------------------------------------------------------- mr.push [ text, ] mr.push @$tunnel tunnel_wrap mr.push @$transpile_markdownish() # mr.push ( text ) -> info '^394^', rpr text mr.push @$parse_htmlish() mr.push @$add_location() mr.push @$set_syntax_on_otag tag_catalog if tag_catalog? mr.push @$convert_nonhtml_syntax() if tag_catalog? mr.push @$set_syntax_on_other_tokens tag_catalog if tag_catalog? mr.push @$parse_ncrs() mr.push @$complain_about_bareachrs() mr.push @$reveal_tunneled_text tunnel_wrap mr.push @$remove_backslashes() mr.push @$treat_xws_in_opening_tags() mr.push @$treat_xws_in_closing_tags() mr.push @$validate_paired_tags() mr.push @$relabel_rawtexts() # mr.push @$consolidate_texts() # mr.push @$split_lines() mr.push ( d ) -> R.push d mr.drive() return R #--------------------------------------------------------------------------------------------------------- _as_error: ( token, ref, code, message ) -> token.$key = '^error' token.origin = 'htmlish' token.code = code token.message = message token.$ = ref return token #----------------------------------------------------------------------------------------------------------- @HTMLISH = HTMLISH = new @Htmlish()
28064
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'DBAY-MIRAGE/HTMLISH-PARSER' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #........................................................................................................... types = new ( require 'intertype' ).Intertype() { isa type_of validate validate_list_of } = types.export() GUY = require 'guy' _HTMLISH = ( require 'paragate/lib/htmlish.grammar' ).new_grammar { bare: true, } { lets freeze thaw } = GUY.lft TIMETUNNEL = require 'timetunnel' { Moonriver } = require 'moonriver' { $ } = Moonriver #=========================================================================================================== ### TAINT use more relaxed syntax for names ### # G: grouped # O: optional xncr = {} xncr.nameG = ( /// (?<name> [a-z][a-z0-9]* ) /// ).source xncr.nameOG = ( /// (?: (?<csg> (?: [a-z][a-z0-9]* ) ) | ) /// ).source xncr.hexG = ( /// (?: x (?<hex> [a-fA-F0-9]+ ) ) /// ).source xncr.decG = ( /// (?<dec> [ 0-9]+ ) /// ).source xncr.matcher = /// ^ & #{xncr.nameG} ; | & #{xncr.nameOG} \# (?: #{xncr.hexG} | #{xncr.decG} ) ; $ /// xncr.splitter = /// ( & [^\s;]+ ; ) /// #=========================================================================================================== class @Htmlish #--------------------------------------------------------------------------------------------------------- @C: GUY.lft.freeze xncr: xncr # #--------------------------------------------------------------------------------------------------------- # constructor: -> # return undefined #--------------------------------------------------------------------------------------------------------- _tunnel: ( text ) -> ### TAINT do not reconstruct tunnel for each call ### # guards = 'äöüßp' # guards = '①②③④⑤' guards = '¥₽₨฿₮' intalph = '0123456789' tnl = new TIMETUNNEL.Timetunnel { guards, intalph, } tnl.add_tunnel TIMETUNNEL.tunnels.keep_backslash # tnl.add_tunnel TIMETUNNEL.tunnels.remove_backslash text = tnl.hide text return { text, reveal: ( tnl.reveal.bind tnl ), } #--------------------------------------------------------------------------------------------------------- _entity_token_from_match: ( d, start, stop, match ) -> g = match.groups R = { d..., } R.$key = '^entity' R.text = match[ 0 ] R.start = start R.stop = stop if g.name? R.type = 'named' R.name = g.name else R.type = if g.csg? then 'xncr' else 'ncr' R.csg = g.csg if g.csg? R.$value = parseInt g.hex ? g.dec, ( if g.hex? then 16 else 10 ) return R #--------------------------------------------------------------------------------------------------------- _text_token_from_part: ( d, start, stop, part ) -> R = { d..., } R.text = part R.start = start R.stop = stop return R #========================================================================================================= # #--------------------------------------------------------------------------------------------------------- $tunnel: ( tunnel_wrap ) -> ( text, send ) => { text reveal } = @_tunnel text tunnel_wrap.reveal = reveal send text return null #--------------------------------------------------------------------------------------------------------- $reveal_tunneled_text: ( tunnel_wrap ) -> ( d, send ) => return send d unless ( d.$key is '^text' ) or ( d.$key is '^rawtext' ) d.text = tunnel_wrap.reveal d.text send d #--------------------------------------------------------------------------------------------------------- $transpile_markdownish: -> mdit_cfg = html: true # Enable HTML tags in source xhtmlOut: false # Use '/' to close single tags (<br />). breaks: false # Convert '\n' in paragraphs into <br> langPrefix: 'language-' # CSS language prefix for fenced blocks. linkify: false # Autoconvert URL-like text to links typographer: false # see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js quotes: '“”‘’' # '„“‚‘' for German, ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French highlight: null # function (/*str, lang*/) { return ''; } # md = ( require 'markdown-it' ) 'zero' md = ( require 'markdown-it' ) mdit_cfg md.enable 'emphasis' # md.enable 'autolink' md.enable 'backticks' md.disable 'entity' # md.enable 'escape' # md.enable 'html_inline' # md.enable 'image' md.enable 'link' # md.enable 'newline' # md.enable 'text' # md.enable 'balance_pairs' # md.enable 'text_collapse' md.disable 'smartquotes' return ( text, send ) => text = md.renderInline text ### TAINT didn't find a way to keep markdown-it from escaping `<`, `&`; as a hotfix, undo these: ### text = text.replace /&lt;/g, '<' text = text.replace /&amp;/g, '&' send text #--------------------------------------------------------------------------------------------------------- $parse_htmlish: -> ( text, send ) => send d for d in thaw _HTMLISH.parse text #--------------------------------------------------------------------------------------------------------- $add_location: -> ( d, send ) => [ lnr col ] = d.$vnr ? [ null, null, ] d.delta_lnr = lnr - 1 d.col = col send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_otag: ( tag_catalog ) -> ( d, send ) => return send d unless ( d.$key is '<tag' ) d.syntax = tag_catalog[ d.name ]?.syntax ? 'html' send d #--------------------------------------------------------------------------------------------------------- $convert_nonhtml_syntax: -> wait_for_name = null return ( d, send ) => if wait_for_name? #................................................................................................... if ( d.$key is '>tag' ) and ( d.name is wait_for_name ) wait_for_name = null return send d #................................................................................................... e = { d..., } e.$key = <KEY> <KEY>' e.syntax = null delete e.atrs return send e #..................................................................................................... if ( d.$key is '<tag' ) and ( d.syntax isnt 'html' ) wait_for_name = d.name #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_other_tokens: ( tag_catalog ) -> stack = [ 'html', ] return ( d, send ) => if ( d.$key is '<tag' ) then stack.push d.syntax ? 'html' else if ( d.$key is '>tag' ) then stack.pop() d.syntax = stack[ stack.length - 1 ] ? 'html' send d #--------------------------------------------------------------------------------------------------------- $parse_ncrs: -> xncr_matcher = @constructor.C.xncr.matcher xncr_splitter = @constructor.C.xncr.splitter return ( d, send ) => return send d unless ( d.$key is '^text' ) parts = d.text.split xncr_splitter return send d unless parts.length > 1 is_entity = true start = 0 #..................................................................................................... for part in parts is_entity = not is_entity continue if part is '' stop = start + part.length #................................................................................................... if is_entity and ( match = part.match xncr_matcher )? send @_entity_token_from_match d, start, stop, match else send @_text_token_from_part d, start, stop, part #................................................................................................... start = stop return null #--------------------------------------------------------------------------------------------------------- $complain_about_bareachrs: -> ( d, send ) => return send d unless ( d.$key is '^text' ) #..................................................................................................... if ( d.$key is '^text' ) if ( /(?<!\\)[<&]/.test d.text ) @_as_error d, '^ð1^', 'bareachrs', "bare active characters" #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $remove_backslashes: -> ( d, send ) => return send d unless ( d.$key is '^text' ) d.text = d.text.replace /\\</g, '&lt;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\&/g, '&amp;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\\n/ugs, '' ### replace escaped newlines with empty string ### d.text = d.text.replace /\\(.)/ugs, '$1' ### obliterate remaining backslashes (exc. escaped ones) ### send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_opening_tags: -> ( d, send ) => return send d unless ( d.$key is '<tag' ) if ( d.type is 'otag' ) and ( /^<\s+/.test d.text ) @_as_error d, '^ð1^', 'xtraows', "extraneous whitespace before tag name" send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_closing_tags: -> ( d, send ) => return send d unless ( d.$key is '>tag' ) if ( d.type is 'ctag' ) and ( ( /^<\s*\/\s+/.test d.text ) or ( /^<\s+\/\s*/.test d.text ) ) @_as_error d, '^ð2^', 'xtracws', "extraneous whitespace in closing tag" send d #--------------------------------------------------------------------------------------------------------- $validate_paired_tags: -> stack = [] return ( d, send ) => if ( d.$key is '<tag' ) stack.push d send d #..................................................................................................... else if ( d.$key is '>tag' ) #................................................................................................... if stack.length is 0 return send @_as_error d, '^ð2^', 'xtractag', "extraneous closing tag </#{d.name}>" #................................................................................................... matching_d = stack.pop() if d.name? if ( d.name != matching_d.name ) return send @_as_error d, '^ð2^', 'nomatch', "expected </#{matching_d.name}>, got </#{d.name}>" #................................................................................................... else d.name = matching_d.name send d #..................................................................................................... else send d #..................................................................................................... return null #--------------------------------------------------------------------------------------------------------- $relabel_rawtexts: -> ( d, send ) -> d.$key = '^text' if d.$key is '^rawtext' send d #--------------------------------------------------------------------------------------------------------- $consolidate_texts: -> last = Symbol 'last' # prv_was_text = false send = null collector = [] #....................................................................................................... flush = -> # prv_was_text = false return if collector.length is 0 d = collector[ 0 ] if collector.length > 1 d.text = ( e.text for e in collector ).join '' d.stop = collector[ collector.length - 1 ].stop send d collector.length = 0 #....................................................................................................... return $ { last, }, ( d, _send ) -> send = _send return flush() if d is last unless d.$key is '^text' flush() return send d collector.push d #--------------------------------------------------------------------------------------------------------- $split_lines: -> ( d, send ) => return send d unless ( d.$key is '^text' ) return send d unless ( lines = d.text.split '\n' ).length > 1 e = d ### TAINT makes `start`, `stop` invalid (but are thery still needed?) ### for line, idx in lines e = { e..., } e.oln += idx e.col = 1 unless idx is 0 e.text = line send e return null #--------------------------------------------------------------------------------------------------------- parse: ( text, tag_catalog = null ) -> ### TAINT use `cfg` pattern ### ### TAINT do not reconstruct pipeline on each run ### tunnel_wrap = {} R = [] mr = new Moonriver() #------------------------------------------------------------------------------------------------------- mr.push [ text, ] mr.push @$tunnel tunnel_wrap mr.push @$transpile_markdownish() # mr.push ( text ) -> info '^394^', rpr text mr.push @$parse_htmlish() mr.push @$add_location() mr.push @$set_syntax_on_otag tag_catalog if tag_catalog? mr.push @$convert_nonhtml_syntax() if tag_catalog? mr.push @$set_syntax_on_other_tokens tag_catalog if tag_catalog? mr.push @$parse_ncrs() mr.push @$complain_about_bareachrs() mr.push @$reveal_tunneled_text tunnel_wrap mr.push @$remove_backslashes() mr.push @$treat_xws_in_opening_tags() mr.push @$treat_xws_in_closing_tags() mr.push @$validate_paired_tags() mr.push @$relabel_rawtexts() # mr.push @$consolidate_texts() # mr.push @$split_lines() mr.push ( d ) -> R.push d mr.drive() return R #--------------------------------------------------------------------------------------------------------- _as_error: ( token, ref, code, message ) -> token.$key = '^<KEY>' token.origin = 'htmlish' token.code = code token.message = message token.$ = ref return token #----------------------------------------------------------------------------------------------------------- @HTMLISH = HTMLISH = new @Htmlish()
true
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'DBAY-MIRAGE/HTMLISH-PARSER' debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge info = CND.get_logger 'info', badge urge = CND.get_logger 'urge', badge help = CND.get_logger 'help', badge whisper = CND.get_logger 'whisper', badge echo = CND.echo.bind CND #........................................................................................................... types = new ( require 'intertype' ).Intertype() { isa type_of validate validate_list_of } = types.export() GUY = require 'guy' _HTMLISH = ( require 'paragate/lib/htmlish.grammar' ).new_grammar { bare: true, } { lets freeze thaw } = GUY.lft TIMETUNNEL = require 'timetunnel' { Moonriver } = require 'moonriver' { $ } = Moonriver #=========================================================================================================== ### TAINT use more relaxed syntax for names ### # G: grouped # O: optional xncr = {} xncr.nameG = ( /// (?<name> [a-z][a-z0-9]* ) /// ).source xncr.nameOG = ( /// (?: (?<csg> (?: [a-z][a-z0-9]* ) ) | ) /// ).source xncr.hexG = ( /// (?: x (?<hex> [a-fA-F0-9]+ ) ) /// ).source xncr.decG = ( /// (?<dec> [ 0-9]+ ) /// ).source xncr.matcher = /// ^ & #{xncr.nameG} ; | & #{xncr.nameOG} \# (?: #{xncr.hexG} | #{xncr.decG} ) ; $ /// xncr.splitter = /// ( & [^\s;]+ ; ) /// #=========================================================================================================== class @Htmlish #--------------------------------------------------------------------------------------------------------- @C: GUY.lft.freeze xncr: xncr # #--------------------------------------------------------------------------------------------------------- # constructor: -> # return undefined #--------------------------------------------------------------------------------------------------------- _tunnel: ( text ) -> ### TAINT do not reconstruct tunnel for each call ### # guards = 'äöüßp' # guards = '①②③④⑤' guards = '¥₽₨฿₮' intalph = '0123456789' tnl = new TIMETUNNEL.Timetunnel { guards, intalph, } tnl.add_tunnel TIMETUNNEL.tunnels.keep_backslash # tnl.add_tunnel TIMETUNNEL.tunnels.remove_backslash text = tnl.hide text return { text, reveal: ( tnl.reveal.bind tnl ), } #--------------------------------------------------------------------------------------------------------- _entity_token_from_match: ( d, start, stop, match ) -> g = match.groups R = { d..., } R.$key = '^entity' R.text = match[ 0 ] R.start = start R.stop = stop if g.name? R.type = 'named' R.name = g.name else R.type = if g.csg? then 'xncr' else 'ncr' R.csg = g.csg if g.csg? R.$value = parseInt g.hex ? g.dec, ( if g.hex? then 16 else 10 ) return R #--------------------------------------------------------------------------------------------------------- _text_token_from_part: ( d, start, stop, part ) -> R = { d..., } R.text = part R.start = start R.stop = stop return R #========================================================================================================= # #--------------------------------------------------------------------------------------------------------- $tunnel: ( tunnel_wrap ) -> ( text, send ) => { text reveal } = @_tunnel text tunnel_wrap.reveal = reveal send text return null #--------------------------------------------------------------------------------------------------------- $reveal_tunneled_text: ( tunnel_wrap ) -> ( d, send ) => return send d unless ( d.$key is '^text' ) or ( d.$key is '^rawtext' ) d.text = tunnel_wrap.reveal d.text send d #--------------------------------------------------------------------------------------------------------- $transpile_markdownish: -> mdit_cfg = html: true # Enable HTML tags in source xhtmlOut: false # Use '/' to close single tags (<br />). breaks: false # Convert '\n' in paragraphs into <br> langPrefix: 'language-' # CSS language prefix for fenced blocks. linkify: false # Autoconvert URL-like text to links typographer: false # see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js quotes: '“”‘’' # '„“‚‘' for German, ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French highlight: null # function (/*str, lang*/) { return ''; } # md = ( require 'markdown-it' ) 'zero' md = ( require 'markdown-it' ) mdit_cfg md.enable 'emphasis' # md.enable 'autolink' md.enable 'backticks' md.disable 'entity' # md.enable 'escape' # md.enable 'html_inline' # md.enable 'image' md.enable 'link' # md.enable 'newline' # md.enable 'text' # md.enable 'balance_pairs' # md.enable 'text_collapse' md.disable 'smartquotes' return ( text, send ) => text = md.renderInline text ### TAINT didn't find a way to keep markdown-it from escaping `<`, `&`; as a hotfix, undo these: ### text = text.replace /&lt;/g, '<' text = text.replace /&amp;/g, '&' send text #--------------------------------------------------------------------------------------------------------- $parse_htmlish: -> ( text, send ) => send d for d in thaw _HTMLISH.parse text #--------------------------------------------------------------------------------------------------------- $add_location: -> ( d, send ) => [ lnr col ] = d.$vnr ? [ null, null, ] d.delta_lnr = lnr - 1 d.col = col send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_otag: ( tag_catalog ) -> ( d, send ) => return send d unless ( d.$key is '<tag' ) d.syntax = tag_catalog[ d.name ]?.syntax ? 'html' send d #--------------------------------------------------------------------------------------------------------- $convert_nonhtml_syntax: -> wait_for_name = null return ( d, send ) => if wait_for_name? #................................................................................................... if ( d.$key is '>tag' ) and ( d.name is wait_for_name ) wait_for_name = null return send d #................................................................................................... e = { d..., } e.$key = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI' e.syntax = null delete e.atrs return send e #..................................................................................................... if ( d.$key is '<tag' ) and ( d.syntax isnt 'html' ) wait_for_name = d.name #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $set_syntax_on_other_tokens: ( tag_catalog ) -> stack = [ 'html', ] return ( d, send ) => if ( d.$key is '<tag' ) then stack.push d.syntax ? 'html' else if ( d.$key is '>tag' ) then stack.pop() d.syntax = stack[ stack.length - 1 ] ? 'html' send d #--------------------------------------------------------------------------------------------------------- $parse_ncrs: -> xncr_matcher = @constructor.C.xncr.matcher xncr_splitter = @constructor.C.xncr.splitter return ( d, send ) => return send d unless ( d.$key is '^text' ) parts = d.text.split xncr_splitter return send d unless parts.length > 1 is_entity = true start = 0 #..................................................................................................... for part in parts is_entity = not is_entity continue if part is '' stop = start + part.length #................................................................................................... if is_entity and ( match = part.match xncr_matcher )? send @_entity_token_from_match d, start, stop, match else send @_text_token_from_part d, start, stop, part #................................................................................................... start = stop return null #--------------------------------------------------------------------------------------------------------- $complain_about_bareachrs: -> ( d, send ) => return send d unless ( d.$key is '^text' ) #..................................................................................................... if ( d.$key is '^text' ) if ( /(?<!\\)[<&]/.test d.text ) @_as_error d, '^ð1^', 'bareachrs', "bare active characters" #..................................................................................................... send d #--------------------------------------------------------------------------------------------------------- $remove_backslashes: -> ( d, send ) => return send d unless ( d.$key is '^text' ) d.text = d.text.replace /\\</g, '&lt;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\&/g, '&amp;' ### TAINT conflicts with NCR parsing ### d.text = d.text.replace /\\\n/ugs, '' ### replace escaped newlines with empty string ### d.text = d.text.replace /\\(.)/ugs, '$1' ### obliterate remaining backslashes (exc. escaped ones) ### send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_opening_tags: -> ( d, send ) => return send d unless ( d.$key is '<tag' ) if ( d.type is 'otag' ) and ( /^<\s+/.test d.text ) @_as_error d, '^ð1^', 'xtraows', "extraneous whitespace before tag name" send d #--------------------------------------------------------------------------------------------------------- $treat_xws_in_closing_tags: -> ( d, send ) => return send d unless ( d.$key is '>tag' ) if ( d.type is 'ctag' ) and ( ( /^<\s*\/\s+/.test d.text ) or ( /^<\s+\/\s*/.test d.text ) ) @_as_error d, '^ð2^', 'xtracws', "extraneous whitespace in closing tag" send d #--------------------------------------------------------------------------------------------------------- $validate_paired_tags: -> stack = [] return ( d, send ) => if ( d.$key is '<tag' ) stack.push d send d #..................................................................................................... else if ( d.$key is '>tag' ) #................................................................................................... if stack.length is 0 return send @_as_error d, '^ð2^', 'xtractag', "extraneous closing tag </#{d.name}>" #................................................................................................... matching_d = stack.pop() if d.name? if ( d.name != matching_d.name ) return send @_as_error d, '^ð2^', 'nomatch', "expected </#{matching_d.name}>, got </#{d.name}>" #................................................................................................... else d.name = matching_d.name send d #..................................................................................................... else send d #..................................................................................................... return null #--------------------------------------------------------------------------------------------------------- $relabel_rawtexts: -> ( d, send ) -> d.$key = '^text' if d.$key is '^rawtext' send d #--------------------------------------------------------------------------------------------------------- $consolidate_texts: -> last = Symbol 'last' # prv_was_text = false send = null collector = [] #....................................................................................................... flush = -> # prv_was_text = false return if collector.length is 0 d = collector[ 0 ] if collector.length > 1 d.text = ( e.text for e in collector ).join '' d.stop = collector[ collector.length - 1 ].stop send d collector.length = 0 #....................................................................................................... return $ { last, }, ( d, _send ) -> send = _send return flush() if d is last unless d.$key is '^text' flush() return send d collector.push d #--------------------------------------------------------------------------------------------------------- $split_lines: -> ( d, send ) => return send d unless ( d.$key is '^text' ) return send d unless ( lines = d.text.split '\n' ).length > 1 e = d ### TAINT makes `start`, `stop` invalid (but are thery still needed?) ### for line, idx in lines e = { e..., } e.oln += idx e.col = 1 unless idx is 0 e.text = line send e return null #--------------------------------------------------------------------------------------------------------- parse: ( text, tag_catalog = null ) -> ### TAINT use `cfg` pattern ### ### TAINT do not reconstruct pipeline on each run ### tunnel_wrap = {} R = [] mr = new Moonriver() #------------------------------------------------------------------------------------------------------- mr.push [ text, ] mr.push @$tunnel tunnel_wrap mr.push @$transpile_markdownish() # mr.push ( text ) -> info '^394^', rpr text mr.push @$parse_htmlish() mr.push @$add_location() mr.push @$set_syntax_on_otag tag_catalog if tag_catalog? mr.push @$convert_nonhtml_syntax() if tag_catalog? mr.push @$set_syntax_on_other_tokens tag_catalog if tag_catalog? mr.push @$parse_ncrs() mr.push @$complain_about_bareachrs() mr.push @$reveal_tunneled_text tunnel_wrap mr.push @$remove_backslashes() mr.push @$treat_xws_in_opening_tags() mr.push @$treat_xws_in_closing_tags() mr.push @$validate_paired_tags() mr.push @$relabel_rawtexts() # mr.push @$consolidate_texts() # mr.push @$split_lines() mr.push ( d ) -> R.push d mr.drive() return R #--------------------------------------------------------------------------------------------------------- _as_error: ( token, ref, code, message ) -> token.$key = '^PI:KEY:<KEY>END_PI' token.origin = 'htmlish' token.code = code token.message = message token.$ = ref return token #----------------------------------------------------------------------------------------------------------- @HTMLISH = HTMLISH = new @Htmlish()
[ { "context": "##! Extrascore (requires jQuery and Underscore) by Casey Foster (caseywebdev.com) ###\n\n# Check dependencies\nif no", "end": 64, "score": 0.9998811483383179, "start": 52, "tag": "NAME", "value": "Casey Foster" }, { "context": "uires jQuery and Underscore) by Casey Foster (caseywebdev.com) ###\n\n# Check dependencies\nif not Extrascore?", "end": 77, "score": 0.6550595164299011, "start": 70, "tag": "EMAIL", "value": "ywebdev" }, { "context": "uery and Underscore) by Casey Foster (caseywebdev.com) ###\n\n# Check dependencies\nif not Extrascore? and", "end": 81, "score": 0.742404580116272, "start": 78, "tag": "EMAIL", "value": "com" } ]
vendor/assets/javascripts/extrascore.coffee
sucram1/cuddly-potato111trtr
2
###! Extrascore (requires jQuery and Underscore) by Casey Foster (caseywebdev.com) ### # Check dependencies if not Extrascore? and jQuery? and _? # Use the jQuery shortcut $ = jQuery # Define the Extrascore object window.Extrascore = # Mixins for Underscore Mixins: # Mass method call for every child of obj mass: (obj, key, args...) -> for __, val of obj val?[key]? args... # Initialize an object by calling init on children and then assigning the load method to jQuery's DOM ready call # This is a special _.mass() function init: (obj) -> # Call on jQuery's DOM ready call load = (obj) -> _.mass obj, 'load' dom obj $('body').on 'DOMSubtreeModified', (e) -> dom obj, e unless obj._extrascoreDomLocked # Call on every DOMSubtreeModified event (use carefully, doesn't work in Opera *shocking*) dom = (obj, e) -> obj._extrascoreDomLocked = true _.mass obj, 'dom', e delete obj._extrascoreDomLocked # Call `init()` on all children of obj if the method exists _.mass obj, 'init' $ -> load obj # Clean a string for use in a URL or query clean: (str, opt = {}) -> opt = _.extend delimiter: ' ' alphanumeric: false downcase: false , opt str = str+'' str = str.toLowerCase() if opt.downcase str = str.replace(/'/g, '').replace(/[^\w\s]|_/g, ' ') if opt.alphanumeric $.trim(str.replace /\s+/g, ' ').replace /\s/g, opt.delimiter # Shortcut for _.clean str, delimiter: '-', alphanumeric: true, downcase: true urlize: (str, delimiter = '-') -> _.clean str, delimiter: delimiter, alphanumeric: true, downcase: true # This sucker comes in handy startsWith: (str, start) -> str = '' + str start = '' + start return start.length <= str.length and str.substr(0, start.length) is start # This guy too endsWith: (str, end) -> str = '' + str end = '' + end return end.length <= str.length and str.substr(str.length-end.length) is end # Sort an object by key for iteration sortByKey: (obj) -> newObj = {} _.chain(obj) .map((val, key) -> [key, val]) .sortBy((val) -> val[0]) .each (val) -> newObj[val[0]] = val[1] newObj # A quick zip to the top of the page, or optionally to an integer or jQuery object specified by `val` scrollTo: (val = 0, duration, callback) -> if val instanceof $ val = val.offset().top $(if $.browser.webkit then document.body else document.documentElement).animate scrollTop: val, duration, callback # Get a full URL from a relative url url: (path = '', protocol = location.protocol) -> # Append a colon to the protocol if necessary protocol += ':' unless _.endsWith protocol, ':' # See if it's already a URL unless path.match /^\w+:/ # See if it's a URL looking for a protocol if _.startsWith path, '//' path = location.protocol + path # See if it's relative to the domain root else if _.startsWith path, '/' path = "#{location.protocol}//#{location.host + path}" # Otherwise it must be relative to the current location else path = location.href + path # Swap the protocols if necessary path.replace location.protocol, protocol # The reverse of _.url() relativeUrl: (path = '') -> _.url(path).replace /^\w+:\/\/[^/]+/, '' # Sometimes it's handy to know the size of the scrollbars in a browser scrollbarSize: (dimension = 'width') -> $out = $('<div><div/></div>') .appendTo('body') .css position: 'fixed' overflow: 'hidden' left: -50 top: -50 width: 50 height: 50 $in = $out.find('> div').css height: '100%' d1 = $in[dimension]() $out.css overflow: 'scroll' d2 = $in[dimension]() $out.remove() d1-d2 # Does the element have a scrollbar? hasScrollbar: ($obj) -> style = $obj.attr 'style' d1 = $obj.width() d2 = $obj.css(overflow: 'hidden').width() if style? $obj.attr style: style else $obj.removeAttr 'style' d1 isnt d2 # Break a query up into components if colons are used, otherwise just return the cleaned string parseQuery: (str, downcase = true) -> str = _.clean str, downcase: downcase colon = _.compact str.replace(/^:+|:+$/g, '').split ':' if colon.length > 1 colon = _.map colon, (str) -> $.trim(str).match /(?:^|^(.*)\s)(\S*)$/ terms = {} _.each colon, (match, i) -> if i < colon.length - 1 terms[match[2]] = colon[i + 1][1] else prev = colon[i - 1][2] terms[prev] = (if terms[prev] then terms[prev]+' ' else '')+match[2] return terms str # Ghetto nextTick nextTick: (fn) -> setTimeout fn, 0 # Extensions for Underscore (more of individual classes using Underscore for the namespace then actual extentions) Extensions: # Placeholder for lame browsers Placeholder: # After the DOM is loaded load: -> # Hijack jQuery's .val() so it will return an empty string if Placeholder says it should $.fn._val = $.fn.val $.fn.val = (str) -> if str? $(@).each -> $(@)._val str else if $(@).data 'placeholderEmpty' then '' else $(@)._val() # Check for new inputs or textareas than need to be initialized with Placeholder dom: -> $('.js-placeholder, .js-placeholder-password').each -> $t = $ @ if $t.data('placeholderHtml')? and not $t.data('placeholderEmpty')? password = $t.hasClass 'js-placeholder-password' placeholder = $t.data 'placeholderHtml' $t[0].type = 'password' if password unless password and $.browser.msie and $.browser.version.split('.') < 9 if not $t.val() or $t.val() is placeholder $t.data placeholderEmpty: true $t.val placeholder $t[0].type = 'text' if password else $t.data placeholderEmpty: false $t.attr placeholder: placeholder title: placeholder $t.focus(-> $t.val '' if $t.data 'placeholderEmpty' if password $t[0].type = 'password' $t.attr placeholder: placeholder $t.data placeholderEmpty: false ).blur -> if $t.val() $t.data placeholderEmpty: false else $t.val placeholder $t.data placeholderEmpty: true $t[0].type = 'text' if password # Multipurpose PopUp PopUp: # Duration and Fade duration default, feel free to change DURATION: 0 FADE_DURATION: 250 # Build the PopUp element build: -> # Shortcut o = _.PopUp; unless $('#js-pop-up-container').length # Until 'display: box' becomes more widely available, we're stuck with table/table-cell $('body').append o.$container = $('<div><div><div><div/></div></div></div>') .attr( id: 'js-pop-up-container' ).css display: 'none' position: 'fixed' zIndex: 999999 left: 0 top: 0 width: '100%' height: '100%' opacity: 0 overflow: 'auto' o.hide() o.$container.find('> div') .attr( id: 'js-pop-up-table' ).css display: 'table' width: '100%' height: '100%' o.$container.find('> div > div') .attr( id: 'js-pop-up-table-cell' ).css display: 'table-cell' textAlign: 'center' verticalAlign: 'middle' o.$div = o.$container.find('> div > div > div') .attr( id: 'js-pop-up' ).css display: 'inline-block' position: 'relative' o.$container.on 'click', -> o.$div.find('.js-pop-up-outside').click() o.$div .on('click', false) .on 'click', '.js-pop-up-hide', o.hide $(document).keydown (e) -> if o.$container.css('display') is 'block' and not $('body :focus').length switch e.keyCode when 13 then o.$div.find('.js-pop-up-enter').click() when 27 then o.$div.find('.js-pop-up-esc').click() else return true false # Fade the PopUp out hide: (fadeDuration) -> o = _.PopUp if o.$container? o.$container .stop() .animate opacity: 0 , (if isNaN(fadeDuration) then o.fadeDuration else fadeDuration) , -> o.$container.css display: 'none' if o.saveBodyStyle? $('body').attr style: o.saveBodyStyle else $('body').removeAttr 'style' o.saveBodyStyle = null # Show the PopUp with the given `html`, optionally for a 'duration', with a 'callback', and/or with a 'fadeDuration' show: (html, opt = {}) -> o = _.PopUp # Build the PopUp element o.build() opt = _.extend duration: o.DURATION callback: null fadeDuration: o.FADE_DURATION , opt o.saveBodyStyle = $('body').attr 'style' unless o.$container.css('display') is 'block' $('body').css marginRight: _.scrollbarSize() if _.hasScrollbar $ 'body' $('body').css overflow: 'hidden' $('body :focus').blur() o.fadeDuration = opt.fadeDuration o.$div.html html o.$container .stop() .css( display: 'block') .animate opacity: 1 , opt.fadeDuration clearTimeout o.timeout if o.timeout? o.timeout = setTimeout -> o.hide() opt.callback?() , opt.duration if opt.duration # Search (as you type) Search: # Check for Search objects to be initialized dom: -> $('.js-search').each -> $search = $ @ unless $search.data('searchCache')? o = _.Search $search.data searchCache: [] searchId: 0 searchAjax: {} searchLastQ: null searchPage: 0 searchHoldHover: false search$Q: $search.find '.js-search-q' search$Results: $search.find '.js-search-results' $q = $search.data 'search$Q' $results = $search.data 'search$Results' o.query $search if $q.is ':focus' $search.hover(-> $search.data searchHover: true , -> $search.data searchHover: false $results.css display: 'none' unless $q.is(':focus') or $search.data 'searchHoldHover' ).mouseover -> $search.data searchHoldHover: false $q.blur(-> _.nextTick -> $results.css display: 'none' unless $search.data 'searchHover') .focus(-> $search.data searchHoldHover: false) .keydown((e) -> switch e.keyCode when 13 then $search.find('.js-search-selected').click() when 38 then o.select $search, 'prev' when 40 then o.select $search, 'next' when 27 if $q.val() is '' $q.blur() _.nextTick -> o.query $search else _.nextTick -> $q.val '' o.query $search else _.nextTick -> o.query $search if $q.is ':focus' return true false ).on 'focus keyup change', -> o.query $search $results.on 'mouseenter click', '.js-search-result', (e) -> $t = $ @ $results.find('.js-search-result.js-search-selected').removeClass 'js-search-selected' $t.addClass 'js-search-selected' if e.type is 'click' if $t.hasClass 'js-search-prev' o.page $search, $search.data('searchPage') - 1, true $search.data searchHoldHover: true else if $t.hasClass 'js-search-next' o.page $search, $search.data('searchPage') + 1 $search.data searchHoldHover: true else if $t.hasClass 'js-search-submit' $t.parents('form').submit() if $t.hasClass 'js-search-hide' $q.blur() $results.css display: 'none' # Change the current search results page page: ($searches, n, prev) -> $searches.each -> $search = $ @ $results = $search.data 'search$Results' n = Math.min $results.find('.js-search-page').length - 1, Math.max n, 0 $results.find('.js-search-selected').removeClass 'js-search-selected' $results.find('.js-search-page') .css(display: 'none') .eq(n) .removeAttr('style') .find('.js-search-result:not(.js-search-prev):not(.js-search-next)')[if prev then 'last' else 'first']() .addClass 'js-search-selected' $search.data 'searchPage', n # Send the value of q to the correct search function and return the result to the correct callback query: ($searches, urlN = 1) -> $searches.each -> o = _.Search $search = $ @ $results = $search.data 'search$Results' $q = $search.data 'search$Q' callback = eval $search.data 'searchCallback' q = _.clean $q.val(), downcase: true t = new Date().getTime() $results.css display: 'block' unless q or $search.data('js-search-empty')? $results.css(display: 'none').empty() $search.removeClass 'js-search-loading' else if q isnt $search.data('searchLastQ') or urlN > 1 callback $search clearTimeout $search.data 'searchTimeout' $search.data('searchAjax').abort?() if $search.data('searchCache')["#{urlN}_" + q]? callback $search, $search.data('searchCache')["#{urlN}_" + q], urlN $search.removeClass 'js-search-loading' o.query $search, urlN + 1 if $search.data("searchUrl#{urlN+1}")? else $search.addClass('js-search-loading').data 'searchTimeout', setTimeout -> handleData = (data) -> $search.data('searchCache')["#{urlN}_" + q] = data if check is $search.data('searchId') and (_.clean($q.val()) or $search.data('js-search-empty')?) $search.removeClass 'js-search-loading' callback $search, data, urlN o.query $search, urlN + 1 if $search.data "searchUrl#{urlN+1}" check = $search.data(searchId: $search.data('searchId') + 1).data 'searchId' if $search.data('searchJs')? handleData eval($search.data 'searchJs')(q) else if $search.data('searchUrl')? $search.data searchAjax: $.getJSON($search.data("searchUrl#{if urlN is 1 then '' else urlN}"), q: q, handleData) , $search.data('searchDelay') ? 0 $search.data 'searchLastQ', q # Select the next or previous in a list of results select: ($searches, dir) -> $searches.each -> o = _.Search $search = $ @ $page = $search.find('.js-search-page').eq $search.data 'searchPage' $page.find('.js-search-result')[if dir is 'prev' then 'first' else 'last']().addClass 'js-search-selected' unless $page.find('.js-search-selected').removeClass('js-search-selected')[dir]().addClass('js-search-selected').length if $page.find('.js-search-result.js-search-selected.js-search-prev').length o.page $search, $search.data('searchPage') - 1, true else if $page.find('.js-search-result.js-search-selected.js-search-next').length o.page $search, $search.data('searchPage') + 1 # Yay tooltips! Tooltip: # Store mouse coordinates mouse: x: 0 y: 0 # Set mousemove on document to track coordinates load: -> o = _.Tooltip $('body').mousemove((e) -> o.mouse = x: e.pageX y: e.pageY $('.js-tooltip').each -> $t = $ @ $t.data('tooltip$Div').css o.position($t).home if $t.data('tooltip$Div')? and $t.data('tooltipMouse')? ).on('mouseenter', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ o.show $t $t.data tooltipHover: true ).on('mouseleave', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ $t.data tooltipHover: false o.hide $t ).on('focus', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.show $ @ ).on('blur', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.hide $ @ ) # Get the current tooltip$Div for an item or create a new one and return that divFor: ($t) -> o = _.Tooltip unless $t.data 'tooltip$Div' $t.parent().css position: 'relative' if $t.parent().css position: 'static' $t.data tooltipHoverable: null if $t.data('tooltipMouse')? $t.data _.extend tooltipPosition: 'top' tooltipOffset: 0 tooltipDuration: 0 , $t.data() $div = $('<div><div/></div>') .addClass("tooltip #{$t.data('tooltipPosition')}") .css display: 'none' position: 'absolute' zIndex: 999999; $div .find('> div') .html($t.data 'tooltipHtml') .css position: 'relative' $t .data(tooltip$Div: $div) .parent() .append $div position = o.position $t $div .css(position.home) .find('> div') .css _.extend {opacity: 0}, position.away # If the tooltip is 'hoverable' (aka it should stay while the mouse is over the tooltip itself) if $t.data('tooltipHoverable')? $div.hover -> _.Tooltip.show $t $t.data tooltipHoverableHover: true , -> $t.data tooltipHoverableHover: false _.Tooltip.hide $t else # Otherwise turn off interaction with the mouse $div.css pointerEvents: 'none' '-webkit-user-select': 'none' '-moz-user-select': 'none' userSelect: 'none' $t.data 'tooltip$Div' # Show the tooltip if it's not already visible show: ($t) -> o = _.Tooltip $div = o.divFor $t unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .appendTo($t.parent()) .css(_.extend {display: 'block'}, position.home) .find('> div') .stop() .animate opacity: 1 top: 0 left: 0 , $t.data 'tooltipDuration' # Hide the tooltip if it's not already hidden hide: ($t) -> o = _.Tooltip if $div = $t.data 'tooltip$Div' unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .css(position.home) .find('> div') .stop() .animate _.extend({opacity: 0}, position.away), duration: $t.data 'tooltipDuration' complete: -> $t.data tooltip$Div: null $(@).parent().remove() # Method for getting the correct CSS position data for a tooltip position: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' $parent = $t.parent() offset = $t.data 'tooltipOffset' divWidth = $div.outerWidth() divHeight = $div.outerHeight() parentScrollLeft = $parent.scrollLeft() parentScrollTop = $parent.scrollTop() if $t.data('tooltipMouse')? tLeft = o.mouse.x - $t.parent().offset().left + parentScrollLeft tTop = o.mouse.y - $t.parent().offset().top + parentScrollTop tWidth = tHeight = 0 else tPosition = $t.position() tLeft = tPosition.left + parentScrollLeft + parseInt $t.css 'marginLeft' tTop = tPosition.top + parentScrollTop + parseInt $t.css 'marginTop' tWidth = $t.outerWidth() tHeight = $t.outerHeight() home = left: tLeft top: tTop away = {} switch $t.data('tooltipPosition') when 'top' home.left += (tWidth - divWidth)/2 home.top -= divHeight away.top = -offset when 'right' home.left += tWidth home.top += (tHeight - divHeight)/2 away.left = offset when 'bottom' home.left += (tWidth - divWidth)/2 home.top += tHeight away.top = offset when 'left' home.left -= divWidth home.top += (tHeight - divHeight)/2 away.left = -offset {home: home, away: away} # Use this to correct the tooltip content and positioning between events if necessary correct: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' if $div if $t.css('display') is 'none' $t.mouseleave().blur() else $div.find('> div').html($t.data 'tooltipHtml') $div.css _.Tooltip.position($t).home # Use this to remove a tooltip remove: ($t) -> $t .data( tooltipHover: false tooltipHoverableHover: false ).removeClass('js-tooltip') .data('tooltip$Div')?.remove() # State manager State: # Header to send with the XHR HEADER: 'X-Chromeless' xhr: {} cache: {} # The attributes below are optional and can be set at runtime as needed # When true, forces State to reload the page on the next request. # refresh: false # Specify data to send with the XHR request data : {} load: -> o = _.State if history.state? history.replaceState true, null $(window).on 'popstate', (e) -> if e.originalEvent.state? o.push location.href else history.replaceState true, null $("body").on 'click', '.js-state', -> $t = $ @ o.push (if $t.data 'stateUrl' then $t.data 'stateUrl' else $t.attr 'href'), $t.data 'stateProtocol' false updateCache: (url, obj) -> o = _.State if o.cache[url]? _.extend o.cache[url], obj else o.cache[url] = obj push: (url, protocol = location.protocol) -> o = _.State url = _.url url, protocol if history.pushState? and not o.refresh and not _.State.data[url]?.refresh and _.startsWith url, location.protocol o.xhr.abort?() o.clear o.cache[url], url if o.cache[url]? and o.cache[url].cache isnt false o.change url else o.before o.cache[url], url o.xhr = $.ajax url, data: o.data success: (data) -> valid = null selectors = {} $(data.replace /<(\/)?script>/gi, '<!--$1state-script-->').each -> $t = $ @ unless $t[0] instanceof Text if (s = $t.attr 'id') or $t.is 'title' selectors[s and "##{s}" or 'title'] = $t.html().replace /<!--(\/)?state-script-->/g, '<$1script>' valid = true if s else unless valid? valid = false url = selectors['#chromeless-request-url'] if selectors['#chromeless-request-url']? and selectors['#chromeless-request-url'] isnt url if valid o.updateCache url, selectors o.after o.cache[url], url o.change url else location.assign url beforeSend: (xhr) -> xhr.setRequestHeader o.HEADER, 1 error: -> location.assign url else location.assign url change: (url) -> o = _.State history[if o.cache[url].replace then 'replaceState' else 'pushState'] true, null, url if location.href isnt url o.parse o.cache[url], url clear: -> before: -> after: -> parse: -> # Load images only when they're on the page or about to be on it Lazy: # Default tolerance, can be overidden here or with data-tolerance='xxx' TOLERANCE: 100 # After the DOM is ready load: -> o = _.Lazy $(window).on 'scroll resize', o.dom # Check for new lazy images dom: -> # Wait for the browser to position the element on the page before checking its coordinates _.nextTick -> $('img.js-lazy').each -> $t = $ @ visible = _.reduce $t.parents(), (memo, parent) -> memo and $(parent).css('display') isnt 'none' and $(parent).css('visibility') isnt 'hidden' , true if visible and $(window).scrollTop() + $(window).outerHeight() >= $t.offset().top - ($t.data('lazyTolerance') ? _.Lazy.TOLERANCE) url = $t.data 'lazyUrl' $t.removeClass('js-lazy').attr 'src', url # Everyone's favorite cheat code Konami: (callback, onlyOnce = false, code = '38,38,40,40,37,39,37,39,66,65,13', touchCode = 'up,up,down,down,left,right,left,right,tap,tap,tap') -> keysPressed = [] touchEvents = [] tap = false startX = startY = dX = dY = 0 keyDownEvent = (e) -> keysPressed.push e.keyCode if _.endsWith keysPressed + '', code $(document).off 'keydown', keyDownEvent if onlyOnce keysPressed = [] e.preventDefault() callback() touchStartEvent = (e) -> e = e.originalEvent if e.touches.length is 1 touch = e.touches[0] {screenX: startX, screenY: startY} = touch tap = tracking = true touchMoveEvent = (e) -> e = e.originalEvent if e.touches.length is 1 and tap touch = e.touches[0] dX = touch.screenX - startX dY = touch.screenY - startY rightLeft = if dX > 0 then 'right' else 'left' downUp = if dY > 0 then 'down' else 'up' val = if Math.abs(dX) > Math.abs dY then rightLeft else downUp touchEvents.push val tap = false checkEvents e touchEndEvent = (e) -> e = e.originalEvent if e.touches.length is 0 and tap touchEvents.push 'tap' checkEvents e checkEvents = (e) -> if _.endsWith touchEvents + '', touchCode if onlyOnce $(document).off 'touchmove', touchMoveEvent $(document).off 'touchend', touchEndEvent touchEvents = [] e.preventDefault() callback() $(document).on 'keydown', keyDownEvent $(document).on 'touchstart', touchStartEvent $(document).on 'touchmove', touchMoveEvent $(document).on 'touchend', touchEndEvent # Making Cookie management easy on you Cookie: (name, val, opt = {}) -> if typeof name is 'object' _.Cookie n, v, val for n, v of name else if typeof name is 'string' and val isnt undefined opt.expires = -1 if val is null val ||= '' params = [] params.push "; Expires=#{if opt.expires.toGMTString? then opt.expires.toGMTString() else new Date(new Date().getTime()+opt.expires*1000*60*60*24).toGMTString()}" if opt.expires params.push "; Path=#{opt.path}" if opt.path params.push "; Domain=#{opt.domain}" if opt.domain params.push '; HttpOnly' if opt.httpOnly params.push '; Secure' if opt.secure document.cookie = "#{encodeURIComponent name}=#{encodeURIComponent val}#{params.join ''}" else cookies = {} if document.cookie _.each decodeURIComponent(document.cookie).split(/\s*;\s*/), (cookie) -> {1: n, 2: v} = /^([^=]*)\s*=\s*(.*)$/.exec cookie if typeof name is 'string' and name is n return v else if not name? cookies[n] = v if not name then cookies else null # Mixin the Extrascore Mixins _.mixin Extrascore.Mixins # Extend the Extrascore Extensions _.extend _, Extrascore.Extensions # Initialize the Extrascore Extensions _.init Extrascore.Extensions
188882
###! Extrascore (requires jQuery and Underscore) by <NAME> (case<EMAIL>.<EMAIL>) ### # Check dependencies if not Extrascore? and jQuery? and _? # Use the jQuery shortcut $ = jQuery # Define the Extrascore object window.Extrascore = # Mixins for Underscore Mixins: # Mass method call for every child of obj mass: (obj, key, args...) -> for __, val of obj val?[key]? args... # Initialize an object by calling init on children and then assigning the load method to jQuery's DOM ready call # This is a special _.mass() function init: (obj) -> # Call on jQuery's DOM ready call load = (obj) -> _.mass obj, 'load' dom obj $('body').on 'DOMSubtreeModified', (e) -> dom obj, e unless obj._extrascoreDomLocked # Call on every DOMSubtreeModified event (use carefully, doesn't work in Opera *shocking*) dom = (obj, e) -> obj._extrascoreDomLocked = true _.mass obj, 'dom', e delete obj._extrascoreDomLocked # Call `init()` on all children of obj if the method exists _.mass obj, 'init' $ -> load obj # Clean a string for use in a URL or query clean: (str, opt = {}) -> opt = _.extend delimiter: ' ' alphanumeric: false downcase: false , opt str = str+'' str = str.toLowerCase() if opt.downcase str = str.replace(/'/g, '').replace(/[^\w\s]|_/g, ' ') if opt.alphanumeric $.trim(str.replace /\s+/g, ' ').replace /\s/g, opt.delimiter # Shortcut for _.clean str, delimiter: '-', alphanumeric: true, downcase: true urlize: (str, delimiter = '-') -> _.clean str, delimiter: delimiter, alphanumeric: true, downcase: true # This sucker comes in handy startsWith: (str, start) -> str = '' + str start = '' + start return start.length <= str.length and str.substr(0, start.length) is start # This guy too endsWith: (str, end) -> str = '' + str end = '' + end return end.length <= str.length and str.substr(str.length-end.length) is end # Sort an object by key for iteration sortByKey: (obj) -> newObj = {} _.chain(obj) .map((val, key) -> [key, val]) .sortBy((val) -> val[0]) .each (val) -> newObj[val[0]] = val[1] newObj # A quick zip to the top of the page, or optionally to an integer or jQuery object specified by `val` scrollTo: (val = 0, duration, callback) -> if val instanceof $ val = val.offset().top $(if $.browser.webkit then document.body else document.documentElement).animate scrollTop: val, duration, callback # Get a full URL from a relative url url: (path = '', protocol = location.protocol) -> # Append a colon to the protocol if necessary protocol += ':' unless _.endsWith protocol, ':' # See if it's already a URL unless path.match /^\w+:/ # See if it's a URL looking for a protocol if _.startsWith path, '//' path = location.protocol + path # See if it's relative to the domain root else if _.startsWith path, '/' path = "#{location.protocol}//#{location.host + path}" # Otherwise it must be relative to the current location else path = location.href + path # Swap the protocols if necessary path.replace location.protocol, protocol # The reverse of _.url() relativeUrl: (path = '') -> _.url(path).replace /^\w+:\/\/[^/]+/, '' # Sometimes it's handy to know the size of the scrollbars in a browser scrollbarSize: (dimension = 'width') -> $out = $('<div><div/></div>') .appendTo('body') .css position: 'fixed' overflow: 'hidden' left: -50 top: -50 width: 50 height: 50 $in = $out.find('> div').css height: '100%' d1 = $in[dimension]() $out.css overflow: 'scroll' d2 = $in[dimension]() $out.remove() d1-d2 # Does the element have a scrollbar? hasScrollbar: ($obj) -> style = $obj.attr 'style' d1 = $obj.width() d2 = $obj.css(overflow: 'hidden').width() if style? $obj.attr style: style else $obj.removeAttr 'style' d1 isnt d2 # Break a query up into components if colons are used, otherwise just return the cleaned string parseQuery: (str, downcase = true) -> str = _.clean str, downcase: downcase colon = _.compact str.replace(/^:+|:+$/g, '').split ':' if colon.length > 1 colon = _.map colon, (str) -> $.trim(str).match /(?:^|^(.*)\s)(\S*)$/ terms = {} _.each colon, (match, i) -> if i < colon.length - 1 terms[match[2]] = colon[i + 1][1] else prev = colon[i - 1][2] terms[prev] = (if terms[prev] then terms[prev]+' ' else '')+match[2] return terms str # Ghetto nextTick nextTick: (fn) -> setTimeout fn, 0 # Extensions for Underscore (more of individual classes using Underscore for the namespace then actual extentions) Extensions: # Placeholder for lame browsers Placeholder: # After the DOM is loaded load: -> # Hijack jQuery's .val() so it will return an empty string if Placeholder says it should $.fn._val = $.fn.val $.fn.val = (str) -> if str? $(@).each -> $(@)._val str else if $(@).data 'placeholderEmpty' then '' else $(@)._val() # Check for new inputs or textareas than need to be initialized with Placeholder dom: -> $('.js-placeholder, .js-placeholder-password').each -> $t = $ @ if $t.data('placeholderHtml')? and not $t.data('placeholderEmpty')? password = $t.hasClass 'js-placeholder-password' placeholder = $t.data 'placeholderHtml' $t[0].type = 'password' if password unless password and $.browser.msie and $.browser.version.split('.') < 9 if not $t.val() or $t.val() is placeholder $t.data placeholderEmpty: true $t.val placeholder $t[0].type = 'text' if password else $t.data placeholderEmpty: false $t.attr placeholder: placeholder title: placeholder $t.focus(-> $t.val '' if $t.data 'placeholderEmpty' if password $t[0].type = 'password' $t.attr placeholder: placeholder $t.data placeholderEmpty: false ).blur -> if $t.val() $t.data placeholderEmpty: false else $t.val placeholder $t.data placeholderEmpty: true $t[0].type = 'text' if password # Multipurpose PopUp PopUp: # Duration and Fade duration default, feel free to change DURATION: 0 FADE_DURATION: 250 # Build the PopUp element build: -> # Shortcut o = _.PopUp; unless $('#js-pop-up-container').length # Until 'display: box' becomes more widely available, we're stuck with table/table-cell $('body').append o.$container = $('<div><div><div><div/></div></div></div>') .attr( id: 'js-pop-up-container' ).css display: 'none' position: 'fixed' zIndex: 999999 left: 0 top: 0 width: '100%' height: '100%' opacity: 0 overflow: 'auto' o.hide() o.$container.find('> div') .attr( id: 'js-pop-up-table' ).css display: 'table' width: '100%' height: '100%' o.$container.find('> div > div') .attr( id: 'js-pop-up-table-cell' ).css display: 'table-cell' textAlign: 'center' verticalAlign: 'middle' o.$div = o.$container.find('> div > div > div') .attr( id: 'js-pop-up' ).css display: 'inline-block' position: 'relative' o.$container.on 'click', -> o.$div.find('.js-pop-up-outside').click() o.$div .on('click', false) .on 'click', '.js-pop-up-hide', o.hide $(document).keydown (e) -> if o.$container.css('display') is 'block' and not $('body :focus').length switch e.keyCode when 13 then o.$div.find('.js-pop-up-enter').click() when 27 then o.$div.find('.js-pop-up-esc').click() else return true false # Fade the PopUp out hide: (fadeDuration) -> o = _.PopUp if o.$container? o.$container .stop() .animate opacity: 0 , (if isNaN(fadeDuration) then o.fadeDuration else fadeDuration) , -> o.$container.css display: 'none' if o.saveBodyStyle? $('body').attr style: o.saveBodyStyle else $('body').removeAttr 'style' o.saveBodyStyle = null # Show the PopUp with the given `html`, optionally for a 'duration', with a 'callback', and/or with a 'fadeDuration' show: (html, opt = {}) -> o = _.PopUp # Build the PopUp element o.build() opt = _.extend duration: o.DURATION callback: null fadeDuration: o.FADE_DURATION , opt o.saveBodyStyle = $('body').attr 'style' unless o.$container.css('display') is 'block' $('body').css marginRight: _.scrollbarSize() if _.hasScrollbar $ 'body' $('body').css overflow: 'hidden' $('body :focus').blur() o.fadeDuration = opt.fadeDuration o.$div.html html o.$container .stop() .css( display: 'block') .animate opacity: 1 , opt.fadeDuration clearTimeout o.timeout if o.timeout? o.timeout = setTimeout -> o.hide() opt.callback?() , opt.duration if opt.duration # Search (as you type) Search: # Check for Search objects to be initialized dom: -> $('.js-search').each -> $search = $ @ unless $search.data('searchCache')? o = _.Search $search.data searchCache: [] searchId: 0 searchAjax: {} searchLastQ: null searchPage: 0 searchHoldHover: false search$Q: $search.find '.js-search-q' search$Results: $search.find '.js-search-results' $q = $search.data 'search$Q' $results = $search.data 'search$Results' o.query $search if $q.is ':focus' $search.hover(-> $search.data searchHover: true , -> $search.data searchHover: false $results.css display: 'none' unless $q.is(':focus') or $search.data 'searchHoldHover' ).mouseover -> $search.data searchHoldHover: false $q.blur(-> _.nextTick -> $results.css display: 'none' unless $search.data 'searchHover') .focus(-> $search.data searchHoldHover: false) .keydown((e) -> switch e.keyCode when 13 then $search.find('.js-search-selected').click() when 38 then o.select $search, 'prev' when 40 then o.select $search, 'next' when 27 if $q.val() is '' $q.blur() _.nextTick -> o.query $search else _.nextTick -> $q.val '' o.query $search else _.nextTick -> o.query $search if $q.is ':focus' return true false ).on 'focus keyup change', -> o.query $search $results.on 'mouseenter click', '.js-search-result', (e) -> $t = $ @ $results.find('.js-search-result.js-search-selected').removeClass 'js-search-selected' $t.addClass 'js-search-selected' if e.type is 'click' if $t.hasClass 'js-search-prev' o.page $search, $search.data('searchPage') - 1, true $search.data searchHoldHover: true else if $t.hasClass 'js-search-next' o.page $search, $search.data('searchPage') + 1 $search.data searchHoldHover: true else if $t.hasClass 'js-search-submit' $t.parents('form').submit() if $t.hasClass 'js-search-hide' $q.blur() $results.css display: 'none' # Change the current search results page page: ($searches, n, prev) -> $searches.each -> $search = $ @ $results = $search.data 'search$Results' n = Math.min $results.find('.js-search-page').length - 1, Math.max n, 0 $results.find('.js-search-selected').removeClass 'js-search-selected' $results.find('.js-search-page') .css(display: 'none') .eq(n) .removeAttr('style') .find('.js-search-result:not(.js-search-prev):not(.js-search-next)')[if prev then 'last' else 'first']() .addClass 'js-search-selected' $search.data 'searchPage', n # Send the value of q to the correct search function and return the result to the correct callback query: ($searches, urlN = 1) -> $searches.each -> o = _.Search $search = $ @ $results = $search.data 'search$Results' $q = $search.data 'search$Q' callback = eval $search.data 'searchCallback' q = _.clean $q.val(), downcase: true t = new Date().getTime() $results.css display: 'block' unless q or $search.data('js-search-empty')? $results.css(display: 'none').empty() $search.removeClass 'js-search-loading' else if q isnt $search.data('searchLastQ') or urlN > 1 callback $search clearTimeout $search.data 'searchTimeout' $search.data('searchAjax').abort?() if $search.data('searchCache')["#{urlN}_" + q]? callback $search, $search.data('searchCache')["#{urlN}_" + q], urlN $search.removeClass 'js-search-loading' o.query $search, urlN + 1 if $search.data("searchUrl#{urlN+1}")? else $search.addClass('js-search-loading').data 'searchTimeout', setTimeout -> handleData = (data) -> $search.data('searchCache')["#{urlN}_" + q] = data if check is $search.data('searchId') and (_.clean($q.val()) or $search.data('js-search-empty')?) $search.removeClass 'js-search-loading' callback $search, data, urlN o.query $search, urlN + 1 if $search.data "searchUrl#{urlN+1}" check = $search.data(searchId: $search.data('searchId') + 1).data 'searchId' if $search.data('searchJs')? handleData eval($search.data 'searchJs')(q) else if $search.data('searchUrl')? $search.data searchAjax: $.getJSON($search.data("searchUrl#{if urlN is 1 then '' else urlN}"), q: q, handleData) , $search.data('searchDelay') ? 0 $search.data 'searchLastQ', q # Select the next or previous in a list of results select: ($searches, dir) -> $searches.each -> o = _.Search $search = $ @ $page = $search.find('.js-search-page').eq $search.data 'searchPage' $page.find('.js-search-result')[if dir is 'prev' then 'first' else 'last']().addClass 'js-search-selected' unless $page.find('.js-search-selected').removeClass('js-search-selected')[dir]().addClass('js-search-selected').length if $page.find('.js-search-result.js-search-selected.js-search-prev').length o.page $search, $search.data('searchPage') - 1, true else if $page.find('.js-search-result.js-search-selected.js-search-next').length o.page $search, $search.data('searchPage') + 1 # Yay tooltips! Tooltip: # Store mouse coordinates mouse: x: 0 y: 0 # Set mousemove on document to track coordinates load: -> o = _.Tooltip $('body').mousemove((e) -> o.mouse = x: e.pageX y: e.pageY $('.js-tooltip').each -> $t = $ @ $t.data('tooltip$Div').css o.position($t).home if $t.data('tooltip$Div')? and $t.data('tooltipMouse')? ).on('mouseenter', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ o.show $t $t.data tooltipHover: true ).on('mouseleave', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ $t.data tooltipHover: false o.hide $t ).on('focus', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.show $ @ ).on('blur', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.hide $ @ ) # Get the current tooltip$Div for an item or create a new one and return that divFor: ($t) -> o = _.Tooltip unless $t.data 'tooltip$Div' $t.parent().css position: 'relative' if $t.parent().css position: 'static' $t.data tooltipHoverable: null if $t.data('tooltipMouse')? $t.data _.extend tooltipPosition: 'top' tooltipOffset: 0 tooltipDuration: 0 , $t.data() $div = $('<div><div/></div>') .addClass("tooltip #{$t.data('tooltipPosition')}") .css display: 'none' position: 'absolute' zIndex: 999999; $div .find('> div') .html($t.data 'tooltipHtml') .css position: 'relative' $t .data(tooltip$Div: $div) .parent() .append $div position = o.position $t $div .css(position.home) .find('> div') .css _.extend {opacity: 0}, position.away # If the tooltip is 'hoverable' (aka it should stay while the mouse is over the tooltip itself) if $t.data('tooltipHoverable')? $div.hover -> _.Tooltip.show $t $t.data tooltipHoverableHover: true , -> $t.data tooltipHoverableHover: false _.Tooltip.hide $t else # Otherwise turn off interaction with the mouse $div.css pointerEvents: 'none' '-webkit-user-select': 'none' '-moz-user-select': 'none' userSelect: 'none' $t.data 'tooltip$Div' # Show the tooltip if it's not already visible show: ($t) -> o = _.Tooltip $div = o.divFor $t unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .appendTo($t.parent()) .css(_.extend {display: 'block'}, position.home) .find('> div') .stop() .animate opacity: 1 top: 0 left: 0 , $t.data 'tooltipDuration' # Hide the tooltip if it's not already hidden hide: ($t) -> o = _.Tooltip if $div = $t.data 'tooltip$Div' unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .css(position.home) .find('> div') .stop() .animate _.extend({opacity: 0}, position.away), duration: $t.data 'tooltipDuration' complete: -> $t.data tooltip$Div: null $(@).parent().remove() # Method for getting the correct CSS position data for a tooltip position: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' $parent = $t.parent() offset = $t.data 'tooltipOffset' divWidth = $div.outerWidth() divHeight = $div.outerHeight() parentScrollLeft = $parent.scrollLeft() parentScrollTop = $parent.scrollTop() if $t.data('tooltipMouse')? tLeft = o.mouse.x - $t.parent().offset().left + parentScrollLeft tTop = o.mouse.y - $t.parent().offset().top + parentScrollTop tWidth = tHeight = 0 else tPosition = $t.position() tLeft = tPosition.left + parentScrollLeft + parseInt $t.css 'marginLeft' tTop = tPosition.top + parentScrollTop + parseInt $t.css 'marginTop' tWidth = $t.outerWidth() tHeight = $t.outerHeight() home = left: tLeft top: tTop away = {} switch $t.data('tooltipPosition') when 'top' home.left += (tWidth - divWidth)/2 home.top -= divHeight away.top = -offset when 'right' home.left += tWidth home.top += (tHeight - divHeight)/2 away.left = offset when 'bottom' home.left += (tWidth - divWidth)/2 home.top += tHeight away.top = offset when 'left' home.left -= divWidth home.top += (tHeight - divHeight)/2 away.left = -offset {home: home, away: away} # Use this to correct the tooltip content and positioning between events if necessary correct: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' if $div if $t.css('display') is 'none' $t.mouseleave().blur() else $div.find('> div').html($t.data 'tooltipHtml') $div.css _.Tooltip.position($t).home # Use this to remove a tooltip remove: ($t) -> $t .data( tooltipHover: false tooltipHoverableHover: false ).removeClass('js-tooltip') .data('tooltip$Div')?.remove() # State manager State: # Header to send with the XHR HEADER: 'X-Chromeless' xhr: {} cache: {} # The attributes below are optional and can be set at runtime as needed # When true, forces State to reload the page on the next request. # refresh: false # Specify data to send with the XHR request data : {} load: -> o = _.State if history.state? history.replaceState true, null $(window).on 'popstate', (e) -> if e.originalEvent.state? o.push location.href else history.replaceState true, null $("body").on 'click', '.js-state', -> $t = $ @ o.push (if $t.data 'stateUrl' then $t.data 'stateUrl' else $t.attr 'href'), $t.data 'stateProtocol' false updateCache: (url, obj) -> o = _.State if o.cache[url]? _.extend o.cache[url], obj else o.cache[url] = obj push: (url, protocol = location.protocol) -> o = _.State url = _.url url, protocol if history.pushState? and not o.refresh and not _.State.data[url]?.refresh and _.startsWith url, location.protocol o.xhr.abort?() o.clear o.cache[url], url if o.cache[url]? and o.cache[url].cache isnt false o.change url else o.before o.cache[url], url o.xhr = $.ajax url, data: o.data success: (data) -> valid = null selectors = {} $(data.replace /<(\/)?script>/gi, '<!--$1state-script-->').each -> $t = $ @ unless $t[0] instanceof Text if (s = $t.attr 'id') or $t.is 'title' selectors[s and "##{s}" or 'title'] = $t.html().replace /<!--(\/)?state-script-->/g, '<$1script>' valid = true if s else unless valid? valid = false url = selectors['#chromeless-request-url'] if selectors['#chromeless-request-url']? and selectors['#chromeless-request-url'] isnt url if valid o.updateCache url, selectors o.after o.cache[url], url o.change url else location.assign url beforeSend: (xhr) -> xhr.setRequestHeader o.HEADER, 1 error: -> location.assign url else location.assign url change: (url) -> o = _.State history[if o.cache[url].replace then 'replaceState' else 'pushState'] true, null, url if location.href isnt url o.parse o.cache[url], url clear: -> before: -> after: -> parse: -> # Load images only when they're on the page or about to be on it Lazy: # Default tolerance, can be overidden here or with data-tolerance='xxx' TOLERANCE: 100 # After the DOM is ready load: -> o = _.Lazy $(window).on 'scroll resize', o.dom # Check for new lazy images dom: -> # Wait for the browser to position the element on the page before checking its coordinates _.nextTick -> $('img.js-lazy').each -> $t = $ @ visible = _.reduce $t.parents(), (memo, parent) -> memo and $(parent).css('display') isnt 'none' and $(parent).css('visibility') isnt 'hidden' , true if visible and $(window).scrollTop() + $(window).outerHeight() >= $t.offset().top - ($t.data('lazyTolerance') ? _.Lazy.TOLERANCE) url = $t.data 'lazyUrl' $t.removeClass('js-lazy').attr 'src', url # Everyone's favorite cheat code Konami: (callback, onlyOnce = false, code = '38,38,40,40,37,39,37,39,66,65,13', touchCode = 'up,up,down,down,left,right,left,right,tap,tap,tap') -> keysPressed = [] touchEvents = [] tap = false startX = startY = dX = dY = 0 keyDownEvent = (e) -> keysPressed.push e.keyCode if _.endsWith keysPressed + '', code $(document).off 'keydown', keyDownEvent if onlyOnce keysPressed = [] e.preventDefault() callback() touchStartEvent = (e) -> e = e.originalEvent if e.touches.length is 1 touch = e.touches[0] {screenX: startX, screenY: startY} = touch tap = tracking = true touchMoveEvent = (e) -> e = e.originalEvent if e.touches.length is 1 and tap touch = e.touches[0] dX = touch.screenX - startX dY = touch.screenY - startY rightLeft = if dX > 0 then 'right' else 'left' downUp = if dY > 0 then 'down' else 'up' val = if Math.abs(dX) > Math.abs dY then rightLeft else downUp touchEvents.push val tap = false checkEvents e touchEndEvent = (e) -> e = e.originalEvent if e.touches.length is 0 and tap touchEvents.push 'tap' checkEvents e checkEvents = (e) -> if _.endsWith touchEvents + '', touchCode if onlyOnce $(document).off 'touchmove', touchMoveEvent $(document).off 'touchend', touchEndEvent touchEvents = [] e.preventDefault() callback() $(document).on 'keydown', keyDownEvent $(document).on 'touchstart', touchStartEvent $(document).on 'touchmove', touchMoveEvent $(document).on 'touchend', touchEndEvent # Making Cookie management easy on you Cookie: (name, val, opt = {}) -> if typeof name is 'object' _.Cookie n, v, val for n, v of name else if typeof name is 'string' and val isnt undefined opt.expires = -1 if val is null val ||= '' params = [] params.push "; Expires=#{if opt.expires.toGMTString? then opt.expires.toGMTString() else new Date(new Date().getTime()+opt.expires*1000*60*60*24).toGMTString()}" if opt.expires params.push "; Path=#{opt.path}" if opt.path params.push "; Domain=#{opt.domain}" if opt.domain params.push '; HttpOnly' if opt.httpOnly params.push '; Secure' if opt.secure document.cookie = "#{encodeURIComponent name}=#{encodeURIComponent val}#{params.join ''}" else cookies = {} if document.cookie _.each decodeURIComponent(document.cookie).split(/\s*;\s*/), (cookie) -> {1: n, 2: v} = /^([^=]*)\s*=\s*(.*)$/.exec cookie if typeof name is 'string' and name is n return v else if not name? cookies[n] = v if not name then cookies else null # Mixin the Extrascore Mixins _.mixin Extrascore.Mixins # Extend the Extrascore Extensions _.extend _, Extrascore.Extensions # Initialize the Extrascore Extensions _.init Extrascore.Extensions
true
###! Extrascore (requires jQuery and Underscore) by PI:NAME:<NAME>END_PI (casePI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI) ### # Check dependencies if not Extrascore? and jQuery? and _? # Use the jQuery shortcut $ = jQuery # Define the Extrascore object window.Extrascore = # Mixins for Underscore Mixins: # Mass method call for every child of obj mass: (obj, key, args...) -> for __, val of obj val?[key]? args... # Initialize an object by calling init on children and then assigning the load method to jQuery's DOM ready call # This is a special _.mass() function init: (obj) -> # Call on jQuery's DOM ready call load = (obj) -> _.mass obj, 'load' dom obj $('body').on 'DOMSubtreeModified', (e) -> dom obj, e unless obj._extrascoreDomLocked # Call on every DOMSubtreeModified event (use carefully, doesn't work in Opera *shocking*) dom = (obj, e) -> obj._extrascoreDomLocked = true _.mass obj, 'dom', e delete obj._extrascoreDomLocked # Call `init()` on all children of obj if the method exists _.mass obj, 'init' $ -> load obj # Clean a string for use in a URL or query clean: (str, opt = {}) -> opt = _.extend delimiter: ' ' alphanumeric: false downcase: false , opt str = str+'' str = str.toLowerCase() if opt.downcase str = str.replace(/'/g, '').replace(/[^\w\s]|_/g, ' ') if opt.alphanumeric $.trim(str.replace /\s+/g, ' ').replace /\s/g, opt.delimiter # Shortcut for _.clean str, delimiter: '-', alphanumeric: true, downcase: true urlize: (str, delimiter = '-') -> _.clean str, delimiter: delimiter, alphanumeric: true, downcase: true # This sucker comes in handy startsWith: (str, start) -> str = '' + str start = '' + start return start.length <= str.length and str.substr(0, start.length) is start # This guy too endsWith: (str, end) -> str = '' + str end = '' + end return end.length <= str.length and str.substr(str.length-end.length) is end # Sort an object by key for iteration sortByKey: (obj) -> newObj = {} _.chain(obj) .map((val, key) -> [key, val]) .sortBy((val) -> val[0]) .each (val) -> newObj[val[0]] = val[1] newObj # A quick zip to the top of the page, or optionally to an integer or jQuery object specified by `val` scrollTo: (val = 0, duration, callback) -> if val instanceof $ val = val.offset().top $(if $.browser.webkit then document.body else document.documentElement).animate scrollTop: val, duration, callback # Get a full URL from a relative url url: (path = '', protocol = location.protocol) -> # Append a colon to the protocol if necessary protocol += ':' unless _.endsWith protocol, ':' # See if it's already a URL unless path.match /^\w+:/ # See if it's a URL looking for a protocol if _.startsWith path, '//' path = location.protocol + path # See if it's relative to the domain root else if _.startsWith path, '/' path = "#{location.protocol}//#{location.host + path}" # Otherwise it must be relative to the current location else path = location.href + path # Swap the protocols if necessary path.replace location.protocol, protocol # The reverse of _.url() relativeUrl: (path = '') -> _.url(path).replace /^\w+:\/\/[^/]+/, '' # Sometimes it's handy to know the size of the scrollbars in a browser scrollbarSize: (dimension = 'width') -> $out = $('<div><div/></div>') .appendTo('body') .css position: 'fixed' overflow: 'hidden' left: -50 top: -50 width: 50 height: 50 $in = $out.find('> div').css height: '100%' d1 = $in[dimension]() $out.css overflow: 'scroll' d2 = $in[dimension]() $out.remove() d1-d2 # Does the element have a scrollbar? hasScrollbar: ($obj) -> style = $obj.attr 'style' d1 = $obj.width() d2 = $obj.css(overflow: 'hidden').width() if style? $obj.attr style: style else $obj.removeAttr 'style' d1 isnt d2 # Break a query up into components if colons are used, otherwise just return the cleaned string parseQuery: (str, downcase = true) -> str = _.clean str, downcase: downcase colon = _.compact str.replace(/^:+|:+$/g, '').split ':' if colon.length > 1 colon = _.map colon, (str) -> $.trim(str).match /(?:^|^(.*)\s)(\S*)$/ terms = {} _.each colon, (match, i) -> if i < colon.length - 1 terms[match[2]] = colon[i + 1][1] else prev = colon[i - 1][2] terms[prev] = (if terms[prev] then terms[prev]+' ' else '')+match[2] return terms str # Ghetto nextTick nextTick: (fn) -> setTimeout fn, 0 # Extensions for Underscore (more of individual classes using Underscore for the namespace then actual extentions) Extensions: # Placeholder for lame browsers Placeholder: # After the DOM is loaded load: -> # Hijack jQuery's .val() so it will return an empty string if Placeholder says it should $.fn._val = $.fn.val $.fn.val = (str) -> if str? $(@).each -> $(@)._val str else if $(@).data 'placeholderEmpty' then '' else $(@)._val() # Check for new inputs or textareas than need to be initialized with Placeholder dom: -> $('.js-placeholder, .js-placeholder-password').each -> $t = $ @ if $t.data('placeholderHtml')? and not $t.data('placeholderEmpty')? password = $t.hasClass 'js-placeholder-password' placeholder = $t.data 'placeholderHtml' $t[0].type = 'password' if password unless password and $.browser.msie and $.browser.version.split('.') < 9 if not $t.val() or $t.val() is placeholder $t.data placeholderEmpty: true $t.val placeholder $t[0].type = 'text' if password else $t.data placeholderEmpty: false $t.attr placeholder: placeholder title: placeholder $t.focus(-> $t.val '' if $t.data 'placeholderEmpty' if password $t[0].type = 'password' $t.attr placeholder: placeholder $t.data placeholderEmpty: false ).blur -> if $t.val() $t.data placeholderEmpty: false else $t.val placeholder $t.data placeholderEmpty: true $t[0].type = 'text' if password # Multipurpose PopUp PopUp: # Duration and Fade duration default, feel free to change DURATION: 0 FADE_DURATION: 250 # Build the PopUp element build: -> # Shortcut o = _.PopUp; unless $('#js-pop-up-container').length # Until 'display: box' becomes more widely available, we're stuck with table/table-cell $('body').append o.$container = $('<div><div><div><div/></div></div></div>') .attr( id: 'js-pop-up-container' ).css display: 'none' position: 'fixed' zIndex: 999999 left: 0 top: 0 width: '100%' height: '100%' opacity: 0 overflow: 'auto' o.hide() o.$container.find('> div') .attr( id: 'js-pop-up-table' ).css display: 'table' width: '100%' height: '100%' o.$container.find('> div > div') .attr( id: 'js-pop-up-table-cell' ).css display: 'table-cell' textAlign: 'center' verticalAlign: 'middle' o.$div = o.$container.find('> div > div > div') .attr( id: 'js-pop-up' ).css display: 'inline-block' position: 'relative' o.$container.on 'click', -> o.$div.find('.js-pop-up-outside').click() o.$div .on('click', false) .on 'click', '.js-pop-up-hide', o.hide $(document).keydown (e) -> if o.$container.css('display') is 'block' and not $('body :focus').length switch e.keyCode when 13 then o.$div.find('.js-pop-up-enter').click() when 27 then o.$div.find('.js-pop-up-esc').click() else return true false # Fade the PopUp out hide: (fadeDuration) -> o = _.PopUp if o.$container? o.$container .stop() .animate opacity: 0 , (if isNaN(fadeDuration) then o.fadeDuration else fadeDuration) , -> o.$container.css display: 'none' if o.saveBodyStyle? $('body').attr style: o.saveBodyStyle else $('body').removeAttr 'style' o.saveBodyStyle = null # Show the PopUp with the given `html`, optionally for a 'duration', with a 'callback', and/or with a 'fadeDuration' show: (html, opt = {}) -> o = _.PopUp # Build the PopUp element o.build() opt = _.extend duration: o.DURATION callback: null fadeDuration: o.FADE_DURATION , opt o.saveBodyStyle = $('body').attr 'style' unless o.$container.css('display') is 'block' $('body').css marginRight: _.scrollbarSize() if _.hasScrollbar $ 'body' $('body').css overflow: 'hidden' $('body :focus').blur() o.fadeDuration = opt.fadeDuration o.$div.html html o.$container .stop() .css( display: 'block') .animate opacity: 1 , opt.fadeDuration clearTimeout o.timeout if o.timeout? o.timeout = setTimeout -> o.hide() opt.callback?() , opt.duration if opt.duration # Search (as you type) Search: # Check for Search objects to be initialized dom: -> $('.js-search').each -> $search = $ @ unless $search.data('searchCache')? o = _.Search $search.data searchCache: [] searchId: 0 searchAjax: {} searchLastQ: null searchPage: 0 searchHoldHover: false search$Q: $search.find '.js-search-q' search$Results: $search.find '.js-search-results' $q = $search.data 'search$Q' $results = $search.data 'search$Results' o.query $search if $q.is ':focus' $search.hover(-> $search.data searchHover: true , -> $search.data searchHover: false $results.css display: 'none' unless $q.is(':focus') or $search.data 'searchHoldHover' ).mouseover -> $search.data searchHoldHover: false $q.blur(-> _.nextTick -> $results.css display: 'none' unless $search.data 'searchHover') .focus(-> $search.data searchHoldHover: false) .keydown((e) -> switch e.keyCode when 13 then $search.find('.js-search-selected').click() when 38 then o.select $search, 'prev' when 40 then o.select $search, 'next' when 27 if $q.val() is '' $q.blur() _.nextTick -> o.query $search else _.nextTick -> $q.val '' o.query $search else _.nextTick -> o.query $search if $q.is ':focus' return true false ).on 'focus keyup change', -> o.query $search $results.on 'mouseenter click', '.js-search-result', (e) -> $t = $ @ $results.find('.js-search-result.js-search-selected').removeClass 'js-search-selected' $t.addClass 'js-search-selected' if e.type is 'click' if $t.hasClass 'js-search-prev' o.page $search, $search.data('searchPage') - 1, true $search.data searchHoldHover: true else if $t.hasClass 'js-search-next' o.page $search, $search.data('searchPage') + 1 $search.data searchHoldHover: true else if $t.hasClass 'js-search-submit' $t.parents('form').submit() if $t.hasClass 'js-search-hide' $q.blur() $results.css display: 'none' # Change the current search results page page: ($searches, n, prev) -> $searches.each -> $search = $ @ $results = $search.data 'search$Results' n = Math.min $results.find('.js-search-page').length - 1, Math.max n, 0 $results.find('.js-search-selected').removeClass 'js-search-selected' $results.find('.js-search-page') .css(display: 'none') .eq(n) .removeAttr('style') .find('.js-search-result:not(.js-search-prev):not(.js-search-next)')[if prev then 'last' else 'first']() .addClass 'js-search-selected' $search.data 'searchPage', n # Send the value of q to the correct search function and return the result to the correct callback query: ($searches, urlN = 1) -> $searches.each -> o = _.Search $search = $ @ $results = $search.data 'search$Results' $q = $search.data 'search$Q' callback = eval $search.data 'searchCallback' q = _.clean $q.val(), downcase: true t = new Date().getTime() $results.css display: 'block' unless q or $search.data('js-search-empty')? $results.css(display: 'none').empty() $search.removeClass 'js-search-loading' else if q isnt $search.data('searchLastQ') or urlN > 1 callback $search clearTimeout $search.data 'searchTimeout' $search.data('searchAjax').abort?() if $search.data('searchCache')["#{urlN}_" + q]? callback $search, $search.data('searchCache')["#{urlN}_" + q], urlN $search.removeClass 'js-search-loading' o.query $search, urlN + 1 if $search.data("searchUrl#{urlN+1}")? else $search.addClass('js-search-loading').data 'searchTimeout', setTimeout -> handleData = (data) -> $search.data('searchCache')["#{urlN}_" + q] = data if check is $search.data('searchId') and (_.clean($q.val()) or $search.data('js-search-empty')?) $search.removeClass 'js-search-loading' callback $search, data, urlN o.query $search, urlN + 1 if $search.data "searchUrl#{urlN+1}" check = $search.data(searchId: $search.data('searchId') + 1).data 'searchId' if $search.data('searchJs')? handleData eval($search.data 'searchJs')(q) else if $search.data('searchUrl')? $search.data searchAjax: $.getJSON($search.data("searchUrl#{if urlN is 1 then '' else urlN}"), q: q, handleData) , $search.data('searchDelay') ? 0 $search.data 'searchLastQ', q # Select the next or previous in a list of results select: ($searches, dir) -> $searches.each -> o = _.Search $search = $ @ $page = $search.find('.js-search-page').eq $search.data 'searchPage' $page.find('.js-search-result')[if dir is 'prev' then 'first' else 'last']().addClass 'js-search-selected' unless $page.find('.js-search-selected').removeClass('js-search-selected')[dir]().addClass('js-search-selected').length if $page.find('.js-search-result.js-search-selected.js-search-prev').length o.page $search, $search.data('searchPage') - 1, true else if $page.find('.js-search-result.js-search-selected.js-search-next').length o.page $search, $search.data('searchPage') + 1 # Yay tooltips! Tooltip: # Store mouse coordinates mouse: x: 0 y: 0 # Set mousemove on document to track coordinates load: -> o = _.Tooltip $('body').mousemove((e) -> o.mouse = x: e.pageX y: e.pageY $('.js-tooltip').each -> $t = $ @ $t.data('tooltip$Div').css o.position($t).home if $t.data('tooltip$Div')? and $t.data('tooltipMouse')? ).on('mouseenter', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ o.show $t $t.data tooltipHover: true ).on('mouseleave', '.js-tooltip:not([data-tooltip-no-hover])', -> $t = $ @ $t.data tooltipHover: false o.hide $t ).on('focus', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.show $ @ ).on('blur', 'input.js-tooltip:not([data-tooltip-no-focus]), textarea.js-tooltip:not([data-tooltip-no-focus])', -> o.hide $ @ ) # Get the current tooltip$Div for an item or create a new one and return that divFor: ($t) -> o = _.Tooltip unless $t.data 'tooltip$Div' $t.parent().css position: 'relative' if $t.parent().css position: 'static' $t.data tooltipHoverable: null if $t.data('tooltipMouse')? $t.data _.extend tooltipPosition: 'top' tooltipOffset: 0 tooltipDuration: 0 , $t.data() $div = $('<div><div/></div>') .addClass("tooltip #{$t.data('tooltipPosition')}") .css display: 'none' position: 'absolute' zIndex: 999999; $div .find('> div') .html($t.data 'tooltipHtml') .css position: 'relative' $t .data(tooltip$Div: $div) .parent() .append $div position = o.position $t $div .css(position.home) .find('> div') .css _.extend {opacity: 0}, position.away # If the tooltip is 'hoverable' (aka it should stay while the mouse is over the tooltip itself) if $t.data('tooltipHoverable')? $div.hover -> _.Tooltip.show $t $t.data tooltipHoverableHover: true , -> $t.data tooltipHoverableHover: false _.Tooltip.hide $t else # Otherwise turn off interaction with the mouse $div.css pointerEvents: 'none' '-webkit-user-select': 'none' '-moz-user-select': 'none' userSelect: 'none' $t.data 'tooltip$Div' # Show the tooltip if it's not already visible show: ($t) -> o = _.Tooltip $div = o.divFor $t unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .appendTo($t.parent()) .css(_.extend {display: 'block'}, position.home) .find('> div') .stop() .animate opacity: 1 top: 0 left: 0 , $t.data 'tooltipDuration' # Hide the tooltip if it's not already hidden hide: ($t) -> o = _.Tooltip if $div = $t.data 'tooltip$Div' unless (not $t.data('tooltipNoHover')? and $t.data 'tooltipHover') or (not $t.data('tooltipNoFocus')? and $t.is 'input:focus, textarea:focus') or $t.data 'tooltipHoverableHover' position = o.position $t $div .css(position.home) .find('> div') .stop() .animate _.extend({opacity: 0}, position.away), duration: $t.data 'tooltipDuration' complete: -> $t.data tooltip$Div: null $(@).parent().remove() # Method for getting the correct CSS position data for a tooltip position: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' $parent = $t.parent() offset = $t.data 'tooltipOffset' divWidth = $div.outerWidth() divHeight = $div.outerHeight() parentScrollLeft = $parent.scrollLeft() parentScrollTop = $parent.scrollTop() if $t.data('tooltipMouse')? tLeft = o.mouse.x - $t.parent().offset().left + parentScrollLeft tTop = o.mouse.y - $t.parent().offset().top + parentScrollTop tWidth = tHeight = 0 else tPosition = $t.position() tLeft = tPosition.left + parentScrollLeft + parseInt $t.css 'marginLeft' tTop = tPosition.top + parentScrollTop + parseInt $t.css 'marginTop' tWidth = $t.outerWidth() tHeight = $t.outerHeight() home = left: tLeft top: tTop away = {} switch $t.data('tooltipPosition') when 'top' home.left += (tWidth - divWidth)/2 home.top -= divHeight away.top = -offset when 'right' home.left += tWidth home.top += (tHeight - divHeight)/2 away.left = offset when 'bottom' home.left += (tWidth - divWidth)/2 home.top += tHeight away.top = offset when 'left' home.left -= divWidth home.top += (tHeight - divHeight)/2 away.left = -offset {home: home, away: away} # Use this to correct the tooltip content and positioning between events if necessary correct: ($t) -> o = _.Tooltip $div = $t.data 'tooltip$Div' if $div if $t.css('display') is 'none' $t.mouseleave().blur() else $div.find('> div').html($t.data 'tooltipHtml') $div.css _.Tooltip.position($t).home # Use this to remove a tooltip remove: ($t) -> $t .data( tooltipHover: false tooltipHoverableHover: false ).removeClass('js-tooltip') .data('tooltip$Div')?.remove() # State manager State: # Header to send with the XHR HEADER: 'X-Chromeless' xhr: {} cache: {} # The attributes below are optional and can be set at runtime as needed # When true, forces State to reload the page on the next request. # refresh: false # Specify data to send with the XHR request data : {} load: -> o = _.State if history.state? history.replaceState true, null $(window).on 'popstate', (e) -> if e.originalEvent.state? o.push location.href else history.replaceState true, null $("body").on 'click', '.js-state', -> $t = $ @ o.push (if $t.data 'stateUrl' then $t.data 'stateUrl' else $t.attr 'href'), $t.data 'stateProtocol' false updateCache: (url, obj) -> o = _.State if o.cache[url]? _.extend o.cache[url], obj else o.cache[url] = obj push: (url, protocol = location.protocol) -> o = _.State url = _.url url, protocol if history.pushState? and not o.refresh and not _.State.data[url]?.refresh and _.startsWith url, location.protocol o.xhr.abort?() o.clear o.cache[url], url if o.cache[url]? and o.cache[url].cache isnt false o.change url else o.before o.cache[url], url o.xhr = $.ajax url, data: o.data success: (data) -> valid = null selectors = {} $(data.replace /<(\/)?script>/gi, '<!--$1state-script-->').each -> $t = $ @ unless $t[0] instanceof Text if (s = $t.attr 'id') or $t.is 'title' selectors[s and "##{s}" or 'title'] = $t.html().replace /<!--(\/)?state-script-->/g, '<$1script>' valid = true if s else unless valid? valid = false url = selectors['#chromeless-request-url'] if selectors['#chromeless-request-url']? and selectors['#chromeless-request-url'] isnt url if valid o.updateCache url, selectors o.after o.cache[url], url o.change url else location.assign url beforeSend: (xhr) -> xhr.setRequestHeader o.HEADER, 1 error: -> location.assign url else location.assign url change: (url) -> o = _.State history[if o.cache[url].replace then 'replaceState' else 'pushState'] true, null, url if location.href isnt url o.parse o.cache[url], url clear: -> before: -> after: -> parse: -> # Load images only when they're on the page or about to be on it Lazy: # Default tolerance, can be overidden here or with data-tolerance='xxx' TOLERANCE: 100 # After the DOM is ready load: -> o = _.Lazy $(window).on 'scroll resize', o.dom # Check for new lazy images dom: -> # Wait for the browser to position the element on the page before checking its coordinates _.nextTick -> $('img.js-lazy').each -> $t = $ @ visible = _.reduce $t.parents(), (memo, parent) -> memo and $(parent).css('display') isnt 'none' and $(parent).css('visibility') isnt 'hidden' , true if visible and $(window).scrollTop() + $(window).outerHeight() >= $t.offset().top - ($t.data('lazyTolerance') ? _.Lazy.TOLERANCE) url = $t.data 'lazyUrl' $t.removeClass('js-lazy').attr 'src', url # Everyone's favorite cheat code Konami: (callback, onlyOnce = false, code = '38,38,40,40,37,39,37,39,66,65,13', touchCode = 'up,up,down,down,left,right,left,right,tap,tap,tap') -> keysPressed = [] touchEvents = [] tap = false startX = startY = dX = dY = 0 keyDownEvent = (e) -> keysPressed.push e.keyCode if _.endsWith keysPressed + '', code $(document).off 'keydown', keyDownEvent if onlyOnce keysPressed = [] e.preventDefault() callback() touchStartEvent = (e) -> e = e.originalEvent if e.touches.length is 1 touch = e.touches[0] {screenX: startX, screenY: startY} = touch tap = tracking = true touchMoveEvent = (e) -> e = e.originalEvent if e.touches.length is 1 and tap touch = e.touches[0] dX = touch.screenX - startX dY = touch.screenY - startY rightLeft = if dX > 0 then 'right' else 'left' downUp = if dY > 0 then 'down' else 'up' val = if Math.abs(dX) > Math.abs dY then rightLeft else downUp touchEvents.push val tap = false checkEvents e touchEndEvent = (e) -> e = e.originalEvent if e.touches.length is 0 and tap touchEvents.push 'tap' checkEvents e checkEvents = (e) -> if _.endsWith touchEvents + '', touchCode if onlyOnce $(document).off 'touchmove', touchMoveEvent $(document).off 'touchend', touchEndEvent touchEvents = [] e.preventDefault() callback() $(document).on 'keydown', keyDownEvent $(document).on 'touchstart', touchStartEvent $(document).on 'touchmove', touchMoveEvent $(document).on 'touchend', touchEndEvent # Making Cookie management easy on you Cookie: (name, val, opt = {}) -> if typeof name is 'object' _.Cookie n, v, val for n, v of name else if typeof name is 'string' and val isnt undefined opt.expires = -1 if val is null val ||= '' params = [] params.push "; Expires=#{if opt.expires.toGMTString? then opt.expires.toGMTString() else new Date(new Date().getTime()+opt.expires*1000*60*60*24).toGMTString()}" if opt.expires params.push "; Path=#{opt.path}" if opt.path params.push "; Domain=#{opt.domain}" if opt.domain params.push '; HttpOnly' if opt.httpOnly params.push '; Secure' if opt.secure document.cookie = "#{encodeURIComponent name}=#{encodeURIComponent val}#{params.join ''}" else cookies = {} if document.cookie _.each decodeURIComponent(document.cookie).split(/\s*;\s*/), (cookie) -> {1: n, 2: v} = /^([^=]*)\s*=\s*(.*)$/.exec cookie if typeof name is 'string' and name is n return v else if not name? cookies[n] = v if not name then cookies else null # Mixin the Extrascore Mixins _.mixin Extrascore.Mixins # Extend the Extrascore Extensions _.extend _, Extrascore.Extensions # Initialize the Extrascore Extensions _.init Extrascore.Extensions
[ { "context": "# Author: Josh Bass\n\nReact = require(\"react\");\nmathjs = require(\"math", "end": 19, "score": 0.9998729228973389, "start": 10, "tag": "NAME", "value": "Josh Bass" } ]
src/client/components/orders/OrderView.coffee
jbass86/Aroma
0
# Author: Josh Bass React = require("react"); mathjs = require("mathjs"); CreateOrder = require("./OrderCreate.coffee"); OrderTable = require("./OrderTable.coffee"); Filters = require("client/components/filters/FiltersView.coffee"); require("./res/styles/orders.scss") module.exports = React.createClass getInitialState: -> @filter_types = [{key: "order_date", name: "Order Date", type: "date"}]; {}; componentDidMount: -> render: -> <div className="common-view"> <div className="section-title"> Orders </div> <CreateOrder customerUpdate={@updateOrder} order_model={@props.order_model} /> <Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="order_filters" /> <OrderTable /> </div> updateOrder: ->
225314
# Author: <NAME> React = require("react"); mathjs = require("mathjs"); CreateOrder = require("./OrderCreate.coffee"); OrderTable = require("./OrderTable.coffee"); Filters = require("client/components/filters/FiltersView.coffee"); require("./res/styles/orders.scss") module.exports = React.createClass getInitialState: -> @filter_types = [{key: "order_date", name: "Order Date", type: "date"}]; {}; componentDidMount: -> render: -> <div className="common-view"> <div className="section-title"> Orders </div> <CreateOrder customerUpdate={@updateOrder} order_model={@props.order_model} /> <Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="order_filters" /> <OrderTable /> </div> updateOrder: ->
true
# Author: PI:NAME:<NAME>END_PI React = require("react"); mathjs = require("mathjs"); CreateOrder = require("./OrderCreate.coffee"); OrderTable = require("./OrderTable.coffee"); Filters = require("client/components/filters/FiltersView.coffee"); require("./res/styles/orders.scss") module.exports = React.createClass getInitialState: -> @filter_types = [{key: "order_date", name: "Order Date", type: "date"}]; {}; componentDidMount: -> render: -> <div className="common-view"> <div className="section-title"> Orders </div> <CreateOrder customerUpdate={@updateOrder} order_model={@props.order_model} /> <Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="order_filters" /> <OrderTable /> </div> updateOrder: ->
[ { "context": "# **Author:** Peter Urbak<br/>\n# **Version:** 2013-02-12\n\nroot = exports ? ", "end": 25, "score": 0.9998563528060913, "start": 14, "tag": "NAME", "value": "Peter Urbak" } ]
client_src/constants.coffee
dragonwasrobot/gesture-recognition
2
# **Author:** Peter Urbak<br/> # **Version:** 2013-02-12 root = exports ? window # `App.Constants` contains application-wide constants. # This class should not be instantiated. class App.Constants # ## Constants @OBJECT_ADD: "object:add" @OBJECT_UPDATE: "object:update" @OBJECT_REMOVE: "object:remove" @CURSOR_ADD: "cursor:add" @CURSOR_UPDATE: "cursor:update" @CURSOR_REMOVE: "cursor:remove" @FINGER_SINGLE_TAP: "finger:single-tap" @FINGER_DOUBLE_TAP: "finger:double-tap" @FINGER_FLICK: "finger:flick" @FINGER_HOLD_FLICK: "finger:hold-flick" @OBJECT_SHAKE: "object:shake" # ## Constructors constructor: () -> # So this is a hack throw new Error("App.Constants should not be instantiated");
2027
# **Author:** <NAME><br/> # **Version:** 2013-02-12 root = exports ? window # `App.Constants` contains application-wide constants. # This class should not be instantiated. class App.Constants # ## Constants @OBJECT_ADD: "object:add" @OBJECT_UPDATE: "object:update" @OBJECT_REMOVE: "object:remove" @CURSOR_ADD: "cursor:add" @CURSOR_UPDATE: "cursor:update" @CURSOR_REMOVE: "cursor:remove" @FINGER_SINGLE_TAP: "finger:single-tap" @FINGER_DOUBLE_TAP: "finger:double-tap" @FINGER_FLICK: "finger:flick" @FINGER_HOLD_FLICK: "finger:hold-flick" @OBJECT_SHAKE: "object:shake" # ## Constructors constructor: () -> # So this is a hack throw new Error("App.Constants should not be instantiated");
true
# **Author:** PI:NAME:<NAME>END_PI<br/> # **Version:** 2013-02-12 root = exports ? window # `App.Constants` contains application-wide constants. # This class should not be instantiated. class App.Constants # ## Constants @OBJECT_ADD: "object:add" @OBJECT_UPDATE: "object:update" @OBJECT_REMOVE: "object:remove" @CURSOR_ADD: "cursor:add" @CURSOR_UPDATE: "cursor:update" @CURSOR_REMOVE: "cursor:remove" @FINGER_SINGLE_TAP: "finger:single-tap" @FINGER_DOUBLE_TAP: "finger:double-tap" @FINGER_FLICK: "finger:flick" @FINGER_HOLD_FLICK: "finger:hold-flick" @OBJECT_SHAKE: "object:shake" # ## Constructors constructor: () -> # So this is a hack throw new Error("App.Constants should not be instantiated");
[ { "context": "SnippetsDisabled: []\n projectHome: \"C:\\\\Users\\\\Jordan\\\\Desktop\\\\code\"\n telemetryConsent: \"limited\"\n ", "end": 195, "score": 0.7401601076126099, "start": 189, "tag": "NAME", "value": "Jordan" } ]
editors/atom/config/config.cson
jdtaylor7/workflow
2
"*": "autocomplete-plus": enableAutoActivation: false core: packagesWithKeymapsDisabled: [ "latex" ] packagesWithSnippetsDisabled: [] projectHome: "C:\\Users\\Jordan\\Desktop\\code" telemetryConsent: "limited" themes: [ "one-dark-ui" "base16-tomorrow-dark-theme" ] uriHandlerRegistration: "never" useTreeSitterParsers: false editor: fontSize: 15 scrollPastEnd: true showIndentGuide: true tabLength: 4 "exception-reporting": userId: "4e5d60eb-0f0c-4006-9b96-ae2fdf889161" github: {} latex: buildOnSave: true opener: "pdf-view" texPath: "$PATH" latextools: viewer: "pdf-view" win32: distro: "texlive" "pdf-view": {} pigments: markerType: "native-dot" script: stopOnRerun: true "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false
136521
"*": "autocomplete-plus": enableAutoActivation: false core: packagesWithKeymapsDisabled: [ "latex" ] packagesWithSnippetsDisabled: [] projectHome: "C:\\Users\\<NAME>\\Desktop\\code" telemetryConsent: "limited" themes: [ "one-dark-ui" "base16-tomorrow-dark-theme" ] uriHandlerRegistration: "never" useTreeSitterParsers: false editor: fontSize: 15 scrollPastEnd: true showIndentGuide: true tabLength: 4 "exception-reporting": userId: "4e5d60eb-0f0c-4006-9b96-ae2fdf889161" github: {} latex: buildOnSave: true opener: "pdf-view" texPath: "$PATH" latextools: viewer: "pdf-view" win32: distro: "texlive" "pdf-view": {} pigments: markerType: "native-dot" script: stopOnRerun: true "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false
true
"*": "autocomplete-plus": enableAutoActivation: false core: packagesWithKeymapsDisabled: [ "latex" ] packagesWithSnippetsDisabled: [] projectHome: "C:\\Users\\PI:NAME:<NAME>END_PI\\Desktop\\code" telemetryConsent: "limited" themes: [ "one-dark-ui" "base16-tomorrow-dark-theme" ] uriHandlerRegistration: "never" useTreeSitterParsers: false editor: fontSize: 15 scrollPastEnd: true showIndentGuide: true tabLength: 4 "exception-reporting": userId: "4e5d60eb-0f0c-4006-9b96-ae2fdf889161" github: {} latex: buildOnSave: true opener: "pdf-view" texPath: "$PATH" latextools: viewer: "pdf-view" win32: distro: "texlive" "pdf-view": {} pigments: markerType: "native-dot" script: stopOnRerun: true "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false
[ { "context": "omponent: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 10 } }\n { name: 'about'", "end": 2066, "score": 0.728005588054657, "start": 2059, "tag": "USERNAME", "value": "partner" }, { "context": ": 'news', component: NewsView, options: { partner: @partner }, title: 'News' }\n {\n name: 'sho", "end": 2241, "score": 0.6830226182937622, "start": 2233, "tag": "USERNAME", "value": "@partner" }, { "context": "Carousel\n options:\n partner: @partner\n collection: new PartnerShows\n ", "end": 2389, "score": 0.8218295574188232, "start": 2382, "tag": "USERNAME", "value": "partner" }, { "context": " fetchOptions: [\n { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, ", "end": 2495, "score": 0.7270315885543823, "start": 2487, "tag": "USERNAME", "value": "@partner" }, { "context": " 9, sort: 'start_at' }\n { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: f", "end": 2619, "score": 0.4910435378551483, "start": 2619, "tag": "USERNAME", "value": "" }, { "context": "ef()}/shows\"\n }\n {\n name: 'fair-booths'\n component: FixedCellsCountCarou", "end": 2885, "score": 0.47321817278862, "start": 2881, "tag": "NAME", "value": "fair" }, { "context": "}/shows\"\n }\n {\n name: 'fair-booths'\n component: FixedCellsCountCarousel\n ", "end": 2892, "score": 0.6113682389259338, "start": 2886, "tag": "USERNAME", "value": "booths" }, { "context": "ntCarousel\n options:\n partner: @partner\n collection: new PartnerShows\n ", "end": 2987, "score": 0.8052468299865723, "start": 2979, "tag": "USERNAME", "value": "@partner" }, { "context": " fetchOptions: [\n { partner_id: @partner.get('_id'), status: 'current', at_a_fair: ", "end": 3084, "score": 0.6674432158470154, "start": 3084, "tag": "USERNAME", "value": "" }, { "context": " component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined }\n ", "end": 3544, "score": 0.8162428736686707, "start": 3537, "tag": "USERNAME", "value": "partner" }, { "context": "ntCarousel\n options:\n partner: @partner\n collection: new Articles\n ", "end": 3717, "score": 0.8226586580276489, "start": 3709, "tag": "USERNAME", "value": "@partner" }, { "context": "', component: ArtistsGridView, options: { partner: @partner } }\n { name: 'locations', title: 'Location", "end": 14464, "score": 0.9632208347320557, "start": 14456, "tag": "USERNAME", "value": "@partner" }, { "context": "ations', component: undefined, options: { partner: @partner } }\n ]\n", "end": 14568, "score": 0.9234285354614258, "start": 14560, "tag": "USERNAME", "value": "@partner" } ]
src/desktop/apps/partner2/test/client/overview_layout_factory.coffee
kanaabe/force
1
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' Artworks = require '../../../../collections/artworks.coffee' PartnerShows = require '../../../../collections/partner_shows.coffee' Articles = require '../../../../collections/articles.coffee' Profile = require '../../../../models/profile.coffee' Partner = require '../../../../models/partner.coffee' { resolve } = require 'path' { fabricate } = require 'antigravity' factory = rewire '../../client/overview_layout_factory.coffee' factory.__set__ 'HeroShowsCarousel', HeroShowsCarousel = sinon.stub() factory.__set__ 'HeroArtworksCarousel', HeroArtworksCarousel = sinon.stub() factory.__set__ 'ArtistsListView', ArtistsListView = sinon.stub() factory.__set__ 'ArtistsGridView', ArtistsGridView = sinon.stub() factory.__set__ 'aboutTemplate', aboutTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'NewsView', NewsView = sinon.stub() factory.__set__ 'FixedCellsCountCarousel', FixedCellsCountCarousel = sinon.stub() factory.__set__ 'showsTemplate', showsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'fairBoothsTemplate', fairBoothsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'articlesTemplate', articlesTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'ShowsGrid', ShowsGrid = sinon.stub() factory.__set__ 'LocationsView', LocationsView = sinon.stub() describe 'overview_layout_factory', -> describe 'gallery_three', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full_bil' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_three', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 10 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] describe 'gallery_two', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_two', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 2 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'does not return the "Artists" module when display_artists_section is false', -> @partner.set display_artists_section: false modules = factory(@partner, @profile) modules.should.containDeep [{ name: 'artists', component: undefined }] describe 'gallery_one', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_one' it 'returns modules properly', -> factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 1 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: partner: @partner } ] describe 'gallery_default', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: false it 'returns modules without artists for fair partners', -> factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 0 numberOfShows: 6 seeAll: false heading: 'Shows & Fair Booths' } { name: 'artists', component: undefined, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: LocationsView, options: { partner: @partner } } ] it 'returns modules properly otherwise', -> @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: true factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 1 numberOfShows: 6 seeAll: true heading: undefined } { name: 'artists', component: ArtistsGridView, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: undefined, options: { partner: @partner } } ]
59893
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' Artworks = require '../../../../collections/artworks.coffee' PartnerShows = require '../../../../collections/partner_shows.coffee' Articles = require '../../../../collections/articles.coffee' Profile = require '../../../../models/profile.coffee' Partner = require '../../../../models/partner.coffee' { resolve } = require 'path' { fabricate } = require 'antigravity' factory = rewire '../../client/overview_layout_factory.coffee' factory.__set__ 'HeroShowsCarousel', HeroShowsCarousel = sinon.stub() factory.__set__ 'HeroArtworksCarousel', HeroArtworksCarousel = sinon.stub() factory.__set__ 'ArtistsListView', ArtistsListView = sinon.stub() factory.__set__ 'ArtistsGridView', ArtistsGridView = sinon.stub() factory.__set__ 'aboutTemplate', aboutTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'NewsView', NewsView = sinon.stub() factory.__set__ 'FixedCellsCountCarousel', FixedCellsCountCarousel = sinon.stub() factory.__set__ 'showsTemplate', showsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'fairBoothsTemplate', fairBoothsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'articlesTemplate', articlesTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'ShowsGrid', ShowsGrid = sinon.stub() factory.__set__ 'LocationsView', LocationsView = sinon.stub() describe 'overview_layout_factory', -> describe 'gallery_three', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full_bil' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_three', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 10 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: '<NAME>-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] describe 'gallery_two', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_two', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 2 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'does not return the "Artists" module when display_artists_section is false', -> @partner.set display_artists_section: false modules = factory(@partner, @profile) modules.should.containDeep [{ name: 'artists', component: undefined }] describe 'gallery_one', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_one' it 'returns modules properly', -> factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 1 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: partner: @partner } ] describe 'gallery_default', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: false it 'returns modules without artists for fair partners', -> factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 0 numberOfShows: 6 seeAll: false heading: 'Shows & Fair Booths' } { name: 'artists', component: undefined, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: LocationsView, options: { partner: @partner } } ] it 'returns modules properly otherwise', -> @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: true factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 1 numberOfShows: 6 seeAll: true heading: undefined } { name: 'artists', component: ArtistsGridView, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: undefined, options: { partner: @partner } } ]
true
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' Artworks = require '../../../../collections/artworks.coffee' PartnerShows = require '../../../../collections/partner_shows.coffee' Articles = require '../../../../collections/articles.coffee' Profile = require '../../../../models/profile.coffee' Partner = require '../../../../models/partner.coffee' { resolve } = require 'path' { fabricate } = require 'antigravity' factory = rewire '../../client/overview_layout_factory.coffee' factory.__set__ 'HeroShowsCarousel', HeroShowsCarousel = sinon.stub() factory.__set__ 'HeroArtworksCarousel', HeroArtworksCarousel = sinon.stub() factory.__set__ 'ArtistsListView', ArtistsListView = sinon.stub() factory.__set__ 'ArtistsGridView', ArtistsGridView = sinon.stub() factory.__set__ 'aboutTemplate', aboutTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'NewsView', NewsView = sinon.stub() factory.__set__ 'FixedCellsCountCarousel', FixedCellsCountCarousel = sinon.stub() factory.__set__ 'showsTemplate', showsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'fairBoothsTemplate', fairBoothsTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'articlesTemplate', articlesTemplate = sinon.stub().returns '<article></article>' factory.__set__ 'ShowsGrid', ShowsGrid = sinon.stub() factory.__set__ 'LocationsView', LocationsView = sinon.stub() describe 'overview_layout_factory', -> describe 'gallery_three', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full_bil' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_three', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 10 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'PI:NAME:<NAME>END_PI-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] describe 'gallery_two', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_two', display_artists_section: true it 'returns modules properly for profile_banner_display: "Shows", profile_artists_layout: "Grid"', -> @partner.set profile_banner_display: 'Shows' @partner.set profile_artists_layout: 'Grid' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 2 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: { partner: @partner }, title: undefined, viewAll: undefined } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'returns modules properly for profile_banner_display: "Artworks", profile_artists_layout: "List"', -> @partner.set profile_banner_display: 'Artworks' @partner.set profile_artists_layout: 'List' factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroArtworksCarousel, options: { partner: @partner } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'news', component: NewsView, options: { partner: @partner }, title: 'News' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsListView, options: { partner: @partner }, title: 'Artists', viewAll: "#{@partner.href()}/artists" } { name: 'articles' component: FixedCellsCountCarousel options: partner: @partner collection: new Articles fetchOptions: partner_id: @partner.get('_id'), published: true, limit: 9, sort: '-published_at' template: articlesTemplate title: 'Articles' viewAll: "#{@partner.href()}/articles" } ] it 'does not return the "Artists" module when display_artists_section is false', -> @partner.set display_artists_section: false modules = factory(@partner, @profile) modules.should.containDeep [{ name: 'artists', component: undefined }] describe 'gallery_one', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_one' it 'returns modules properly', -> factory(@partner, @profile).should.eql [ { name: 'hero', component: HeroShowsCarousel, options: { partner: @partner, maxNumberOfShows: 1 } } { name: 'about', template: '<article></article>', title: 'About' } { name: 'shows', component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: false, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: false, displayable: true, size: 9, sort: '-end_at' } ] template: showsTemplate title: 'Shows' viewAll: "#{@partner.href()}/shows" } { name: 'fair-booths' component: FixedCellsCountCarousel options: partner: @partner collection: new PartnerShows fetchOptions: [ { partner_id: @partner.get('_id'), status: 'current', at_a_fair: true, displayable: true, size: 9, sort: 'start_at' } { partner_id: @partner.get('_id'), status: 'closed', at_a_fair: true, displayable: true, size: 9, sort: '-end_at' } ] template: fairBoothsTemplate title: 'Fair Booths' viewAll: "#{@partner.href()}/shows" } { name: 'artists', component: ArtistsGridView, options: partner: @partner } ] describe 'gallery_default', -> beforeEach -> @profile = new Profile fabricate 'partner_profile', full_bio: 'full bio here' @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: false it 'returns modules without artists for fair partners', -> factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 0 numberOfShows: 6 seeAll: false heading: 'Shows & Fair Booths' } { name: 'artists', component: undefined, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: LocationsView, options: { partner: @partner } } ] it 'returns modules properly otherwise', -> @partner = new Partner fabricate 'partner', profile_layout: 'gallery_default', claimed: true factory(@partner, @profile).should.eql [ { name: 'shows' component: ShowsGrid options: partner: @partner isCombined: true numberOfFeatured: 1 numberOfShows: 6 seeAll: true heading: undefined } { name: 'artists', component: ArtistsGridView, options: { partner: @partner } } { name: 'locations', title: 'Locations', component: undefined, options: { partner: @partner } } ]
[ { "context": "Things = [{\n \"id\": 1,\n \"body\": \"Geppetto, a poor old wood carver, was making a puppet from", "end": 452, "score": 0.9273120760917664, "start": 444, "tag": "NAME", "value": "Geppetto" }, { "context": "y,” he said to the puppet, “and I shall call you ‘Pinocchio’.” He worked for hours, carefully carving each de", "end": 603, "score": 0.9540944695472717, "start": 594, "tag": "NAME", "value": "Pinocchio" }, { "context": "lded, “Stop that at once !” “I won’t stop !” cried Pinocchio.\",\n \"comments\": [\n {\n ", "end": 829, "score": 0.5607642531394958, "start": 824, "tag": "NAME", "value": "Pinoc" }, { "context": "he puppet. “You’ve given me a mouth to talk with.” Pinocchio rose to his feet and danced on the table top. “Lo", "end": 1129, "score": 0.7024406790733337, "start": 1120, "tag": "NAME", "value": "Pinocchio" }, { "context": "\n {\n \"id\": 3,\n \"body\": \"“Pinocchio, this is not the time to dance,” Geppetto explain", "end": 1428, "score": 0.8182205557823181, "start": 1419, "tag": "NAME", "value": "Pinocchio" }, { "context": "t Master. Then he noticed how much the crowd liked Pinocchio. He did not say anything and let Pinocchio ", "end": 1910, "score": 0.6639575958251953, "start": 1907, "tag": "NAME", "value": "Pin" }, { "context": " earned five copper coins,” the Puppet Master told Pinocchio.\",\n \"comments\": [\n {\n ", "end": 2033, "score": 0.5599355101585388, "start": 2030, "tag": "NAME", "value": "Pin" } ]
app/scripts/controllers/post.coffee
djbuen/matchmove
0
'use strict' ###* # @ngdoc function # @name angularSlickApp.controller:PostCtrl # @description # # PostCtrl # Controller of the angularSlickApp ### angular.module('slick') .controller 'PostCtrl', ($scope, $cookies, $cookieStore, $routeParams) -> console.log($routeParams) $scope.post_id = $routeParams.id $scope.post_body = "" $scope.comment_body = "" $scope.awesomeThings = [{ "id": 1, "body": "Geppetto, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘Pinocchio’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried Pinocchio.", "comments": [ { "id": 1, "comment": "Ohh poor boy pinocchio...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” Pinocchio rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "Pinocchio tries to rationalize" } ] }, { "id": 3, "body": "“Pinocchio, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked Pinocchio. He did not say anything and let Pinocchio stay. “Here, you’ve earned five copper coins,” the Puppet Master told Pinocchio.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] $scope.posts = {} i=0 while i < $scope.awesomeThings.length $scope.posts[$scope.awesomeThings[i].id] = $scope.awesomeThings[i] i++ console.log($scope.posts) $scope.addPost = (body)-> last = $scope.awesomeThings.length console.log($scope.awesomeThings[last-1].id) $scope.awesomeThings.push({post_id: $scope.awesomeThings[last-1].id + 1, body: body, comments: []}) $cookieStore.put('test', $scope.awesomeThings); x = $cookieStore.get('test') console.log(x) $scope.addComment = (comments) -> console.log(comments) console.log($scope.comment_body) comments.push({comment: $scope.comment_body})
123216
'use strict' ###* # @ngdoc function # @name angularSlickApp.controller:PostCtrl # @description # # PostCtrl # Controller of the angularSlickApp ### angular.module('slick') .controller 'PostCtrl', ($scope, $cookies, $cookieStore, $routeParams) -> console.log($routeParams) $scope.post_id = $routeParams.id $scope.post_body = "" $scope.comment_body = "" $scope.awesomeThings = [{ "id": 1, "body": "<NAME>, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘<NAME>’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried <NAME>chio.", "comments": [ { "id": 1, "comment": "Ohh poor boy pinocchio...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” <NAME> rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "Pinocchio tries to rationalize" } ] }, { "id": 3, "body": "“<NAME>, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked <NAME>occhio. He did not say anything and let Pinocchio stay. “Here, you’ve earned five copper coins,” the Puppet Master told <NAME>occhio.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] $scope.posts = {} i=0 while i < $scope.awesomeThings.length $scope.posts[$scope.awesomeThings[i].id] = $scope.awesomeThings[i] i++ console.log($scope.posts) $scope.addPost = (body)-> last = $scope.awesomeThings.length console.log($scope.awesomeThings[last-1].id) $scope.awesomeThings.push({post_id: $scope.awesomeThings[last-1].id + 1, body: body, comments: []}) $cookieStore.put('test', $scope.awesomeThings); x = $cookieStore.get('test') console.log(x) $scope.addComment = (comments) -> console.log(comments) console.log($scope.comment_body) comments.push({comment: $scope.comment_body})
true
'use strict' ###* # @ngdoc function # @name angularSlickApp.controller:PostCtrl # @description # # PostCtrl # Controller of the angularSlickApp ### angular.module('slick') .controller 'PostCtrl', ($scope, $cookies, $cookieStore, $routeParams) -> console.log($routeParams) $scope.post_id = $routeParams.id $scope.post_body = "" $scope.comment_body = "" $scope.awesomeThings = [{ "id": 1, "body": "PI:NAME:<NAME>END_PI, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘PI:NAME:<NAME>END_PI’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried PI:NAME:<NAME>END_PIchio.", "comments": [ { "id": 1, "comment": "Ohh poor boy pinocchio...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” PI:NAME:<NAME>END_PI rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "Pinocchio tries to rationalize" } ] }, { "id": 3, "body": "“PI:NAME:<NAME>END_PI, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked PI:NAME:<NAME>END_PIocchio. He did not say anything and let Pinocchio stay. “Here, you’ve earned five copper coins,” the Puppet Master told PI:NAME:<NAME>END_PIocchio.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] $scope.posts = {} i=0 while i < $scope.awesomeThings.length $scope.posts[$scope.awesomeThings[i].id] = $scope.awesomeThings[i] i++ console.log($scope.posts) $scope.addPost = (body)-> last = $scope.awesomeThings.length console.log($scope.awesomeThings[last-1].id) $scope.awesomeThings.push({post_id: $scope.awesomeThings[last-1].id + 1, body: body, comments: []}) $cookieStore.put('test', $scope.awesomeThings); x = $cookieStore.get('test') console.log(x) $scope.addComment = (comments) -> console.log(comments) console.log($scope.comment_body) comments.push({comment: $scope.comment_body})
[ { "context": "'name\\' | join \\', \\'\"></div>',\n posts: [\n Batman\n name: 'one'\n comments: 10\n , Ba", "end": 4548, "score": 0.8016042709350586, "start": 4542, "tag": "NAME", "value": "Batman" }, { "context": "</div>',\n posts: [\n Batman\n name: 'one'\n comments: 10\n , Batman\n name: ", "end": 4567, "score": 0.8758162260055542, "start": 4564, "tag": "NAME", "value": "one" }, { "context": "man\n name: 'one'\n comments: 10\n , Batman\n name: 'two'\n comments: 20\n ]", "end": 4599, "score": 0.6585772037506104, "start": 4596, "tag": "NAME", "value": "Bat" }, { "context": "\n comments: 10\n , Batman\n name: 'two'\n comments: 20\n ]\n , (node) ->\n equ", "end": 4621, "score": 0.9465779662132263, "start": 4618, "tag": "NAME", "value": "two" } ]
tests/batman/view/filter_execution_test.coffee
nickjs/batman
1
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View filter execution' asyncTest 'get', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo | get \'bar\'"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get dotted syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo.bar"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[\'bar\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with looked-up key', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with complex key', 1, -> context = Batman complex: { key: 'bar'} foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[complex.key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with chained dot lookup', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: { baz: "qux" }}) helpers.render '<div data-bind="foo[key].baz"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get chained short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: {baz: "qux"}}) helpers.render '<div data-bind="foo[\'bar\'][\'baz\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'hideously complex chain of property lookups', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h"></div>', context, (node) -> equals node.html(), "value" QUnit.start() asyncTest 'hideously complex chain of property lookups with filters', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' spyOn Batman.Filters, 'spy' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h | spy"></div>', context, (node) -> equal Batman.Filters.spy.lastCallArguments[0], 'value' delete Batman.Filters.spy QUnit.start() asyncTest 'truncate', 2, -> helpers.render '<div data-bind="foo | truncate 5"></div>', foo: 'your mother was a hampster' , (node) -> equals node.html(), "yo..." helpers.render '<div data-bind="foo.bar | truncate 5, \'\'"></div>', foo: Batman bar: 'your mother was a hampster' , (node) -> equals node.html(), "your " QUnit.start() asyncTest 'prepend', 1, -> helpers.render '<div data-bind="foo | prepend \'special-\'"></div>', foo: 'bar' , (node) -> equals node.html(), "special-bar" QUnit.start() asyncTest 'append', 1, -> helpers.render '<div data-bind="foo | append \'-special\'"></div>', foo: 'bar' , (node) -> equals node.html(), "bar-special" QUnit.start() asyncTest 'downcase', 1, -> helpers.render '<div data-bind="foo | downcase"></div>', foo: 'BAR' , (node) -> equals node.html(), "bar" QUnit.start() asyncTest 'upcase', 1, -> helpers.render '<div data-bind="foo | upcase"></div>', foo: 'bar' , (node) -> equals node.html(), "BAR" QUnit.start() asyncTest 'join', 2, -> helpers.render '<div data-bind="foo | join"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "abc" helpers.render '<div data-bind="foo | join \'|\'"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "a|b|c" QUnit.start() asyncTest 'sort', 1, -> helpers.render '<div data-bind="foo | sort | join"></div>', foo: ['b', 'c', 'a', '1'] , (node) -> equals node.html(), "1abc" QUnit.start() asyncTest 'not', 1, -> helpers.render '<div data-showif="foo | not"></div>', foo: true , (node) -> equals node[0].style.display, "none" QUnit.start() asyncTest 'map', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: [ Batman name: 'one' comments: 10 , Batman name: 'two' comments: 20 ] , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'map with a numeric key', 1, -> helpers.render '<div data-bind="counts | map 1 | join \', \'"></div>', counts: [ [1, 2, 3] [4, 5, 6] ] , (node) -> equals node.html(), "2, 5" QUnit.start() asyncTest 'map over a set', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: new Batman.Set( Batman name: 'one' comments: 10 , Batman name: 'two' comments: 20 ) , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'meta', 2, -> context = Batman foo: Batman meta: get: spy = createSpy().whichReturns("something") helpers.render '<div data-bind="foo | meta \'bar\'"></div>', context, (node) -> equals node.html(), "something" deepEqual spy.lastCallArguments, ['bar'] QUnit.start() asyncTest 'meta binding to a hash', 2, -> context = Batman foo: new Batman.Hash(bar: "qux") helpers.render '<div data-bind="foo | meta \'length\'"></div>', context, (node) -> equals node.html(), "1" context.get('foo').set('corge', 'test') delay => equals node.html(), "2" QUnit.module "Batman.View filter value and parameter parsing" setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, false] QUnit.start() QUnit.module "Batman.View user defined filter execution" asyncTest 'should render a user defined filter', 3, -> Batman.Filters['test'] = spy = createSpy().whichReturns("testValue") ctx = Batman foo: 'bar' bar: 'baz' helpers.render '<div data-bind="foo | test 1, \'baz\'"></div>', ctx, (node) -> equals node.html(), "testValue" equals spy.lastCallContext, ctx deepEqual spy.lastCallArguments, ['bar', 1, 'baz'] delete Batman.Filters.test QUnit.start()
85288
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View filter execution' asyncTest 'get', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo | get \'bar\'"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get dotted syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo.bar"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[\'bar\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with looked-up key', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with complex key', 1, -> context = Batman complex: { key: 'bar'} foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[complex.key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with chained dot lookup', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: { baz: "qux" }}) helpers.render '<div data-bind="foo[key].baz"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get chained short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: {baz: "qux"}}) helpers.render '<div data-bind="foo[\'bar\'][\'baz\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'hideously complex chain of property lookups', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h"></div>', context, (node) -> equals node.html(), "value" QUnit.start() asyncTest 'hideously complex chain of property lookups with filters', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' spyOn Batman.Filters, 'spy' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h | spy"></div>', context, (node) -> equal Batman.Filters.spy.lastCallArguments[0], 'value' delete Batman.Filters.spy QUnit.start() asyncTest 'truncate', 2, -> helpers.render '<div data-bind="foo | truncate 5"></div>', foo: 'your mother was a hampster' , (node) -> equals node.html(), "yo..." helpers.render '<div data-bind="foo.bar | truncate 5, \'\'"></div>', foo: Batman bar: 'your mother was a hampster' , (node) -> equals node.html(), "your " QUnit.start() asyncTest 'prepend', 1, -> helpers.render '<div data-bind="foo | prepend \'special-\'"></div>', foo: 'bar' , (node) -> equals node.html(), "special-bar" QUnit.start() asyncTest 'append', 1, -> helpers.render '<div data-bind="foo | append \'-special\'"></div>', foo: 'bar' , (node) -> equals node.html(), "bar-special" QUnit.start() asyncTest 'downcase', 1, -> helpers.render '<div data-bind="foo | downcase"></div>', foo: 'BAR' , (node) -> equals node.html(), "bar" QUnit.start() asyncTest 'upcase', 1, -> helpers.render '<div data-bind="foo | upcase"></div>', foo: 'bar' , (node) -> equals node.html(), "BAR" QUnit.start() asyncTest 'join', 2, -> helpers.render '<div data-bind="foo | join"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "abc" helpers.render '<div data-bind="foo | join \'|\'"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "a|b|c" QUnit.start() asyncTest 'sort', 1, -> helpers.render '<div data-bind="foo | sort | join"></div>', foo: ['b', 'c', 'a', '1'] , (node) -> equals node.html(), "1abc" QUnit.start() asyncTest 'not', 1, -> helpers.render '<div data-showif="foo | not"></div>', foo: true , (node) -> equals node[0].style.display, "none" QUnit.start() asyncTest 'map', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: [ <NAME> name: '<NAME>' comments: 10 , <NAME>man name: '<NAME>' comments: 20 ] , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'map with a numeric key', 1, -> helpers.render '<div data-bind="counts | map 1 | join \', \'"></div>', counts: [ [1, 2, 3] [4, 5, 6] ] , (node) -> equals node.html(), "2, 5" QUnit.start() asyncTest 'map over a set', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: new Batman.Set( Batman name: 'one' comments: 10 , Batman name: 'two' comments: 20 ) , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'meta', 2, -> context = Batman foo: Batman meta: get: spy = createSpy().whichReturns("something") helpers.render '<div data-bind="foo | meta \'bar\'"></div>', context, (node) -> equals node.html(), "something" deepEqual spy.lastCallArguments, ['bar'] QUnit.start() asyncTest 'meta binding to a hash', 2, -> context = Batman foo: new Batman.Hash(bar: "qux") helpers.render '<div data-bind="foo | meta \'length\'"></div>', context, (node) -> equals node.html(), "1" context.get('foo').set('corge', 'test') delay => equals node.html(), "2" QUnit.module "Batman.View filter value and parameter parsing" setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, false] QUnit.start() QUnit.module "Batman.View user defined filter execution" asyncTest 'should render a user defined filter', 3, -> Batman.Filters['test'] = spy = createSpy().whichReturns("testValue") ctx = Batman foo: 'bar' bar: 'baz' helpers.render '<div data-bind="foo | test 1, \'baz\'"></div>', ctx, (node) -> equals node.html(), "testValue" equals spy.lastCallContext, ctx deepEqual spy.lastCallArguments, ['bar', 1, 'baz'] delete Batman.Filters.test QUnit.start()
true
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View filter execution' asyncTest 'get', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo | get \'bar\'"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get dotted syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo.bar"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[\'bar\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with looked-up key', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with complex key', 1, -> context = Batman complex: { key: 'bar'} foo: new Batman.Hash({bar: "qux"}) helpers.render '<div data-bind="foo[complex.key]"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get short syntax with chained dot lookup', 1, -> context = Batman key: 'bar' foo: new Batman.Hash({bar: { baz: "qux" }}) helpers.render '<div data-bind="foo[key].baz"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'get chained short syntax', 1, -> context = Batman foo: new Batman.Hash({bar: {baz: "qux"}}) helpers.render '<div data-bind="foo[\'bar\'][\'baz\']"></div>', context, (node) -> equals node.html(), "qux" QUnit.start() asyncTest 'hideously complex chain of property lookups', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h"></div>', context, (node) -> equals node.html(), "value" QUnit.start() asyncTest 'hideously complex chain of property lookups with filters', 1, -> context = Batman ss: { ee: 'c' } a: new Batman.Hash b: c: d: e: f: g: h: 'value' spyOn Batman.Filters, 'spy' helpers.render '<div data-bind="a.b[ss.ee].d[\'e\'][\'f\'].g.h | spy"></div>', context, (node) -> equal Batman.Filters.spy.lastCallArguments[0], 'value' delete Batman.Filters.spy QUnit.start() asyncTest 'truncate', 2, -> helpers.render '<div data-bind="foo | truncate 5"></div>', foo: 'your mother was a hampster' , (node) -> equals node.html(), "yo..." helpers.render '<div data-bind="foo.bar | truncate 5, \'\'"></div>', foo: Batman bar: 'your mother was a hampster' , (node) -> equals node.html(), "your " QUnit.start() asyncTest 'prepend', 1, -> helpers.render '<div data-bind="foo | prepend \'special-\'"></div>', foo: 'bar' , (node) -> equals node.html(), "special-bar" QUnit.start() asyncTest 'append', 1, -> helpers.render '<div data-bind="foo | append \'-special\'"></div>', foo: 'bar' , (node) -> equals node.html(), "bar-special" QUnit.start() asyncTest 'downcase', 1, -> helpers.render '<div data-bind="foo | downcase"></div>', foo: 'BAR' , (node) -> equals node.html(), "bar" QUnit.start() asyncTest 'upcase', 1, -> helpers.render '<div data-bind="foo | upcase"></div>', foo: 'bar' , (node) -> equals node.html(), "BAR" QUnit.start() asyncTest 'join', 2, -> helpers.render '<div data-bind="foo | join"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "abc" helpers.render '<div data-bind="foo | join \'|\'"></div>', foo: ['a', 'b', 'c'] , (node) -> equals node.html(), "a|b|c" QUnit.start() asyncTest 'sort', 1, -> helpers.render '<div data-bind="foo | sort | join"></div>', foo: ['b', 'c', 'a', '1'] , (node) -> equals node.html(), "1abc" QUnit.start() asyncTest 'not', 1, -> helpers.render '<div data-showif="foo | not"></div>', foo: true , (node) -> equals node[0].style.display, "none" QUnit.start() asyncTest 'map', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: [ PI:NAME:<NAME>END_PI name: 'PI:NAME:<NAME>END_PI' comments: 10 , PI:NAME:<NAME>END_PIman name: 'PI:NAME:<NAME>END_PI' comments: 20 ] , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'map with a numeric key', 1, -> helpers.render '<div data-bind="counts | map 1 | join \', \'"></div>', counts: [ [1, 2, 3] [4, 5, 6] ] , (node) -> equals node.html(), "2, 5" QUnit.start() asyncTest 'map over a set', 1, -> helpers.render '<div data-bind="posts | map \'name\' | join \', \'"></div>', posts: new Batman.Set( Batman name: 'one' comments: 10 , Batman name: 'two' comments: 20 ) , (node) -> equals node.html(), "one, two" QUnit.start() asyncTest 'meta', 2, -> context = Batman foo: Batman meta: get: spy = createSpy().whichReturns("something") helpers.render '<div data-bind="foo | meta \'bar\'"></div>', context, (node) -> equals node.html(), "something" deepEqual spy.lastCallArguments, ['bar'] QUnit.start() asyncTest 'meta binding to a hash', 2, -> context = Batman foo: new Batman.Hash(bar: "qux") helpers.render '<div data-bind="foo | meta \'length\'"></div>', context, (node) -> equals node.html(), "1" context.get('foo').set('corge', 'test') delay => equals node.html(), "2" QUnit.module "Batman.View filter value and parameter parsing" setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equals node.html(), "testValue" deepEqual @spy.lastCallArguments, [1, false] QUnit.start() QUnit.module "Batman.View user defined filter execution" asyncTest 'should render a user defined filter', 3, -> Batman.Filters['test'] = spy = createSpy().whichReturns("testValue") ctx = Batman foo: 'bar' bar: 'baz' helpers.render '<div data-bind="foo | test 1, \'baz\'"></div>', ctx, (node) -> equals node.html(), "testValue" equals spy.lastCallContext, ctx deepEqual spy.lastCallArguments, ['bar', 1, 'baz'] delete Batman.Filters.test QUnit.start()
[ { "context": "# /*\n# * mqtt-methods\n# * https://github.com/boomfly/mqtt-methods\n# * https://github.com/wolfeidau/mq", "end": 54, "score": 0.999508261680603, "start": 47, "tag": "USERNAME", "value": "boomfly" }, { "context": ".com/boomfly/mqtt-methods\n# * https://github.com/wolfeidau/mqtt-rpc\n# *\n# * Copyright (c) 2013 Mark Wolfe\n", "end": 101, "score": 0.9996946454048157, "start": 92, "tag": "USERNAME", "value": "wolfeidau" }, { "context": "om/wolfeidau/mqtt-rpc\n# *\n# * Copyright (c) 2013 Mark Wolfe\n# * Licensed under the MIT license.\n# */\nimport", "end": 150, "score": 0.9998719692230225, "start": 140, "tag": "NAME", "value": "Mark Wolfe" } ]
lib/client.coffee
boomfly/mqtt-methods
0
# /* # * mqtt-methods # * https://github.com/boomfly/mqtt-methods # * https://github.com/wolfeidau/mqtt-rpc # * # * Copyright (c) 2013 Mark Wolfe # * Licensed under the MIT license. # */ import crypto from 'crypto' import mqtt from 'mqtt' import mqttrouter from 'mqtt-router' import codecs from './codecs.js' import Debug from 'debug' debug = Debug('mqtt-methods:client') export default class Client constructor: (mqttclient) -> # default to JSON codec @codec = codecs.byName('json') @mqttclient = mqttclient or mqtt.createClient() @router = mqttrouter.wrap(mqttclient) @inFlight = {} _generator: () -> crypto.randomBytes(5).readUInt32BE(0).toString(16) _handleResponse: (topic, message) => msg = @codec.decode(message) id = msg._correlationId debug('handleResponse', topic, id, 'message', message) debug('inflight', @inFlight[id]) if id and @inFlight[id] @inFlight[id].cb(msg.err, msg.data) delete @inFlight[id] _sendMessage: (topic, message, cb) -> id = @_generator() debug('sendMessage', topic, id, message) @inFlight[id] = {cb: cb} message._correlationId = id @mqttclient.publish(topic, @codec.encode(message)) callRemote: (prefix, name, args, cb) -> replyTopic = prefix + '/' + name + '/reply' requestTopic = prefix + '/' + name + '/request' @router.subscribe(replyTopic, @_handleResponse) debug('callRemote', 'subscribe', replyTopic) @_sendMessage(requestTopic, args, cb) format: (format) -> @codec = codecs.byName(format)
17662
# /* # * mqtt-methods # * https://github.com/boomfly/mqtt-methods # * https://github.com/wolfeidau/mqtt-rpc # * # * Copyright (c) 2013 <NAME> # * Licensed under the MIT license. # */ import crypto from 'crypto' import mqtt from 'mqtt' import mqttrouter from 'mqtt-router' import codecs from './codecs.js' import Debug from 'debug' debug = Debug('mqtt-methods:client') export default class Client constructor: (mqttclient) -> # default to JSON codec @codec = codecs.byName('json') @mqttclient = mqttclient or mqtt.createClient() @router = mqttrouter.wrap(mqttclient) @inFlight = {} _generator: () -> crypto.randomBytes(5).readUInt32BE(0).toString(16) _handleResponse: (topic, message) => msg = @codec.decode(message) id = msg._correlationId debug('handleResponse', topic, id, 'message', message) debug('inflight', @inFlight[id]) if id and @inFlight[id] @inFlight[id].cb(msg.err, msg.data) delete @inFlight[id] _sendMessage: (topic, message, cb) -> id = @_generator() debug('sendMessage', topic, id, message) @inFlight[id] = {cb: cb} message._correlationId = id @mqttclient.publish(topic, @codec.encode(message)) callRemote: (prefix, name, args, cb) -> replyTopic = prefix + '/' + name + '/reply' requestTopic = prefix + '/' + name + '/request' @router.subscribe(replyTopic, @_handleResponse) debug('callRemote', 'subscribe', replyTopic) @_sendMessage(requestTopic, args, cb) format: (format) -> @codec = codecs.byName(format)
true
# /* # * mqtt-methods # * https://github.com/boomfly/mqtt-methods # * https://github.com/wolfeidau/mqtt-rpc # * # * Copyright (c) 2013 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # */ import crypto from 'crypto' import mqtt from 'mqtt' import mqttrouter from 'mqtt-router' import codecs from './codecs.js' import Debug from 'debug' debug = Debug('mqtt-methods:client') export default class Client constructor: (mqttclient) -> # default to JSON codec @codec = codecs.byName('json') @mqttclient = mqttclient or mqtt.createClient() @router = mqttrouter.wrap(mqttclient) @inFlight = {} _generator: () -> crypto.randomBytes(5).readUInt32BE(0).toString(16) _handleResponse: (topic, message) => msg = @codec.decode(message) id = msg._correlationId debug('handleResponse', topic, id, 'message', message) debug('inflight', @inFlight[id]) if id and @inFlight[id] @inFlight[id].cb(msg.err, msg.data) delete @inFlight[id] _sendMessage: (topic, message, cb) -> id = @_generator() debug('sendMessage', topic, id, message) @inFlight[id] = {cb: cb} message._correlationId = id @mqttclient.publish(topic, @codec.encode(message)) callRemote: (prefix, name, args, cb) -> replyTopic = prefix + '/' + name + '/reply' requestTopic = prefix + '/' + name + '/request' @router.subscribe(replyTopic, @_handleResponse) debug('callRemote', 'subscribe', replyTopic) @_sendMessage(requestTopic, args, cb) format: (format) -> @codec = codecs.byName(format)
[ { "context": "key: 'superscript'\n\npatterns: [\n # Matches superscript\n #\n # Exa", "end": 17, "score": 0.9828454256057739, "start": 6, "tag": "KEY", "value": "superscript" } ]
grammars/repositories/inlines/superscript-grammar.cson
andrewcarver/atom-language-asciidoc
45
key: 'superscript' patterns: [ # Matches superscript # # Examples # # ^superscript^ # name: 'markup.superscript.asciidoc' match: '(?<!\\\\)(\\[.+?\\])?((\\^)(\\S+?)(\\^))' captures: 1: name: 'markup.meta.super.attribute-list.asciidoc' 2: name: 'markup.super.superscript.asciidoc' 3: name: 'punctuation.definition.asciidoc' 5: name: 'punctuation.definition.asciidoc' ]
199849
key: '<KEY>' patterns: [ # Matches superscript # # Examples # # ^superscript^ # name: 'markup.superscript.asciidoc' match: '(?<!\\\\)(\\[.+?\\])?((\\^)(\\S+?)(\\^))' captures: 1: name: 'markup.meta.super.attribute-list.asciidoc' 2: name: 'markup.super.superscript.asciidoc' 3: name: 'punctuation.definition.asciidoc' 5: name: 'punctuation.definition.asciidoc' ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ # Matches superscript # # Examples # # ^superscript^ # name: 'markup.superscript.asciidoc' match: '(?<!\\\\)(\\[.+?\\])?((\\^)(\\S+?)(\\^))' captures: 1: name: 'markup.meta.super.attribute-list.asciidoc' 2: name: 'markup.super.superscript.asciidoc' 3: name: 'punctuation.definition.asciidoc' 5: name: 'punctuation.definition.asciidoc' ]
[ { "context": "based on jQuery Cookie plugin\n# Copyright (c) 2010 Klaus Hartl (stilbuero.de)\n# Dual licensed under the MIT and ", "end": 244, "score": 0.9998771548271179, "start": 233, "tag": "NAME", "value": "Klaus Hartl" } ]
bootstrap-tour.coffee
thebyrd/bootstrap-tour
1
# bootstrap-tour.js v0.0.2 # Copyright 2012 Gild, Inc. # # Free to use under the MIT license. # http://www.opensource.org/licenses/mit-license.php # References jQuery $ = jQuery # based on jQuery Cookie plugin # Copyright (c) 2010 Klaus Hartl (stilbuero.de) # Dual licensed under the MIT and GPL licenses: # http://www.opensource.org/licenses/mit-license.php # http://www.gnu.org/licenses/gpl.html cookie = (key, value, options) -> if arguments.length > 1 and String(value) isnt "[object Object]" options = jQuery.extend({}, options) options.expires = -1 unless value? if typeof options.expires is "number" days = options.expires t = options.expires = new Date() t.setDate t.getDate() + days value = String(value) return (document.cookie = [ encodeURIComponent(key), "=", (if options.raw then value else encodeURIComponent(value)), (if options.expires then "; expires=" + options.expires.toUTCString() else ""), (if options.path then "; path=" + options.path else ""), (if options.domain then "; domain=" + options.domain else ""), (if options.secure then "; secure" else "") ].join("")) options = value or {} result = undefined decode = (if options.raw then (s) -> s else decodeURIComponent) return (if (result = new RegExp("(?:^|; )" + encodeURIComponent(key) + "=([^;]*)").exec(document.cookie)) then decode(result[1]) else null) # Adds plugin object to jQuery $.fn.extend {}= featureTour: (options) -> # Default settings settings = tipContent: '#featureTourTipContent' # What is the ID of the <ol> you put the content in cookieMonster: false # true or false to control whether cookies are used cookieName: 'bootstrapFeatureTour' # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.mydomain.com' postRideCallback: $.noop # A method to call once the tour closes postStepCallback: $.noop # A method to call after each step nextOnClose: false # If cookies are enabled, increment the current step on close debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log('[bootstrap-tour]', msg) if settings.debug # returns current step stored in the cookie, or `1` if cookie disabled, no # cookie or invalid cookie value currentStep = -> return 1 unless settings.cookieMonster? current_cookie = cookie(settings.cookieName) # start from step 1 if there's no cookie set return 1 unless current_cookie? try return parseInt(current_cookie) catch e # start from step 1 if there cookie is invalid return 1 setCookieStep = (step) -> cookie(settings.cookieName, "#{step}", { expires: 365, domain: settings.cookieDomain }) if settings.cookieMonster return @each () -> $tipContent = $(settings.tipContent).first() unless $tipContent? log "can't find tipContent from selector: #{settings.tipContent}" $tips = $tipContent.find('li') first_step = currentStep() log "first step: #{first_step}" if first_step > $tips.length log 'tour already completed, skipping' return $tips.each (idx) -> # skip steps until we reach the first one if idx < (first_step - 1) log "skipping step: #{idx + 1}" return $li = $(@) tip_data = $li.data() return unless (target = tip_data['target'])? return unless ($target = $(target).first())? $target.popover trigger: 'manual' title: if tip_data['title']? then "#{tip_data['title']} <a class=\"tour-tip-close close\" data-touridx=\"#{idx + 1}\">&times;</a>" else null content: "<p>#{$li.html()}</p><p style=\"text-align: right\"><a href=\"#\" class=\"tour-tip-next btn btn-success\" data-touridx=\"#{idx + 1}\">#{if (idx + 1) < $tips.length then 'Next <i class="icon-chevron-right icon-white"></i>' else '<i class="icon-ok icon-white"></i> Done'}</a></p>" placement: tip_data['placement'] || 'right' # save the target element in the tip node $li.data('target', $target) # show the first tip $target.popover('show') if idx == (first_step - 1) # handle the close button $('a.tour-tip-close').live 'click', -> current_step = $(@).data('touridx') $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') setCookieStep(current_step + 1) if settings.nextOnClose # handle the next and done buttons $('a.tour-tip-next').live 'click', -> current_step = $(@).data('touridx') log "current step: #{current_step}" $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') settings.postStepCallback($(@).data('touridx')) if settings.postStepCallback != $.noop next_tip = $(settings.tipContent).first().find("li:nth-child(#{current_step + 1})")?.data('target') setCookieStep(current_step + 1) if next_tip? next_tip_id = '#' + next_tip.attr('id'); targetOffset = $(next_tip_id).offset().top - 300; $('html, body').animate({scrollTop: targetOffset}, 1000) next_tip.popover('show') return false #so that href will get ignored else # last tip settings.postRideCallback() if settings.postRideCallback != $.noop
220802
# bootstrap-tour.js v0.0.2 # Copyright 2012 Gild, Inc. # # Free to use under the MIT license. # http://www.opensource.org/licenses/mit-license.php # References jQuery $ = jQuery # based on jQuery Cookie plugin # Copyright (c) 2010 <NAME> (stilbuero.de) # Dual licensed under the MIT and GPL licenses: # http://www.opensource.org/licenses/mit-license.php # http://www.gnu.org/licenses/gpl.html cookie = (key, value, options) -> if arguments.length > 1 and String(value) isnt "[object Object]" options = jQuery.extend({}, options) options.expires = -1 unless value? if typeof options.expires is "number" days = options.expires t = options.expires = new Date() t.setDate t.getDate() + days value = String(value) return (document.cookie = [ encodeURIComponent(key), "=", (if options.raw then value else encodeURIComponent(value)), (if options.expires then "; expires=" + options.expires.toUTCString() else ""), (if options.path then "; path=" + options.path else ""), (if options.domain then "; domain=" + options.domain else ""), (if options.secure then "; secure" else "") ].join("")) options = value or {} result = undefined decode = (if options.raw then (s) -> s else decodeURIComponent) return (if (result = new RegExp("(?:^|; )" + encodeURIComponent(key) + "=([^;]*)").exec(document.cookie)) then decode(result[1]) else null) # Adds plugin object to jQuery $.fn.extend {}= featureTour: (options) -> # Default settings settings = tipContent: '#featureTourTipContent' # What is the ID of the <ol> you put the content in cookieMonster: false # true or false to control whether cookies are used cookieName: 'bootstrapFeatureTour' # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.mydomain.com' postRideCallback: $.noop # A method to call once the tour closes postStepCallback: $.noop # A method to call after each step nextOnClose: false # If cookies are enabled, increment the current step on close debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log('[bootstrap-tour]', msg) if settings.debug # returns current step stored in the cookie, or `1` if cookie disabled, no # cookie or invalid cookie value currentStep = -> return 1 unless settings.cookieMonster? current_cookie = cookie(settings.cookieName) # start from step 1 if there's no cookie set return 1 unless current_cookie? try return parseInt(current_cookie) catch e # start from step 1 if there cookie is invalid return 1 setCookieStep = (step) -> cookie(settings.cookieName, "#{step}", { expires: 365, domain: settings.cookieDomain }) if settings.cookieMonster return @each () -> $tipContent = $(settings.tipContent).first() unless $tipContent? log "can't find tipContent from selector: #{settings.tipContent}" $tips = $tipContent.find('li') first_step = currentStep() log "first step: #{first_step}" if first_step > $tips.length log 'tour already completed, skipping' return $tips.each (idx) -> # skip steps until we reach the first one if idx < (first_step - 1) log "skipping step: #{idx + 1}" return $li = $(@) tip_data = $li.data() return unless (target = tip_data['target'])? return unless ($target = $(target).first())? $target.popover trigger: 'manual' title: if tip_data['title']? then "#{tip_data['title']} <a class=\"tour-tip-close close\" data-touridx=\"#{idx + 1}\">&times;</a>" else null content: "<p>#{$li.html()}</p><p style=\"text-align: right\"><a href=\"#\" class=\"tour-tip-next btn btn-success\" data-touridx=\"#{idx + 1}\">#{if (idx + 1) < $tips.length then 'Next <i class="icon-chevron-right icon-white"></i>' else '<i class="icon-ok icon-white"></i> Done'}</a></p>" placement: tip_data['placement'] || 'right' # save the target element in the tip node $li.data('target', $target) # show the first tip $target.popover('show') if idx == (first_step - 1) # handle the close button $('a.tour-tip-close').live 'click', -> current_step = $(@).data('touridx') $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') setCookieStep(current_step + 1) if settings.nextOnClose # handle the next and done buttons $('a.tour-tip-next').live 'click', -> current_step = $(@).data('touridx') log "current step: #{current_step}" $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') settings.postStepCallback($(@).data('touridx')) if settings.postStepCallback != $.noop next_tip = $(settings.tipContent).first().find("li:nth-child(#{current_step + 1})")?.data('target') setCookieStep(current_step + 1) if next_tip? next_tip_id = '#' + next_tip.attr('id'); targetOffset = $(next_tip_id).offset().top - 300; $('html, body').animate({scrollTop: targetOffset}, 1000) next_tip.popover('show') return false #so that href will get ignored else # last tip settings.postRideCallback() if settings.postRideCallback != $.noop
true
# bootstrap-tour.js v0.0.2 # Copyright 2012 Gild, Inc. # # Free to use under the MIT license. # http://www.opensource.org/licenses/mit-license.php # References jQuery $ = jQuery # based on jQuery Cookie plugin # Copyright (c) 2010 PI:NAME:<NAME>END_PI (stilbuero.de) # Dual licensed under the MIT and GPL licenses: # http://www.opensource.org/licenses/mit-license.php # http://www.gnu.org/licenses/gpl.html cookie = (key, value, options) -> if arguments.length > 1 and String(value) isnt "[object Object]" options = jQuery.extend({}, options) options.expires = -1 unless value? if typeof options.expires is "number" days = options.expires t = options.expires = new Date() t.setDate t.getDate() + days value = String(value) return (document.cookie = [ encodeURIComponent(key), "=", (if options.raw then value else encodeURIComponent(value)), (if options.expires then "; expires=" + options.expires.toUTCString() else ""), (if options.path then "; path=" + options.path else ""), (if options.domain then "; domain=" + options.domain else ""), (if options.secure then "; secure" else "") ].join("")) options = value or {} result = undefined decode = (if options.raw then (s) -> s else decodeURIComponent) return (if (result = new RegExp("(?:^|; )" + encodeURIComponent(key) + "=([^;]*)").exec(document.cookie)) then decode(result[1]) else null) # Adds plugin object to jQuery $.fn.extend {}= featureTour: (options) -> # Default settings settings = tipContent: '#featureTourTipContent' # What is the ID of the <ol> you put the content in cookieMonster: false # true or false to control whether cookies are used cookieName: 'bootstrapFeatureTour' # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.mydomain.com' postRideCallback: $.noop # A method to call once the tour closes postStepCallback: $.noop # A method to call after each step nextOnClose: false # If cookies are enabled, increment the current step on close debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log('[bootstrap-tour]', msg) if settings.debug # returns current step stored in the cookie, or `1` if cookie disabled, no # cookie or invalid cookie value currentStep = -> return 1 unless settings.cookieMonster? current_cookie = cookie(settings.cookieName) # start from step 1 if there's no cookie set return 1 unless current_cookie? try return parseInt(current_cookie) catch e # start from step 1 if there cookie is invalid return 1 setCookieStep = (step) -> cookie(settings.cookieName, "#{step}", { expires: 365, domain: settings.cookieDomain }) if settings.cookieMonster return @each () -> $tipContent = $(settings.tipContent).first() unless $tipContent? log "can't find tipContent from selector: #{settings.tipContent}" $tips = $tipContent.find('li') first_step = currentStep() log "first step: #{first_step}" if first_step > $tips.length log 'tour already completed, skipping' return $tips.each (idx) -> # skip steps until we reach the first one if idx < (first_step - 1) log "skipping step: #{idx + 1}" return $li = $(@) tip_data = $li.data() return unless (target = tip_data['target'])? return unless ($target = $(target).first())? $target.popover trigger: 'manual' title: if tip_data['title']? then "#{tip_data['title']} <a class=\"tour-tip-close close\" data-touridx=\"#{idx + 1}\">&times;</a>" else null content: "<p>#{$li.html()}</p><p style=\"text-align: right\"><a href=\"#\" class=\"tour-tip-next btn btn-success\" data-touridx=\"#{idx + 1}\">#{if (idx + 1) < $tips.length then 'Next <i class="icon-chevron-right icon-white"></i>' else '<i class="icon-ok icon-white"></i> Done'}</a></p>" placement: tip_data['placement'] || 'right' # save the target element in the tip node $li.data('target', $target) # show the first tip $target.popover('show') if idx == (first_step - 1) # handle the close button $('a.tour-tip-close').live 'click', -> current_step = $(@).data('touridx') $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') setCookieStep(current_step + 1) if settings.nextOnClose # handle the next and done buttons $('a.tour-tip-next').live 'click', -> current_step = $(@).data('touridx') log "current step: #{current_step}" $(settings.tipContent).first().find("li:nth-child(#{current_step})").data('target').popover('hide') settings.postStepCallback($(@).data('touridx')) if settings.postStepCallback != $.noop next_tip = $(settings.tipContent).first().find("li:nth-child(#{current_step + 1})")?.data('target') setCookieStep(current_step + 1) if next_tip? next_tip_id = '#' + next_tip.attr('id'); targetOffset = $(next_tip_id).offset().top - 300; $('html, body').animate({scrollTop: targetOffset}, 1000) next_tip.popover('show') return false #so that href will get ignored else # last tip settings.postRideCallback() if settings.postRideCallback != $.noop
[ { "context": " id: \"answer\"\n keys: ['1', '2', '3']\n correct: if @trial.number is", "end": 2075, "score": 0.6612785458564758, "start": 2074, "tag": "KEY", "value": "2" }, { "context": " id: \"answer\"\n keys: ['1', '2', '3']\n correct: if @trial.number is 1 th", "end": 2080, "score": 0.6788144111633301, "start": 2079, "tag": "KEY", "value": "3" } ]
examples/word_stroop/runner.coffee
bbuchsbaum/psycloud
0
factorSet = condition: levels: ["congruent", "incongruent", "neutral"] wordItems = ["and", "that", "how", "where", "the", "which"] numberItems = ["one", "two", "three"] numbers = [1,2,3] numberMap = { 1: "one", 2: "two", 3: "three"} fnode = Psy.FactorSetNode.build(factorSet) # create 5 blocks of trials with 5 complete replications per block @trials = fnode.trialList(5, 5) @trials = @trials.bind (record) -> number = Psy.oneOf(numbers) ret = word: Psy.match record.condition, congruent: numberMap[number] incongruent: numberMap[Psy.sample(numbers.exclude(number), 1)[0]] neutral: Psy.sample(wordItems, 1)[0] number: number ret.text = Psy.rep(ret.word, ret.number).join(" ") ret @trials.shuffle() @context = Psy.createContext() window.display = Display: Prelude: Events: 1: Markdown: """ Welcome to the Experiment! ========================== This a simple task. Press any key to continue ------------------------- """ Next: AnyKey: "" Block: Start: -> console.log("START BLOCK") Text: position: "center" origin: "center" content: ["Get Ready for Block #{@blockNumber}!", "Press Space Bar to start"] Next: SpaceKey: "" End: -> console.log("END BLOCK") Text: position: "center" origin: "center" content: ["End of Block #{@blockNumber}", "Press any key to continue"] Next: AnyKey: "" Trial: -> Background: Blank: fill: "gray" CanvasBorder: stroke: "black" Events: 1: FixationCross: fill: "black" Next: Timeout: duration: 1000 2: Text: position: "center" origin: "center" content: @trial.text Next: KeyPress: id: "answer" keys: ['1', '2', '3'] correct: if @trial.number is 1 then '1' else if @trial.number is 2 then '2' else '3' timeout: 2500 Feedback: -> console.log("Feedback this", this) Blank: fill: if @answer.accuracy then "green" else "red" opacity: .1 Next: Timeout: duration: 200 #Coda: # Events: # 1: # Text: # position: "center" # origin: "center" # content: "The End" # fontSize: 200 # # Next: # Timeout: duration: 5000 pres = new Psy.Presenter(trials, display.Display, context) pres.start()
184958
factorSet = condition: levels: ["congruent", "incongruent", "neutral"] wordItems = ["and", "that", "how", "where", "the", "which"] numberItems = ["one", "two", "three"] numbers = [1,2,3] numberMap = { 1: "one", 2: "two", 3: "three"} fnode = Psy.FactorSetNode.build(factorSet) # create 5 blocks of trials with 5 complete replications per block @trials = fnode.trialList(5, 5) @trials = @trials.bind (record) -> number = Psy.oneOf(numbers) ret = word: Psy.match record.condition, congruent: numberMap[number] incongruent: numberMap[Psy.sample(numbers.exclude(number), 1)[0]] neutral: Psy.sample(wordItems, 1)[0] number: number ret.text = Psy.rep(ret.word, ret.number).join(" ") ret @trials.shuffle() @context = Psy.createContext() window.display = Display: Prelude: Events: 1: Markdown: """ Welcome to the Experiment! ========================== This a simple task. Press any key to continue ------------------------- """ Next: AnyKey: "" Block: Start: -> console.log("START BLOCK") Text: position: "center" origin: "center" content: ["Get Ready for Block #{@blockNumber}!", "Press Space Bar to start"] Next: SpaceKey: "" End: -> console.log("END BLOCK") Text: position: "center" origin: "center" content: ["End of Block #{@blockNumber}", "Press any key to continue"] Next: AnyKey: "" Trial: -> Background: Blank: fill: "gray" CanvasBorder: stroke: "black" Events: 1: FixationCross: fill: "black" Next: Timeout: duration: 1000 2: Text: position: "center" origin: "center" content: @trial.text Next: KeyPress: id: "answer" keys: ['1', '<KEY>', '<KEY>'] correct: if @trial.number is 1 then '1' else if @trial.number is 2 then '2' else '3' timeout: 2500 Feedback: -> console.log("Feedback this", this) Blank: fill: if @answer.accuracy then "green" else "red" opacity: .1 Next: Timeout: duration: 200 #Coda: # Events: # 1: # Text: # position: "center" # origin: "center" # content: "The End" # fontSize: 200 # # Next: # Timeout: duration: 5000 pres = new Psy.Presenter(trials, display.Display, context) pres.start()
true
factorSet = condition: levels: ["congruent", "incongruent", "neutral"] wordItems = ["and", "that", "how", "where", "the", "which"] numberItems = ["one", "two", "three"] numbers = [1,2,3] numberMap = { 1: "one", 2: "two", 3: "three"} fnode = Psy.FactorSetNode.build(factorSet) # create 5 blocks of trials with 5 complete replications per block @trials = fnode.trialList(5, 5) @trials = @trials.bind (record) -> number = Psy.oneOf(numbers) ret = word: Psy.match record.condition, congruent: numberMap[number] incongruent: numberMap[Psy.sample(numbers.exclude(number), 1)[0]] neutral: Psy.sample(wordItems, 1)[0] number: number ret.text = Psy.rep(ret.word, ret.number).join(" ") ret @trials.shuffle() @context = Psy.createContext() window.display = Display: Prelude: Events: 1: Markdown: """ Welcome to the Experiment! ========================== This a simple task. Press any key to continue ------------------------- """ Next: AnyKey: "" Block: Start: -> console.log("START BLOCK") Text: position: "center" origin: "center" content: ["Get Ready for Block #{@blockNumber}!", "Press Space Bar to start"] Next: SpaceKey: "" End: -> console.log("END BLOCK") Text: position: "center" origin: "center" content: ["End of Block #{@blockNumber}", "Press any key to continue"] Next: AnyKey: "" Trial: -> Background: Blank: fill: "gray" CanvasBorder: stroke: "black" Events: 1: FixationCross: fill: "black" Next: Timeout: duration: 1000 2: Text: position: "center" origin: "center" content: @trial.text Next: KeyPress: id: "answer" keys: ['1', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] correct: if @trial.number is 1 then '1' else if @trial.number is 2 then '2' else '3' timeout: 2500 Feedback: -> console.log("Feedback this", this) Blank: fill: if @answer.accuracy then "green" else "red" opacity: .1 Next: Timeout: duration: 200 #Coda: # Events: # 1: # Text: # position: "center" # origin: "center" # content: "The End" # fontSize: 200 # # Next: # Timeout: duration: 5000 pres = new Psy.Presenter(trials, display.Display, context) pres.start()
[ { "context": "rd \"colour\" correctly.\n#\n# jColour is written by [Aaron Russell](http://aaronrussell.co.uk),\n# the [source code f", "end": 373, "score": 0.9999039173126221, "start": 360, "tag": "NAME", "value": "Aaron Russell" }, { "context": "# the [source code for jColour](http://github.com/aaronrussell/jcolour) is available on Github and\n# is released", "end": 465, "score": 0.9885700345039368, "start": 453, "tag": "USERNAME", "value": "aaronrussell" }, { "context": "load the minified version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.min.js) (8kb)\n# * [D", "end": 688, "score": 0.8587359189987183, "start": 676, "tag": "USERNAME", "value": "aaronrussell" }, { "context": "wnload the fatter version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.js) (14kb)\n\n#### Cre", "end": 801, "score": 0.977077841758728, "start": 789, "tag": "USERNAME", "value": "aaronrussell" }, { "context": "l]\n\n\n\n#### Copyright\n#\n# Copyright (c) 2010-2011 [Aaron Russell](http://aaronrussell.co.uk).\n# Licensed under the", "end": 22762, "score": 0.9997377395629883, "start": 22749, "tag": "NAME", "value": "Aaron Russell" } ]
data/coffeescript/9da947b3d452bdb6b48eac1739a633d6_jColour.coffee
maxim5/code-inspector
5
# **jColour** is a JavaScript colour manipulation library written in [CoffeeScript](http://coffeescript.org). # jColour is inspired heavily by the [SASS](http://sass-lang.com)/[Compass](http://compass-style.org) # colour manipulation functions. # # jColour is also the first ever colour library to spell the word "colour" correctly. # # jColour is written by [Aaron Russell](http://aaronrussell.co.uk), # the [source code for jColour](http://github.com/aaronrussell/jcolour) is available on Github and # is released under the [MIT license](http://www.opensource.org/licenses/mit-license.php). #### Download jColour # * [Download the minified version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.min.js) (8kb) # * [Download the fatter version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.js) (14kb) #### Creating a jColour object # The jColour class can be used in the browser or in your CommonJS projects. # root = exports ? this class root.jColour # Create a new jColour object by passing a colour string. jColour will parse a string in any of # the following formats: [recognised colour name](http://www.w3.org/TR/SVG/types.html#ColorKeywords), # hexidecimal, rgb/a, hsl/a. For example, all the following statements work: # # c = new jColour('red'); # c = new jColour('#f00'); # c = new jColour('#ff0000'); # c = new jColour('rgb(255,0,0)'); # c = new jColour('rgba(255,0,0,1)'); # c = new jColour('hsl(0,100,100)'); # c = new jColour('hsla(0,100,100,1)'); # # Internally, colours are represented in both RGB and HSL. Any colour adjustments result in # both representaions being recalculated. The alpha channel of a colour is stored independent # it's RGB or HSL representation. If no alpha value is supplied, it defaults to 1. # constructor: (col = '#ffffff') -> col = colourNames[col] if col.toLowerCase() of colourNames if hex = col.match /^#?([a-f0-9]{3})$/i h1 = hex[1].substring(0,1) h2 = hex[1].substring(1,2) h3 = hex[1].substring(2,3) col = "##{h1+h1+h2+h2+h3+h3}" if hex = col.match /^#?([a-f0-9]{6,8})$/i @red = parseInt hex[1].substring(0,2), 16 @green = parseInt hex[1].substring(2,4), 16 @blue = parseInt hex[1].substring(4,6), 16 @alpha = if hex[1].substring(6,8) then parseInt(hex[1].substring(6,8), 16) / 255 else 1 rgbToHsl this else if rgb = col.match /^rgba?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @red = parseInt rgb[1] @green = parseInt rgb[2] @blue = parseInt rgb[3] @alpha = if rgb[4] then rgb[4] else 1 rgbToHsl this else if hsl = col.match /^hsla?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @hue = parseInt hsl[1] @saturation = parseInt hsl[2] @lightness = parseInt hsl[3] @alpha = if hsl[4] then hsl[4] else 1 hslToRgb this else throw 'Invalid colour string.' #### Accessing colour representations # At any time, a jColour object can return a string of any of it's colour represenations. ##### `hex(show_alpha = false)` # # To return the hexidecimal value of the colour use the `hex()` method. By default, any alpha # value of the jColour object will be ignored. However, in specialist cases you may want a # hexdecimal representation of the alpha channel, in which case pass `true` to the method. # # c.hex(); # -> '#ff0000' # hex: (showAlpha = false) -> hex = if showAlpha && @alpha < 1 "##{hexify @red}#{hexify @green}#{hexify @blue}#{hexify @alpha * 255}" else "##{hexify @red}#{hexify @green}#{hexify @blue}" hex.toLowerCase() ##### `rgb()` # # Returns the RGB value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be RGBA. # # c.rgb(); # -> 'rgb(255,0,0)' # rgb: -> if @alpha == 1 "rgb(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue})" else "rgba(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue}, #{Math.round(@alpha * 100) / 100})" ##### `hsl()` # # Returns the HSL value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be HSLA. # # c.hsl(); # -> 'hsl(0,100,100)' # hsl: -> if @alpha == 1 "hsl(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness})" else "hsla(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness}, #{Math.round(@alpha * 100) / 100})" ##### `toS()` # # Returns the name of the colour if it is a recognised colour keyworld. Alternatively, the hex # code will be returned. # toS: -> for key, value of colourNames return key if @hex() == value.toLowerCase() @hex() #### Manipulating colours # A jColour object can be manipulated using a range of colour manipulation methods. Each method # makes the required adjustment to the colour representations and updates the jColour object. # This allows the "chaining" of methods, for example: # # c = new jColour('#ff0000'); # c.adjustHue(20).darken(10).transparentize(25).rgb(); # -> 'rgba(204, 68, 0, 0.75)' # # Most of the colour manipulation methods allow colour values to be manipulated relatively # (eg. 50 + 10 = 60) or scaled by a percentage (eg. 50 + 10% = 55). The name of the method should # make it obvious as to what calculation you should expect. ##### `lighten(amount)` # # Makes the colour lighter. Takes an amount between 0 and 100 which makes a relative adjustment # (increase) to the current lightness. # # c.lighten(25); # lighten: (amount) -> @lightness += amount hslToRgb this ##### `lightenPercent(percent)` # # Also makes the colour lighter. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* up relative to it's current value. # # c.lightenPercent(25); # lightenPercent: (percent) -> @lightness += (@lightness / 100) * percent hslToRgb this ##### `darken(amount)` # # Makes the colour darker. Takes an amount between 0 and 100 which makes a relative adjustment # (decrease) to the current lightness. # # c.darken(25); # darken: (amount) -> @lightness -= amount hslToRgb this ##### `darkenPercent(percent)` # # Also makes the colour darker. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* down relative to it's current value. # # c.darkenPercent(25); # darkenPercent: (percent) -> @lightness -= (@lightness / 100) * percent hslToRgb this ##### `saturate(amount)` # # Makes the colour more saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (increase) to the current saturation. # # c.saturate(25); # saturate: (amount) -> @saturation += amount hslToRgb this ##### `saturatePercent(percent)` # # Also makes the colour more saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* up relative to it's current value. # # c.saturatePercent(25); # saturatePercent: (percent) -> @saturation += (@saturation / 100) * percent hslToRgb this ##### `desaturate(amount)` # # Makes the colour less saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current saturation. # # c.desaturate(25); # desaturate: (amount) -> @saturation -= amount hslToRgb this ##### `desaturatePercent(percent)` # # Also makes the colour less saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* down relative to it's current value. # # c.desaturatePercent(25); # desaturatePercent: (percent) -> @saturation -= (@saturation / 100) * percent hslToRgb this ##### `greyscale()` # # Converts the color to greyscale. This is identical to `desaturate(100)`. Can also use the alias, `grayscale()`. # # c.greyscale(); # greyscale: -> @saturation = 0 hslToRgb this grayscale: -> @greyscale() ##### `adjustHue(degrees)` # # Changes the hue of the colour whilst retaining the lightness and saturation. This method should # be passed a number of degrees (usually between -360 and 360) and makes a relative adjustment to # the current hue. # # c.adjustHue(45); # adjustHue: (degrees) -> @hue += degrees hslToRgb this ##### `complement()` # # Returns the complement of the current colour. This is identical to `adjustHue(180)`. # # c.complement(); # complement: -> @hue += 180 hslToRgb this ##### `opacify(amount)` # # Makes the colour more opaque. Takes an amount between 0 and 1 which makes a relative # adjustment (increase) to the current alpha channel. # # c.opacify(0.25); # opacify: (amount) -> @alpha += amount @alpha = minMax @alpha, 0, 1 this ##### `transparentize(amount)` # # Makes the colour more transparent. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current alpha channel. # # c.transparentize(0.25); # transparentize: (amount) -> @alpha -= amount @alpha = minMax @alpha, 0, 1 this ##### `invert()` # # Returns the inverse (negative) of the color. The red, green, and blue values are inverted, while # the opacity is left alone. # # c.invert(); # invert: -> for color in ['red', 'green', 'blue'] @[color] = 255 - @[color] rgbToHsl this ##### `adjustColour(params = {})` # # Makes a relative adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, hue, saturation, lightness and alpha. All properties are # optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between -255 and 255. The hue property should # have a value between -360 and 360. The saturation and lightness properties should have a value # between -100 and 100. The alpha property should have a value between 0 and 1. All values will # make a relative adjustment to their current value. # # c.adjustColour({ # red: 25, # green: -30, # alpha: -0.25 # }) # c.adjustColour({ # hue: 120, # lightness: 25, # saturation: -10 # }) # adjustColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `scaleColour(params = {})` # # Makes a scaled adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, saturation, lightness and alpha. Note that you can't scale the # hue value. All properties are optional and you can't specify both RGB and HSL properties at the # same time. # # All properties should have a value between -100 and 100. The property will be scaled up or down # relative to it's current value. # # c.scaleColour({ # red: 25, # green: -15 # }) # c.scaleColour({ # lightness: 25, # saturation: -10 # }) # scaleColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += (@[key] / 100) * params[key] if key in properties and key isnt 'hue' if kind[0] then rgbToHsl this else hslToRgb this ##### `changeColour(params = {})` # # Changes one or more properties of the colour to the absolute value provided. Takes an object # with the properties of red, green, blue, hue, saturation, lightness and alpha. All properties # are optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between 0 and 255. The hue property should # have a value between 0 and 360. The saturation and lightness properties should have a value # between 0 and 100. The alpha property should have a value between 0 and 1. All properties will # be set to the new value. # # c.changeColour({ # red: 255, # green: 0, # blue: 0 # }) # c.changeColour({ # hue: 0, # lightness: 100, # saturation: 100 # }) # changeColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] = params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `mixWith(colour, weight = 50)` # # Mixes the colour with another 'mix' colour. The mix colour can be passed as either a jColour # object or a string. Each of the RGB components are averaged, optionally weighted with a given # percentage. The opacity of the colours is also considered when weighting the components. # # The weight specifies the weight of the mix. The default, 50%, means half the original colour # and half the mix colour will be used. A weight of 25% means the a quarter of the mix colour # will be mixed with three quarters of the original colour. # # red = new jColour('#ff0000'); # red.mixWith('#ffffff', 75).rgb(); # -> 'rgb(255, 191, 191)' # mixWith: (colour, weight = 50) -> colour = new jColour(colour) unless colour instanceof jColour p = weight / 100 w = p * 2 - 1 a = colour.alpha - @alpha w1 = ((if w * a == -1 then w else (w + a) / (1 + w * a)) + 1) / 2 w2 = 1 - w1 @red = (colour.red * w1) + (@red * w2) @green = (colour.green * w1) + (@green * w2) @blue = (colour.blue * w1) + (@blue * w2) @alpha = (colour.alpha * p) + (@alpha * (1-p)) rgbToHsl this #### Private properties # This properties array is useful to have around. # properties = ['red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha'] # A mahoosive list of recognised colour keyword names as defined at # [http://www.w3.org/TR/SVG/types.html#ColorKeywords](http://www.w3.org/TR/SVG/types.html#ColorKeywords) # colourNames = aliceblue: '#F0F8FF' antiquewhite: '#FAEBD7' aqua: '#00FFFF' aquamarine: '#7FFFD4' azure: '#F0FFFF' beige: '#F5F5DC' bisque: '#FFE4C4' black: '#000000' blanchedalmond: '#FFEBCD' blue: '#0000FF' blueviolet: '#8A2BE2' brown: '#A52A2A' burlywood: '#DEB887' cadetblue: '#5F9EA0' chartreuse: '#7FFF00' chocolate: '#D2691E' coral: '#FF7F50' cornflowerblue: '#6495ED' cornsilk: '#FFF8DC' crimson: '#DC143C' cyan: '#00FFFF' darkblue: '#00008B' darkcyan: '#008B8B' darkgoldenrod: '#B8860B' darkgray: '#A9A9A9' darkgreen: '#006400' darkgrey: '#A9A9A9' darkkhaki: '#BDB76B' darkmagenta: '#8B008B' darkolivegreen: '#556B2F' darkorange: '#FF8C00' darkorchid: '#9932CC' darkred: '#8B0000' darksalmon: '#E9967A' darkseagreen: '#8FBC8F' darkslateblue: '#483D8B' darkslategray: '#2F4F4F' darkslategrey: '#2F4F4F' darkturquoise: '#00CED1' darkviolet: '#9400D3' deeppink: '#FF1493' deepskyblue: '#00BFFF' dimgray: '#696969' dimgrey: '#696969' dodgerblue: '#1E90FF' firebrick: '#B22222' floralwhite: '#FFFAF0' forestgreen: '#228B22' fuchsia: '#FF00FF' gainsboro: '#DCDCDC' ghostwhite: '#F8F8FF' gold: '#FFD700' goldenrod: '#DAA520' gray: '#808080' green: '#008000' greenyellow: '#ADFF2F' grey: '#808080' honeydew: '#F0FFF0' hotpink: '#FF69B4' indianred: '#CD5C5C' indigo: '#4B0082' ivory: '#FFFFF0' khaki: '#F0E68C' lavender: '#E6E6FA' lavenderblush: '#FFF0F5' lawngreen: '#7CFC00' lemonchiffon: '#FFFACD' lightblue: '#ADD8E6' lightcoral: '#F08080' lightcyan: '#E0FFFF' lightgoldenrodyellow: '#FAFAD2' lightgray: '#D3D3D3' lightgreen: '#90EE90' lightgrey: '#D3D3D3' lightpink: '#FFB6C1' lightsalmon: '#FFA07A' lightseagreen: '#20B2AA' lightskyblue: '#87CEFA' lightslategray: '#778899' lightslategrey: '#778899' lightsteelblue: '#B0C4DE' lightyellow: '#FFFFE0' lime: '#00FF00' limegreen: '#32CD32' linen: '#FAF0E6' magenta: '#FF00FF' maroon: '#800000' mediumaquamarine: '#66CDAA' mediumblue: '#0000CD' mediumorchid: '#BA55D3' mediumpurple: '#9370DB' mediumseagreen: '#3CB371' mediumslateblue: '#7B68EE' mediumspringgreen: '#00FA9A' mediumturquoise: '#48D1CC' mediumvioletred: '#C71585' midnightblue: '#191970' mintcream: '#F5FFFA' mistyrose: '#FFE4E1' moccasin: '#FFE4B5' navajowhite: '#FFDEAD' navy: '#000080' oldlace: '#FDF5E6' olive: '#808000' olivedrab: '#6B8E23' orange: '#FFA500' orangered: '#FF4500' orchid: '#DA70D6' palegoldenrod: '#EEE8AA' palegreen: '#98FB98' paleturquoise: '#AFEEEE' palevioletred: '#DB7093' papayawhip: '#FFEFD5' peachpuff: '#FFDAB9' peru: '#CD853F' pink: '#FFC0CB' plum: '#DDA0DD' powderblue: '#B0E0E6' purple: '#800080' red: '#FF0000' rosybrown: '#BC8F8F' royalblue: '#4169E1' saddlebrown: '#8B4513' salmon: '#FA8072' sandybrown: '#F4A460' seagreen: '#2E8B57' seashell: '#FFF5EE' sienna: '#A0522D' silver: '#C0C0C0' skyblue: '#87CEEB' slateblue: '#6A5ACD' slategray: '#708090' slategrey: '#708090' snow: '#FFFAFA' springgreen: '#00FF7F' steelblue: '#4682B4' tan: '#D2B48C' teal: '#008080' thistle: '#D8BFD8' tomato: '#FF6347' turquoise: '#40E0D0' violet: '#EE82EE' wheat: '#F5DEB3' white: '#FFFFFF' whitesmoke: '#F5F5F5' yellow: '#FFFF00' yellowgreen: '#9ACD32' #### Private helper methods # # The following methods are all used internally and are not accessible from outside the jColour object. # ##### `rgbToHsl(c)` # # Converts the RGB representation to a HSL representation. # rgbToHsl = (c) -> c.red = minMax c.red, 0, 255 c.green = minMax c.green, 0, 255 c.blue = minMax c.blue, 0, 255 c.alpha = minMax c.alpha, 0, 1 r = c.red / 255 g = c.green / 255 b = c.blue / 255 max = Math.max r, g, b min = Math.min r, g, b d = max - min h = switch max when min then 0 when r then 60 * (g - b) / d when g then 60 * (b - r) / d + 120 when b then 60 * (r - g) / d + 240 l = (max + min) / 2 s = if max == min 0 else if l < 0.5 d / (2 * l) else d / (2 - 2 * l) c.hue = h % 360 c.saturation = s * 100 c.lightness = l * 100 c ##### `hslToRgb(c)` # # Converts the HSL representation to a RGB representation. # hslToRgb = (c) -> c.hue -= Math.floor(c.hue/360)*360 if c.hue >= 360 c.hue -= Math.ceil(c.hue/360)*360 if c.hue < 0 c.saturation = minMax c.saturation, 0, 100 c.lightness = minMax c.lightness, 0, 100 c.alpha = minMax c.alpha, 0, 1 h = c.hue / 360 s = c.saturation / 100 l = c.lightness / 100 m2 = if l < 0.5 then l * (s + 1) else l + s - (l * s) m1 = l * 2 - m2 r = hueToRgb m1, m2, h + 1/3 g = hueToRgb m1, m2, h b = hueToRgb m1, m2, h - 1/3 c.red = r * 255 c.green = g * 255 c.blue = b * 255 c ##### `hueToRgb(p, q, t)` # # Algorithm for converting hue to each of the red, green and blue properties. # hueToRgb = (m1, m2, h) -> h += 1 if h < 0 h -= 1 if h > 1 return m1 + (m2 - m1) * h * 6 if h * 6 < 1 return m2 if h * 2 < 1 return m1 + (m2 - m1) * (2/3 - h) * 6 if h * 3 < 2 m1 ##### `hexify(n = '00')` # # Algorithm for converting each of the RGB colour channels to it's hex value. # hexify = (n = '00') -> n = parseInt n return '00' if n == 0 or isNaN n n = Math.round minMax(n, 0, 255) "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16) ##### `minMax(i, min, max)` # # Helper method to clip a provided number between a minimum and maximum value. # minMax = (i, min, max) -> Math.min Math.max(i, min), max ##### `throwIfIncompatible(params)` # # Throws an error if incompatible colour properties are provided. # throwIfIncompatible = (params) -> rgb = hsl = false for key of params rgb = true if key in ['red', 'green', 'blue'] hsl = true if key in ['hue', 'saturation', 'luminosity'] if rgb and hsl throw 'Cannot change both RGB and HSL properties.' [rgb, hsl] #### Copyright # # Copyright (c) 2010-2011 [Aaron Russell](http://aaronrussell.co.uk). # Licensed under the [MIT license](http://www.opensource.org/licenses/mit-license.php).
16719
# **jColour** is a JavaScript colour manipulation library written in [CoffeeScript](http://coffeescript.org). # jColour is inspired heavily by the [SASS](http://sass-lang.com)/[Compass](http://compass-style.org) # colour manipulation functions. # # jColour is also the first ever colour library to spell the word "colour" correctly. # # jColour is written by [<NAME>](http://aaronrussell.co.uk), # the [source code for jColour](http://github.com/aaronrussell/jcolour) is available on Github and # is released under the [MIT license](http://www.opensource.org/licenses/mit-license.php). #### Download jColour # * [Download the minified version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.min.js) (8kb) # * [Download the fatter version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.js) (14kb) #### Creating a jColour object # The jColour class can be used in the browser or in your CommonJS projects. # root = exports ? this class root.jColour # Create a new jColour object by passing a colour string. jColour will parse a string in any of # the following formats: [recognised colour name](http://www.w3.org/TR/SVG/types.html#ColorKeywords), # hexidecimal, rgb/a, hsl/a. For example, all the following statements work: # # c = new jColour('red'); # c = new jColour('#f00'); # c = new jColour('#ff0000'); # c = new jColour('rgb(255,0,0)'); # c = new jColour('rgba(255,0,0,1)'); # c = new jColour('hsl(0,100,100)'); # c = new jColour('hsla(0,100,100,1)'); # # Internally, colours are represented in both RGB and HSL. Any colour adjustments result in # both representaions being recalculated. The alpha channel of a colour is stored independent # it's RGB or HSL representation. If no alpha value is supplied, it defaults to 1. # constructor: (col = '#ffffff') -> col = colourNames[col] if col.toLowerCase() of colourNames if hex = col.match /^#?([a-f0-9]{3})$/i h1 = hex[1].substring(0,1) h2 = hex[1].substring(1,2) h3 = hex[1].substring(2,3) col = "##{h1+h1+h2+h2+h3+h3}" if hex = col.match /^#?([a-f0-9]{6,8})$/i @red = parseInt hex[1].substring(0,2), 16 @green = parseInt hex[1].substring(2,4), 16 @blue = parseInt hex[1].substring(4,6), 16 @alpha = if hex[1].substring(6,8) then parseInt(hex[1].substring(6,8), 16) / 255 else 1 rgbToHsl this else if rgb = col.match /^rgba?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @red = parseInt rgb[1] @green = parseInt rgb[2] @blue = parseInt rgb[3] @alpha = if rgb[4] then rgb[4] else 1 rgbToHsl this else if hsl = col.match /^hsla?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @hue = parseInt hsl[1] @saturation = parseInt hsl[2] @lightness = parseInt hsl[3] @alpha = if hsl[4] then hsl[4] else 1 hslToRgb this else throw 'Invalid colour string.' #### Accessing colour representations # At any time, a jColour object can return a string of any of it's colour represenations. ##### `hex(show_alpha = false)` # # To return the hexidecimal value of the colour use the `hex()` method. By default, any alpha # value of the jColour object will be ignored. However, in specialist cases you may want a # hexdecimal representation of the alpha channel, in which case pass `true` to the method. # # c.hex(); # -> '#ff0000' # hex: (showAlpha = false) -> hex = if showAlpha && @alpha < 1 "##{hexify @red}#{hexify @green}#{hexify @blue}#{hexify @alpha * 255}" else "##{hexify @red}#{hexify @green}#{hexify @blue}" hex.toLowerCase() ##### `rgb()` # # Returns the RGB value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be RGBA. # # c.rgb(); # -> 'rgb(255,0,0)' # rgb: -> if @alpha == 1 "rgb(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue})" else "rgba(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue}, #{Math.round(@alpha * 100) / 100})" ##### `hsl()` # # Returns the HSL value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be HSLA. # # c.hsl(); # -> 'hsl(0,100,100)' # hsl: -> if @alpha == 1 "hsl(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness})" else "hsla(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness}, #{Math.round(@alpha * 100) / 100})" ##### `toS()` # # Returns the name of the colour if it is a recognised colour keyworld. Alternatively, the hex # code will be returned. # toS: -> for key, value of colourNames return key if @hex() == value.toLowerCase() @hex() #### Manipulating colours # A jColour object can be manipulated using a range of colour manipulation methods. Each method # makes the required adjustment to the colour representations and updates the jColour object. # This allows the "chaining" of methods, for example: # # c = new jColour('#ff0000'); # c.adjustHue(20).darken(10).transparentize(25).rgb(); # -> 'rgba(204, 68, 0, 0.75)' # # Most of the colour manipulation methods allow colour values to be manipulated relatively # (eg. 50 + 10 = 60) or scaled by a percentage (eg. 50 + 10% = 55). The name of the method should # make it obvious as to what calculation you should expect. ##### `lighten(amount)` # # Makes the colour lighter. Takes an amount between 0 and 100 which makes a relative adjustment # (increase) to the current lightness. # # c.lighten(25); # lighten: (amount) -> @lightness += amount hslToRgb this ##### `lightenPercent(percent)` # # Also makes the colour lighter. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* up relative to it's current value. # # c.lightenPercent(25); # lightenPercent: (percent) -> @lightness += (@lightness / 100) * percent hslToRgb this ##### `darken(amount)` # # Makes the colour darker. Takes an amount between 0 and 100 which makes a relative adjustment # (decrease) to the current lightness. # # c.darken(25); # darken: (amount) -> @lightness -= amount hslToRgb this ##### `darkenPercent(percent)` # # Also makes the colour darker. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* down relative to it's current value. # # c.darkenPercent(25); # darkenPercent: (percent) -> @lightness -= (@lightness / 100) * percent hslToRgb this ##### `saturate(amount)` # # Makes the colour more saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (increase) to the current saturation. # # c.saturate(25); # saturate: (amount) -> @saturation += amount hslToRgb this ##### `saturatePercent(percent)` # # Also makes the colour more saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* up relative to it's current value. # # c.saturatePercent(25); # saturatePercent: (percent) -> @saturation += (@saturation / 100) * percent hslToRgb this ##### `desaturate(amount)` # # Makes the colour less saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current saturation. # # c.desaturate(25); # desaturate: (amount) -> @saturation -= amount hslToRgb this ##### `desaturatePercent(percent)` # # Also makes the colour less saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* down relative to it's current value. # # c.desaturatePercent(25); # desaturatePercent: (percent) -> @saturation -= (@saturation / 100) * percent hslToRgb this ##### `greyscale()` # # Converts the color to greyscale. This is identical to `desaturate(100)`. Can also use the alias, `grayscale()`. # # c.greyscale(); # greyscale: -> @saturation = 0 hslToRgb this grayscale: -> @greyscale() ##### `adjustHue(degrees)` # # Changes the hue of the colour whilst retaining the lightness and saturation. This method should # be passed a number of degrees (usually between -360 and 360) and makes a relative adjustment to # the current hue. # # c.adjustHue(45); # adjustHue: (degrees) -> @hue += degrees hslToRgb this ##### `complement()` # # Returns the complement of the current colour. This is identical to `adjustHue(180)`. # # c.complement(); # complement: -> @hue += 180 hslToRgb this ##### `opacify(amount)` # # Makes the colour more opaque. Takes an amount between 0 and 1 which makes a relative # adjustment (increase) to the current alpha channel. # # c.opacify(0.25); # opacify: (amount) -> @alpha += amount @alpha = minMax @alpha, 0, 1 this ##### `transparentize(amount)` # # Makes the colour more transparent. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current alpha channel. # # c.transparentize(0.25); # transparentize: (amount) -> @alpha -= amount @alpha = minMax @alpha, 0, 1 this ##### `invert()` # # Returns the inverse (negative) of the color. The red, green, and blue values are inverted, while # the opacity is left alone. # # c.invert(); # invert: -> for color in ['red', 'green', 'blue'] @[color] = 255 - @[color] rgbToHsl this ##### `adjustColour(params = {})` # # Makes a relative adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, hue, saturation, lightness and alpha. All properties are # optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between -255 and 255. The hue property should # have a value between -360 and 360. The saturation and lightness properties should have a value # between -100 and 100. The alpha property should have a value between 0 and 1. All values will # make a relative adjustment to their current value. # # c.adjustColour({ # red: 25, # green: -30, # alpha: -0.25 # }) # c.adjustColour({ # hue: 120, # lightness: 25, # saturation: -10 # }) # adjustColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `scaleColour(params = {})` # # Makes a scaled adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, saturation, lightness and alpha. Note that you can't scale the # hue value. All properties are optional and you can't specify both RGB and HSL properties at the # same time. # # All properties should have a value between -100 and 100. The property will be scaled up or down # relative to it's current value. # # c.scaleColour({ # red: 25, # green: -15 # }) # c.scaleColour({ # lightness: 25, # saturation: -10 # }) # scaleColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += (@[key] / 100) * params[key] if key in properties and key isnt 'hue' if kind[0] then rgbToHsl this else hslToRgb this ##### `changeColour(params = {})` # # Changes one or more properties of the colour to the absolute value provided. Takes an object # with the properties of red, green, blue, hue, saturation, lightness and alpha. All properties # are optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between 0 and 255. The hue property should # have a value between 0 and 360. The saturation and lightness properties should have a value # between 0 and 100. The alpha property should have a value between 0 and 1. All properties will # be set to the new value. # # c.changeColour({ # red: 255, # green: 0, # blue: 0 # }) # c.changeColour({ # hue: 0, # lightness: 100, # saturation: 100 # }) # changeColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] = params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `mixWith(colour, weight = 50)` # # Mixes the colour with another 'mix' colour. The mix colour can be passed as either a jColour # object or a string. Each of the RGB components are averaged, optionally weighted with a given # percentage. The opacity of the colours is also considered when weighting the components. # # The weight specifies the weight of the mix. The default, 50%, means half the original colour # and half the mix colour will be used. A weight of 25% means the a quarter of the mix colour # will be mixed with three quarters of the original colour. # # red = new jColour('#ff0000'); # red.mixWith('#ffffff', 75).rgb(); # -> 'rgb(255, 191, 191)' # mixWith: (colour, weight = 50) -> colour = new jColour(colour) unless colour instanceof jColour p = weight / 100 w = p * 2 - 1 a = colour.alpha - @alpha w1 = ((if w * a == -1 then w else (w + a) / (1 + w * a)) + 1) / 2 w2 = 1 - w1 @red = (colour.red * w1) + (@red * w2) @green = (colour.green * w1) + (@green * w2) @blue = (colour.blue * w1) + (@blue * w2) @alpha = (colour.alpha * p) + (@alpha * (1-p)) rgbToHsl this #### Private properties # This properties array is useful to have around. # properties = ['red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha'] # A mahoosive list of recognised colour keyword names as defined at # [http://www.w3.org/TR/SVG/types.html#ColorKeywords](http://www.w3.org/TR/SVG/types.html#ColorKeywords) # colourNames = aliceblue: '#F0F8FF' antiquewhite: '#FAEBD7' aqua: '#00FFFF' aquamarine: '#7FFFD4' azure: '#F0FFFF' beige: '#F5F5DC' bisque: '#FFE4C4' black: '#000000' blanchedalmond: '#FFEBCD' blue: '#0000FF' blueviolet: '#8A2BE2' brown: '#A52A2A' burlywood: '#DEB887' cadetblue: '#5F9EA0' chartreuse: '#7FFF00' chocolate: '#D2691E' coral: '#FF7F50' cornflowerblue: '#6495ED' cornsilk: '#FFF8DC' crimson: '#DC143C' cyan: '#00FFFF' darkblue: '#00008B' darkcyan: '#008B8B' darkgoldenrod: '#B8860B' darkgray: '#A9A9A9' darkgreen: '#006400' darkgrey: '#A9A9A9' darkkhaki: '#BDB76B' darkmagenta: '#8B008B' darkolivegreen: '#556B2F' darkorange: '#FF8C00' darkorchid: '#9932CC' darkred: '#8B0000' darksalmon: '#E9967A' darkseagreen: '#8FBC8F' darkslateblue: '#483D8B' darkslategray: '#2F4F4F' darkslategrey: '#2F4F4F' darkturquoise: '#00CED1' darkviolet: '#9400D3' deeppink: '#FF1493' deepskyblue: '#00BFFF' dimgray: '#696969' dimgrey: '#696969' dodgerblue: '#1E90FF' firebrick: '#B22222' floralwhite: '#FFFAF0' forestgreen: '#228B22' fuchsia: '#FF00FF' gainsboro: '#DCDCDC' ghostwhite: '#F8F8FF' gold: '#FFD700' goldenrod: '#DAA520' gray: '#808080' green: '#008000' greenyellow: '#ADFF2F' grey: '#808080' honeydew: '#F0FFF0' hotpink: '#FF69B4' indianred: '#CD5C5C' indigo: '#4B0082' ivory: '#FFFFF0' khaki: '#F0E68C' lavender: '#E6E6FA' lavenderblush: '#FFF0F5' lawngreen: '#7CFC00' lemonchiffon: '#FFFACD' lightblue: '#ADD8E6' lightcoral: '#F08080' lightcyan: '#E0FFFF' lightgoldenrodyellow: '#FAFAD2' lightgray: '#D3D3D3' lightgreen: '#90EE90' lightgrey: '#D3D3D3' lightpink: '#FFB6C1' lightsalmon: '#FFA07A' lightseagreen: '#20B2AA' lightskyblue: '#87CEFA' lightslategray: '#778899' lightslategrey: '#778899' lightsteelblue: '#B0C4DE' lightyellow: '#FFFFE0' lime: '#00FF00' limegreen: '#32CD32' linen: '#FAF0E6' magenta: '#FF00FF' maroon: '#800000' mediumaquamarine: '#66CDAA' mediumblue: '#0000CD' mediumorchid: '#BA55D3' mediumpurple: '#9370DB' mediumseagreen: '#3CB371' mediumslateblue: '#7B68EE' mediumspringgreen: '#00FA9A' mediumturquoise: '#48D1CC' mediumvioletred: '#C71585' midnightblue: '#191970' mintcream: '#F5FFFA' mistyrose: '#FFE4E1' moccasin: '#FFE4B5' navajowhite: '#FFDEAD' navy: '#000080' oldlace: '#FDF5E6' olive: '#808000' olivedrab: '#6B8E23' orange: '#FFA500' orangered: '#FF4500' orchid: '#DA70D6' palegoldenrod: '#EEE8AA' palegreen: '#98FB98' paleturquoise: '#AFEEEE' palevioletred: '#DB7093' papayawhip: '#FFEFD5' peachpuff: '#FFDAB9' peru: '#CD853F' pink: '#FFC0CB' plum: '#DDA0DD' powderblue: '#B0E0E6' purple: '#800080' red: '#FF0000' rosybrown: '#BC8F8F' royalblue: '#4169E1' saddlebrown: '#8B4513' salmon: '#FA8072' sandybrown: '#F4A460' seagreen: '#2E8B57' seashell: '#FFF5EE' sienna: '#A0522D' silver: '#C0C0C0' skyblue: '#87CEEB' slateblue: '#6A5ACD' slategray: '#708090' slategrey: '#708090' snow: '#FFFAFA' springgreen: '#00FF7F' steelblue: '#4682B4' tan: '#D2B48C' teal: '#008080' thistle: '#D8BFD8' tomato: '#FF6347' turquoise: '#40E0D0' violet: '#EE82EE' wheat: '#F5DEB3' white: '#FFFFFF' whitesmoke: '#F5F5F5' yellow: '#FFFF00' yellowgreen: '#9ACD32' #### Private helper methods # # The following methods are all used internally and are not accessible from outside the jColour object. # ##### `rgbToHsl(c)` # # Converts the RGB representation to a HSL representation. # rgbToHsl = (c) -> c.red = minMax c.red, 0, 255 c.green = minMax c.green, 0, 255 c.blue = minMax c.blue, 0, 255 c.alpha = minMax c.alpha, 0, 1 r = c.red / 255 g = c.green / 255 b = c.blue / 255 max = Math.max r, g, b min = Math.min r, g, b d = max - min h = switch max when min then 0 when r then 60 * (g - b) / d when g then 60 * (b - r) / d + 120 when b then 60 * (r - g) / d + 240 l = (max + min) / 2 s = if max == min 0 else if l < 0.5 d / (2 * l) else d / (2 - 2 * l) c.hue = h % 360 c.saturation = s * 100 c.lightness = l * 100 c ##### `hslToRgb(c)` # # Converts the HSL representation to a RGB representation. # hslToRgb = (c) -> c.hue -= Math.floor(c.hue/360)*360 if c.hue >= 360 c.hue -= Math.ceil(c.hue/360)*360 if c.hue < 0 c.saturation = minMax c.saturation, 0, 100 c.lightness = minMax c.lightness, 0, 100 c.alpha = minMax c.alpha, 0, 1 h = c.hue / 360 s = c.saturation / 100 l = c.lightness / 100 m2 = if l < 0.5 then l * (s + 1) else l + s - (l * s) m1 = l * 2 - m2 r = hueToRgb m1, m2, h + 1/3 g = hueToRgb m1, m2, h b = hueToRgb m1, m2, h - 1/3 c.red = r * 255 c.green = g * 255 c.blue = b * 255 c ##### `hueToRgb(p, q, t)` # # Algorithm for converting hue to each of the red, green and blue properties. # hueToRgb = (m1, m2, h) -> h += 1 if h < 0 h -= 1 if h > 1 return m1 + (m2 - m1) * h * 6 if h * 6 < 1 return m2 if h * 2 < 1 return m1 + (m2 - m1) * (2/3 - h) * 6 if h * 3 < 2 m1 ##### `hexify(n = '00')` # # Algorithm for converting each of the RGB colour channels to it's hex value. # hexify = (n = '00') -> n = parseInt n return '00' if n == 0 or isNaN n n = Math.round minMax(n, 0, 255) "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16) ##### `minMax(i, min, max)` # # Helper method to clip a provided number between a minimum and maximum value. # minMax = (i, min, max) -> Math.min Math.max(i, min), max ##### `throwIfIncompatible(params)` # # Throws an error if incompatible colour properties are provided. # throwIfIncompatible = (params) -> rgb = hsl = false for key of params rgb = true if key in ['red', 'green', 'blue'] hsl = true if key in ['hue', 'saturation', 'luminosity'] if rgb and hsl throw 'Cannot change both RGB and HSL properties.' [rgb, hsl] #### Copyright # # Copyright (c) 2010-2011 [<NAME>](http://aaronrussell.co.uk). # Licensed under the [MIT license](http://www.opensource.org/licenses/mit-license.php).
true
# **jColour** is a JavaScript colour manipulation library written in [CoffeeScript](http://coffeescript.org). # jColour is inspired heavily by the [SASS](http://sass-lang.com)/[Compass](http://compass-style.org) # colour manipulation functions. # # jColour is also the first ever colour library to spell the word "colour" correctly. # # jColour is written by [PI:NAME:<NAME>END_PI](http://aaronrussell.co.uk), # the [source code for jColour](http://github.com/aaronrussell/jcolour) is available on Github and # is released under the [MIT license](http://www.opensource.org/licenses/mit-license.php). #### Download jColour # * [Download the minified version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.min.js) (8kb) # * [Download the fatter version](https://raw.github.com/aaronrussell/jcolour/master/build/jColour.js) (14kb) #### Creating a jColour object # The jColour class can be used in the browser or in your CommonJS projects. # root = exports ? this class root.jColour # Create a new jColour object by passing a colour string. jColour will parse a string in any of # the following formats: [recognised colour name](http://www.w3.org/TR/SVG/types.html#ColorKeywords), # hexidecimal, rgb/a, hsl/a. For example, all the following statements work: # # c = new jColour('red'); # c = new jColour('#f00'); # c = new jColour('#ff0000'); # c = new jColour('rgb(255,0,0)'); # c = new jColour('rgba(255,0,0,1)'); # c = new jColour('hsl(0,100,100)'); # c = new jColour('hsla(0,100,100,1)'); # # Internally, colours are represented in both RGB and HSL. Any colour adjustments result in # both representaions being recalculated. The alpha channel of a colour is stored independent # it's RGB or HSL representation. If no alpha value is supplied, it defaults to 1. # constructor: (col = '#ffffff') -> col = colourNames[col] if col.toLowerCase() of colourNames if hex = col.match /^#?([a-f0-9]{3})$/i h1 = hex[1].substring(0,1) h2 = hex[1].substring(1,2) h3 = hex[1].substring(2,3) col = "##{h1+h1+h2+h2+h3+h3}" if hex = col.match /^#?([a-f0-9]{6,8})$/i @red = parseInt hex[1].substring(0,2), 16 @green = parseInt hex[1].substring(2,4), 16 @blue = parseInt hex[1].substring(4,6), 16 @alpha = if hex[1].substring(6,8) then parseInt(hex[1].substring(6,8), 16) / 255 else 1 rgbToHsl this else if rgb = col.match /^rgba?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @red = parseInt rgb[1] @green = parseInt rgb[2] @blue = parseInt rgb[3] @alpha = if rgb[4] then rgb[4] else 1 rgbToHsl this else if hsl = col.match /^hsla?\(\s*(\d+)[,\s]*(\d+)[,\s]*(\d+)[,\s]*([\.\d]+)?\s*\)$/i @hue = parseInt hsl[1] @saturation = parseInt hsl[2] @lightness = parseInt hsl[3] @alpha = if hsl[4] then hsl[4] else 1 hslToRgb this else throw 'Invalid colour string.' #### Accessing colour representations # At any time, a jColour object can return a string of any of it's colour represenations. ##### `hex(show_alpha = false)` # # To return the hexidecimal value of the colour use the `hex()` method. By default, any alpha # value of the jColour object will be ignored. However, in specialist cases you may want a # hexdecimal representation of the alpha channel, in which case pass `true` to the method. # # c.hex(); # -> '#ff0000' # hex: (showAlpha = false) -> hex = if showAlpha && @alpha < 1 "##{hexify @red}#{hexify @green}#{hexify @blue}#{hexify @alpha * 255}" else "##{hexify @red}#{hexify @green}#{hexify @blue}" hex.toLowerCase() ##### `rgb()` # # Returns the RGB value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be RGBA. # # c.rgb(); # -> 'rgb(255,0,0)' # rgb: -> if @alpha == 1 "rgb(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue})" else "rgba(#{Math.round @red}, #{Math.round @green}, #{Math.round @blue}, #{Math.round(@alpha * 100) / 100})" ##### `hsl()` # # Returns the HSL value of the colour. If the jColour object's alpha channel is anything but 1, # the returned representation will be HSLA. # # c.hsl(); # -> 'hsl(0,100,100)' # hsl: -> if @alpha == 1 "hsl(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness})" else "hsla(#{Math.round @hue}, #{Math.round @saturation}, #{Math.round @lightness}, #{Math.round(@alpha * 100) / 100})" ##### `toS()` # # Returns the name of the colour if it is a recognised colour keyworld. Alternatively, the hex # code will be returned. # toS: -> for key, value of colourNames return key if @hex() == value.toLowerCase() @hex() #### Manipulating colours # A jColour object can be manipulated using a range of colour manipulation methods. Each method # makes the required adjustment to the colour representations and updates the jColour object. # This allows the "chaining" of methods, for example: # # c = new jColour('#ff0000'); # c.adjustHue(20).darken(10).transparentize(25).rgb(); # -> 'rgba(204, 68, 0, 0.75)' # # Most of the colour manipulation methods allow colour values to be manipulated relatively # (eg. 50 + 10 = 60) or scaled by a percentage (eg. 50 + 10% = 55). The name of the method should # make it obvious as to what calculation you should expect. ##### `lighten(amount)` # # Makes the colour lighter. Takes an amount between 0 and 100 which makes a relative adjustment # (increase) to the current lightness. # # c.lighten(25); # lighten: (amount) -> @lightness += amount hslToRgb this ##### `lightenPercent(percent)` # # Also makes the colour lighter. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* up relative to it's current value. # # c.lightenPercent(25); # lightenPercent: (percent) -> @lightness += (@lightness / 100) * percent hslToRgb this ##### `darken(amount)` # # Makes the colour darker. Takes an amount between 0 and 100 which makes a relative adjustment # (decrease) to the current lightness. # # c.darken(25); # darken: (amount) -> @lightness -= amount hslToRgb this ##### `darkenPercent(percent)` # # Also makes the colour darker. This method should also be passed a value between 0 and 100, but # in this case the lightness is *scaled* down relative to it's current value. # # c.darkenPercent(25); # darkenPercent: (percent) -> @lightness -= (@lightness / 100) * percent hslToRgb this ##### `saturate(amount)` # # Makes the colour more saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (increase) to the current saturation. # # c.saturate(25); # saturate: (amount) -> @saturation += amount hslToRgb this ##### `saturatePercent(percent)` # # Also makes the colour more saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* up relative to it's current value. # # c.saturatePercent(25); # saturatePercent: (percent) -> @saturation += (@saturation / 100) * percent hslToRgb this ##### `desaturate(amount)` # # Makes the colour less saturated. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current saturation. # # c.desaturate(25); # desaturate: (amount) -> @saturation -= amount hslToRgb this ##### `desaturatePercent(percent)` # # Also makes the colour less saturated. This method should also be passed a value between 0 and # 100, but in this case the saturation is *scaled* down relative to it's current value. # # c.desaturatePercent(25); # desaturatePercent: (percent) -> @saturation -= (@saturation / 100) * percent hslToRgb this ##### `greyscale()` # # Converts the color to greyscale. This is identical to `desaturate(100)`. Can also use the alias, `grayscale()`. # # c.greyscale(); # greyscale: -> @saturation = 0 hslToRgb this grayscale: -> @greyscale() ##### `adjustHue(degrees)` # # Changes the hue of the colour whilst retaining the lightness and saturation. This method should # be passed a number of degrees (usually between -360 and 360) and makes a relative adjustment to # the current hue. # # c.adjustHue(45); # adjustHue: (degrees) -> @hue += degrees hslToRgb this ##### `complement()` # # Returns the complement of the current colour. This is identical to `adjustHue(180)`. # # c.complement(); # complement: -> @hue += 180 hslToRgb this ##### `opacify(amount)` # # Makes the colour more opaque. Takes an amount between 0 and 1 which makes a relative # adjustment (increase) to the current alpha channel. # # c.opacify(0.25); # opacify: (amount) -> @alpha += amount @alpha = minMax @alpha, 0, 1 this ##### `transparentize(amount)` # # Makes the colour more transparent. Takes an amount between 0 and 100 which makes a relative # adjustment (decrease) to the current alpha channel. # # c.transparentize(0.25); # transparentize: (amount) -> @alpha -= amount @alpha = minMax @alpha, 0, 1 this ##### `invert()` # # Returns the inverse (negative) of the color. The red, green, and blue values are inverted, while # the opacity is left alone. # # c.invert(); # invert: -> for color in ['red', 'green', 'blue'] @[color] = 255 - @[color] rgbToHsl this ##### `adjustColour(params = {})` # # Makes a relative adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, hue, saturation, lightness and alpha. All properties are # optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between -255 and 255. The hue property should # have a value between -360 and 360. The saturation and lightness properties should have a value # between -100 and 100. The alpha property should have a value between 0 and 1. All values will # make a relative adjustment to their current value. # # c.adjustColour({ # red: 25, # green: -30, # alpha: -0.25 # }) # c.adjustColour({ # hue: 120, # lightness: 25, # saturation: -10 # }) # adjustColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `scaleColour(params = {})` # # Makes a scaled adjustment to one or more properties of the colour. Takes an object with the # properties of red, green, blue, saturation, lightness and alpha. Note that you can't scale the # hue value. All properties are optional and you can't specify both RGB and HSL properties at the # same time. # # All properties should have a value between -100 and 100. The property will be scaled up or down # relative to it's current value. # # c.scaleColour({ # red: 25, # green: -15 # }) # c.scaleColour({ # lightness: 25, # saturation: -10 # }) # scaleColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] += (@[key] / 100) * params[key] if key in properties and key isnt 'hue' if kind[0] then rgbToHsl this else hslToRgb this ##### `changeColour(params = {})` # # Changes one or more properties of the colour to the absolute value provided. Takes an object # with the properties of red, green, blue, hue, saturation, lightness and alpha. All properties # are optional and you can't specify both RGB and HSL properties at the same time. # # Red, green and blue propeties should have a value between 0 and 255. The hue property should # have a value between 0 and 360. The saturation and lightness properties should have a value # between 0 and 100. The alpha property should have a value between 0 and 1. All properties will # be set to the new value. # # c.changeColour({ # red: 255, # green: 0, # blue: 0 # }) # c.changeColour({ # hue: 0, # lightness: 100, # saturation: 100 # }) # changeColour: (params = {}) -> kind = throwIfIncompatible params for key of params @[key] = params[key] if key in properties if kind[0] then rgbToHsl this else hslToRgb this ##### `mixWith(colour, weight = 50)` # # Mixes the colour with another 'mix' colour. The mix colour can be passed as either a jColour # object or a string. Each of the RGB components are averaged, optionally weighted with a given # percentage. The opacity of the colours is also considered when weighting the components. # # The weight specifies the weight of the mix. The default, 50%, means half the original colour # and half the mix colour will be used. A weight of 25% means the a quarter of the mix colour # will be mixed with three quarters of the original colour. # # red = new jColour('#ff0000'); # red.mixWith('#ffffff', 75).rgb(); # -> 'rgb(255, 191, 191)' # mixWith: (colour, weight = 50) -> colour = new jColour(colour) unless colour instanceof jColour p = weight / 100 w = p * 2 - 1 a = colour.alpha - @alpha w1 = ((if w * a == -1 then w else (w + a) / (1 + w * a)) + 1) / 2 w2 = 1 - w1 @red = (colour.red * w1) + (@red * w2) @green = (colour.green * w1) + (@green * w2) @blue = (colour.blue * w1) + (@blue * w2) @alpha = (colour.alpha * p) + (@alpha * (1-p)) rgbToHsl this #### Private properties # This properties array is useful to have around. # properties = ['red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha'] # A mahoosive list of recognised colour keyword names as defined at # [http://www.w3.org/TR/SVG/types.html#ColorKeywords](http://www.w3.org/TR/SVG/types.html#ColorKeywords) # colourNames = aliceblue: '#F0F8FF' antiquewhite: '#FAEBD7' aqua: '#00FFFF' aquamarine: '#7FFFD4' azure: '#F0FFFF' beige: '#F5F5DC' bisque: '#FFE4C4' black: '#000000' blanchedalmond: '#FFEBCD' blue: '#0000FF' blueviolet: '#8A2BE2' brown: '#A52A2A' burlywood: '#DEB887' cadetblue: '#5F9EA0' chartreuse: '#7FFF00' chocolate: '#D2691E' coral: '#FF7F50' cornflowerblue: '#6495ED' cornsilk: '#FFF8DC' crimson: '#DC143C' cyan: '#00FFFF' darkblue: '#00008B' darkcyan: '#008B8B' darkgoldenrod: '#B8860B' darkgray: '#A9A9A9' darkgreen: '#006400' darkgrey: '#A9A9A9' darkkhaki: '#BDB76B' darkmagenta: '#8B008B' darkolivegreen: '#556B2F' darkorange: '#FF8C00' darkorchid: '#9932CC' darkred: '#8B0000' darksalmon: '#E9967A' darkseagreen: '#8FBC8F' darkslateblue: '#483D8B' darkslategray: '#2F4F4F' darkslategrey: '#2F4F4F' darkturquoise: '#00CED1' darkviolet: '#9400D3' deeppink: '#FF1493' deepskyblue: '#00BFFF' dimgray: '#696969' dimgrey: '#696969' dodgerblue: '#1E90FF' firebrick: '#B22222' floralwhite: '#FFFAF0' forestgreen: '#228B22' fuchsia: '#FF00FF' gainsboro: '#DCDCDC' ghostwhite: '#F8F8FF' gold: '#FFD700' goldenrod: '#DAA520' gray: '#808080' green: '#008000' greenyellow: '#ADFF2F' grey: '#808080' honeydew: '#F0FFF0' hotpink: '#FF69B4' indianred: '#CD5C5C' indigo: '#4B0082' ivory: '#FFFFF0' khaki: '#F0E68C' lavender: '#E6E6FA' lavenderblush: '#FFF0F5' lawngreen: '#7CFC00' lemonchiffon: '#FFFACD' lightblue: '#ADD8E6' lightcoral: '#F08080' lightcyan: '#E0FFFF' lightgoldenrodyellow: '#FAFAD2' lightgray: '#D3D3D3' lightgreen: '#90EE90' lightgrey: '#D3D3D3' lightpink: '#FFB6C1' lightsalmon: '#FFA07A' lightseagreen: '#20B2AA' lightskyblue: '#87CEFA' lightslategray: '#778899' lightslategrey: '#778899' lightsteelblue: '#B0C4DE' lightyellow: '#FFFFE0' lime: '#00FF00' limegreen: '#32CD32' linen: '#FAF0E6' magenta: '#FF00FF' maroon: '#800000' mediumaquamarine: '#66CDAA' mediumblue: '#0000CD' mediumorchid: '#BA55D3' mediumpurple: '#9370DB' mediumseagreen: '#3CB371' mediumslateblue: '#7B68EE' mediumspringgreen: '#00FA9A' mediumturquoise: '#48D1CC' mediumvioletred: '#C71585' midnightblue: '#191970' mintcream: '#F5FFFA' mistyrose: '#FFE4E1' moccasin: '#FFE4B5' navajowhite: '#FFDEAD' navy: '#000080' oldlace: '#FDF5E6' olive: '#808000' olivedrab: '#6B8E23' orange: '#FFA500' orangered: '#FF4500' orchid: '#DA70D6' palegoldenrod: '#EEE8AA' palegreen: '#98FB98' paleturquoise: '#AFEEEE' palevioletred: '#DB7093' papayawhip: '#FFEFD5' peachpuff: '#FFDAB9' peru: '#CD853F' pink: '#FFC0CB' plum: '#DDA0DD' powderblue: '#B0E0E6' purple: '#800080' red: '#FF0000' rosybrown: '#BC8F8F' royalblue: '#4169E1' saddlebrown: '#8B4513' salmon: '#FA8072' sandybrown: '#F4A460' seagreen: '#2E8B57' seashell: '#FFF5EE' sienna: '#A0522D' silver: '#C0C0C0' skyblue: '#87CEEB' slateblue: '#6A5ACD' slategray: '#708090' slategrey: '#708090' snow: '#FFFAFA' springgreen: '#00FF7F' steelblue: '#4682B4' tan: '#D2B48C' teal: '#008080' thistle: '#D8BFD8' tomato: '#FF6347' turquoise: '#40E0D0' violet: '#EE82EE' wheat: '#F5DEB3' white: '#FFFFFF' whitesmoke: '#F5F5F5' yellow: '#FFFF00' yellowgreen: '#9ACD32' #### Private helper methods # # The following methods are all used internally and are not accessible from outside the jColour object. # ##### `rgbToHsl(c)` # # Converts the RGB representation to a HSL representation. # rgbToHsl = (c) -> c.red = minMax c.red, 0, 255 c.green = minMax c.green, 0, 255 c.blue = minMax c.blue, 0, 255 c.alpha = minMax c.alpha, 0, 1 r = c.red / 255 g = c.green / 255 b = c.blue / 255 max = Math.max r, g, b min = Math.min r, g, b d = max - min h = switch max when min then 0 when r then 60 * (g - b) / d when g then 60 * (b - r) / d + 120 when b then 60 * (r - g) / d + 240 l = (max + min) / 2 s = if max == min 0 else if l < 0.5 d / (2 * l) else d / (2 - 2 * l) c.hue = h % 360 c.saturation = s * 100 c.lightness = l * 100 c ##### `hslToRgb(c)` # # Converts the HSL representation to a RGB representation. # hslToRgb = (c) -> c.hue -= Math.floor(c.hue/360)*360 if c.hue >= 360 c.hue -= Math.ceil(c.hue/360)*360 if c.hue < 0 c.saturation = minMax c.saturation, 0, 100 c.lightness = minMax c.lightness, 0, 100 c.alpha = minMax c.alpha, 0, 1 h = c.hue / 360 s = c.saturation / 100 l = c.lightness / 100 m2 = if l < 0.5 then l * (s + 1) else l + s - (l * s) m1 = l * 2 - m2 r = hueToRgb m1, m2, h + 1/3 g = hueToRgb m1, m2, h b = hueToRgb m1, m2, h - 1/3 c.red = r * 255 c.green = g * 255 c.blue = b * 255 c ##### `hueToRgb(p, q, t)` # # Algorithm for converting hue to each of the red, green and blue properties. # hueToRgb = (m1, m2, h) -> h += 1 if h < 0 h -= 1 if h > 1 return m1 + (m2 - m1) * h * 6 if h * 6 < 1 return m2 if h * 2 < 1 return m1 + (m2 - m1) * (2/3 - h) * 6 if h * 3 < 2 m1 ##### `hexify(n = '00')` # # Algorithm for converting each of the RGB colour channels to it's hex value. # hexify = (n = '00') -> n = parseInt n return '00' if n == 0 or isNaN n n = Math.round minMax(n, 0, 255) "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16) ##### `minMax(i, min, max)` # # Helper method to clip a provided number between a minimum and maximum value. # minMax = (i, min, max) -> Math.min Math.max(i, min), max ##### `throwIfIncompatible(params)` # # Throws an error if incompatible colour properties are provided. # throwIfIncompatible = (params) -> rgb = hsl = false for key of params rgb = true if key in ['red', 'green', 'blue'] hsl = true if key in ['hue', 'saturation', 'luminosity'] if rgb and hsl throw 'Cannot change both RGB and HSL properties.' [rgb, hsl] #### Copyright # # Copyright (c) 2010-2011 [PI:NAME:<NAME>END_PI](http://aaronrussell.co.uk). # Licensed under the [MIT license](http://www.opensource.org/licenses/mit-license.php).
[ { "context": "m: ({gameKey, userAgent} = {}) =>\n gameKey ?= 'freeroam'\n userAgent ?= navigator?.userAgent\n\n isApp", "end": 2101, "score": 0.9989674687385559, "start": 2093, "tag": "KEY", "value": "freeroam" } ]
src/services/environment.coffee
FreeRoamApp/free-roam
14
_includes = require 'lodash/includes' config = require '../config' class Environment isMobile: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent /// Mobile | iP(hone|od|ad) | Android | BlackBerry | IEMobile | Kindle | NetFront | Silk-Accelerated | (hpw|web)OS | Fennec | Minimo | Opera\ M(obi|ini) | Blazer | Dolfin | Dolphin | Skyfire | Zune ///.test userAgent isFacebook: -> window? and window.name.indexOf('canvas_fb') isnt -1 isTwitch: -> window?.Twitch isScreenshotter: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'SCREENSHOTTER' isAndroid: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'Android' isIos: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean userAgent?.match /iP(hone|od|ad)/g isNativeApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/") isMainApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/#{gameKey}") isGroupApp: (groupAppKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean groupAppKey and _includes(userAgent?.toLowerCase(), " freeroam/#{groupAppKey}/") getAppKey: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /freeroam\/([a-zA-Z0-9-]+)/ matches?[1] or 'browser' getChromeVerison: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /Chrome\/(.+?)\./ version = parseInt matches?[1] if isNaN version false else version getAppVersion: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent regex = new RegExp("(#{gameKey})\/(?:[a-zA-Z0-9]+/)?([0-9\.]+)") matches = userAgent.match(regex) matches?[2] getPlatform: ({gameKey, userAgent} = {}) => gameKey ?= 'freeroam' userAgent ?= navigator?.userAgent isApp = @isNativeApp gameKey, {userAgent} if @isFacebook() then 'facebook' else if @isTwitch() then 'twitch' else if isApp and @isIos(gameKey, {userAgent}) then 'ios' else if isApp and @isAndroid({userAgent}) then 'android' else 'web' module.exports = new Environment()
215862
_includes = require 'lodash/includes' config = require '../config' class Environment isMobile: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent /// Mobile | iP(hone|od|ad) | Android | BlackBerry | IEMobile | Kindle | NetFront | Silk-Accelerated | (hpw|web)OS | Fennec | Minimo | Opera\ M(obi|ini) | Blazer | Dolfin | Dolphin | Skyfire | Zune ///.test userAgent isFacebook: -> window? and window.name.indexOf('canvas_fb') isnt -1 isTwitch: -> window?.Twitch isScreenshotter: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'SCREENSHOTTER' isAndroid: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'Android' isIos: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean userAgent?.match /iP(hone|od|ad)/g isNativeApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/") isMainApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/#{gameKey}") isGroupApp: (groupAppKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean groupAppKey and _includes(userAgent?.toLowerCase(), " freeroam/#{groupAppKey}/") getAppKey: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /freeroam\/([a-zA-Z0-9-]+)/ matches?[1] or 'browser' getChromeVerison: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /Chrome\/(.+?)\./ version = parseInt matches?[1] if isNaN version false else version getAppVersion: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent regex = new RegExp("(#{gameKey})\/(?:[a-zA-Z0-9]+/)?([0-9\.]+)") matches = userAgent.match(regex) matches?[2] getPlatform: ({gameKey, userAgent} = {}) => gameKey ?= '<KEY>' userAgent ?= navigator?.userAgent isApp = @isNativeApp gameKey, {userAgent} if @isFacebook() then 'facebook' else if @isTwitch() then 'twitch' else if isApp and @isIos(gameKey, {userAgent}) then 'ios' else if isApp and @isAndroid({userAgent}) then 'android' else 'web' module.exports = new Environment()
true
_includes = require 'lodash/includes' config = require '../config' class Environment isMobile: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent /// Mobile | iP(hone|od|ad) | Android | BlackBerry | IEMobile | Kindle | NetFront | Silk-Accelerated | (hpw|web)OS | Fennec | Minimo | Opera\ M(obi|ini) | Blazer | Dolfin | Dolphin | Skyfire | Zune ///.test userAgent isFacebook: -> window? and window.name.indexOf('canvas_fb') isnt -1 isTwitch: -> window?.Twitch isScreenshotter: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'SCREENSHOTTER' isAndroid: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent _includes userAgent, 'Android' isIos: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean userAgent?.match /iP(hone|od|ad)/g isNativeApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/") isMainApp: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean gameKey and _includes(userAgent?.toLowerCase(), " #{gameKey}/#{gameKey}") isGroupApp: (groupAppKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent Boolean groupAppKey and _includes(userAgent?.toLowerCase(), " freeroam/#{groupAppKey}/") getAppKey: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /freeroam\/([a-zA-Z0-9-]+)/ matches?[1] or 'browser' getChromeVerison: ({userAgent} = {}) -> userAgent ?= navigator?.userAgent matches = userAgent.match /Chrome\/(.+?)\./ version = parseInt matches?[1] if isNaN version false else version getAppVersion: (gameKey, {userAgent} = {}) -> userAgent ?= navigator?.userAgent regex = new RegExp("(#{gameKey})\/(?:[a-zA-Z0-9]+/)?([0-9\.]+)") matches = userAgent.match(regex) matches?[2] getPlatform: ({gameKey, userAgent} = {}) => gameKey ?= 'PI:KEY:<KEY>END_PI' userAgent ?= navigator?.userAgent isApp = @isNativeApp gameKey, {userAgent} if @isFacebook() then 'facebook' else if @isTwitch() then 'twitch' else if isApp and @isIos(gameKey, {userAgent}) then 'ios' else if isApp and @isAndroid({userAgent}) then 'android' else 'web' module.exports = new Environment()
[ { "context": "3nd3} and chain A;')\n cmd.do('run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};')\n cmd.", "end": 13799, "score": 0.9934656620025635, "start": 13786, "tag": "USERNAME", "value": "blaine-mooers" }, { "context": "ells in all directions. This script was written by Thomas Holder.':\n 'prefix': 'sc222'\n 'body': '''\n cm", "end": 19242, "score": 0.9997041821479797, "start": 19229, "tag": "NAME", "value": "Thomas Holder" }, { "context": "\n 'body': '''\n cmd.do('https://github.com/MooersLab/pymolsnips/blob/master/README.md')\n \n $", "end": 39387, "score": 0.9149256348609924, "start": 39378, "tag": "USERNAME", "value": "MooersLab" }, { "context": " cmd.do(' The ipymol module was developed by Carlos Hernandez:')\n cmd.do(' ')\n cmd.do(' https:/", "end": 53175, "score": 0.9998868107795715, "start": 53159, "tag": "NAME", "value": "Carlos Hernandez" }, { "context": "d.do(' ')\n cmd.do(' https://github.com/cxhernandez/ipymol')\n cmd.do(' ')\n cmd.do(' T", "end": 53248, "score": 0.9992146492004395, "start": 53237, "tag": "USERNAME", "value": "cxhernandez" }, { "context": "ip install git+pip install git+https://github.com/cxhernandez/ipymol.git@2a30d6ec1588434e6f0f72a1d572444f89ff53", "end": 53862, "score": 0.9993327260017395, "start": 53851, "tag": "USERNAME", "value": "cxhernandez" }, { "context": ")\n cmd.do(' Copyright:')\n cmd.do(' Blaine Mooers and the OU Board of Regents')\n cmd.do(' U", "end": 55324, "score": 0.9998312592506409, "start": 55311, "tag": "NAME", "value": "Blaine Mooers" }, { "context": ")\n cmd.do(' Copyright:')\n cmd.do(' Blaine Mooers and the OU Board of Regents')\n cmd.do(' U", "end": 61025, "score": 0.999821662902832, "start": 61012, "tag": "NAME", "value": "Blaine Mooers" }, { "context": "ochem.queensu.ca/~rlc/work/pymol/draw_links.py] by Robert Campbell.':\n 'prefix': 'drawLinks'\n 'body': '''\n ", "end": 65331, "score": 0.999781608581543, "start": 65316, "tag": "NAME", "value": "Robert Campbell" }, { "context": "iochem.queensu.ca/~rlc/work/pymol/draw_links.py by Robert Campbell')\n cmd.do('# To connect the alpha carbons of", "end": 65501, "score": 0.9997487664222717, "start": 65486, "tag": "NAME", "value": "Robert Campbell" }, { "context": "ep)')\n \n ${0}\n '''\n 'OptiAlign.py by Jason Vertree modified for aligning multiple RNA structures.':\n", "end": 67971, "score": 0.9998780488967896, "start": 67958, "tag": "NAME", "value": "Jason Vertree" }, { "context": "1978.')\n cmd.do('#')\n cmd.do('# @AUTHOR: Jason Vertrees')\n cmd.do('# @COPYRIGHT: Jason Vertrees (C),", "end": 68455, "score": 0.9998912811279297, "start": 68441, "tag": "NAME", "value": "Jason Vertrees" }, { "context": "THOR: Jason Vertrees')\n cmd.do('# @COPYRIGHT: Jason Vertrees (C), 2005-2007')\n cmd.do('# @LICENSE: Releas", "end": 68500, "score": 0.9998868703842163, "start": 68486, "tag": "NAME", "value": "Jason Vertrees" }, { "context": ")\n cmd.do('# Jan. 29, 2020 ')\n cmd.do('# Blaine Mooers, PhD')\n cmd.do('# Univ. of Oklahoma Health S", "end": 69755, "score": 0.999865710735321, "start": 69742, "tag": "NAME", "value": "Blaine Mooers" }, { "context": " files with a common file stem. The is a script by Robert Campbell that updated for Python3.':\n 'prefix': 'loadMa", "end": 75869, "score": 0.9997851848602295, "start": 75854, "tag": "NAME", "value": "Robert Campbell" }, { "context": " 'body': '''\n cmd.do('# Copyright (c) 2004 Robert L. Campbell')\n cmd.do('#')\n cmd.do('# Modified for ", "end": 75997, "score": 0.9998868703842163, "start": 75979, "tag": "NAME", "value": "Robert L. Campbell" }, { "context": ")\n cmd.do('# Jan. 29, 2020 ')\n cmd.do('# Blaine Mooers, PhD')\n cmd.do('# Univ. of Oklahoma Health S", "end": 76129, "score": 0.9998777508735657, "start": 76116, "tag": "NAME", "value": "Blaine Mooers" }, { "context": "cartoons after loading the dssr_block.py script by Thomas Holder.':\n 'prefix': 'dssrBlock'\n 'body': '''\n ", "end": 78603, "score": 0.9937956929206848, "start": 78590, "tag": "NAME", "value": "Thomas Holder" }, { "context": "d blocks after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PAT", "end": 79015, "score": 0.9470787048339844, "start": 79002, "tag": "NAME", "value": "Thomas Holder" }, { "context": " example after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PAT", "end": 79326, "score": 0.9997780323028564, "start": 79313, "tag": "NAME", "value": "Thomas Holder" }, { "context": "coloring after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PAT", "end": 79659, "score": 0.9997830390930176, "start": 79646, "tag": "NAME", "value": "Thomas Holder" }, { "context": "Print a list of protein--ligand distances. Code by Dan Kulp. Updated for Python3.':\n 'prefix': 'listLigand", "end": 90075, "score": 0.9998392462730408, "start": 90067, "tag": "NAME", "value": "Dan Kulp" }, { "context": ")\n cmd.do('Adapted and updated from script by Dan Kulp posted here')\n cmd.do('https://sourceforge.n", "end": 90374, "score": 0.9997597336769104, "start": 90366, "tag": "NAME", "value": "Dan Kulp" }, { "context": "o(' ')\n cmd.do(' Pymol script copyright Matthew O'Meara and Xavier Ambroggio 2007')\n cmd.do(' ')\n", "end": 94533, "score": 0.9998845458030701, "start": 94518, "tag": "NAME", "value": "Matthew O'Meara" }, { "context": "do(' Pymol script copyright Matthew O'Meara and Xavier Ambroggio 2007')\n cmd.do(' ')\n cmd.do(' Und", "end": 94554, "score": 0.9998793601989746, "start": 94538, "tag": "NAME", "value": "Xavier Ambroggio" }, { "context": ".do(' Updated 15 June 2020 ')\n cmd.do(' Blaine Mooers')\n cmd.do(' ')\n cmd.do(' Notes:')", "end": 94940, "score": 0.999858558177948, "start": 94927, "tag": "NAME", "value": "Blaine Mooers" } ]
atompymolpysnips/pymolpysnippets.cson
MooersLab/pymolpysnips
0
'.source.python': 'Ambient occlussion.': 'prefix': 'ao' 'body': ''' cmd.do('set_color oxygen, [1.0,0.4,0.4];') cmd.do('set_color nitrogen, [0.5,0.5,1.0];') cmd.do('remove solvent;') cmd.do('as spheres;') cmd.do('util.cbaw;') cmd.do('bg white;') cmd.do('set light_count,10;') cmd.do('set spec_count,1;') cmd.do('set shininess, 10;') cmd.do('set specular,0.25;') cmd.do('set ambient,0;') cmd.do('set direct,0;') cmd.do('set reflect,1.5;') cmd.do('set ray_shadow_decay_factor, 0.1;') cmd.do('set ray_shadow_decay_range, 2;') cmd.do('unset depth_cue;') cmd.do('ray;') ${0} ''' 'Set ellipsoid color.': 'prefix': 'ellipcol' 'body': ''' cmd.do('set ellipsoid_color, ${1:color};') cmd.do('${0}') ${0} ''' 'set distance labels to display 2 decimals': 'prefix': 'sigdist' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') ${0} ''' 'Set angle labels to display 2 decimals places': 'prefix': 'sigang' 'body': ''' cmd.do('set label_angle_digits, ${1:2};') ${0} ''' 'Ball and stick representation. ': 'prefix': 'bs' 'body': ''' cmd.do('show sticks;') cmd.do('set stick_radius, 0.12;') cmd.do('set stick_ball, on;') cmd.do('set stick_ball_ratio, 1.9;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size=0.33;') ${0} ''' 'Base-stacking figure.': 'prefix': 'stack' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4PCO}, type=pdb,async=0;') cmd.do('select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );') cmd.do('hide everything, element h; ') cmd.do('remove not ${2:G2G3};') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7. 24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('hide everything, element H;') cmd.do('select carbon1, element C and (resi ${4:3} or resi ${5:8}); ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi ${3:2} or resi ${6:9});') cmd.do('#select upper base pair;') cmd.do('color gray70,carbon1;') cmd.do('color gray10,carbon2;') cmd.do('space cmyk;') cmd.do('distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;') cmd.do('distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;') cmd.do('distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;') cmd.do('distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png ${1:4PCO}.png') ${0} ''' 'Biological unit.': 'prefix': 'bu' 'body': ''' cmd.do('run ~/Scripts/PyMOLScripts/quat.py; quat') ${0} ''' 'Valence bond. ': 'prefix': 'doubleBond' 'body': ''' cmd.do('set valence, 1; ') cmd.do('set valence_mode, 1;') ${0} ''' 'Color blindness.': 'prefix': 'cblind' 'body': ''' cmd.do('run ~/Pymol-script-repo/colorblindfriendly.py;') cmd.do('as cartoon;') cmd.do('color cb_red, ss H;') cmd.do('color cb_yellow,ss S;') cmd.do('color cb_green, ss L+;') ${0} ''' 'Center pi.': 'prefix': 'centerpi' 'body': ''' cmd.do('pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;') cmd.do('dist pi_cent////ps1, b/${4:U`15}/${5:aaa};') ${0} ''' 'Color ribbon H red, strand yellow, loop green.': 'prefix': 'cribbon' 'body': ''' cmd.do('as cartoon;') cmd.do('color red, ss H;') cmd.do('color yellow,ss S;') cmd.do('color green, ss L+;') ${0} ''' 'Colored spheres.': 'prefix': 'cspheres' 'body': ''' cmd.do('as spheres;') cmd.do('color gray30, chain ${1:A};') cmd.do('color white, chain ${2:B};') cmd.do('color green, name CL;') cmd.do('color brown, resn NAG;') cmd.do('color red, resi 381;') cmd.do('remove solvent;') cmd.do('unset specular;') cmd.do('set ray_trace_gain, 0;') cmd.do('set ray_trace_mode, 3;') cmd.do('bg_color white;') cmd.do('set ray_trace_color, black;') cmd.do('unset depth_cue;') ${0} ''' 'Coordinate covalent bonds to metals and H-bonds friom RNA.': 'prefix': 'coordinate' 'body': ''' cmd.do('viewport 900,600;') cmd.do('fetch 3nd4, type=pdb, async=0;') cmd.do('run ~/Scripts/PyMOLScripts/quat.py;') cmd.do('quat 3nd4;') cmd.do('show sticks;') cmd.do('set stick_radius=0.125;') cmd.do('hide everything, name H*;') cmd.do('bg_color white;') cmd.do('create coorCov, (3nd4_1 and (resi 19 or resi 119 or resi 219 or resi 319 or resi 419 or resi 519 or (resi 3 and name N7)));') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);') cmd.do('distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);') cmd.do('show nb_spheres; ') cmd.do('set nb_spheres_size, .35;') cmd.do('distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;') cmd.do('distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;') cmd.do('distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;') cmd.do('distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;') cmd.do('distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;') cmd.do('distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;') cmd.do('distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;') cmd.do('distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;') cmd.do('distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;') cmd.do('distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;') cmd.do('distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;') cmd.do('distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;') cmd.do(' distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;') cmd.do('distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;') cmd.do('distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;') cmd.do('distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2; ') cmd.do('set depth_cue=0;') cmd.do('set ray_trace_fog=0;') cmd.do('set dash_color, black;') cmd.do('set label_font_id, 5;') cmd.do('set label_size, 36;') cmd.do('set label_position, (0.5, 1.0, 2.0);') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('select carbon, element C;') cmd.do('color yellow, carbon;') cmd.do('disable carbon;') cmd.do('set_view(-0.9,0.34,-0.26,0.33,0.18,-0.93,-0.27,-0.92,-0.28,-0.07,-0.23,-27.83,8.63,19.85,13.2,16.0,31.63,-20.0)') ${0} ''' 'H-bond distances.': 'prefix': 'distance' 'body': ''' cmd.do('distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}') ${0} ''' 'Draw H-bonds. ': 'prefix': 'drawHbonds' 'body': ''' cmd.do('hide everything, hydrogens') cmd.do('hide labels') cmd.do('set dash_color, ${1:black}${2:yelow} ') cmd.do('set dash_gap, 0.4') cmd.do('set dash_radius, 0.08') ${0} ''' 'Carved isomesh representation of electron density. ': 'prefix': 'carvedIsomesh' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isomesh.': 'prefix': 'fetch2FoFcIsomesh' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isomesh 2fofcmap, ${1:3nd4_2fofc}, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Fetch cif file.': 'prefix': 'fetchCIF' 'body': ''' cmd.do('fetch ${1:3nd4}, type=cif, async=0;') ${0} ''' 'Fetch fofc map.': 'prefix': 'fetchFoFc' 'body': ''' cmd.do('fetch ${1:3nd4}, type=fofc, async=0;') ${0} ''' 'Filled rings in nucleic acids. ': 'prefix': 'filledRing' 'body': ''' cmd.do('show sticks;set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'Get coordinates. ': 'prefix': 'getCoordinates' 'body': ''' cmd.do('print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');') ${0} ''' 'H-bond dashes.': 'prefix': 'hbonddash' 'body': ''' cmd.do('hide everything, hydrogens;') cmd.do('hide labels;') cmd.do('set dash_color, black; ') cmd.do('set dash_gap, 0.4;') cmd.do('set dash_radius, 0.08;') ${0} ''' 'Hbond setup. ': 'prefix': 'hbond' 'body': ''' cmd.do('hide labels;') cmd.do('set dash_color, black ;') cmd.do('set dash_length, ${1:0.15};') cmd.do('set dash_gap, ${2:0.35};') cmd.do('set dash_width, ${3:3.0};') ${0} ''' 'Hide alt loc.': 'prefix': 'hidealtloc' 'body': ''' cmd.do('select altconf, alt ${1:b} # select B alternative locators;') cmd.do('hide everything, altconf # hide alt B locators;') ${0} ''' 'Label CA atom with single-letter residue name and residue number.': 'prefix': 'labelResnResi' 'body': ''' cmd.do('label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});') ${0} ''' 'Label SS. ': 'prefix': 'labelSS' 'body': ''' cmd.do('alter ${1:}, ss='%1';') cmd.do('label (%2),'%3';') ${0} ''' 'Load PDB ball-and-stick.': 'prefix': 'loadPDBbs' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('hide (name H*);') cmd.do('hide lines;') cmd.do('show sticks;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('set nb_sphere_radius, ${3:0.35};') cmd.do('orient;') ${0} ''' 'Load PDB nb spheres. ': 'prefix': 'loadPDBnb' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;') cmd.do('orient;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('hide (name H*);') cmd.do('set nb_sphere_size, ${3:0.35};') cmd.do('set nb_spheres_quality, ${4:1};') cmd.do('show nb_spheres;') ${0} ''' 'Measure surface area. ': 'prefix': 'ms' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('select ${2:temp}, ${3:3nd3} and chain A;') cmd.do('run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};') cmd.do('calc_msms_area ${2:temp};') ${0} ''' 'Molscript ribbons.': 'prefix': 'molscriptRibbon' 'body': ''' cmd.do('set cartoon_highlight_color, grey;') cmd.do('show cartoon;') cmd.do('set cartoon_flat_sheets, 0;') cmd.do('set cartoon_smooth_loops, 0;') cmd.do('set cartoon_fancy_helices, 1;') ${0} ''' 'One letter amino acid. ': 'prefix': 'oneLetter' 'body': ''' cmd.do('one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%') cmd.do(''ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%') cmd.do(''SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%') ${0} ''' 'Print Fasta from PDB file. ': 'prefix': 'fasta' 'body': ''' cmd.do('print cmd.get_fastastr('all')') ${0} ''' 'Position label with pseudoatom. ': 'prefix': 'pseudolabel' 'body': ''' cmd.do('pseudoatom ${1:forLabel};') cmd.do('label ${1:forLabel}, '%0';') cmd.do('set label_color, ${2:red};') ${0} ''' 'Rotate about axis.': 'prefix': 'rotate' 'body': ''' cmd.do('rotate ${1:x}, ${2:45}, ${3:pept};') ${0} ''' 'Stereo draw.': 'prefix': 'stereoDraw' 'body': ''' cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') ${0} ''' 'Stereo ray.': 'prefix': 'stereoRay' 'body': ''' cmd.do('stereo; ') cmd.do('set ray_shadow, off;') cmd.do('ray ${1:2400,1200};') cmd.do('png ${2:aaa}.png;') ${0} ''' 'Three electron density as Isomesh. ': 'prefix': 'threeMapsIsomesh' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Turn about axis. ': 'prefix': 'turnAboutAxis' 'body': ''' cmd.do('turn ${1:x},${2:90};') ${0} ''' 'Volume ramp.': 'prefix': 'volumeRamp' 'body': ''' cmd.do('cmd.volume_ramp_new('ramp_magenta', [0.01, 1.00, 0.00, 1.00, 0.00, 4.01, 1.00, 0.00, 1.00, 0.10, 4.99, 1.00, 0.00, 1.00, 0.50,])') ${0} ''' 'Set radius of ball used to make solvent accessible surface.': 'prefix': 'solventRadius' 'body': ''' cmd.do('set solvent_radius, ${1:1.55};') ${0} ''' 'Scale the radius and color of atoms as spheres by property in the B-value column.': 'prefix': 'scaleRadiusColor' 'body': ''' cmd.do('bg_color white;') cmd.do('hide everything;') cmd.do('show spheres;') cmd.do('set stick_radius = 0.1;') cmd.do('hide everything, HET;') cmd.do('show spheres, HET;') cmd.do('set sphere_quality=3;') cmd.do('show sticks, resi $1{1102};') cmd.do('from pymol import stored;') cmd.do('# set the stored array equal to the b−values or use your own values; ') cmd.do('stored.bb = [ ];') cmd.do('iterate all, stored.bb.append(b);') cmd.do('# execute a python−block;') cmd.do('python;') cmd.do('# scale the b−values;') cmd.do('M = max(stored.bb);') cmd.do('scaledBB = map(lambda x: float (x/M), stored.bb);') cmd.do('count = 0;') cmd.do('# set the sphere radii independently;') cmd.do('#[(cmd.set("sphere_scale", x ,"ID %s"%count); count = count + 1) for x in scaledBB]') cmd.do('for x in scaledBB:') cmd.do(' cmd.set("sphere_scale", x ,"ID %s"%count)') cmd.do(' count = count + 1') cmd.do('python end') cmd.do('spectrum b, selection=${2:4gdx};') cmd.do('space cmyk;') cmd.do('set specular_intensity , 0.25;') ${0} ''' 'Return settings in rounded format.': 'prefix': 'rv' 'body': ''' cmd.do('run roundview.py;') ${0} ''' 'Save png flle with timestamp': 'prefix': 'spng' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".png"); ') cmd.do('end python;') ${0} ''' 'Save pse flle with timestamp': 'prefix': 'spse' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".pse"); ') cmd.do('end python;') ${0} ''' 'Run supercell script to generate three cells in all directions. This script was written by Thomas Holder.': 'prefix': 'sc222' 'body': ''' cmd.do('run ${1:$HOME/Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 2, 2, 2, , orange, supercell2, 1;') ${0} ''' 'The pearl effect is made with two spheres with the outer sphere being transparent.': 'prefix': 'pearl' 'body': ''' cmd.do('create ${1:sodium2}, ${2:sodium1};') cmd.do('set sphere_transparency, 0.4, ${1:sodium2};') cmd.do('set sphere_scale, 1.05, ${1:sodium2};') cmd.do('ray;') ${0} ''' 'Blur the background atoms.': 'prefix': 'fog' 'body': ''' cmd.do('set fog, 0;') ${0} ''' 'Remove waters from molecular object.': 'prefix': 'rmwater' 'body': ''' cmd.do('remove resn HOH;') ${0} ''' 'Set color name to a RGB code.': 'prefix': 'setcolor' 'body': ''' cmd.do('set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}];') cmd.do('color ${1:bark}, ${5:protein};') ${0} ''' 'Duplicate object.': 'prefix': 'duplicateObject' 'body': ''' cmd.do('create ${1:t4l}, ${2:1lw9};') ${0} ''' 'Select a chain. ': 'prefix': 'selectChain' 'body': ''' cmd.do('select rna, chain B;') ${0} ''' 'Select residues by name.': 'prefix': 'selectResidues' 'body': ''' cmd.do('select aromatic, resn phe+tyr+trp;') ${0} ''' 'Select residues by a range of numbers.': 'prefix': 'selectResi' 'body': ''' cmd.do('select ${!:se}; resi ${2:1-100};') ${0} ''' 'Select atoms by element.': 'prefix': 'selectElement' 'body': ''' cmd.do('select ${1:oxygen}, elem ${2:O}') ${0} ''' 'Select atoms by name.': 'prefix': 'selectName' 'body': ''' cmd.do('select ${1:oxygen2}, name ${2:O2}') ${0} ''' 'Select atoms by alpha helices.': 'prefix': 'selectHelices' 'body': ''' cmd.do('select ${1:helices}, ss h; ') ${0} ''' 'Select atoms by beta strands.': 'prefix': 'selectStrands' 'body': ''' cmd.do('select ${1:strands}, ss s; ') ${0} ''' 'Select atoms by beta loops.': 'prefix': 'selectLoops' 'body': ''' cmd.do('select ${1:loops}, ss l;') ${0} ''' 'Select all nitrogen atom in a selelction except from lysine.': 'prefix': 'selectAllBut' 'body': ''' cmd.do('select ${1:select1}, elem ${2:N} and chain ${3:A} and not resn ${4:LYS};') ${0} ''' 'Select atoms within a radius around a ligand.': 'prefix': 'selectAtomsAround' 'body': ''' cmd.do('select ${1:nearby}, resn ${2:drug} around ${3:5};') ${0} ''' 'Select residues within a radius around a ligand.': 'prefix': 'selectResiduesAround' 'body': ''' cmd.do('select ${1:nearby}, br. resn ${2:drug} around ${3:5};') ${0} ''' 'Undo a selection.': 'prefix': 'undoSelection' 'body': ''' cmd.do('disable ${1:sele}; ') ${0} ''' 'Load a pdb file in the current directory.': 'prefix': 'loadPDBfile' 'body': ''' cmd.do('load ${1:my.pdb};') ${0} ''' 'Save a png file of current scene to the current directory.': 'prefix': 'savePNG' 'body': ''' cmd.do('png ${1:saveMe.png};') ${0} ''' 'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.': 'prefix': 'ringMode' 'body': ''' cmd.do('show cartoon, ${1:rna}; set cartoon_ring_mode, ${2:3};') ${0} ''' 'In cartoons, hide the backbone atoms of selected residues when showing then as sticks.': 'prefix': 'sidehChainHelper' 'body': ''' cmd.do('set cartoon_side_chain_helper, on;') ${0} ''' 'Create a new object from part of an existing object.': 'prefix': 'extractPartObj' 'body': ''' cmd.do('extract new_obj, chain A;') ${0} ''' 'Create a putty cartoon.': 'prefix': 'puttyCartoon' 'body': ''' cmd.do('show cartoon;') cmd.do('cartoon putty;') cmd.do('unset cartoon_smooth_loops;') cmd.do('unset cartoon_flat_sheets;') ${0} ''' 'Trun off magenta squares on current selection.': 'prefix': 'hideSelection' 'body': ''' cmd.do('indicate none') ${0} ''' 'Turn on discrete colors between secondary structure elements.': 'prefix': 'discreteCartoonColoring' 'body': ''' cmd.do('set cartoon_discrete_colors, on;') ${0} ''' 'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc111' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , orange, supercell1, 1;') ${0} ''' 'Display SAXS envelope': 'prefix': 'saxsEnvelope' 'body': ''' cmd.do('alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0;') cmd.do('set solvent_radius = 3.0;') ${0} ''' 'Set additional path for PyMOL to search on startup': 'prefix': 'setpath' 'body': ''' cmd.do('os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};') ${0} ''' 'Set path for location to save fetched pdb files. ': 'prefix': 'fetchPath' 'body': ''' cmd.do('set fetch_path, ${1:/Users/blaine/pdbFiles};') ${0} ''' 'Set antialias to get smooth edges': 'prefix': 'antialias' 'body': ''' cmd.do('set antialias, 1;') ${0} ''' 'Print list of active pymolrc files.': 'prefix': 'lspymolrc' 'body': ''' cmd.do('print invocation.options.deferred;') ${0} ''' 'Set number of decimals places to show in distance labels. ': 'prefix': 'sigDigits' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') cmd.do('set label_angle_digits, ${2:2};') ${0} ''' 'Label the CA atoms with the Ala333 style format': 'prefix': 'labelCAs' 'body': ''' cmd.do('label name CA,"%s%s" % (resn,resi);') ${0} ''' 'Label waters HOH.': 'prefix': 'labelWatersHOH' 'body': ''' cmd.do('label resn HOH ,"%s%s" % (resn,resi);') ${0} ''' 'Label waters W.': 'prefix': 'labelWatersW' 'body': ''' cmd.do('label resn HOH ,"W%s" % (resi);') ${0} ''' 'Find hbonds around a residue.': 'prefix': 'findHbonds' 'body': ''' cmd.do('remove element h; distance hbonds, all, all, 3.2, mode=2;') ${0} ''' 'Print the B-factors of a residue. ': 'prefix': 'printBs' 'body': ''' cmd.do('remove element h; iterate resi %{1:133}, print resi, name,b;') ${0} ''' 'Label the main chain atoms by resn,resi,atom name.': 'prefix': 'labelMainChain' 'body': ''' cmd.do('label name n+c+o+ca,"%s%s%s" % (resn,resi,name);') ${0} ''' 'Print B factors of part B of a residue.': 'prefix': 'printBspartB' 'body': ''' cmd.do('iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;') ${0} ''' 'Print B--factors for a residue with the B-factors rounded off to two decimal places.': 'prefix': 'printBs2digits' 'body': ''' cmd.do('iterate (resi %{1:133}), print(name + " %.2f" % b);') ${0} ''' 'Write the command reference to html file in the present working directory. ': 'prefix': 'writeCommandReference2HTML' 'body': ''' cmd.do('cmd.write_html_ref('pymol-command-ref.html');') ${0} ''' 'Average the B-factors by using a regular list as opposed to a stored list in PyMOL. Edit the selection as needed.': 'prefix': 'averageB' 'body': ''' cmd.do('"""Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""') cmd.do('Bfactors = []; ') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print("Sum = ", "%.2f" % (sum(Bfactors)));') cmd.do('print("Number of atoms = ", len(Bfactors));') cmd.do('print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));') ${0} ''' 'AveBResiX, prints the resiude number and the average bfactor. ': 'prefix': 'aveB4resiX' 'body': ''' cmd.do('""""AveBResiX, prints the resiude number and the average bfactor. ') cmd.do('Uses reduce and lambda, builtin Python functional porgramming functions. ') cmd.do('Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum. ') cmd.do('"""') cmd.do('Bfactors = [];') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print( "Average B-factor of residue ", %{1:133} , " = ", "%.2f" %(reduce(lambda x, y: x + y, Bfactors) / float(len(Bfactors))) )') ${0} ''' 'Print name and b-factor for a residue.': 'prefix': 'printNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((name, b))", space=Bfac_dict); for i,j in Bfac_dict['Bfactors3']: print("%s %.2f" % (i,j));') ${0} ''' 'Print resn, resi, atom name, and b-factor. ': 'prefix': 'printResiResnNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Print name and b-factor for a residue or residue range (e.g. 81:120). The noH variant.': 'prefix': 'printResiResnNameB4ResiXNoH' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133 and not elem H)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Make the background of the internal gui transparent to expand viewport.': 'prefix': 'internalGUImode2 ' 'body': ''' cmd.do('internal_gui_mode=2;') ${0} ''' 'Set the width of the internal gui. ': 'prefix': 'internalGUIwidth' 'body': ''' cmd.do('internal_gui_width=%{1:20};') ${0} ''' 'Print document string of a function.': 'prefix': 'printDoc' 'body': ''' cmd.do('print ${1:my_func}.__doc__;') ${0} ''' 'List all snips by tab trigger and description': 'prefix': 'lsSnips' 'body': ''' cmd.do('"""Tab trigger Description') cmd.do('--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------') cmd.do('antialias Set antialias to get smooth edges') cmd.do('ao Ambient occlussion.') cmd.do('aveB4resiX AveBResiX, prints the resiude number and the average bfactor.') cmd.do(' Uses reduce and lambda, builtin Python functional porgramming functions.') cmd.do(' Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.') cmd.do('averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.') cmd.do('bs Ball and stick representation.') cmd.do('bu Biological unit.') cmd.do('carvedDensity Carved electron density.') cmd.do('cblind Color blindness.') cmd.do('centerpi Center pi.') cmd.do('coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.') cmd.do('cribbon Color ribbon H red, strand yellow, loop green.') cmd.do('cspheres Colored spheres.') cmd.do('discreteCartoonColoring Turn on discrete colors between secondary structure elements.') cmd.do('distance H-bond distances.') cmd.do('doubleBond Valence bond.') cmd.do('drawHbonds Draw H-bonds.') cmd.do('duplicateObject Duplicate object.') cmd.do('ellipcol Set ellipsoid color.') cmd.do('extractPartObj Create a new object from part of an existing object.') cmd.do('fasta Print Fasta from PDB file.') cmd.do('fetch2FoFc Fetch 2FoFc map.') cmd.do('fetchCIF Fetch cif file.') cmd.do('fetchFoFc Fetch fofc map.') cmd.do('fetchPath Set path for location to save fetched pdb files.') cmd.do('filledRing Filled rings in nucleic acids.') cmd.do('findHbonds Find hbonds around a residue.') cmd.do('fog Blur the background atoms.') cmd.do('getCoordinates Get coordinates.') cmd.do('hbond Hbond setup.') cmd.do('hbonddash H-bond dashes.') cmd.do('hideSelection Trun off magenta squares on current selection.') cmd.do('hidealtloc Hide alt loc.') cmd.do('internalGUImode2 Makes the background of the internal gui transparent with the viewport extended into this region of the gui. This may be a useful mode for workshops.') cmd.do('internalGUIwidth Set the width of the internal gui.') cmd.do('labelCAs Label the CA atoms with the Ala333 style format') cmd.do('labelMainChain Label the main chain atoms by resn,resi,atom name.') cmd.do('labelResnResi Label CA atom with residue name and residue number.') cmd.do('labelSS Label SS.') cmd.do('labelWatersHOH Label waters HOH.') cmd.do('labelWatersW Label waters W.') cmd.do('loadPDBbs Load PDB ball-and-stick.') cmd.do('loadPDBfile Load a pdb file in the current directory.') cmd.do('loadPDBnb Load PDB nb spheres.') cmd.do('lsSnips List all snips by tab trigger and description') cmd.do('lspymolrc Print list of active pymolrc files.') cmd.do('molscriptRibbon Molscript ribbons.') cmd.do('ms Measure surface area.') cmd.do('oneLetter One letter amino acid.') cmd.do('pearl The pearl effect is made with two spheres with the outer sphere being transparent.') cmd.do('printBs Print the B-factors of a residue.') cmd.do('printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.') cmd.do('printBspartB Print B factors of part B of a rsidues.') cmd.do('printDoc Print document string of a function.') cmd.do('printNameB4ResiX Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). Use the noH variant if H atoms are present.') cmd.do('printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.') cmd.do('printResiResnNameB4ResiXNoH Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). The noH variant.') cmd.do('pseudolabel Position label with pseudoatom.') cmd.do('puttyCartoon Create a putty cartoon.') cmd.do('ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.') cmd.do('rmwater Remove waters from molecular object.') cmd.do('rotate Rotate about axis.') cmd.do('rv Return settings in rounded format.') cmd.do('savePNG Save a png file of current scene to the current directory.') cmd.do('saxsEnvelope Display SAXS envelope') cmd.do('sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.') cmd.do('sc222 Run Tom Holder's supercell script to generate three cells in all directions.') cmd.do('scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.') cmd.do('selectAllBut Select all nitrogen atom in a selelction except from lysine.') cmd.do('selectAtomsAround Select atoms within a radius around a ligand.') cmd.do('selectChain Select a chain.') cmd.do('selectElement Select atoms by elemnt.') cmd.do('selectHelices Select atoms by alpha helices.') cmd.do('selectLoops Select atoms by beta loops.') cmd.do('selectName Select atoms by name.') cmd.do('selectResi Select residues by a range of numbers.') cmd.do('selectResidues Select residues by name.') cmd.do('selectResiduesAround Select residues within a radius around a ligand.') cmd.do('selectStrands Select atoms by beta strands.') cmd.do('setcolor Set color name to a RGB code.') cmd.do('setpath Set additional path for PyMOL to search on startup') cmd.do('sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.') cmd.do('sigDigits Set number of decimals places to show in distance labels.') cmd.do('sigang Set angle labels to display 2 decimals places') cmd.do('sigdist set distance labels to display 2 decimals') cmd.do('solventRadius Set radius of ball used to make solvent accessible surface.') cmd.do('spng Save png flle with timestamp') cmd.do('spse Save pse flle with timestamp') cmd.do('stack Base-stacking figure.') cmd.do('stereoDraw Stereo draw.') cmd.do('stereoRay Stereo ray.') cmd.do('threeMaps Three electron density.') cmd.do('turnAboutAxis Turn about axis.') cmd.do('undoSelection Undo a selection.') cmd.do('volumeRamp Volume ramp.') cmd.do('writeCommandReference2HTML Write the command reference to html file in the present working directory."""') ${0} ''' 'Asp70-His31 salt-bridge from T4 lysozyme. ': 'prefix': 'his31asp70' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom (resi 31 or resi 70); ') cmd.do('preset.technical(selection='all'); ') cmd.do('bg_color gray70; ') cmd.do('clip slab, 7,(resi 31 or resi 70);') cmd.do('rock;') ${0} ''' 'triple water pentagon.': 'prefix': 'waterTriple' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom resi 313; ') cmd.do('preset.technical(selection='all', mode=1);') ${0} ''' 'Make selection of ligand atoms.': 'prefix': 'ligandSelect' 'body': ''' cmd.do('select substrates, organic;') ${0} ''' 'Print url of README.md file of the pymolsnips repository.': 'prefix': 'github' 'body': ''' cmd.do('https://github.com/MooersLab/pymolsnips/blob/master/README.md') ${0} ''' 'Set dihedral labels to display 2 decimals places to the right of the decimal point.': 'prefix': 'sigdihedral' 'body': ''' cmd.do('set label_dihedral_digits, ${1:2};') ${0} ''' 'Select state 1 from a model with multiple states.': 'prefix': 'stateOne' 'body': ''' cmd.do('cmd.create('newobject', 'oldobject', '1', '1');') ${0} ''' 'Display all symmetry mates in two unit cells along the c axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc112' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cels along c. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc113' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates three three unit cells along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc311' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cells along b. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc131' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cell along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc211' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cells along the b axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc121' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 1 x 2 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc122' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 2 x 2 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc221' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 1 x 2 arrays of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc212' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 1 x 3 x 3 array of unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc133' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 1 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc313' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc331' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc233' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 2 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc323' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc332' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc333' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long c-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc114' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long b-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc141' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long a-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc411' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Save aln flle with timestamp': 'prefix': 'saln' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd;') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT);') cmd.do('cmd.save(stemName+s+".aln");') cmd.do('end python;') ${0} ''' 'Save electron density map flle with timestamp': 'prefix': 'sccp4' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".ccp4"); ') cmd.do('end python;') ${0} ''' 'Save dae flle with timestamp': 'prefix': 'sdae' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".dae"); ') cmd.do('end python;') ${0} ''' 'Carved isosurface representation of electron density. ': 'prefix': 'carvedIsosurface' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isosurface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isosurface.': 'prefix': 'fetch2FoFcIsosurface' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isosurface 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as isosurface. ': 'prefix': 'threeMapsIsosurface' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isosurface ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isosurface ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isosurface ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Carved volume representation of electron density. ': 'prefix': 'carvedVolume' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('surface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as a volume.': 'prefix': 'fetch2FoFcVolume' 'body': ''' cmd.do('fetch ${1:3nd4}, type=2fofc, async=0;') cmd.do('volume 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as volumes. ': 'prefix': 'threeMapsVolume' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('volume ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('volume ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('volume ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server ipymol in a jupuyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvi' 'body': ''' cmd.do('def rvj(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """') cmd.do(' rvj() is a modification of the the rv() function (aka the roundview.py) ') cmd.do(' so that it can run in Jupyter notebooks with the ipymol.viewer. ') cmd.do(' A set_view string is printed to the noteobook in a format that is ready ') cmd.do(' for reuse. ') cmd.do(' ') cmd.do(' The ipymol module was developed by Carlos Hernandez:') cmd.do(' ') cmd.do(' https://github.com/cxhernandez/ipymol') cmd.do(' ') cmd.do(' The pre-requisites for installing ipymol are as follows:') cmd.do(' ') cmd.do(' 1. Make a jupyter notebook kernel for Python interpreter inside of ') cmd.do(' the Schrodinger PyMOL. See the PyMOL Snippets GitHub Page for ') cmd.do(' a description of how to make one.') cmd.do(' 2. Install the following build of ipymol at the PyMOL prompt.') cmd.do(' You need to log into your GitHub account first.') cmd.do(' ') cmd.do(' pip install git+pip install git+https://github.com/cxhernandez/ipymol.git@2a30d6ec1588434e6f0f72a1d572444f89ff535b') cmd.do(' ') cmd.do(' 3. Make a bash alias to this PyMOL app file.') cmd.do(' ') cmd.do(' 4. Launch the jupyter notebook and select the pymol.python kernel.') cmd.do(' ') cmd.do(' 5. Open a terminal instance from the File pulldown in jupyter notebook.') cmd.do(' ') cmd.do(' 6. Enter `pymol -Rq` to launch an interactive instance of PyMOL.') cmd.do(' ') cmd.do(' 7. Enter the following code to load ipymol and conmect to PyMOL') cmd.do(' ') cmd.do(' from ipymol import viewer as ipv') cmd.do(' ipv.start() # Start PyMOL RPC server') cmd.do(' ') cmd.do(' Now you can change the scene manually and send the display as static ') cmd.do(' image to a cell in the jupyter notebook.') cmd.do(' ') cmd.do(' It is assumed that the viewer class of the ipymol moduel has been ') cmd.do(' imported as ipv. ') cmd.do(' ') cmd.do(' I made the following modifications of roundview.py.') cmd.do(' The cmd.get_view was replaced with ipv.get_view.') cmd.do(' The cmd.extend was replaced with ipv.extend.') cmd.do(' The myRoundedList was returned for further processing.') cmd.do(' ') cmd.do(' MIT License') cmd.do(' ') cmd.do(' Copyright:') cmd.do(' Blaine Mooers and the OU Board of Regents') cmd.do(' Uniersity of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' ') cmd.do(' 29 April 2020') cmd.do(' ') cmd.do(' """') cmd.do(' ') cmd.do(' ') cmd.do(' StoredView = int(StoredView)') cmd.do(' decimal_places = int(decimal_places)') cmd.do(' ') cmd.do(' #call the get_view function') cmd.do(' ') cmd.do(' m = ipv.get_view(StoredView)') cmd.do(' ') cmd.do(' ') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' ') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9],') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' ') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' ') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' ') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' ') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' ') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' ') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a")') cmd.do(' myFile.write(x.format(*myRoundedList) + "")') cmd.do(' myFile.close()') cmd.do(' return myRoundedList') cmd.do('ipv.extend("rv", rv)') ${0} ''' 'Demo of the use of the RPC server with a drug compound via rdkit.': 'prefix': 'rdkrpcChem' 'body': ''' cmd.do('import os;') cmd.do('import rdkit;') cmd.do('from rdkit import Chem;') cmd.do('from rdkit.Chem import AllChem;') cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('s = PyMOL.MolViewer();') cmd.do('mol = Chem.MolFromSmiles \') cmd.do(' ('CCOCCn1c(C2CC[NH+](CCc3ccc(C(C)(C)C(=O)[O-])cc3)CC2)nc2ccccc21');') cmd.do('mol = AllChem.AddHs(mol);') cmd.do('AllChem.EmbedMolecule(mol);') cmd.do('AllChem.MMFFOptimizeMolecule(mol);') cmd.do('s.ShowMol(mol, name = 'bilastine', showOnly = False);') cmd.do('s.Zoom('bilastine');') cmd.do('s.SetDisplayStyle('bilastine', 'sticks');') cmd.do('s.GetPNG(preDelay=5);') ${0} ''' 'A kernel.json file for runnig PyMOL python interpreter in the Jupyter notebook. ': 'prefix': 'kernel' 'body': ''' cmd.do('framerule=2pt,') cmd.do('framesep=2mm,') cmd.do('framesep=2mm,') cmd.do('breaklines=True,') cmd.do('baselinestretch=1.2') cmd.do(']{bash}') cmd.do('{') cmd.do(' "argv": [') cmd.do(' "/Applications/PyMOL.app/Contents/bin/python",') cmd.do(' "-m",') cmd.do(' "ipykernel_launcher",') cmd.do(' "-f",') cmd.do(' "{connection_file}"') cmd.do(' ],') cmd.do(' "display_name": "pymol.python",') cmd.do(' "language": "python"') cmd.do('}') ${0} ''' 'Demo of the use of the RPC server with a protein via rdkit.': 'prefix': 'rdkrpcProtein' 'body': ''' cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('Usage=""""Start pymol from command line with -R flag.') cmd.do('Select the pymol.python kernel in Jupyter notebook. """;') cmd.do('') cmd.do('s = PyMol.MolViewer();') cmd.do('du = s.server.do;') cmd.do('du('rein; bg_color white; fetch 1lw9, type=pdb, async=0, show;nb_spheres; set_view (0.46,-0.28,-0.84,0.74,-0.41,0.54,-0.49,-0.87,0.02,0.0,0.0,\') cmd.do(' -155.16,35.13,11.48,9.72,122.33,187.99,-20.0);');') cmd.do('s.GetPNG(preDelay=3);') cmd.do('du('png T4L600dpi.png, dpi=600');') ${0} ''' 'Code to start the RPC server with ipymol.': 'prefix': 'ipymolStart' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') ${0} ''' 'Demo of the use of the RPC server with a protein via ipymol.': 'prefix': 'ipymolProtein' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') cmd.do('') cmd.do('ipv.do('fetch 1lw9');') cmd.do('ipv.do('rv');') cmd.do('# The double parentheses are required when set_view is run this way.;') cmd.do('ipv.set_view((-0.13,-0.4,-0.91,0.89,-0.45,0.07,-0.44,-0.8,0.41,0.0,0.0,-182.47,35.13,11.48,9.72,149.64,215.3,-20.0));') cmd.do('ipv.do('AOD');') cmd.do('ipv.png('testipymolT4L.png');') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server rdkit in a jupyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvr' 'body': ''' cmd.do('def rvr(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """MIT License') cmd.do(' Copyright:') cmd.do(' Blaine Mooers and the OU Board of Regents') cmd.do(' University of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' 30 April 2020') cmd.do(' ') cmd.do(' First run the following:') cmd.do(' ') cmd.do(' from rdkit.Chem import PyMol') cmd.do(' s = PyMol.MolViewer()') cmd.do(' du = s.server.do') cmd.do('') cmd.do(' """') cmd.do(' StoredView = int(StoredView) decimal_places = int(decimal_places)') cmd.do(' #call the get_view function') cmd.do(' m = s.get_view(StoredView)') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9], ') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a") myFile.write(x.format(*myRoundedList) + "") myFile.close()') cmd.do(' return myRoundedList') cmd.do('du.extend("rvr", rvr)') ${0} ''' 'Return to the command history window the docstrings for all of the functions in the cmd module.': 'prefix': 'cmddocs' 'body': ''' cmd.do('[help(i) for i in dir(cmd)];') ${0} ''' 'Return to the command history window the docstrings for all of the functions in a module.': 'prefix': 'pymoldocs' 'body': ''' cmd.do('[help(i) for i in dir(pymol)];') ${0} ''' 'Print the number of residues in a protein.': 'prefix': 'numResiProtein' 'body': ''' cmd.do('sel = 'polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in chain A of a protein.': 'prefix': 'numResiProteinChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid (all chains).': 'prefix': 'numResiNucleic' 'body': ''' cmd.do('sel = 'polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid chain.': 'prefix': 'numResiNucleicChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Create bonds between phosphorous and O3* atoms in a low resolution DNA structure that is 80 base pairs long.': 'prefix': 'brokenNucleicBackbone' 'body': ''' cmd.do('[cmd.bond(f"/5fur//E/{i}/O3'", f"/5fur//E/{i+1}/P") for i in range(${1:1}, ${2:80})]; ') cmd.do('[cmd.bond(f"/5fur//F/{i}/O3'", f"/5fur//F/{i+1}/P") for i in range(${3:81}, ${3:160})];') ${0} ''' 'To change stick color and radius for the bond between atom 2 and 3, use the set_bond command. ': 'prefix': 'oneBondThicknessColor' 'body': ''' cmd.do('# To change stick color and radius for the bond between atom 2 and 3;') cmd.do('set_bond stick_color, ${1:yellow}, index 2, index 3;') cmd.do('set_bond stick_radius, ${2:0.2}, index 2, index 3;') ${0} ''' 'Connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18. Note that this example requires the draw_links.py [http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py] by Robert Campbell.': 'prefix': 'drawLinks' 'body': ''' cmd.do('# Requires draw_links.py http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py by Robert Campbell') cmd.do('# To connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18.') cmd.do('draw_links ${1:mol1} & chain ${2:A} & name ${3:CA} & resi ${4:1+6+7+8}, ${5:mol1} & chain ${6:A}& name ${7:CA} & resi ${8:10+16+17+18} ') ${0} ''' 'Print the path to the currently used PyMOL binary.': 'prefix': 'printPath' 'body': ''' cmd.do('# Print the path to the current used PyMOL binary.') cmd.do('print pymol.__path__') ${0} ''' 'Turn on the ligand valence.': 'prefix': 'setLigandValenceOn' 'body': ''' cmd.do('#Set on the valence of the ligand only') cmd.do('set valence, on, resn ${1:RZS}; set valence, off, not resn ${2:RZS}') ${0} ''' 'Return the docustring for the preset submodule. The command help preset fails to return anything. The command help(pymol.preset) has the same effect as help(preset).': 'prefix': 'presetDocs' 'body': ''' cmd.do('help(preset)') ${0} ''' 'Return the docustring for the help submodule. The command help help is more concise.': 'prefix': 'helpDocs' 'body': ''' cmd.do('help(help)') ${0} ''' 'The amber trajectories have to be loaded into the same object.': 'prefix': 'loadAmberTrajs' 'body': ''' cmd.do('load file.top, protein;') cmd.do('load file.rst, protein') ${0} ''' 'Saves multiple objects into multiple files using an optional prefix name.': 'prefix': 'saveSep' 'body': ''' cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('import re') cmd.do('') cmd.do('def saveSep(prefix=''):') cmd.do(' """') cmd.do(' save_sep <prefix>') cmd.do('') cmd.do(' saves multiple objects into multiple files using an optional prefix name.') cmd.do('') cmd.do(' e.g. save_sep prefix') cmd.do(' """') cmd.do(' obj_list = cmd.get_names("all")') cmd.do('') cmd.do(' if obj_list:') cmd.do(' for i in range(len(obj_list)):') cmd.do(' obj_name = "%s%s.pdb" % (prefix, obj_list[i])') cmd.do(' cmd.save(obj_name, obj_list[i])') cmd.do(' print("Saving %s" % obj_name)') cmd.do(' else:') cmd.do(' print("No objects found")') cmd.do(' ') cmd.do('cmd.extend('saveSep',saveSep)') ${0} ''' 'OptiAlign.py by Jason Vertree modified for aligning multiple RNA structures.': 'prefix': 'optAlignRNA' 'body': ''' cmd.do('#!python') cmd.do(' ') cmd.do('##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py. A python implementation of the optimal superposition') cmd.do('# of two sets of vectors as proposed by Kabsch 1976 & 1978.') cmd.do('#') cmd.do('# @AUTHOR: Jason Vertrees') cmd.do('# @COPYRIGHT: Jason Vertrees (C), 2005-2007') cmd.do('# @LICENSE: Released under GPL:') cmd.do('# This program is free software; you can redistribute it and/or modify') cmd.do('# it under the terms of the GNU General Public License as published by') cmd.do('# the Free Software Foundation; either version 2 of the License, or') cmd.do('# (at your option) any later version.') cmd.do('# This program is distributed in the hope that it will be useful, but WITHOUT') cmd.do('# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS') cmd.do('# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.') cmd.do('#') cmd.do('# You should have received a copy of the GNU General Public License along with') cmd.do('# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin') cmd.do('# Street, Fifth Floor, Boston, MA 02110-1301, USA ') cmd.do('#') cmd.do('# DATE : 2007-01-01') cmd.do('# REV : 2') cmd.do('# REQUIREMENTS: numpy') cmd.do('#') cmd.do('#') cmd.do('# Modified optAlign.py to use C1' carbon atoms of RNA for alignment.') cmd.do('# Jan. 29, 2020 ') cmd.do('# Blaine Mooers, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#############################################################################') cmd.do('from array import *') cmd.do(' ') cmd.do('# system stuff') cmd.do('import os') cmd.do('import copy') cmd.do(' ') cmd.do('# pretty printing') cmd.do('import pprint') cmd.do(' ') cmd.do('# for importing as a plugin into PyMol') cmd.do('from pymol import cmd') cmd.do('from pymol import stored') cmd.do('from pymol import selector') cmd.do(' ') cmd.do('# using numpy for linear algebra') cmd.do('import numpy') cmd.do(' ') cmd.do('def optAlignRNA( sel1, sel2 ):') cmd.do(' """') cmd.do(' optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections.') cmd.do(' Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1'') cmd.do(' ') cmd.do(' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from') cmd.do(' PyMOL based upon your selections.') cmd.do(' ') cmd.do(' This function can be run in a for loop to fit multiple structures with a common prefix name:') cmd.do(' ') cmd.do(' for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001")') cmd.do(' ') cmd.do(' or get the rmsds for all combinations, do the following:') cmd.do(' ') cmd.do(' [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do(' """') cmd.do(' cmd.reset()') cmd.do(' ') cmd.do(' # make the lists for holding coordinates') cmd.do(' # partial lists') cmd.do(' stored.sel1 = []') cmd.do(' stored.sel2 = []') cmd.do(' # full lists') cmd.do(' stored.mol1 = []') cmd.do(' stored.mol2 = []') cmd.do(' ') cmd.do(' # -- CUT HERE') cmd.do(' sel1 += " and N. C1'"') cmd.do(' sel2 += " and N. C1'"') cmd.do(' # -- CUT HERE') cmd.do(' ') cmd.do(' # Get the selected coordinates. We') cmd.do(' # align these coords.') cmd.do(' cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")') cmd.do(' ') cmd.do(' # get molecule name') cmd.do(' mol1 = cmd.identify(sel1,1)[0][0]') cmd.do(' mol2 = cmd.identify(sel2,1)[0][0]') cmd.do(' ') cmd.do(' # Get all molecule coords. We do this because') cmd.do(' # we have to rotate the whole molcule, not just') cmd.do(' # the aligned selection') cmd.do(' cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")') cmd.do(' ') cmd.do(' # check for consistency') cmd.do(' assert len(stored.sel1) == len(stored.sel2)') cmd.do(' L = len(stored.sel1)') cmd.do(' assert L > 0') cmd.do(' ') cmd.do(' # must alway center the two proteins to avoid') cmd.do(' # affine transformations. Center the two proteins') cmd.do(' # to their selections.') cmd.do(' COM1 = numpy.sum(stored.sel1,axis=0) / float(L)') cmd.do(' COM2 = numpy.sum(stored.sel2,axis=0) / float(L)') cmd.do(' stored.sel1 -= COM1') cmd.do(' stored.sel2 -= COM2') cmd.do(' ') cmd.do(' # Initial residual, see Kabsch.') cmd.do(' E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)') cmd.do(' ') cmd.do(' #') cmd.do(' # This beautiful step provides the answer. V and Wt are the orthonormal') cmd.do(' # bases that when multiplied by each other give us the rotation matrix, U.') cmd.do(' # S, (Sigma, from SVD) provides us with the error! Isn't SVD great!') cmd.do(' V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))') cmd.do(' ') cmd.do(' # we already have our solution, in the results from SVD.') cmd.do(' # we just need to check for reflections and then produce') cmd.do(' # the rotation. V and Wt are orthonormal, so their det's') cmd.do(' # are +/-1.') cmd.do(' reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))') cmd.do(' ') cmd.do(' if reflect == -1.0:') cmd.do(' S[-1] = -S[-1]') cmd.do(' V[:,-1] = -V[:,-1]') cmd.do(' ') cmd.do(' RMSD = E0 - (2.0 * sum(S))') cmd.do(' RMSD = numpy.sqrt(abs(RMSD / L))') cmd.do(' ') cmd.do(' #U is simply V*Wt') cmd.do(' U = numpy.dot(V, Wt)') cmd.do(' ') cmd.do(' # rotate and translate the molecule') cmd.do(' stored.sel2 = numpy.dot((stored.mol2 - COM2), U)') cmd.do(' stored.sel2 = stored.sel2.tolist()') cmd.do(' # center the molecule') cmd.do(' stored.sel1 = stored.mol1 - COM1') cmd.do(' stored.sel1 = stored.sel1.tolist()') cmd.do(' ') cmd.do(' # let PyMol know about the changes to the coordinates') cmd.do(' cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")') cmd.do(' cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")') cmd.do(' ') cmd.do(' #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD)') cmd.do(' print("% s, % s,% 5.3f" % (mol1, mol2, RMSD))') cmd.do(' ') cmd.do(' # make the alignment OBVIOUS') cmd.do(' cmd.hide('everything')') cmd.do(' cmd.show('ribbon', sel1 + ' or ' + sel2)') cmd.do(' cmd.color('gray70', mol1 )') cmd.do(' cmd.color('magenta', mol2 )') cmd.do(' cmd.color('red', 'visible')') cmd.do(' cmd.show('ribbon', 'not visible')') cmd.do(' cmd.center('visible')') cmd.do(' cmd.orient()') cmd.do(' cmd.zoom('visible')') cmd.do(' ') cmd.do('cmd.extend("optAlignRNA", optAlignRNA)') ${0} ''' 'Load into PyMOL multiple files with a common file stem. The is a script by Robert Campbell that updated for Python3.': 'prefix': 'loadManyFiles' 'body': ''' cmd.do('# Copyright (c) 2004 Robert L. Campbell') cmd.do('#') cmd.do('# Modified for use with Python3.') cmd.do('# Jan. 29, 2020 ') cmd.do('# Blaine Mooers, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#') cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('') cmd.do('def loadFiles(files):') cmd.do(' """') cmd.do(' load_files <files>') cmd.do('') cmd.do(' loads multiple files (using filename globbing)') cmd.do(' into a multiple objects named as the files are (e.g. collection of') cmd.do(' downloaded PDB files).') cmd.do('') cmd.do(' e.g. load_files prot_*.pdb') cmd.do(' """') cmd.do(' file_list = glob.glob(files)') cmd.do(' if file_list:') cmd.do(' file_list.sort()') cmd.do(' for i in file_list:') cmd.do(' #obj_name = i.replace('.pdb','')') cmd.do(' #cmd.load(file_list[i],obj_name)') cmd.do(' cmd.load(i)') cmd.do(' else:') cmd.do(' print("No files found for pattern %s" % files)') cmd.do('') cmd.do('cmd.extend('loadFiles',loadFiles)') ${0} ''' 'These are the instructions for loading and aligning multiple files.': 'prefix': 'loadAndAlignManyFiles' 'body': ''' cmd.do('To load a bunch of related files from inside PyMOL all at once:') cmd.do('') cmd.do('run loadFiles.py') cmd.do('loadFiles refine_*.pdb') cmd.do('') cmd.do('') cmd.do('To align all of the loaded RNA structures in all possible combinations by their C1' carbon atoms:') cmd.do('') cmd.do('run optAlignRNA.py') cmd.do('[[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do('(Yes, that construct is a list comprehension inside a list comprehension!)') cmd.do('') cmd.do('To save a multiple models in a file to separate pdb files,') cmd.do('') cmd.do('run saveSep.py') cmd.do('saveSep ') cmd.do('or ') cmd.do('saveSep prefix') ${0} ''' 'This is a two-fold nested list comprehension for any all parwise operation on the currently loaded objects. Replace optAlginRNA with any other function that operations on a pair of structrures.': 'prefix': 'allPairs' 'body': ''' cmd.do('[[${1:optAlignRNA}(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') ${0} ''' 'Combining DSSR block representation with regular PyMOL cartoons after loading the dssr_block.py script by Thomas Holder.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('as cartoon;') cmd.do('set cartoon_ladder_radius, 0.1;') cmd.do('set cartoon_ladder_color, gray;') cmd.do('set cartoon_nucleic_acid_mode, 1;') cmd.do('dssr_block') ${0} ''' 'DSSR block representation with fused blocks after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('dssr_block block_file=wc') ${0} ''' 'DSSR block representation for a multi-state example after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 2n2d, async=0;') cmd.do('dssr_block 2n2d, 0;') cmd.do('set all_states;') ${0} ''' 'DSSR block representation with custom coloring after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1msy, async=0;') cmd.do('dssr_block block_color=N red | minor 0.9 | major yellow;') ${0} ''' 'Settings for nucliec acid cartoon.': 'prefix': 'nucleicAcidCartoon' 'body': ''' cmd.do('set cartoon_ladder_color, ${1:density};') cmd.do('set cartoon_ladder_radius, ${2:0.2};') cmd.do('set cartoon_nucleic_acid_color, ${3:red};') cmd.do('set cartoon_ring_mode, ${4:2};') ${0} ''' 'Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. The set command as the syntax of setting_name [, setting_value [, selection [,state ]]] . In this case, the selection has to be global, object, object-state, or per-atom settings. It cannot be a named selection. This is a weak spot in PyMOL. Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. Many double-stranded helices have one strand in the asymmetric unit. The second strand is in the biological unit. The coordinates for the second strand are in the pdb1 file type at the PDB. The second strand is in the second state, which is equivalent to the second model in the pdb file. The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting). The bases are colored differently too (via the cartoon_ladder_color setting). ': 'prefix': 'nucleicAcidCartoon2Strands' 'body': ''' cmd.do('# There is not support for applying different settings to different selections.') cmd.do('# Instead, this can be done for different objects.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# The set command as the syntax of setting_name [, setting_value [, selection [,state ]]]') cmd.do('# In this case, the selection has to be global, object, object-state, or per-atom settings.') cmd.do('# It cannot be a named selection.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# Many double-stranded helices have one strand in the asymmetric unit.') cmd.do('# The second strand is in the biological unit.;') cmd.do('# The coordinates for the second strand are in the pdb1 file type at the PDB.;') cmd.do('# The second strand is in the second state, which is equivalent to the second model in the pdb file.;') cmd.do('# The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting).;') cmd.do('# The bases are colored differently too (via the cartoon_ladder_color setting).;') cmd.do('fetch ${1:3nd3}, ${2:3nd3}, type=${3:pdb1};') cmd.do('set all_states, on;') cmd.do('create chA, ${2:3nd3}, 1, 1;') cmd.do('create chB, ${2:3nd3}, 2, 1;') cmd.do('# colors only the backbone;') cmd.do('set cartoon_nucleic_acid_color, ${4:magenta}, chA;') cmd.do('set cartoon_nucleic_acid_color, ${5:orange}, chB;') cmd.do('# color the bases;') cmd.do('set cartoon_ladder_color, ${6:density}, chA;') cmd.do('set cartoon_ladder_color, ${7:yellow}, chB;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It could make a good shortcut.': 'prefix': 'nucleicAcidColorbySequence' 'body': ''' cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${1:yellow}, rna_A;') cmd.do('color ${2:red}, rna_C; ') cmd.do('color ${3:gray40}, rna_G;') cmd.do('color ${4:palecyan}, rna_U;') cmd.do('color ${5:brown}, dna_T;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It is dervied from the CR shortcut. The backcone is shown as a flatten ribbon.': 'prefix': 'nucleicAcidFlatRibbonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85};') cmd.do('set cartoon_oval_width, ${2:0.5};') cmd.do('cartoon oval;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval;') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'The code provides a cartoon of the loaded nucleic acid that has the ladder rungs replaced by filled rings that are colored by atom type. The code can be applied to any nucleic acid. It is derived from the FR shortuct.': 'prefix': 'nucleicAcidCartoonFilledRings' 'body': ''' cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'This code make as standard base stacking diagram with ball and stick representation. ': 'prefix': 'basePairStacking' 'body': ''' cmd.do('delete all;') cmd.do('fetch 4PCO, type=pdb, async=0;') cmd.do('select G2G3, ( ((resi 2 or resi 3) and chain A) or ((resi 8 or resi 9) and chain B));') cmd.do('remove not G2G3;') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7.24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('remove name H*;') cmd.do('select carbon1, element C and (resi 3 or resi 8) ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi 2 or resi 9) ') cmd.do('#select upper base pair;') cmd.do('color gray70, carbon1;') cmd.do('color gray10, carbon2;') cmd.do('show sticks;') cmd.do('space cmyk;') cmd.do('distance hbond1, /4PCO//B/U`9/N3,/4PCO//A/G`2/O6;') cmd.do('distance hbond2, /4PCO//B/U`9/O2,/4PCO//A/G`2/N1;') cmd.do('distance hbond3, /4PCO//A/U`3/N3,/4PCO//B/G`8/O6;') cmd.do('distance hbond4, /4PCO//A/U`3/O2,/4PCO//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png 4PCO.png;') ${0} ''' 'This code colors by the nucleotides by base seqence. The backcone is shown as a flatten ribbon with rolled edges that give the dumbell effect. The code can be applied to any nucleic acid. The code is dervied from the CR and DU shortcuts. ': 'prefix': 'nucleicAcidDumbellCartoonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85}') cmd.do('set cartoon_oval_width, ${2:0.5}') cmd.do('cartoon oval;') cmd.do('cartoon dumbbell;') cmd.do('set cartoon_dumbbell_width, 0.2;') cmd.do('set cartoon_dumbbell_radius, 0.4;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'Set keyboard shortcut by mapping F1 to stereo.': 'prefix': 'stereokb' 'body': ''' cmd.do('cmd.set_key('F1',lambda:cmd.stereo({'on':0,'off':1}[cmd.get('stereo')]));') ${0} ''' 'Print to the screen the settings and their current parameter values.': 'prefix': 'listSettings2' 'body': ''' cmd.do('list = setting.get_name_list();[print("%s => %s" % (name, setting.get_setting_text(name))) for name in list];') ${0} ''' 'Print to the screen the settings and their current parameter values. This is the more compact version.': 'prefix': 'listSettings' 'body': ''' cmd.do('[print("%s => %s" % (name, setting.get_setting_text(name))) for name in setting.get_name_list()];') ${0} ''' 'Print to the screen as labels that 21 font ids in their corresponding fonts in a grid. Each label is an object and appears in the internal gui. You can turn on and off the display of specific fonts.': 'prefix': 'displayFonts' 'body': ''' cmd.do('python;') cmd.do('from pymol import cmd;') cmd.do('for i in range(1,21):') cmd.do(' name = 'label%d' % i;') cmd.do(' cmd.pseudoatom(name, label='label font id %d' % i, pos=(0,0,0));') cmd.do(' cmd.set('label_font_id', i, name);') cmd.do('cmd.set('label_size', 50);') cmd.do('cmd.set('grid_mode');') cmd.do('python end;') ${0} ''' 'Print to disk a list of H-bond pairs and this H-bond length.': 'prefix': 'listHBonds' 'body': ''' cmd.do('Finish latter. See file listHBonds.py.;') ${0} ''' 'Create a list of objects in the internal gui and print this list to the screen.': 'prefix': 'listObjects' 'body': ''' cmd.do('objList = cmd.get_names("objects");print(objList);') ${0} ''' 'Print a list of protein--ligand distances. Code by Dan Kulp. Updated for Python3.': 'prefix': 'listLigandProteinDistances' 'body': ''' cmd.do('from pymol import cmd') cmd.do('"""') cmd.do('Find all distances betwen all ligand atoms and all protein atoms. ') cmd.do('') cmd.do('Adapted and updated from script by Dan Kulp posted here') cmd.do('https://sourceforge.net/p/pymol/mailman/message/10097804/') cmd.do('') cmd.do('There are probably better solutions like finding just the ') cmd.do('distances to proein atoms within a certain distance from ') cmd.do('the ligand.') cmd.do('') cmd.do('Due to the nested for loops, this script is takes several second') cmd.do('to run on a medium-sized human protein. This script is a ') cmd.do('good candidate for vectorization. ') cmd.do('') cmd.do('It is also a good candiate for becoming a function and a shortcut. ') cmd.do('') cmd.do('"""') cmd.do('') cmd.do('# customize these lines to your protein.') cmd.do('cmd.fetch("6NEC")') cmd.do('cmd.select("prot","not resn XIN and not resn HOH and not chain C")') cmd.do('cmd.select("lig", "resn XIN and not chain C")') cmd.do('') cmd.do('dist_list = {}') cmd.do('pro_atoms = cmd.get_model("prot")') cmd.do('lig_atoms = cmd.get_model("lig")') cmd.do('') cmd.do('for l_at in lig_atoms.atom:') cmd.do(' for p_at in pro_atoms.atom:') cmd.do(' dist_list[str(l_at.resn) +') cmd.do(' ":" +') cmd.do(' str(l_at.resi) +') cmd.do(' " " +') cmd.do(' l_at.name +') cmd.do(' " ---- " + ') cmd.do(' str(p_at.resn) +') cmd.do(' ":" +') cmd.do(' str(p_at.resi) +') cmd.do(' " " +') cmd.do(' p_at.name] = cmd.dist("foo", ') cmd.do(' "index " +') cmd.do(' str(l_at.index),"index " + str(p_at.index))') cmd.do(' cmd.delete("foo")') cmd.do('print("List of all pairwise ligand--protein atom-atom distances:")') cmd.do('# [print("Distance of " + d + " is " + str(dist_list[d])) for d in dist_list.keys()]') cmd.do('') cmd.do('# More compact print statement. Need an f-string format statement.') cmd.do('[print( d + " " + str(dist_list[d])) for d in dist_list.keys()]') ${0} ''' 'This code shows that cartoon backbone tube as 65% transparent. It hides the rungs of the cartoon. It shows all of the non-H atoms are sticks. The motivation is to have the cartoon highlight the backbone without dominanting the scene.': 'prefix': 'nucleicAcidBackboneTubesSticks' 'body': ''' cmd.do('set bg_rgb, white;') cmd.do('hide everything, all;') cmd.do('show cartoon, ${1:3nd3};') cmd.do('set cartoon_sampling,1;') cmd.do('set cartoon_tube_radius, 0.5;') cmd.do('set cartoon_ladder_mode, 0;') cmd.do('set cartoon_transparency, ${2:0.65};') cmd.do('set stick_radius ${3:0.12};') cmd.do('show sticks;') cmd.do('hide sticks, element H;') ${0} ''' 'The code expands the asymmetric unit. It like the generate symmetry mates command but it provides more control over the prefix name of the symmetry mates and the addition of unique segment identifiers for each symmetry mate. The usage: symexp prefix, object, (selection), cutoff, segidFlag. The cutoff is in Angstroms. The segidFlag set to 1 will add unique segids. For related functions, see SC***.': 'prefix': 'symexp' 'body': ''' cmd.do('symexp ${1:symm}, ${2:3fa0}, (${2:3fa0}), ${3:20},${4:1};') ${0} ''' 'Adds the function draw_axis(). Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.': 'prefix': 'addAxis' 'body': ''' cmd.do('from pymol.cgo import * # get constants') cmd.do('from pymol import cmd') cmd.do('') cmd.do('import math') cmd.do('') cmd.do('class Counter:') cmd.do(' """') cmd.do(' draw_line') cmd.do(' source https://www.pymolwiki.org/index.php/Symmetry_Axis') cmd.do(' ') cmd.do(' Pymol script copyright Matthew O'Meara and Xavier Ambroggio 2007') cmd.do(' ') cmd.do(' Under GNU Free Documentation License 1.2') cmd.do(' ') cmd.do(' Example:') cmd.do(' ') cmd.do(' draw_axis(x=18.232, y=17.150, z=9.488,i=-.226639, j=0.708772, k=-.668039, r=1, b=0, g=0, width=1, length=100)') cmd.do(' ') cmd.do(' Updated 15 June 2020 ') cmd.do(' Blaine Mooers') cmd.do(' ') cmd.do(' Notes:') cmd.do(' 1) Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.') cmd.do(' 2) The postion (xyz) is the middle of the line, not one end as expected for a vector.') cmd.do(' 3) Another example: draw_axis(x=0, y=0, z=0,i=0, j=0, k=1, r=1, b=0, g=0, width=300, length=96) ') cmd.do(' 4) Changed print statement to Python3 print function.') cmd.do(' 5) Replaced cmd.extend() with function generator.') cmd.do(' """') cmd.do(' def __init__(self):') cmd.do(' self.state = 1') cmd.do('counter = Counter()') cmd.do('') cmd.do('@cmd.extend') cmd.do('def draw_axis(x=None, y=None, z=None, i=None, j=None, k=None, length=20.0, r=1.0, g=1.0, b=1.0, width=1.0 ):') cmd.do(' if x == None or y == None or z == None or i == None or j == None or k== None :') cmd.do(' print('Usage: draw_axis x,y,z, i,k,j, length, r,g,b, width')') cmd.do(' print('draw a line centered at (x,y,z) with the direction vector (i,j,k)')') cmd.do(' print('length, color (r,g,b), and width arguments are optional')') cmd.do('# print 'For a fun example of the command, run draw_axis_example'') cmd.do(' else :') cmd.do(' x,y,z = float(x), float(y), float(z)') cmd.do(' i,j,k = float(i), float(j), float(k)') cmd.do(' r,g,b = float(r), float(g), float(b)') cmd.do(' width = float(width)') cmd.do(' length = float(length) / 2.0') cmd.do('') cmd.do(' x1,y1,z1 = (x+i*length,y+j*length,z+k*length)') cmd.do(' x2,y2,z2 = (x-i*length,y-j*length,z-k*length)') cmd.do('') cmd.do(' obj = [') cmd.do(' LINEWIDTH, width,') cmd.do(' BEGIN, LINES,') cmd.do('') cmd.do(' COLOR, r, g, b,') cmd.do(' VERTEX, x1, y1, z1,') cmd.do(' VERTEX, x2, y2, z2,') cmd.do('') cmd.do(' END') cmd.do(' ]') cmd.do('') cmd.do(' cmd.load_cgo(obj,'axis'+str(counter.state))') cmd.do(' counter.state += 1') ${0} ''' 'Wait unitl all current commands have been executed. A timeout ensures that that command ecentually returns.': 'prefix': 'synch' 'body': ''' cmd.do('cmd.sync(timeout=${1:1.0},poll=${2:0.05});') ${0} ''' 'Add or substract a residue number offset.': 'prefix': 'renumResi' 'body': ''' cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;') ${0} ''' 'Add or substract a atom number offset.': 'prefix': 'renumAtoms' 'body': ''' cmd.do('alter {$1:3fa0}, ID=ID+${2:100};') cmd.do('sort;') ${0} ''' 'Rename a chain. ': 'prefix': 'renameChain' 'body': ''' cmd.do('alter ${1:3fa0} and chain ${2:A}, chain=${3:"C"};') cmd.do('sort;') ${0} ''' 'Print the atom number2 of a residue.': 'prefix': 'printAtomNumbers' 'body': ''' cmd.do('iterate (resi 1), print(name + " %i5" % ID);') ${0} ''' 'Print the atom names of a residue.': 'prefix': 'printAtomNames' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name);') ${0} ''' 'Print the bfactors of a residue.': 'prefix': 'printBfactors' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % b);') ${0} ''' 'Print the van Der Waals radii of the atoms in of a residue.': 'prefix': 'printVDWradii' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % vdw);') ${0} ''' 'Print the coordinates of the atoms in a residue.': 'prefix': 'printCoordinates' 'body': ''' cmd.do('stored.coords = []; ') cmd.do('iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('[print(i) for i in stored.coords];') ${0} ''' 'Print the atom names and coordinates of the atoms in a residue.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]); ') cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101})), stored.coords.append([x,y,z]); ') cmd.do('[print(i,j) for i,j in zip(stored.names, stored.coords)];') ${0} ''' 'Print the atom names as tuples and coordinates of the atoms in a residue as a list.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]);') cmd.do('stored.names3 = [tuple(i) for i in stored.names];') cmd.do('[print(i,j) for i,j in(zip(stored.names3, stored.coords)];') ${0} ''' 'Source block template in org-mode with emacs-jupyter package. ': 'prefix': 'emacsjupyterSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC jupyter-python :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') cmd.do('$0') ${0} ''' 'Source block template in org-mode with ob-ipython package. ': 'prefix': 'obipythonSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC ipython :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') ${0} '''
191726
'.source.python': 'Ambient occlussion.': 'prefix': 'ao' 'body': ''' cmd.do('set_color oxygen, [1.0,0.4,0.4];') cmd.do('set_color nitrogen, [0.5,0.5,1.0];') cmd.do('remove solvent;') cmd.do('as spheres;') cmd.do('util.cbaw;') cmd.do('bg white;') cmd.do('set light_count,10;') cmd.do('set spec_count,1;') cmd.do('set shininess, 10;') cmd.do('set specular,0.25;') cmd.do('set ambient,0;') cmd.do('set direct,0;') cmd.do('set reflect,1.5;') cmd.do('set ray_shadow_decay_factor, 0.1;') cmd.do('set ray_shadow_decay_range, 2;') cmd.do('unset depth_cue;') cmd.do('ray;') ${0} ''' 'Set ellipsoid color.': 'prefix': 'ellipcol' 'body': ''' cmd.do('set ellipsoid_color, ${1:color};') cmd.do('${0}') ${0} ''' 'set distance labels to display 2 decimals': 'prefix': 'sigdist' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') ${0} ''' 'Set angle labels to display 2 decimals places': 'prefix': 'sigang' 'body': ''' cmd.do('set label_angle_digits, ${1:2};') ${0} ''' 'Ball and stick representation. ': 'prefix': 'bs' 'body': ''' cmd.do('show sticks;') cmd.do('set stick_radius, 0.12;') cmd.do('set stick_ball, on;') cmd.do('set stick_ball_ratio, 1.9;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size=0.33;') ${0} ''' 'Base-stacking figure.': 'prefix': 'stack' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4PCO}, type=pdb,async=0;') cmd.do('select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );') cmd.do('hide everything, element h; ') cmd.do('remove not ${2:G2G3};') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7. 24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('hide everything, element H;') cmd.do('select carbon1, element C and (resi ${4:3} or resi ${5:8}); ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi ${3:2} or resi ${6:9});') cmd.do('#select upper base pair;') cmd.do('color gray70,carbon1;') cmd.do('color gray10,carbon2;') cmd.do('space cmyk;') cmd.do('distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;') cmd.do('distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;') cmd.do('distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;') cmd.do('distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png ${1:4PCO}.png') ${0} ''' 'Biological unit.': 'prefix': 'bu' 'body': ''' cmd.do('run ~/Scripts/PyMOLScripts/quat.py; quat') ${0} ''' 'Valence bond. ': 'prefix': 'doubleBond' 'body': ''' cmd.do('set valence, 1; ') cmd.do('set valence_mode, 1;') ${0} ''' 'Color blindness.': 'prefix': 'cblind' 'body': ''' cmd.do('run ~/Pymol-script-repo/colorblindfriendly.py;') cmd.do('as cartoon;') cmd.do('color cb_red, ss H;') cmd.do('color cb_yellow,ss S;') cmd.do('color cb_green, ss L+;') ${0} ''' 'Center pi.': 'prefix': 'centerpi' 'body': ''' cmd.do('pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;') cmd.do('dist pi_cent////ps1, b/${4:U`15}/${5:aaa};') ${0} ''' 'Color ribbon H red, strand yellow, loop green.': 'prefix': 'cribbon' 'body': ''' cmd.do('as cartoon;') cmd.do('color red, ss H;') cmd.do('color yellow,ss S;') cmd.do('color green, ss L+;') ${0} ''' 'Colored spheres.': 'prefix': 'cspheres' 'body': ''' cmd.do('as spheres;') cmd.do('color gray30, chain ${1:A};') cmd.do('color white, chain ${2:B};') cmd.do('color green, name CL;') cmd.do('color brown, resn NAG;') cmd.do('color red, resi 381;') cmd.do('remove solvent;') cmd.do('unset specular;') cmd.do('set ray_trace_gain, 0;') cmd.do('set ray_trace_mode, 3;') cmd.do('bg_color white;') cmd.do('set ray_trace_color, black;') cmd.do('unset depth_cue;') ${0} ''' 'Coordinate covalent bonds to metals and H-bonds friom RNA.': 'prefix': 'coordinate' 'body': ''' cmd.do('viewport 900,600;') cmd.do('fetch 3nd4, type=pdb, async=0;') cmd.do('run ~/Scripts/PyMOLScripts/quat.py;') cmd.do('quat 3nd4;') cmd.do('show sticks;') cmd.do('set stick_radius=0.125;') cmd.do('hide everything, name H*;') cmd.do('bg_color white;') cmd.do('create coorCov, (3nd4_1 and (resi 19 or resi 119 or resi 219 or resi 319 or resi 419 or resi 519 or (resi 3 and name N7)));') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);') cmd.do('distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);') cmd.do('show nb_spheres; ') cmd.do('set nb_spheres_size, .35;') cmd.do('distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;') cmd.do('distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;') cmd.do('distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;') cmd.do('distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;') cmd.do('distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;') cmd.do('distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;') cmd.do('distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;') cmd.do('distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;') cmd.do('distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;') cmd.do('distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;') cmd.do('distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;') cmd.do('distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;') cmd.do(' distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;') cmd.do('distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;') cmd.do('distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;') cmd.do('distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2; ') cmd.do('set depth_cue=0;') cmd.do('set ray_trace_fog=0;') cmd.do('set dash_color, black;') cmd.do('set label_font_id, 5;') cmd.do('set label_size, 36;') cmd.do('set label_position, (0.5, 1.0, 2.0);') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('select carbon, element C;') cmd.do('color yellow, carbon;') cmd.do('disable carbon;') cmd.do('set_view(-0.9,0.34,-0.26,0.33,0.18,-0.93,-0.27,-0.92,-0.28,-0.07,-0.23,-27.83,8.63,19.85,13.2,16.0,31.63,-20.0)') ${0} ''' 'H-bond distances.': 'prefix': 'distance' 'body': ''' cmd.do('distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}') ${0} ''' 'Draw H-bonds. ': 'prefix': 'drawHbonds' 'body': ''' cmd.do('hide everything, hydrogens') cmd.do('hide labels') cmd.do('set dash_color, ${1:black}${2:yelow} ') cmd.do('set dash_gap, 0.4') cmd.do('set dash_radius, 0.08') ${0} ''' 'Carved isomesh representation of electron density. ': 'prefix': 'carvedIsomesh' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isomesh.': 'prefix': 'fetch2FoFcIsomesh' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isomesh 2fofcmap, ${1:3nd4_2fofc}, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Fetch cif file.': 'prefix': 'fetchCIF' 'body': ''' cmd.do('fetch ${1:3nd4}, type=cif, async=0;') ${0} ''' 'Fetch fofc map.': 'prefix': 'fetchFoFc' 'body': ''' cmd.do('fetch ${1:3nd4}, type=fofc, async=0;') ${0} ''' 'Filled rings in nucleic acids. ': 'prefix': 'filledRing' 'body': ''' cmd.do('show sticks;set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'Get coordinates. ': 'prefix': 'getCoordinates' 'body': ''' cmd.do('print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');') ${0} ''' 'H-bond dashes.': 'prefix': 'hbonddash' 'body': ''' cmd.do('hide everything, hydrogens;') cmd.do('hide labels;') cmd.do('set dash_color, black; ') cmd.do('set dash_gap, 0.4;') cmd.do('set dash_radius, 0.08;') ${0} ''' 'Hbond setup. ': 'prefix': 'hbond' 'body': ''' cmd.do('hide labels;') cmd.do('set dash_color, black ;') cmd.do('set dash_length, ${1:0.15};') cmd.do('set dash_gap, ${2:0.35};') cmd.do('set dash_width, ${3:3.0};') ${0} ''' 'Hide alt loc.': 'prefix': 'hidealtloc' 'body': ''' cmd.do('select altconf, alt ${1:b} # select B alternative locators;') cmd.do('hide everything, altconf # hide alt B locators;') ${0} ''' 'Label CA atom with single-letter residue name and residue number.': 'prefix': 'labelResnResi' 'body': ''' cmd.do('label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});') ${0} ''' 'Label SS. ': 'prefix': 'labelSS' 'body': ''' cmd.do('alter ${1:}, ss='%1';') cmd.do('label (%2),'%3';') ${0} ''' 'Load PDB ball-and-stick.': 'prefix': 'loadPDBbs' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('hide (name H*);') cmd.do('hide lines;') cmd.do('show sticks;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('set nb_sphere_radius, ${3:0.35};') cmd.do('orient;') ${0} ''' 'Load PDB nb spheres. ': 'prefix': 'loadPDBnb' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;') cmd.do('orient;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('hide (name H*);') cmd.do('set nb_sphere_size, ${3:0.35};') cmd.do('set nb_spheres_quality, ${4:1};') cmd.do('show nb_spheres;') ${0} ''' 'Measure surface area. ': 'prefix': 'ms' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('select ${2:temp}, ${3:3nd3} and chain A;') cmd.do('run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};') cmd.do('calc_msms_area ${2:temp};') ${0} ''' 'Molscript ribbons.': 'prefix': 'molscriptRibbon' 'body': ''' cmd.do('set cartoon_highlight_color, grey;') cmd.do('show cartoon;') cmd.do('set cartoon_flat_sheets, 0;') cmd.do('set cartoon_smooth_loops, 0;') cmd.do('set cartoon_fancy_helices, 1;') ${0} ''' 'One letter amino acid. ': 'prefix': 'oneLetter' 'body': ''' cmd.do('one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%') cmd.do(''ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%') cmd.do(''SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%') ${0} ''' 'Print Fasta from PDB file. ': 'prefix': 'fasta' 'body': ''' cmd.do('print cmd.get_fastastr('all')') ${0} ''' 'Position label with pseudoatom. ': 'prefix': 'pseudolabel' 'body': ''' cmd.do('pseudoatom ${1:forLabel};') cmd.do('label ${1:forLabel}, '%0';') cmd.do('set label_color, ${2:red};') ${0} ''' 'Rotate about axis.': 'prefix': 'rotate' 'body': ''' cmd.do('rotate ${1:x}, ${2:45}, ${3:pept};') ${0} ''' 'Stereo draw.': 'prefix': 'stereoDraw' 'body': ''' cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') ${0} ''' 'Stereo ray.': 'prefix': 'stereoRay' 'body': ''' cmd.do('stereo; ') cmd.do('set ray_shadow, off;') cmd.do('ray ${1:2400,1200};') cmd.do('png ${2:aaa}.png;') ${0} ''' 'Three electron density as Isomesh. ': 'prefix': 'threeMapsIsomesh' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Turn about axis. ': 'prefix': 'turnAboutAxis' 'body': ''' cmd.do('turn ${1:x},${2:90};') ${0} ''' 'Volume ramp.': 'prefix': 'volumeRamp' 'body': ''' cmd.do('cmd.volume_ramp_new('ramp_magenta', [0.01, 1.00, 0.00, 1.00, 0.00, 4.01, 1.00, 0.00, 1.00, 0.10, 4.99, 1.00, 0.00, 1.00, 0.50,])') ${0} ''' 'Set radius of ball used to make solvent accessible surface.': 'prefix': 'solventRadius' 'body': ''' cmd.do('set solvent_radius, ${1:1.55};') ${0} ''' 'Scale the radius and color of atoms as spheres by property in the B-value column.': 'prefix': 'scaleRadiusColor' 'body': ''' cmd.do('bg_color white;') cmd.do('hide everything;') cmd.do('show spheres;') cmd.do('set stick_radius = 0.1;') cmd.do('hide everything, HET;') cmd.do('show spheres, HET;') cmd.do('set sphere_quality=3;') cmd.do('show sticks, resi $1{1102};') cmd.do('from pymol import stored;') cmd.do('# set the stored array equal to the b−values or use your own values; ') cmd.do('stored.bb = [ ];') cmd.do('iterate all, stored.bb.append(b);') cmd.do('# execute a python−block;') cmd.do('python;') cmd.do('# scale the b−values;') cmd.do('M = max(stored.bb);') cmd.do('scaledBB = map(lambda x: float (x/M), stored.bb);') cmd.do('count = 0;') cmd.do('# set the sphere radii independently;') cmd.do('#[(cmd.set("sphere_scale", x ,"ID %s"%count); count = count + 1) for x in scaledBB]') cmd.do('for x in scaledBB:') cmd.do(' cmd.set("sphere_scale", x ,"ID %s"%count)') cmd.do(' count = count + 1') cmd.do('python end') cmd.do('spectrum b, selection=${2:4gdx};') cmd.do('space cmyk;') cmd.do('set specular_intensity , 0.25;') ${0} ''' 'Return settings in rounded format.': 'prefix': 'rv' 'body': ''' cmd.do('run roundview.py;') ${0} ''' 'Save png flle with timestamp': 'prefix': 'spng' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".png"); ') cmd.do('end python;') ${0} ''' 'Save pse flle with timestamp': 'prefix': 'spse' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".pse"); ') cmd.do('end python;') ${0} ''' 'Run supercell script to generate three cells in all directions. This script was written by <NAME>.': 'prefix': 'sc222' 'body': ''' cmd.do('run ${1:$HOME/Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 2, 2, 2, , orange, supercell2, 1;') ${0} ''' 'The pearl effect is made with two spheres with the outer sphere being transparent.': 'prefix': 'pearl' 'body': ''' cmd.do('create ${1:sodium2}, ${2:sodium1};') cmd.do('set sphere_transparency, 0.4, ${1:sodium2};') cmd.do('set sphere_scale, 1.05, ${1:sodium2};') cmd.do('ray;') ${0} ''' 'Blur the background atoms.': 'prefix': 'fog' 'body': ''' cmd.do('set fog, 0;') ${0} ''' 'Remove waters from molecular object.': 'prefix': 'rmwater' 'body': ''' cmd.do('remove resn HOH;') ${0} ''' 'Set color name to a RGB code.': 'prefix': 'setcolor' 'body': ''' cmd.do('set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}];') cmd.do('color ${1:bark}, ${5:protein};') ${0} ''' 'Duplicate object.': 'prefix': 'duplicateObject' 'body': ''' cmd.do('create ${1:t4l}, ${2:1lw9};') ${0} ''' 'Select a chain. ': 'prefix': 'selectChain' 'body': ''' cmd.do('select rna, chain B;') ${0} ''' 'Select residues by name.': 'prefix': 'selectResidues' 'body': ''' cmd.do('select aromatic, resn phe+tyr+trp;') ${0} ''' 'Select residues by a range of numbers.': 'prefix': 'selectResi' 'body': ''' cmd.do('select ${!:se}; resi ${2:1-100};') ${0} ''' 'Select atoms by element.': 'prefix': 'selectElement' 'body': ''' cmd.do('select ${1:oxygen}, elem ${2:O}') ${0} ''' 'Select atoms by name.': 'prefix': 'selectName' 'body': ''' cmd.do('select ${1:oxygen2}, name ${2:O2}') ${0} ''' 'Select atoms by alpha helices.': 'prefix': 'selectHelices' 'body': ''' cmd.do('select ${1:helices}, ss h; ') ${0} ''' 'Select atoms by beta strands.': 'prefix': 'selectStrands' 'body': ''' cmd.do('select ${1:strands}, ss s; ') ${0} ''' 'Select atoms by beta loops.': 'prefix': 'selectLoops' 'body': ''' cmd.do('select ${1:loops}, ss l;') ${0} ''' 'Select all nitrogen atom in a selelction except from lysine.': 'prefix': 'selectAllBut' 'body': ''' cmd.do('select ${1:select1}, elem ${2:N} and chain ${3:A} and not resn ${4:LYS};') ${0} ''' 'Select atoms within a radius around a ligand.': 'prefix': 'selectAtomsAround' 'body': ''' cmd.do('select ${1:nearby}, resn ${2:drug} around ${3:5};') ${0} ''' 'Select residues within a radius around a ligand.': 'prefix': 'selectResiduesAround' 'body': ''' cmd.do('select ${1:nearby}, br. resn ${2:drug} around ${3:5};') ${0} ''' 'Undo a selection.': 'prefix': 'undoSelection' 'body': ''' cmd.do('disable ${1:sele}; ') ${0} ''' 'Load a pdb file in the current directory.': 'prefix': 'loadPDBfile' 'body': ''' cmd.do('load ${1:my.pdb};') ${0} ''' 'Save a png file of current scene to the current directory.': 'prefix': 'savePNG' 'body': ''' cmd.do('png ${1:saveMe.png};') ${0} ''' 'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.': 'prefix': 'ringMode' 'body': ''' cmd.do('show cartoon, ${1:rna}; set cartoon_ring_mode, ${2:3};') ${0} ''' 'In cartoons, hide the backbone atoms of selected residues when showing then as sticks.': 'prefix': 'sidehChainHelper' 'body': ''' cmd.do('set cartoon_side_chain_helper, on;') ${0} ''' 'Create a new object from part of an existing object.': 'prefix': 'extractPartObj' 'body': ''' cmd.do('extract new_obj, chain A;') ${0} ''' 'Create a putty cartoon.': 'prefix': 'puttyCartoon' 'body': ''' cmd.do('show cartoon;') cmd.do('cartoon putty;') cmd.do('unset cartoon_smooth_loops;') cmd.do('unset cartoon_flat_sheets;') ${0} ''' 'Trun off magenta squares on current selection.': 'prefix': 'hideSelection' 'body': ''' cmd.do('indicate none') ${0} ''' 'Turn on discrete colors between secondary structure elements.': 'prefix': 'discreteCartoonColoring' 'body': ''' cmd.do('set cartoon_discrete_colors, on;') ${0} ''' 'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc111' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , orange, supercell1, 1;') ${0} ''' 'Display SAXS envelope': 'prefix': 'saxsEnvelope' 'body': ''' cmd.do('alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0;') cmd.do('set solvent_radius = 3.0;') ${0} ''' 'Set additional path for PyMOL to search on startup': 'prefix': 'setpath' 'body': ''' cmd.do('os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};') ${0} ''' 'Set path for location to save fetched pdb files. ': 'prefix': 'fetchPath' 'body': ''' cmd.do('set fetch_path, ${1:/Users/blaine/pdbFiles};') ${0} ''' 'Set antialias to get smooth edges': 'prefix': 'antialias' 'body': ''' cmd.do('set antialias, 1;') ${0} ''' 'Print list of active pymolrc files.': 'prefix': 'lspymolrc' 'body': ''' cmd.do('print invocation.options.deferred;') ${0} ''' 'Set number of decimals places to show in distance labels. ': 'prefix': 'sigDigits' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') cmd.do('set label_angle_digits, ${2:2};') ${0} ''' 'Label the CA atoms with the Ala333 style format': 'prefix': 'labelCAs' 'body': ''' cmd.do('label name CA,"%s%s" % (resn,resi);') ${0} ''' 'Label waters HOH.': 'prefix': 'labelWatersHOH' 'body': ''' cmd.do('label resn HOH ,"%s%s" % (resn,resi);') ${0} ''' 'Label waters W.': 'prefix': 'labelWatersW' 'body': ''' cmd.do('label resn HOH ,"W%s" % (resi);') ${0} ''' 'Find hbonds around a residue.': 'prefix': 'findHbonds' 'body': ''' cmd.do('remove element h; distance hbonds, all, all, 3.2, mode=2;') ${0} ''' 'Print the B-factors of a residue. ': 'prefix': 'printBs' 'body': ''' cmd.do('remove element h; iterate resi %{1:133}, print resi, name,b;') ${0} ''' 'Label the main chain atoms by resn,resi,atom name.': 'prefix': 'labelMainChain' 'body': ''' cmd.do('label name n+c+o+ca,"%s%s%s" % (resn,resi,name);') ${0} ''' 'Print B factors of part B of a residue.': 'prefix': 'printBspartB' 'body': ''' cmd.do('iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;') ${0} ''' 'Print B--factors for a residue with the B-factors rounded off to two decimal places.': 'prefix': 'printBs2digits' 'body': ''' cmd.do('iterate (resi %{1:133}), print(name + " %.2f" % b);') ${0} ''' 'Write the command reference to html file in the present working directory. ': 'prefix': 'writeCommandReference2HTML' 'body': ''' cmd.do('cmd.write_html_ref('pymol-command-ref.html');') ${0} ''' 'Average the B-factors by using a regular list as opposed to a stored list in PyMOL. Edit the selection as needed.': 'prefix': 'averageB' 'body': ''' cmd.do('"""Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""') cmd.do('Bfactors = []; ') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print("Sum = ", "%.2f" % (sum(Bfactors)));') cmd.do('print("Number of atoms = ", len(Bfactors));') cmd.do('print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));') ${0} ''' 'AveBResiX, prints the resiude number and the average bfactor. ': 'prefix': 'aveB4resiX' 'body': ''' cmd.do('""""AveBResiX, prints the resiude number and the average bfactor. ') cmd.do('Uses reduce and lambda, builtin Python functional porgramming functions. ') cmd.do('Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum. ') cmd.do('"""') cmd.do('Bfactors = [];') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print( "Average B-factor of residue ", %{1:133} , " = ", "%.2f" %(reduce(lambda x, y: x + y, Bfactors) / float(len(Bfactors))) )') ${0} ''' 'Print name and b-factor for a residue.': 'prefix': 'printNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((name, b))", space=Bfac_dict); for i,j in Bfac_dict['Bfactors3']: print("%s %.2f" % (i,j));') ${0} ''' 'Print resn, resi, atom name, and b-factor. ': 'prefix': 'printResiResnNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Print name and b-factor for a residue or residue range (e.g. 81:120). The noH variant.': 'prefix': 'printResiResnNameB4ResiXNoH' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133 and not elem H)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Make the background of the internal gui transparent to expand viewport.': 'prefix': 'internalGUImode2 ' 'body': ''' cmd.do('internal_gui_mode=2;') ${0} ''' 'Set the width of the internal gui. ': 'prefix': 'internalGUIwidth' 'body': ''' cmd.do('internal_gui_width=%{1:20};') ${0} ''' 'Print document string of a function.': 'prefix': 'printDoc' 'body': ''' cmd.do('print ${1:my_func}.__doc__;') ${0} ''' 'List all snips by tab trigger and description': 'prefix': 'lsSnips' 'body': ''' cmd.do('"""Tab trigger Description') cmd.do('--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------') cmd.do('antialias Set antialias to get smooth edges') cmd.do('ao Ambient occlussion.') cmd.do('aveB4resiX AveBResiX, prints the resiude number and the average bfactor.') cmd.do(' Uses reduce and lambda, builtin Python functional porgramming functions.') cmd.do(' Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.') cmd.do('averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.') cmd.do('bs Ball and stick representation.') cmd.do('bu Biological unit.') cmd.do('carvedDensity Carved electron density.') cmd.do('cblind Color blindness.') cmd.do('centerpi Center pi.') cmd.do('coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.') cmd.do('cribbon Color ribbon H red, strand yellow, loop green.') cmd.do('cspheres Colored spheres.') cmd.do('discreteCartoonColoring Turn on discrete colors between secondary structure elements.') cmd.do('distance H-bond distances.') cmd.do('doubleBond Valence bond.') cmd.do('drawHbonds Draw H-bonds.') cmd.do('duplicateObject Duplicate object.') cmd.do('ellipcol Set ellipsoid color.') cmd.do('extractPartObj Create a new object from part of an existing object.') cmd.do('fasta Print Fasta from PDB file.') cmd.do('fetch2FoFc Fetch 2FoFc map.') cmd.do('fetchCIF Fetch cif file.') cmd.do('fetchFoFc Fetch fofc map.') cmd.do('fetchPath Set path for location to save fetched pdb files.') cmd.do('filledRing Filled rings in nucleic acids.') cmd.do('findHbonds Find hbonds around a residue.') cmd.do('fog Blur the background atoms.') cmd.do('getCoordinates Get coordinates.') cmd.do('hbond Hbond setup.') cmd.do('hbonddash H-bond dashes.') cmd.do('hideSelection Trun off magenta squares on current selection.') cmd.do('hidealtloc Hide alt loc.') cmd.do('internalGUImode2 Makes the background of the internal gui transparent with the viewport extended into this region of the gui. This may be a useful mode for workshops.') cmd.do('internalGUIwidth Set the width of the internal gui.') cmd.do('labelCAs Label the CA atoms with the Ala333 style format') cmd.do('labelMainChain Label the main chain atoms by resn,resi,atom name.') cmd.do('labelResnResi Label CA atom with residue name and residue number.') cmd.do('labelSS Label SS.') cmd.do('labelWatersHOH Label waters HOH.') cmd.do('labelWatersW Label waters W.') cmd.do('loadPDBbs Load PDB ball-and-stick.') cmd.do('loadPDBfile Load a pdb file in the current directory.') cmd.do('loadPDBnb Load PDB nb spheres.') cmd.do('lsSnips List all snips by tab trigger and description') cmd.do('lspymolrc Print list of active pymolrc files.') cmd.do('molscriptRibbon Molscript ribbons.') cmd.do('ms Measure surface area.') cmd.do('oneLetter One letter amino acid.') cmd.do('pearl The pearl effect is made with two spheres with the outer sphere being transparent.') cmd.do('printBs Print the B-factors of a residue.') cmd.do('printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.') cmd.do('printBspartB Print B factors of part B of a rsidues.') cmd.do('printDoc Print document string of a function.') cmd.do('printNameB4ResiX Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). Use the noH variant if H atoms are present.') cmd.do('printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.') cmd.do('printResiResnNameB4ResiXNoH Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). The noH variant.') cmd.do('pseudolabel Position label with pseudoatom.') cmd.do('puttyCartoon Create a putty cartoon.') cmd.do('ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.') cmd.do('rmwater Remove waters from molecular object.') cmd.do('rotate Rotate about axis.') cmd.do('rv Return settings in rounded format.') cmd.do('savePNG Save a png file of current scene to the current directory.') cmd.do('saxsEnvelope Display SAXS envelope') cmd.do('sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.') cmd.do('sc222 Run Tom Holder's supercell script to generate three cells in all directions.') cmd.do('scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.') cmd.do('selectAllBut Select all nitrogen atom in a selelction except from lysine.') cmd.do('selectAtomsAround Select atoms within a radius around a ligand.') cmd.do('selectChain Select a chain.') cmd.do('selectElement Select atoms by elemnt.') cmd.do('selectHelices Select atoms by alpha helices.') cmd.do('selectLoops Select atoms by beta loops.') cmd.do('selectName Select atoms by name.') cmd.do('selectResi Select residues by a range of numbers.') cmd.do('selectResidues Select residues by name.') cmd.do('selectResiduesAround Select residues within a radius around a ligand.') cmd.do('selectStrands Select atoms by beta strands.') cmd.do('setcolor Set color name to a RGB code.') cmd.do('setpath Set additional path for PyMOL to search on startup') cmd.do('sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.') cmd.do('sigDigits Set number of decimals places to show in distance labels.') cmd.do('sigang Set angle labels to display 2 decimals places') cmd.do('sigdist set distance labels to display 2 decimals') cmd.do('solventRadius Set radius of ball used to make solvent accessible surface.') cmd.do('spng Save png flle with timestamp') cmd.do('spse Save pse flle with timestamp') cmd.do('stack Base-stacking figure.') cmd.do('stereoDraw Stereo draw.') cmd.do('stereoRay Stereo ray.') cmd.do('threeMaps Three electron density.') cmd.do('turnAboutAxis Turn about axis.') cmd.do('undoSelection Undo a selection.') cmd.do('volumeRamp Volume ramp.') cmd.do('writeCommandReference2HTML Write the command reference to html file in the present working directory."""') ${0} ''' 'Asp70-His31 salt-bridge from T4 lysozyme. ': 'prefix': 'his31asp70' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom (resi 31 or resi 70); ') cmd.do('preset.technical(selection='all'); ') cmd.do('bg_color gray70; ') cmd.do('clip slab, 7,(resi 31 or resi 70);') cmd.do('rock;') ${0} ''' 'triple water pentagon.': 'prefix': 'waterTriple' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom resi 313; ') cmd.do('preset.technical(selection='all', mode=1);') ${0} ''' 'Make selection of ligand atoms.': 'prefix': 'ligandSelect' 'body': ''' cmd.do('select substrates, organic;') ${0} ''' 'Print url of README.md file of the pymolsnips repository.': 'prefix': 'github' 'body': ''' cmd.do('https://github.com/MooersLab/pymolsnips/blob/master/README.md') ${0} ''' 'Set dihedral labels to display 2 decimals places to the right of the decimal point.': 'prefix': 'sigdihedral' 'body': ''' cmd.do('set label_dihedral_digits, ${1:2};') ${0} ''' 'Select state 1 from a model with multiple states.': 'prefix': 'stateOne' 'body': ''' cmd.do('cmd.create('newobject', 'oldobject', '1', '1');') ${0} ''' 'Display all symmetry mates in two unit cells along the c axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc112' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cels along c. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc113' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates three three unit cells along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc311' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cells along b. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc131' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cell along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc211' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cells along the b axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc121' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 1 x 2 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc122' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 2 x 2 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc221' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 1 x 2 arrays of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc212' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 1 x 3 x 3 array of unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc133' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 1 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc313' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc331' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc233' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 2 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc323' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc332' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc333' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long c-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc114' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long b-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc141' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long a-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc411' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Save aln flle with timestamp': 'prefix': 'saln' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd;') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT);') cmd.do('cmd.save(stemName+s+".aln");') cmd.do('end python;') ${0} ''' 'Save electron density map flle with timestamp': 'prefix': 'sccp4' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".ccp4"); ') cmd.do('end python;') ${0} ''' 'Save dae flle with timestamp': 'prefix': 'sdae' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".dae"); ') cmd.do('end python;') ${0} ''' 'Carved isosurface representation of electron density. ': 'prefix': 'carvedIsosurface' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isosurface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isosurface.': 'prefix': 'fetch2FoFcIsosurface' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isosurface 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as isosurface. ': 'prefix': 'threeMapsIsosurface' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isosurface ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isosurface ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isosurface ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Carved volume representation of electron density. ': 'prefix': 'carvedVolume' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('surface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as a volume.': 'prefix': 'fetch2FoFcVolume' 'body': ''' cmd.do('fetch ${1:3nd4}, type=2fofc, async=0;') cmd.do('volume 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as volumes. ': 'prefix': 'threeMapsVolume' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('volume ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('volume ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('volume ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server ipymol in a jupuyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvi' 'body': ''' cmd.do('def rvj(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """') cmd.do(' rvj() is a modification of the the rv() function (aka the roundview.py) ') cmd.do(' so that it can run in Jupyter notebooks with the ipymol.viewer. ') cmd.do(' A set_view string is printed to the noteobook in a format that is ready ') cmd.do(' for reuse. ') cmd.do(' ') cmd.do(' The ipymol module was developed by <NAME>:') cmd.do(' ') cmd.do(' https://github.com/cxhernandez/ipymol') cmd.do(' ') cmd.do(' The pre-requisites for installing ipymol are as follows:') cmd.do(' ') cmd.do(' 1. Make a jupyter notebook kernel for Python interpreter inside of ') cmd.do(' the Schrodinger PyMOL. See the PyMOL Snippets GitHub Page for ') cmd.do(' a description of how to make one.') cmd.do(' 2. Install the following build of ipymol at the PyMOL prompt.') cmd.do(' You need to log into your GitHub account first.') cmd.do(' ') cmd.do(' pip install git+pip install git+https://github.com/cxhernandez/ipymol.git@2a30d6ec1588434e6f0f72a1d572444f89ff535b') cmd.do(' ') cmd.do(' 3. Make a bash alias to this PyMOL app file.') cmd.do(' ') cmd.do(' 4. Launch the jupyter notebook and select the pymol.python kernel.') cmd.do(' ') cmd.do(' 5. Open a terminal instance from the File pulldown in jupyter notebook.') cmd.do(' ') cmd.do(' 6. Enter `pymol -Rq` to launch an interactive instance of PyMOL.') cmd.do(' ') cmd.do(' 7. Enter the following code to load ipymol and conmect to PyMOL') cmd.do(' ') cmd.do(' from ipymol import viewer as ipv') cmd.do(' ipv.start() # Start PyMOL RPC server') cmd.do(' ') cmd.do(' Now you can change the scene manually and send the display as static ') cmd.do(' image to a cell in the jupyter notebook.') cmd.do(' ') cmd.do(' It is assumed that the viewer class of the ipymol moduel has been ') cmd.do(' imported as ipv. ') cmd.do(' ') cmd.do(' I made the following modifications of roundview.py.') cmd.do(' The cmd.get_view was replaced with ipv.get_view.') cmd.do(' The cmd.extend was replaced with ipv.extend.') cmd.do(' The myRoundedList was returned for further processing.') cmd.do(' ') cmd.do(' MIT License') cmd.do(' ') cmd.do(' Copyright:') cmd.do(' <NAME> and the OU Board of Regents') cmd.do(' Uniersity of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' ') cmd.do(' 29 April 2020') cmd.do(' ') cmd.do(' """') cmd.do(' ') cmd.do(' ') cmd.do(' StoredView = int(StoredView)') cmd.do(' decimal_places = int(decimal_places)') cmd.do(' ') cmd.do(' #call the get_view function') cmd.do(' ') cmd.do(' m = ipv.get_view(StoredView)') cmd.do(' ') cmd.do(' ') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' ') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9],') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' ') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' ') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' ') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' ') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' ') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' ') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a")') cmd.do(' myFile.write(x.format(*myRoundedList) + "")') cmd.do(' myFile.close()') cmd.do(' return myRoundedList') cmd.do('ipv.extend("rv", rv)') ${0} ''' 'Demo of the use of the RPC server with a drug compound via rdkit.': 'prefix': 'rdkrpcChem' 'body': ''' cmd.do('import os;') cmd.do('import rdkit;') cmd.do('from rdkit import Chem;') cmd.do('from rdkit.Chem import AllChem;') cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('s = PyMOL.MolViewer();') cmd.do('mol = Chem.MolFromSmiles \') cmd.do(' ('CCOCCn1c(C2CC[NH+](CCc3ccc(C(C)(C)C(=O)[O-])cc3)CC2)nc2ccccc21');') cmd.do('mol = AllChem.AddHs(mol);') cmd.do('AllChem.EmbedMolecule(mol);') cmd.do('AllChem.MMFFOptimizeMolecule(mol);') cmd.do('s.ShowMol(mol, name = 'bilastine', showOnly = False);') cmd.do('s.Zoom('bilastine');') cmd.do('s.SetDisplayStyle('bilastine', 'sticks');') cmd.do('s.GetPNG(preDelay=5);') ${0} ''' 'A kernel.json file for runnig PyMOL python interpreter in the Jupyter notebook. ': 'prefix': 'kernel' 'body': ''' cmd.do('framerule=2pt,') cmd.do('framesep=2mm,') cmd.do('framesep=2mm,') cmd.do('breaklines=True,') cmd.do('baselinestretch=1.2') cmd.do(']{bash}') cmd.do('{') cmd.do(' "argv": [') cmd.do(' "/Applications/PyMOL.app/Contents/bin/python",') cmd.do(' "-m",') cmd.do(' "ipykernel_launcher",') cmd.do(' "-f",') cmd.do(' "{connection_file}"') cmd.do(' ],') cmd.do(' "display_name": "pymol.python",') cmd.do(' "language": "python"') cmd.do('}') ${0} ''' 'Demo of the use of the RPC server with a protein via rdkit.': 'prefix': 'rdkrpcProtein' 'body': ''' cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('Usage=""""Start pymol from command line with -R flag.') cmd.do('Select the pymol.python kernel in Jupyter notebook. """;') cmd.do('') cmd.do('s = PyMol.MolViewer();') cmd.do('du = s.server.do;') cmd.do('du('rein; bg_color white; fetch 1lw9, type=pdb, async=0, show;nb_spheres; set_view (0.46,-0.28,-0.84,0.74,-0.41,0.54,-0.49,-0.87,0.02,0.0,0.0,\') cmd.do(' -155.16,35.13,11.48,9.72,122.33,187.99,-20.0);');') cmd.do('s.GetPNG(preDelay=3);') cmd.do('du('png T4L600dpi.png, dpi=600');') ${0} ''' 'Code to start the RPC server with ipymol.': 'prefix': 'ipymolStart' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') ${0} ''' 'Demo of the use of the RPC server with a protein via ipymol.': 'prefix': 'ipymolProtein' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') cmd.do('') cmd.do('ipv.do('fetch 1lw9');') cmd.do('ipv.do('rv');') cmd.do('# The double parentheses are required when set_view is run this way.;') cmd.do('ipv.set_view((-0.13,-0.4,-0.91,0.89,-0.45,0.07,-0.44,-0.8,0.41,0.0,0.0,-182.47,35.13,11.48,9.72,149.64,215.3,-20.0));') cmd.do('ipv.do('AOD');') cmd.do('ipv.png('testipymolT4L.png');') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server rdkit in a jupyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvr' 'body': ''' cmd.do('def rvr(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """MIT License') cmd.do(' Copyright:') cmd.do(' <NAME> and the OU Board of Regents') cmd.do(' University of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' 30 April 2020') cmd.do(' ') cmd.do(' First run the following:') cmd.do(' ') cmd.do(' from rdkit.Chem import PyMol') cmd.do(' s = PyMol.MolViewer()') cmd.do(' du = s.server.do') cmd.do('') cmd.do(' """') cmd.do(' StoredView = int(StoredView) decimal_places = int(decimal_places)') cmd.do(' #call the get_view function') cmd.do(' m = s.get_view(StoredView)') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9], ') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a") myFile.write(x.format(*myRoundedList) + "") myFile.close()') cmd.do(' return myRoundedList') cmd.do('du.extend("rvr", rvr)') ${0} ''' 'Return to the command history window the docstrings for all of the functions in the cmd module.': 'prefix': 'cmddocs' 'body': ''' cmd.do('[help(i) for i in dir(cmd)];') ${0} ''' 'Return to the command history window the docstrings for all of the functions in a module.': 'prefix': 'pymoldocs' 'body': ''' cmd.do('[help(i) for i in dir(pymol)];') ${0} ''' 'Print the number of residues in a protein.': 'prefix': 'numResiProtein' 'body': ''' cmd.do('sel = 'polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in chain A of a protein.': 'prefix': 'numResiProteinChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid (all chains).': 'prefix': 'numResiNucleic' 'body': ''' cmd.do('sel = 'polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid chain.': 'prefix': 'numResiNucleicChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Create bonds between phosphorous and O3* atoms in a low resolution DNA structure that is 80 base pairs long.': 'prefix': 'brokenNucleicBackbone' 'body': ''' cmd.do('[cmd.bond(f"/5fur//E/{i}/O3'", f"/5fur//E/{i+1}/P") for i in range(${1:1}, ${2:80})]; ') cmd.do('[cmd.bond(f"/5fur//F/{i}/O3'", f"/5fur//F/{i+1}/P") for i in range(${3:81}, ${3:160})];') ${0} ''' 'To change stick color and radius for the bond between atom 2 and 3, use the set_bond command. ': 'prefix': 'oneBondThicknessColor' 'body': ''' cmd.do('# To change stick color and radius for the bond between atom 2 and 3;') cmd.do('set_bond stick_color, ${1:yellow}, index 2, index 3;') cmd.do('set_bond stick_radius, ${2:0.2}, index 2, index 3;') ${0} ''' 'Connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18. Note that this example requires the draw_links.py [http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py] by <NAME>.': 'prefix': 'drawLinks' 'body': ''' cmd.do('# Requires draw_links.py http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py by <NAME>') cmd.do('# To connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18.') cmd.do('draw_links ${1:mol1} & chain ${2:A} & name ${3:CA} & resi ${4:1+6+7+8}, ${5:mol1} & chain ${6:A}& name ${7:CA} & resi ${8:10+16+17+18} ') ${0} ''' 'Print the path to the currently used PyMOL binary.': 'prefix': 'printPath' 'body': ''' cmd.do('# Print the path to the current used PyMOL binary.') cmd.do('print pymol.__path__') ${0} ''' 'Turn on the ligand valence.': 'prefix': 'setLigandValenceOn' 'body': ''' cmd.do('#Set on the valence of the ligand only') cmd.do('set valence, on, resn ${1:RZS}; set valence, off, not resn ${2:RZS}') ${0} ''' 'Return the docustring for the preset submodule. The command help preset fails to return anything. The command help(pymol.preset) has the same effect as help(preset).': 'prefix': 'presetDocs' 'body': ''' cmd.do('help(preset)') ${0} ''' 'Return the docustring for the help submodule. The command help help is more concise.': 'prefix': 'helpDocs' 'body': ''' cmd.do('help(help)') ${0} ''' 'The amber trajectories have to be loaded into the same object.': 'prefix': 'loadAmberTrajs' 'body': ''' cmd.do('load file.top, protein;') cmd.do('load file.rst, protein') ${0} ''' 'Saves multiple objects into multiple files using an optional prefix name.': 'prefix': 'saveSep' 'body': ''' cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('import re') cmd.do('') cmd.do('def saveSep(prefix=''):') cmd.do(' """') cmd.do(' save_sep <prefix>') cmd.do('') cmd.do(' saves multiple objects into multiple files using an optional prefix name.') cmd.do('') cmd.do(' e.g. save_sep prefix') cmd.do(' """') cmd.do(' obj_list = cmd.get_names("all")') cmd.do('') cmd.do(' if obj_list:') cmd.do(' for i in range(len(obj_list)):') cmd.do(' obj_name = "%s%s.pdb" % (prefix, obj_list[i])') cmd.do(' cmd.save(obj_name, obj_list[i])') cmd.do(' print("Saving %s" % obj_name)') cmd.do(' else:') cmd.do(' print("No objects found")') cmd.do(' ') cmd.do('cmd.extend('saveSep',saveSep)') ${0} ''' 'OptiAlign.py by <NAME> modified for aligning multiple RNA structures.': 'prefix': 'optAlignRNA' 'body': ''' cmd.do('#!python') cmd.do(' ') cmd.do('##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py. A python implementation of the optimal superposition') cmd.do('# of two sets of vectors as proposed by Kabsch 1976 & 1978.') cmd.do('#') cmd.do('# @AUTHOR: <NAME>') cmd.do('# @COPYRIGHT: <NAME> (C), 2005-2007') cmd.do('# @LICENSE: Released under GPL:') cmd.do('# This program is free software; you can redistribute it and/or modify') cmd.do('# it under the terms of the GNU General Public License as published by') cmd.do('# the Free Software Foundation; either version 2 of the License, or') cmd.do('# (at your option) any later version.') cmd.do('# This program is distributed in the hope that it will be useful, but WITHOUT') cmd.do('# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS') cmd.do('# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.') cmd.do('#') cmd.do('# You should have received a copy of the GNU General Public License along with') cmd.do('# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin') cmd.do('# Street, Fifth Floor, Boston, MA 02110-1301, USA ') cmd.do('#') cmd.do('# DATE : 2007-01-01') cmd.do('# REV : 2') cmd.do('# REQUIREMENTS: numpy') cmd.do('#') cmd.do('#') cmd.do('# Modified optAlign.py to use C1' carbon atoms of RNA for alignment.') cmd.do('# Jan. 29, 2020 ') cmd.do('# <NAME>, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#############################################################################') cmd.do('from array import *') cmd.do(' ') cmd.do('# system stuff') cmd.do('import os') cmd.do('import copy') cmd.do(' ') cmd.do('# pretty printing') cmd.do('import pprint') cmd.do(' ') cmd.do('# for importing as a plugin into PyMol') cmd.do('from pymol import cmd') cmd.do('from pymol import stored') cmd.do('from pymol import selector') cmd.do(' ') cmd.do('# using numpy for linear algebra') cmd.do('import numpy') cmd.do(' ') cmd.do('def optAlignRNA( sel1, sel2 ):') cmd.do(' """') cmd.do(' optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections.') cmd.do(' Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1'') cmd.do(' ') cmd.do(' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from') cmd.do(' PyMOL based upon your selections.') cmd.do(' ') cmd.do(' This function can be run in a for loop to fit multiple structures with a common prefix name:') cmd.do(' ') cmd.do(' for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001")') cmd.do(' ') cmd.do(' or get the rmsds for all combinations, do the following:') cmd.do(' ') cmd.do(' [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do(' """') cmd.do(' cmd.reset()') cmd.do(' ') cmd.do(' # make the lists for holding coordinates') cmd.do(' # partial lists') cmd.do(' stored.sel1 = []') cmd.do(' stored.sel2 = []') cmd.do(' # full lists') cmd.do(' stored.mol1 = []') cmd.do(' stored.mol2 = []') cmd.do(' ') cmd.do(' # -- CUT HERE') cmd.do(' sel1 += " and N. C1'"') cmd.do(' sel2 += " and N. C1'"') cmd.do(' # -- CUT HERE') cmd.do(' ') cmd.do(' # Get the selected coordinates. We') cmd.do(' # align these coords.') cmd.do(' cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")') cmd.do(' ') cmd.do(' # get molecule name') cmd.do(' mol1 = cmd.identify(sel1,1)[0][0]') cmd.do(' mol2 = cmd.identify(sel2,1)[0][0]') cmd.do(' ') cmd.do(' # Get all molecule coords. We do this because') cmd.do(' # we have to rotate the whole molcule, not just') cmd.do(' # the aligned selection') cmd.do(' cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")') cmd.do(' ') cmd.do(' # check for consistency') cmd.do(' assert len(stored.sel1) == len(stored.sel2)') cmd.do(' L = len(stored.sel1)') cmd.do(' assert L > 0') cmd.do(' ') cmd.do(' # must alway center the two proteins to avoid') cmd.do(' # affine transformations. Center the two proteins') cmd.do(' # to their selections.') cmd.do(' COM1 = numpy.sum(stored.sel1,axis=0) / float(L)') cmd.do(' COM2 = numpy.sum(stored.sel2,axis=0) / float(L)') cmd.do(' stored.sel1 -= COM1') cmd.do(' stored.sel2 -= COM2') cmd.do(' ') cmd.do(' # Initial residual, see Kabsch.') cmd.do(' E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)') cmd.do(' ') cmd.do(' #') cmd.do(' # This beautiful step provides the answer. V and Wt are the orthonormal') cmd.do(' # bases that when multiplied by each other give us the rotation matrix, U.') cmd.do(' # S, (Sigma, from SVD) provides us with the error! Isn't SVD great!') cmd.do(' V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))') cmd.do(' ') cmd.do(' # we already have our solution, in the results from SVD.') cmd.do(' # we just need to check for reflections and then produce') cmd.do(' # the rotation. V and Wt are orthonormal, so their det's') cmd.do(' # are +/-1.') cmd.do(' reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))') cmd.do(' ') cmd.do(' if reflect == -1.0:') cmd.do(' S[-1] = -S[-1]') cmd.do(' V[:,-1] = -V[:,-1]') cmd.do(' ') cmd.do(' RMSD = E0 - (2.0 * sum(S))') cmd.do(' RMSD = numpy.sqrt(abs(RMSD / L))') cmd.do(' ') cmd.do(' #U is simply V*Wt') cmd.do(' U = numpy.dot(V, Wt)') cmd.do(' ') cmd.do(' # rotate and translate the molecule') cmd.do(' stored.sel2 = numpy.dot((stored.mol2 - COM2), U)') cmd.do(' stored.sel2 = stored.sel2.tolist()') cmd.do(' # center the molecule') cmd.do(' stored.sel1 = stored.mol1 - COM1') cmd.do(' stored.sel1 = stored.sel1.tolist()') cmd.do(' ') cmd.do(' # let PyMol know about the changes to the coordinates') cmd.do(' cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")') cmd.do(' cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")') cmd.do(' ') cmd.do(' #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD)') cmd.do(' print("% s, % s,% 5.3f" % (mol1, mol2, RMSD))') cmd.do(' ') cmd.do(' # make the alignment OBVIOUS') cmd.do(' cmd.hide('everything')') cmd.do(' cmd.show('ribbon', sel1 + ' or ' + sel2)') cmd.do(' cmd.color('gray70', mol1 )') cmd.do(' cmd.color('magenta', mol2 )') cmd.do(' cmd.color('red', 'visible')') cmd.do(' cmd.show('ribbon', 'not visible')') cmd.do(' cmd.center('visible')') cmd.do(' cmd.orient()') cmd.do(' cmd.zoom('visible')') cmd.do(' ') cmd.do('cmd.extend("optAlignRNA", optAlignRNA)') ${0} ''' 'Load into PyMOL multiple files with a common file stem. The is a script by <NAME> that updated for Python3.': 'prefix': 'loadManyFiles' 'body': ''' cmd.do('# Copyright (c) 2004 <NAME>') cmd.do('#') cmd.do('# Modified for use with Python3.') cmd.do('# Jan. 29, 2020 ') cmd.do('# <NAME>, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#') cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('') cmd.do('def loadFiles(files):') cmd.do(' """') cmd.do(' load_files <files>') cmd.do('') cmd.do(' loads multiple files (using filename globbing)') cmd.do(' into a multiple objects named as the files are (e.g. collection of') cmd.do(' downloaded PDB files).') cmd.do('') cmd.do(' e.g. load_files prot_*.pdb') cmd.do(' """') cmd.do(' file_list = glob.glob(files)') cmd.do(' if file_list:') cmd.do(' file_list.sort()') cmd.do(' for i in file_list:') cmd.do(' #obj_name = i.replace('.pdb','')') cmd.do(' #cmd.load(file_list[i],obj_name)') cmd.do(' cmd.load(i)') cmd.do(' else:') cmd.do(' print("No files found for pattern %s" % files)') cmd.do('') cmd.do('cmd.extend('loadFiles',loadFiles)') ${0} ''' 'These are the instructions for loading and aligning multiple files.': 'prefix': 'loadAndAlignManyFiles' 'body': ''' cmd.do('To load a bunch of related files from inside PyMOL all at once:') cmd.do('') cmd.do('run loadFiles.py') cmd.do('loadFiles refine_*.pdb') cmd.do('') cmd.do('') cmd.do('To align all of the loaded RNA structures in all possible combinations by their C1' carbon atoms:') cmd.do('') cmd.do('run optAlignRNA.py') cmd.do('[[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do('(Yes, that construct is a list comprehension inside a list comprehension!)') cmd.do('') cmd.do('To save a multiple models in a file to separate pdb files,') cmd.do('') cmd.do('run saveSep.py') cmd.do('saveSep ') cmd.do('or ') cmd.do('saveSep prefix') ${0} ''' 'This is a two-fold nested list comprehension for any all parwise operation on the currently loaded objects. Replace optAlginRNA with any other function that operations on a pair of structrures.': 'prefix': 'allPairs' 'body': ''' cmd.do('[[${1:optAlignRNA}(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') ${0} ''' 'Combining DSSR block representation with regular PyMOL cartoons after loading the dssr_block.py script by <NAME>.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('as cartoon;') cmd.do('set cartoon_ladder_radius, 0.1;') cmd.do('set cartoon_ladder_color, gray;') cmd.do('set cartoon_nucleic_acid_mode, 1;') cmd.do('dssr_block') ${0} ''' 'DSSR block representation with fused blocks after loading the dssr_block.py script by <NAME>. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('dssr_block block_file=wc') ${0} ''' 'DSSR block representation for a multi-state example after loading the dssr_block.py script by <NAME>. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 2n2d, async=0;') cmd.do('dssr_block 2n2d, 0;') cmd.do('set all_states;') ${0} ''' 'DSSR block representation with custom coloring after loading the dssr_block.py script by <NAME>. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1msy, async=0;') cmd.do('dssr_block block_color=N red | minor 0.9 | major yellow;') ${0} ''' 'Settings for nucliec acid cartoon.': 'prefix': 'nucleicAcidCartoon' 'body': ''' cmd.do('set cartoon_ladder_color, ${1:density};') cmd.do('set cartoon_ladder_radius, ${2:0.2};') cmd.do('set cartoon_nucleic_acid_color, ${3:red};') cmd.do('set cartoon_ring_mode, ${4:2};') ${0} ''' 'Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. The set command as the syntax of setting_name [, setting_value [, selection [,state ]]] . In this case, the selection has to be global, object, object-state, or per-atom settings. It cannot be a named selection. This is a weak spot in PyMOL. Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. Many double-stranded helices have one strand in the asymmetric unit. The second strand is in the biological unit. The coordinates for the second strand are in the pdb1 file type at the PDB. The second strand is in the second state, which is equivalent to the second model in the pdb file. The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting). The bases are colored differently too (via the cartoon_ladder_color setting). ': 'prefix': 'nucleicAcidCartoon2Strands' 'body': ''' cmd.do('# There is not support for applying different settings to different selections.') cmd.do('# Instead, this can be done for different objects.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# The set command as the syntax of setting_name [, setting_value [, selection [,state ]]]') cmd.do('# In this case, the selection has to be global, object, object-state, or per-atom settings.') cmd.do('# It cannot be a named selection.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# Many double-stranded helices have one strand in the asymmetric unit.') cmd.do('# The second strand is in the biological unit.;') cmd.do('# The coordinates for the second strand are in the pdb1 file type at the PDB.;') cmd.do('# The second strand is in the second state, which is equivalent to the second model in the pdb file.;') cmd.do('# The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting).;') cmd.do('# The bases are colored differently too (via the cartoon_ladder_color setting).;') cmd.do('fetch ${1:3nd3}, ${2:3nd3}, type=${3:pdb1};') cmd.do('set all_states, on;') cmd.do('create chA, ${2:3nd3}, 1, 1;') cmd.do('create chB, ${2:3nd3}, 2, 1;') cmd.do('# colors only the backbone;') cmd.do('set cartoon_nucleic_acid_color, ${4:magenta}, chA;') cmd.do('set cartoon_nucleic_acid_color, ${5:orange}, chB;') cmd.do('# color the bases;') cmd.do('set cartoon_ladder_color, ${6:density}, chA;') cmd.do('set cartoon_ladder_color, ${7:yellow}, chB;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It could make a good shortcut.': 'prefix': 'nucleicAcidColorbySequence' 'body': ''' cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${1:yellow}, rna_A;') cmd.do('color ${2:red}, rna_C; ') cmd.do('color ${3:gray40}, rna_G;') cmd.do('color ${4:palecyan}, rna_U;') cmd.do('color ${5:brown}, dna_T;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It is dervied from the CR shortcut. The backcone is shown as a flatten ribbon.': 'prefix': 'nucleicAcidFlatRibbonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85};') cmd.do('set cartoon_oval_width, ${2:0.5};') cmd.do('cartoon oval;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval;') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'The code provides a cartoon of the loaded nucleic acid that has the ladder rungs replaced by filled rings that are colored by atom type. The code can be applied to any nucleic acid. It is derived from the FR shortuct.': 'prefix': 'nucleicAcidCartoonFilledRings' 'body': ''' cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'This code make as standard base stacking diagram with ball and stick representation. ': 'prefix': 'basePairStacking' 'body': ''' cmd.do('delete all;') cmd.do('fetch 4PCO, type=pdb, async=0;') cmd.do('select G2G3, ( ((resi 2 or resi 3) and chain A) or ((resi 8 or resi 9) and chain B));') cmd.do('remove not G2G3;') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7.24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('remove name H*;') cmd.do('select carbon1, element C and (resi 3 or resi 8) ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi 2 or resi 9) ') cmd.do('#select upper base pair;') cmd.do('color gray70, carbon1;') cmd.do('color gray10, carbon2;') cmd.do('show sticks;') cmd.do('space cmyk;') cmd.do('distance hbond1, /4PCO//B/U`9/N3,/4PCO//A/G`2/O6;') cmd.do('distance hbond2, /4PCO//B/U`9/O2,/4PCO//A/G`2/N1;') cmd.do('distance hbond3, /4PCO//A/U`3/N3,/4PCO//B/G`8/O6;') cmd.do('distance hbond4, /4PCO//A/U`3/O2,/4PCO//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png 4PCO.png;') ${0} ''' 'This code colors by the nucleotides by base seqence. The backcone is shown as a flatten ribbon with rolled edges that give the dumbell effect. The code can be applied to any nucleic acid. The code is dervied from the CR and DU shortcuts. ': 'prefix': 'nucleicAcidDumbellCartoonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85}') cmd.do('set cartoon_oval_width, ${2:0.5}') cmd.do('cartoon oval;') cmd.do('cartoon dumbbell;') cmd.do('set cartoon_dumbbell_width, 0.2;') cmd.do('set cartoon_dumbbell_radius, 0.4;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'Set keyboard shortcut by mapping F1 to stereo.': 'prefix': 'stereokb' 'body': ''' cmd.do('cmd.set_key('F1',lambda:cmd.stereo({'on':0,'off':1}[cmd.get('stereo')]));') ${0} ''' 'Print to the screen the settings and their current parameter values.': 'prefix': 'listSettings2' 'body': ''' cmd.do('list = setting.get_name_list();[print("%s => %s" % (name, setting.get_setting_text(name))) for name in list];') ${0} ''' 'Print to the screen the settings and their current parameter values. This is the more compact version.': 'prefix': 'listSettings' 'body': ''' cmd.do('[print("%s => %s" % (name, setting.get_setting_text(name))) for name in setting.get_name_list()];') ${0} ''' 'Print to the screen as labels that 21 font ids in their corresponding fonts in a grid. Each label is an object and appears in the internal gui. You can turn on and off the display of specific fonts.': 'prefix': 'displayFonts' 'body': ''' cmd.do('python;') cmd.do('from pymol import cmd;') cmd.do('for i in range(1,21):') cmd.do(' name = 'label%d' % i;') cmd.do(' cmd.pseudoatom(name, label='label font id %d' % i, pos=(0,0,0));') cmd.do(' cmd.set('label_font_id', i, name);') cmd.do('cmd.set('label_size', 50);') cmd.do('cmd.set('grid_mode');') cmd.do('python end;') ${0} ''' 'Print to disk a list of H-bond pairs and this H-bond length.': 'prefix': 'listHBonds' 'body': ''' cmd.do('Finish latter. See file listHBonds.py.;') ${0} ''' 'Create a list of objects in the internal gui and print this list to the screen.': 'prefix': 'listObjects' 'body': ''' cmd.do('objList = cmd.get_names("objects");print(objList);') ${0} ''' 'Print a list of protein--ligand distances. Code by <NAME>. Updated for Python3.': 'prefix': 'listLigandProteinDistances' 'body': ''' cmd.do('from pymol import cmd') cmd.do('"""') cmd.do('Find all distances betwen all ligand atoms and all protein atoms. ') cmd.do('') cmd.do('Adapted and updated from script by <NAME> posted here') cmd.do('https://sourceforge.net/p/pymol/mailman/message/10097804/') cmd.do('') cmd.do('There are probably better solutions like finding just the ') cmd.do('distances to proein atoms within a certain distance from ') cmd.do('the ligand.') cmd.do('') cmd.do('Due to the nested for loops, this script is takes several second') cmd.do('to run on a medium-sized human protein. This script is a ') cmd.do('good candidate for vectorization. ') cmd.do('') cmd.do('It is also a good candiate for becoming a function and a shortcut. ') cmd.do('') cmd.do('"""') cmd.do('') cmd.do('# customize these lines to your protein.') cmd.do('cmd.fetch("6NEC")') cmd.do('cmd.select("prot","not resn XIN and not resn HOH and not chain C")') cmd.do('cmd.select("lig", "resn XIN and not chain C")') cmd.do('') cmd.do('dist_list = {}') cmd.do('pro_atoms = cmd.get_model("prot")') cmd.do('lig_atoms = cmd.get_model("lig")') cmd.do('') cmd.do('for l_at in lig_atoms.atom:') cmd.do(' for p_at in pro_atoms.atom:') cmd.do(' dist_list[str(l_at.resn) +') cmd.do(' ":" +') cmd.do(' str(l_at.resi) +') cmd.do(' " " +') cmd.do(' l_at.name +') cmd.do(' " ---- " + ') cmd.do(' str(p_at.resn) +') cmd.do(' ":" +') cmd.do(' str(p_at.resi) +') cmd.do(' " " +') cmd.do(' p_at.name] = cmd.dist("foo", ') cmd.do(' "index " +') cmd.do(' str(l_at.index),"index " + str(p_at.index))') cmd.do(' cmd.delete("foo")') cmd.do('print("List of all pairwise ligand--protein atom-atom distances:")') cmd.do('# [print("Distance of " + d + " is " + str(dist_list[d])) for d in dist_list.keys()]') cmd.do('') cmd.do('# More compact print statement. Need an f-string format statement.') cmd.do('[print( d + " " + str(dist_list[d])) for d in dist_list.keys()]') ${0} ''' 'This code shows that cartoon backbone tube as 65% transparent. It hides the rungs of the cartoon. It shows all of the non-H atoms are sticks. The motivation is to have the cartoon highlight the backbone without dominanting the scene.': 'prefix': 'nucleicAcidBackboneTubesSticks' 'body': ''' cmd.do('set bg_rgb, white;') cmd.do('hide everything, all;') cmd.do('show cartoon, ${1:3nd3};') cmd.do('set cartoon_sampling,1;') cmd.do('set cartoon_tube_radius, 0.5;') cmd.do('set cartoon_ladder_mode, 0;') cmd.do('set cartoon_transparency, ${2:0.65};') cmd.do('set stick_radius ${3:0.12};') cmd.do('show sticks;') cmd.do('hide sticks, element H;') ${0} ''' 'The code expands the asymmetric unit. It like the generate symmetry mates command but it provides more control over the prefix name of the symmetry mates and the addition of unique segment identifiers for each symmetry mate. The usage: symexp prefix, object, (selection), cutoff, segidFlag. The cutoff is in Angstroms. The segidFlag set to 1 will add unique segids. For related functions, see SC***.': 'prefix': 'symexp' 'body': ''' cmd.do('symexp ${1:symm}, ${2:3fa0}, (${2:3fa0}), ${3:20},${4:1};') ${0} ''' 'Adds the function draw_axis(). Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.': 'prefix': 'addAxis' 'body': ''' cmd.do('from pymol.cgo import * # get constants') cmd.do('from pymol import cmd') cmd.do('') cmd.do('import math') cmd.do('') cmd.do('class Counter:') cmd.do(' """') cmd.do(' draw_line') cmd.do(' source https://www.pymolwiki.org/index.php/Symmetry_Axis') cmd.do(' ') cmd.do(' Pymol script copyright <NAME> and <NAME> 2007') cmd.do(' ') cmd.do(' Under GNU Free Documentation License 1.2') cmd.do(' ') cmd.do(' Example:') cmd.do(' ') cmd.do(' draw_axis(x=18.232, y=17.150, z=9.488,i=-.226639, j=0.708772, k=-.668039, r=1, b=0, g=0, width=1, length=100)') cmd.do(' ') cmd.do(' Updated 15 June 2020 ') cmd.do(' <NAME>') cmd.do(' ') cmd.do(' Notes:') cmd.do(' 1) Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.') cmd.do(' 2) The postion (xyz) is the middle of the line, not one end as expected for a vector.') cmd.do(' 3) Another example: draw_axis(x=0, y=0, z=0,i=0, j=0, k=1, r=1, b=0, g=0, width=300, length=96) ') cmd.do(' 4) Changed print statement to Python3 print function.') cmd.do(' 5) Replaced cmd.extend() with function generator.') cmd.do(' """') cmd.do(' def __init__(self):') cmd.do(' self.state = 1') cmd.do('counter = Counter()') cmd.do('') cmd.do('@cmd.extend') cmd.do('def draw_axis(x=None, y=None, z=None, i=None, j=None, k=None, length=20.0, r=1.0, g=1.0, b=1.0, width=1.0 ):') cmd.do(' if x == None or y == None or z == None or i == None or j == None or k== None :') cmd.do(' print('Usage: draw_axis x,y,z, i,k,j, length, r,g,b, width')') cmd.do(' print('draw a line centered at (x,y,z) with the direction vector (i,j,k)')') cmd.do(' print('length, color (r,g,b), and width arguments are optional')') cmd.do('# print 'For a fun example of the command, run draw_axis_example'') cmd.do(' else :') cmd.do(' x,y,z = float(x), float(y), float(z)') cmd.do(' i,j,k = float(i), float(j), float(k)') cmd.do(' r,g,b = float(r), float(g), float(b)') cmd.do(' width = float(width)') cmd.do(' length = float(length) / 2.0') cmd.do('') cmd.do(' x1,y1,z1 = (x+i*length,y+j*length,z+k*length)') cmd.do(' x2,y2,z2 = (x-i*length,y-j*length,z-k*length)') cmd.do('') cmd.do(' obj = [') cmd.do(' LINEWIDTH, width,') cmd.do(' BEGIN, LINES,') cmd.do('') cmd.do(' COLOR, r, g, b,') cmd.do(' VERTEX, x1, y1, z1,') cmd.do(' VERTEX, x2, y2, z2,') cmd.do('') cmd.do(' END') cmd.do(' ]') cmd.do('') cmd.do(' cmd.load_cgo(obj,'axis'+str(counter.state))') cmd.do(' counter.state += 1') ${0} ''' 'Wait unitl all current commands have been executed. A timeout ensures that that command ecentually returns.': 'prefix': 'synch' 'body': ''' cmd.do('cmd.sync(timeout=${1:1.0},poll=${2:0.05});') ${0} ''' 'Add or substract a residue number offset.': 'prefix': 'renumResi' 'body': ''' cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;') ${0} ''' 'Add or substract a atom number offset.': 'prefix': 'renumAtoms' 'body': ''' cmd.do('alter {$1:3fa0}, ID=ID+${2:100};') cmd.do('sort;') ${0} ''' 'Rename a chain. ': 'prefix': 'renameChain' 'body': ''' cmd.do('alter ${1:3fa0} and chain ${2:A}, chain=${3:"C"};') cmd.do('sort;') ${0} ''' 'Print the atom number2 of a residue.': 'prefix': 'printAtomNumbers' 'body': ''' cmd.do('iterate (resi 1), print(name + " %i5" % ID);') ${0} ''' 'Print the atom names of a residue.': 'prefix': 'printAtomNames' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name);') ${0} ''' 'Print the bfactors of a residue.': 'prefix': 'printBfactors' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % b);') ${0} ''' 'Print the van Der Waals radii of the atoms in of a residue.': 'prefix': 'printVDWradii' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % vdw);') ${0} ''' 'Print the coordinates of the atoms in a residue.': 'prefix': 'printCoordinates' 'body': ''' cmd.do('stored.coords = []; ') cmd.do('iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('[print(i) for i in stored.coords];') ${0} ''' 'Print the atom names and coordinates of the atoms in a residue.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]); ') cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101})), stored.coords.append([x,y,z]); ') cmd.do('[print(i,j) for i,j in zip(stored.names, stored.coords)];') ${0} ''' 'Print the atom names as tuples and coordinates of the atoms in a residue as a list.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]);') cmd.do('stored.names3 = [tuple(i) for i in stored.names];') cmd.do('[print(i,j) for i,j in(zip(stored.names3, stored.coords)];') ${0} ''' 'Source block template in org-mode with emacs-jupyter package. ': 'prefix': 'emacsjupyterSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC jupyter-python :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') cmd.do('$0') ${0} ''' 'Source block template in org-mode with ob-ipython package. ': 'prefix': 'obipythonSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC ipython :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') ${0} '''
true
'.source.python': 'Ambient occlussion.': 'prefix': 'ao' 'body': ''' cmd.do('set_color oxygen, [1.0,0.4,0.4];') cmd.do('set_color nitrogen, [0.5,0.5,1.0];') cmd.do('remove solvent;') cmd.do('as spheres;') cmd.do('util.cbaw;') cmd.do('bg white;') cmd.do('set light_count,10;') cmd.do('set spec_count,1;') cmd.do('set shininess, 10;') cmd.do('set specular,0.25;') cmd.do('set ambient,0;') cmd.do('set direct,0;') cmd.do('set reflect,1.5;') cmd.do('set ray_shadow_decay_factor, 0.1;') cmd.do('set ray_shadow_decay_range, 2;') cmd.do('unset depth_cue;') cmd.do('ray;') ${0} ''' 'Set ellipsoid color.': 'prefix': 'ellipcol' 'body': ''' cmd.do('set ellipsoid_color, ${1:color};') cmd.do('${0}') ${0} ''' 'set distance labels to display 2 decimals': 'prefix': 'sigdist' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') ${0} ''' 'Set angle labels to display 2 decimals places': 'prefix': 'sigang' 'body': ''' cmd.do('set label_angle_digits, ${1:2};') ${0} ''' 'Ball and stick representation. ': 'prefix': 'bs' 'body': ''' cmd.do('show sticks;') cmd.do('set stick_radius, 0.12;') cmd.do('set stick_ball, on;') cmd.do('set stick_ball_ratio, 1.9;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size=0.33;') ${0} ''' 'Base-stacking figure.': 'prefix': 'stack' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4PCO}, type=pdb,async=0;') cmd.do('select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );') cmd.do('hide everything, element h; ') cmd.do('remove not ${2:G2G3};') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7. 24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('hide everything, element H;') cmd.do('select carbon1, element C and (resi ${4:3} or resi ${5:8}); ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi ${3:2} or resi ${6:9});') cmd.do('#select upper base pair;') cmd.do('color gray70,carbon1;') cmd.do('color gray10,carbon2;') cmd.do('space cmyk;') cmd.do('distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;') cmd.do('distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;') cmd.do('distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;') cmd.do('distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png ${1:4PCO}.png') ${0} ''' 'Biological unit.': 'prefix': 'bu' 'body': ''' cmd.do('run ~/Scripts/PyMOLScripts/quat.py; quat') ${0} ''' 'Valence bond. ': 'prefix': 'doubleBond' 'body': ''' cmd.do('set valence, 1; ') cmd.do('set valence_mode, 1;') ${0} ''' 'Color blindness.': 'prefix': 'cblind' 'body': ''' cmd.do('run ~/Pymol-script-repo/colorblindfriendly.py;') cmd.do('as cartoon;') cmd.do('color cb_red, ss H;') cmd.do('color cb_yellow,ss S;') cmd.do('color cb_green, ss L+;') ${0} ''' 'Center pi.': 'prefix': 'centerpi' 'body': ''' cmd.do('pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;') cmd.do('dist pi_cent////ps1, b/${4:U`15}/${5:aaa};') ${0} ''' 'Color ribbon H red, strand yellow, loop green.': 'prefix': 'cribbon' 'body': ''' cmd.do('as cartoon;') cmd.do('color red, ss H;') cmd.do('color yellow,ss S;') cmd.do('color green, ss L+;') ${0} ''' 'Colored spheres.': 'prefix': 'cspheres' 'body': ''' cmd.do('as spheres;') cmd.do('color gray30, chain ${1:A};') cmd.do('color white, chain ${2:B};') cmd.do('color green, name CL;') cmd.do('color brown, resn NAG;') cmd.do('color red, resi 381;') cmd.do('remove solvent;') cmd.do('unset specular;') cmd.do('set ray_trace_gain, 0;') cmd.do('set ray_trace_mode, 3;') cmd.do('bg_color white;') cmd.do('set ray_trace_color, black;') cmd.do('unset depth_cue;') ${0} ''' 'Coordinate covalent bonds to metals and H-bonds friom RNA.': 'prefix': 'coordinate' 'body': ''' cmd.do('viewport 900,600;') cmd.do('fetch 3nd4, type=pdb, async=0;') cmd.do('run ~/Scripts/PyMOLScripts/quat.py;') cmd.do('quat 3nd4;') cmd.do('show sticks;') cmd.do('set stick_radius=0.125;') cmd.do('hide everything, name H*;') cmd.do('bg_color white;') cmd.do('create coorCov, (3nd4_1 and (resi 19 or resi 119 or resi 219 or resi 319 or resi 419 or resi 519 or (resi 3 and name N7)));') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);') cmd.do('bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);') cmd.do('distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);') cmd.do('distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);') cmd.do('show nb_spheres; ') cmd.do('set nb_spheres_size, .35;') cmd.do('distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;') cmd.do('distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;') cmd.do('distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;') cmd.do('distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;') cmd.do('distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;') cmd.do('distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;') cmd.do('distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;') cmd.do('distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;') cmd.do('distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;') cmd.do('distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;') cmd.do('distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;') cmd.do('distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;') cmd.do('distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;') cmd.do(' distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;') cmd.do('distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;') cmd.do('distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;') cmd.do('distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2; ') cmd.do('set depth_cue=0;') cmd.do('set ray_trace_fog=0;') cmd.do('set dash_color, black;') cmd.do('set label_font_id, 5;') cmd.do('set label_size, 36;') cmd.do('set label_position, (0.5, 1.0, 2.0);') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('set label_color, black;') cmd.do('set dash_gap, 0.2;') cmd.do('set dash_width, 2.0;') cmd.do('set dash_length, 0.2;') cmd.do('select carbon, element C;') cmd.do('color yellow, carbon;') cmd.do('disable carbon;') cmd.do('set_view(-0.9,0.34,-0.26,0.33,0.18,-0.93,-0.27,-0.92,-0.28,-0.07,-0.23,-27.83,8.63,19.85,13.2,16.0,31.63,-20.0)') ${0} ''' 'H-bond distances.': 'prefix': 'distance' 'body': ''' cmd.do('distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}') ${0} ''' 'Draw H-bonds. ': 'prefix': 'drawHbonds' 'body': ''' cmd.do('hide everything, hydrogens') cmd.do('hide labels') cmd.do('set dash_color, ${1:black}${2:yelow} ') cmd.do('set dash_gap, 0.4') cmd.do('set dash_radius, 0.08') ${0} ''' 'Carved isomesh representation of electron density. ': 'prefix': 'carvedIsomesh' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isomesh.': 'prefix': 'fetch2FoFcIsomesh' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isomesh 2fofcmap, ${1:3nd4_2fofc}, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Fetch cif file.': 'prefix': 'fetchCIF' 'body': ''' cmd.do('fetch ${1:3nd4}, type=cif, async=0;') ${0} ''' 'Fetch fofc map.': 'prefix': 'fetchFoFc' 'body': ''' cmd.do('fetch ${1:3nd4}, type=fofc, async=0;') ${0} ''' 'Filled rings in nucleic acids. ': 'prefix': 'filledRing' 'body': ''' cmd.do('show sticks;set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'Get coordinates. ': 'prefix': 'getCoordinates' 'body': ''' cmd.do('print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');') ${0} ''' 'H-bond dashes.': 'prefix': 'hbonddash' 'body': ''' cmd.do('hide everything, hydrogens;') cmd.do('hide labels;') cmd.do('set dash_color, black; ') cmd.do('set dash_gap, 0.4;') cmd.do('set dash_radius, 0.08;') ${0} ''' 'Hbond setup. ': 'prefix': 'hbond' 'body': ''' cmd.do('hide labels;') cmd.do('set dash_color, black ;') cmd.do('set dash_length, ${1:0.15};') cmd.do('set dash_gap, ${2:0.35};') cmd.do('set dash_width, ${3:3.0};') ${0} ''' 'Hide alt loc.': 'prefix': 'hidealtloc' 'body': ''' cmd.do('select altconf, alt ${1:b} # select B alternative locators;') cmd.do('hide everything, altconf # hide alt B locators;') ${0} ''' 'Label CA atom with single-letter residue name and residue number.': 'prefix': 'labelResnResi' 'body': ''' cmd.do('label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});') ${0} ''' 'Label SS. ': 'prefix': 'labelSS' 'body': ''' cmd.do('alter ${1:}, ss='%1';') cmd.do('label (%2),'%3';') ${0} ''' 'Load PDB ball-and-stick.': 'prefix': 'loadPDBbs' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('hide (name H*);') cmd.do('hide lines;') cmd.do('show sticks;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('set nb_sphere_radius, ${3:0.35};') cmd.do('orient;') ${0} ''' 'Load PDB nb spheres. ': 'prefix': 'loadPDBnb' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;') cmd.do('orient;') cmd.do('set stick_radius, ${2:1.2};') cmd.do('hide (name H*);') cmd.do('set nb_sphere_size, ${3:0.35};') cmd.do('set nb_spheres_quality, ${4:1};') cmd.do('show nb_spheres;') ${0} ''' 'Measure surface area. ': 'prefix': 'ms' 'body': ''' cmd.do('fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0') cmd.do('select ${2:temp}, ${3:3nd3} and chain A;') cmd.do('run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};') cmd.do('calc_msms_area ${2:temp};') ${0} ''' 'Molscript ribbons.': 'prefix': 'molscriptRibbon' 'body': ''' cmd.do('set cartoon_highlight_color, grey;') cmd.do('show cartoon;') cmd.do('set cartoon_flat_sheets, 0;') cmd.do('set cartoon_smooth_loops, 0;') cmd.do('set cartoon_fancy_helices, 1;') ${0} ''' 'One letter amino acid. ': 'prefix': 'oneLetter' 'body': ''' cmd.do('one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%') cmd.do(''ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%') cmd.do(''SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%') ${0} ''' 'Print Fasta from PDB file. ': 'prefix': 'fasta' 'body': ''' cmd.do('print cmd.get_fastastr('all')') ${0} ''' 'Position label with pseudoatom. ': 'prefix': 'pseudolabel' 'body': ''' cmd.do('pseudoatom ${1:forLabel};') cmd.do('label ${1:forLabel}, '%0';') cmd.do('set label_color, ${2:red};') ${0} ''' 'Rotate about axis.': 'prefix': 'rotate' 'body': ''' cmd.do('rotate ${1:x}, ${2:45}, ${3:pept};') ${0} ''' 'Stereo draw.': 'prefix': 'stereoDraw' 'body': ''' cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') ${0} ''' 'Stereo ray.': 'prefix': 'stereoRay' 'body': ''' cmd.do('stereo; ') cmd.do('set ray_shadow, off;') cmd.do('ray ${1:2400,1200};') cmd.do('png ${2:aaa}.png;') ${0} ''' 'Three electron density as Isomesh. ': 'prefix': 'threeMapsIsomesh' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Turn about axis. ': 'prefix': 'turnAboutAxis' 'body': ''' cmd.do('turn ${1:x},${2:90};') ${0} ''' 'Volume ramp.': 'prefix': 'volumeRamp' 'body': ''' cmd.do('cmd.volume_ramp_new('ramp_magenta', [0.01, 1.00, 0.00, 1.00, 0.00, 4.01, 1.00, 0.00, 1.00, 0.10, 4.99, 1.00, 0.00, 1.00, 0.50,])') ${0} ''' 'Set radius of ball used to make solvent accessible surface.': 'prefix': 'solventRadius' 'body': ''' cmd.do('set solvent_radius, ${1:1.55};') ${0} ''' 'Scale the radius and color of atoms as spheres by property in the B-value column.': 'prefix': 'scaleRadiusColor' 'body': ''' cmd.do('bg_color white;') cmd.do('hide everything;') cmd.do('show spheres;') cmd.do('set stick_radius = 0.1;') cmd.do('hide everything, HET;') cmd.do('show spheres, HET;') cmd.do('set sphere_quality=3;') cmd.do('show sticks, resi $1{1102};') cmd.do('from pymol import stored;') cmd.do('# set the stored array equal to the b−values or use your own values; ') cmd.do('stored.bb = [ ];') cmd.do('iterate all, stored.bb.append(b);') cmd.do('# execute a python−block;') cmd.do('python;') cmd.do('# scale the b−values;') cmd.do('M = max(stored.bb);') cmd.do('scaledBB = map(lambda x: float (x/M), stored.bb);') cmd.do('count = 0;') cmd.do('# set the sphere radii independently;') cmd.do('#[(cmd.set("sphere_scale", x ,"ID %s"%count); count = count + 1) for x in scaledBB]') cmd.do('for x in scaledBB:') cmd.do(' cmd.set("sphere_scale", x ,"ID %s"%count)') cmd.do(' count = count + 1') cmd.do('python end') cmd.do('spectrum b, selection=${2:4gdx};') cmd.do('space cmyk;') cmd.do('set specular_intensity , 0.25;') ${0} ''' 'Return settings in rounded format.': 'prefix': 'rv' 'body': ''' cmd.do('run roundview.py;') ${0} ''' 'Save png flle with timestamp': 'prefix': 'spng' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".png"); ') cmd.do('end python;') ${0} ''' 'Save pse flle with timestamp': 'prefix': 'spse' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".pse"); ') cmd.do('end python;') ${0} ''' 'Run supercell script to generate three cells in all directions. This script was written by PI:NAME:<NAME>END_PI.': 'prefix': 'sc222' 'body': ''' cmd.do('run ${1:$HOME/Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 2, 2, 2, , orange, supercell2, 1;') ${0} ''' 'The pearl effect is made with two spheres with the outer sphere being transparent.': 'prefix': 'pearl' 'body': ''' cmd.do('create ${1:sodium2}, ${2:sodium1};') cmd.do('set sphere_transparency, 0.4, ${1:sodium2};') cmd.do('set sphere_scale, 1.05, ${1:sodium2};') cmd.do('ray;') ${0} ''' 'Blur the background atoms.': 'prefix': 'fog' 'body': ''' cmd.do('set fog, 0;') ${0} ''' 'Remove waters from molecular object.': 'prefix': 'rmwater' 'body': ''' cmd.do('remove resn HOH;') ${0} ''' 'Set color name to a RGB code.': 'prefix': 'setcolor' 'body': ''' cmd.do('set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}];') cmd.do('color ${1:bark}, ${5:protein};') ${0} ''' 'Duplicate object.': 'prefix': 'duplicateObject' 'body': ''' cmd.do('create ${1:t4l}, ${2:1lw9};') ${0} ''' 'Select a chain. ': 'prefix': 'selectChain' 'body': ''' cmd.do('select rna, chain B;') ${0} ''' 'Select residues by name.': 'prefix': 'selectResidues' 'body': ''' cmd.do('select aromatic, resn phe+tyr+trp;') ${0} ''' 'Select residues by a range of numbers.': 'prefix': 'selectResi' 'body': ''' cmd.do('select ${!:se}; resi ${2:1-100};') ${0} ''' 'Select atoms by element.': 'prefix': 'selectElement' 'body': ''' cmd.do('select ${1:oxygen}, elem ${2:O}') ${0} ''' 'Select atoms by name.': 'prefix': 'selectName' 'body': ''' cmd.do('select ${1:oxygen2}, name ${2:O2}') ${0} ''' 'Select atoms by alpha helices.': 'prefix': 'selectHelices' 'body': ''' cmd.do('select ${1:helices}, ss h; ') ${0} ''' 'Select atoms by beta strands.': 'prefix': 'selectStrands' 'body': ''' cmd.do('select ${1:strands}, ss s; ') ${0} ''' 'Select atoms by beta loops.': 'prefix': 'selectLoops' 'body': ''' cmd.do('select ${1:loops}, ss l;') ${0} ''' 'Select all nitrogen atom in a selelction except from lysine.': 'prefix': 'selectAllBut' 'body': ''' cmd.do('select ${1:select1}, elem ${2:N} and chain ${3:A} and not resn ${4:LYS};') ${0} ''' 'Select atoms within a radius around a ligand.': 'prefix': 'selectAtomsAround' 'body': ''' cmd.do('select ${1:nearby}, resn ${2:drug} around ${3:5};') ${0} ''' 'Select residues within a radius around a ligand.': 'prefix': 'selectResiduesAround' 'body': ''' cmd.do('select ${1:nearby}, br. resn ${2:drug} around ${3:5};') ${0} ''' 'Undo a selection.': 'prefix': 'undoSelection' 'body': ''' cmd.do('disable ${1:sele}; ') ${0} ''' 'Load a pdb file in the current directory.': 'prefix': 'loadPDBfile' 'body': ''' cmd.do('load ${1:my.pdb};') ${0} ''' 'Save a png file of current scene to the current directory.': 'prefix': 'savePNG' 'body': ''' cmd.do('png ${1:saveMe.png};') ${0} ''' 'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.': 'prefix': 'ringMode' 'body': ''' cmd.do('show cartoon, ${1:rna}; set cartoon_ring_mode, ${2:3};') ${0} ''' 'In cartoons, hide the backbone atoms of selected residues when showing then as sticks.': 'prefix': 'sidehChainHelper' 'body': ''' cmd.do('set cartoon_side_chain_helper, on;') ${0} ''' 'Create a new object from part of an existing object.': 'prefix': 'extractPartObj' 'body': ''' cmd.do('extract new_obj, chain A;') ${0} ''' 'Create a putty cartoon.': 'prefix': 'puttyCartoon' 'body': ''' cmd.do('show cartoon;') cmd.do('cartoon putty;') cmd.do('unset cartoon_smooth_loops;') cmd.do('unset cartoon_flat_sheets;') ${0} ''' 'Trun off magenta squares on current selection.': 'prefix': 'hideSelection' 'body': ''' cmd.do('indicate none') ${0} ''' 'Turn on discrete colors between secondary structure elements.': 'prefix': 'discreteCartoonColoring' 'body': ''' cmd.do('set cartoon_discrete_colors, on;') ${0} ''' 'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc111' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , orange, supercell1, 1;') ${0} ''' 'Display SAXS envelope': 'prefix': 'saxsEnvelope' 'body': ''' cmd.do('alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0;') cmd.do('set solvent_radius = 3.0;') ${0} ''' 'Set additional path for PyMOL to search on startup': 'prefix': 'setpath' 'body': ''' cmd.do('os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};') ${0} ''' 'Set path for location to save fetched pdb files. ': 'prefix': 'fetchPath' 'body': ''' cmd.do('set fetch_path, ${1:/Users/blaine/pdbFiles};') ${0} ''' 'Set antialias to get smooth edges': 'prefix': 'antialias' 'body': ''' cmd.do('set antialias, 1;') ${0} ''' 'Print list of active pymolrc files.': 'prefix': 'lspymolrc' 'body': ''' cmd.do('print invocation.options.deferred;') ${0} ''' 'Set number of decimals places to show in distance labels. ': 'prefix': 'sigDigits' 'body': ''' cmd.do('set label_distance_digits, ${1:2};') cmd.do('set label_angle_digits, ${2:2};') ${0} ''' 'Label the CA atoms with the Ala333 style format': 'prefix': 'labelCAs' 'body': ''' cmd.do('label name CA,"%s%s" % (resn,resi);') ${0} ''' 'Label waters HOH.': 'prefix': 'labelWatersHOH' 'body': ''' cmd.do('label resn HOH ,"%s%s" % (resn,resi);') ${0} ''' 'Label waters W.': 'prefix': 'labelWatersW' 'body': ''' cmd.do('label resn HOH ,"W%s" % (resi);') ${0} ''' 'Find hbonds around a residue.': 'prefix': 'findHbonds' 'body': ''' cmd.do('remove element h; distance hbonds, all, all, 3.2, mode=2;') ${0} ''' 'Print the B-factors of a residue. ': 'prefix': 'printBs' 'body': ''' cmd.do('remove element h; iterate resi %{1:133}, print resi, name,b;') ${0} ''' 'Label the main chain atoms by resn,resi,atom name.': 'prefix': 'labelMainChain' 'body': ''' cmd.do('label name n+c+o+ca,"%s%s%s" % (resn,resi,name);') ${0} ''' 'Print B factors of part B of a residue.': 'prefix': 'printBspartB' 'body': ''' cmd.do('iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;') ${0} ''' 'Print B--factors for a residue with the B-factors rounded off to two decimal places.': 'prefix': 'printBs2digits' 'body': ''' cmd.do('iterate (resi %{1:133}), print(name + " %.2f" % b);') ${0} ''' 'Write the command reference to html file in the present working directory. ': 'prefix': 'writeCommandReference2HTML' 'body': ''' cmd.do('cmd.write_html_ref('pymol-command-ref.html');') ${0} ''' 'Average the B-factors by using a regular list as opposed to a stored list in PyMOL. Edit the selection as needed.': 'prefix': 'averageB' 'body': ''' cmd.do('"""Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""') cmd.do('Bfactors = []; ') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print("Sum = ", "%.2f" % (sum(Bfactors)));') cmd.do('print("Number of atoms = ", len(Bfactors));') cmd.do('print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));') ${0} ''' 'AveBResiX, prints the resiude number and the average bfactor. ': 'prefix': 'aveB4resiX' 'body': ''' cmd.do('""""AveBResiX, prints the resiude number and the average bfactor. ') cmd.do('Uses reduce and lambda, builtin Python functional porgramming functions. ') cmd.do('Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum. ') cmd.do('"""') cmd.do('Bfactors = [];') cmd.do('iterate (resi ${1:133}), Bfactors.append(b);') cmd.do('print( "Average B-factor of residue ", %{1:133} , " = ", "%.2f" %(reduce(lambda x, y: x + y, Bfactors) / float(len(Bfactors))) )') ${0} ''' 'Print name and b-factor for a residue.': 'prefix': 'printNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((name, b))", space=Bfac_dict); for i,j in Bfac_dict['Bfactors3']: print("%s %.2f" % (i,j));') ${0} ''' 'Print resn, resi, atom name, and b-factor. ': 'prefix': 'printResiResnNameB4ResiX' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Print name and b-factor for a residue or residue range (e.g. 81:120). The noH variant.': 'prefix': 'printResiResnNameB4ResiXNoH' 'body': ''' cmd.do('Bfac_dict = { 'Bfactors3' : [] };cmd.iterate("(resi 133 and not elem H)","Bfactors3.append((resn,resi,name, b))", space=Bfac_dict); for i,j,k,l in Bfac_dict['Bfactors3']: print("%s %s %s %.2f" % (i,j,k,l));') ${0} ''' 'Make the background of the internal gui transparent to expand viewport.': 'prefix': 'internalGUImode2 ' 'body': ''' cmd.do('internal_gui_mode=2;') ${0} ''' 'Set the width of the internal gui. ': 'prefix': 'internalGUIwidth' 'body': ''' cmd.do('internal_gui_width=%{1:20};') ${0} ''' 'Print document string of a function.': 'prefix': 'printDoc' 'body': ''' cmd.do('print ${1:my_func}.__doc__;') ${0} ''' 'List all snips by tab trigger and description': 'prefix': 'lsSnips' 'body': ''' cmd.do('"""Tab trigger Description') cmd.do('--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------') cmd.do('antialias Set antialias to get smooth edges') cmd.do('ao Ambient occlussion.') cmd.do('aveB4resiX AveBResiX, prints the resiude number and the average bfactor.') cmd.do(' Uses reduce and lambda, builtin Python functional porgramming functions.') cmd.do(' Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.') cmd.do('averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.') cmd.do('bs Ball and stick representation.') cmd.do('bu Biological unit.') cmd.do('carvedDensity Carved electron density.') cmd.do('cblind Color blindness.') cmd.do('centerpi Center pi.') cmd.do('coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.') cmd.do('cribbon Color ribbon H red, strand yellow, loop green.') cmd.do('cspheres Colored spheres.') cmd.do('discreteCartoonColoring Turn on discrete colors between secondary structure elements.') cmd.do('distance H-bond distances.') cmd.do('doubleBond Valence bond.') cmd.do('drawHbonds Draw H-bonds.') cmd.do('duplicateObject Duplicate object.') cmd.do('ellipcol Set ellipsoid color.') cmd.do('extractPartObj Create a new object from part of an existing object.') cmd.do('fasta Print Fasta from PDB file.') cmd.do('fetch2FoFc Fetch 2FoFc map.') cmd.do('fetchCIF Fetch cif file.') cmd.do('fetchFoFc Fetch fofc map.') cmd.do('fetchPath Set path for location to save fetched pdb files.') cmd.do('filledRing Filled rings in nucleic acids.') cmd.do('findHbonds Find hbonds around a residue.') cmd.do('fog Blur the background atoms.') cmd.do('getCoordinates Get coordinates.') cmd.do('hbond Hbond setup.') cmd.do('hbonddash H-bond dashes.') cmd.do('hideSelection Trun off magenta squares on current selection.') cmd.do('hidealtloc Hide alt loc.') cmd.do('internalGUImode2 Makes the background of the internal gui transparent with the viewport extended into this region of the gui. This may be a useful mode for workshops.') cmd.do('internalGUIwidth Set the width of the internal gui.') cmd.do('labelCAs Label the CA atoms with the Ala333 style format') cmd.do('labelMainChain Label the main chain atoms by resn,resi,atom name.') cmd.do('labelResnResi Label CA atom with residue name and residue number.') cmd.do('labelSS Label SS.') cmd.do('labelWatersHOH Label waters HOH.') cmd.do('labelWatersW Label waters W.') cmd.do('loadPDBbs Load PDB ball-and-stick.') cmd.do('loadPDBfile Load a pdb file in the current directory.') cmd.do('loadPDBnb Load PDB nb spheres.') cmd.do('lsSnips List all snips by tab trigger and description') cmd.do('lspymolrc Print list of active pymolrc files.') cmd.do('molscriptRibbon Molscript ribbons.') cmd.do('ms Measure surface area.') cmd.do('oneLetter One letter amino acid.') cmd.do('pearl The pearl effect is made with two spheres with the outer sphere being transparent.') cmd.do('printBs Print the B-factors of a residue.') cmd.do('printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.') cmd.do('printBspartB Print B factors of part B of a rsidues.') cmd.do('printDoc Print document string of a function.') cmd.do('printNameB4ResiX Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). Use the noH variant if H atoms are present.') cmd.do('printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.') cmd.do('printResiResnNameB4ResiXNoH Print name and b-factor for a rsidue. You can change this to a named selection or a residue range ( e.g., resi 133:155). The noH variant.') cmd.do('pseudolabel Position label with pseudoatom.') cmd.do('puttyCartoon Create a putty cartoon.') cmd.do('ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.') cmd.do('rmwater Remove waters from molecular object.') cmd.do('rotate Rotate about axis.') cmd.do('rv Return settings in rounded format.') cmd.do('savePNG Save a png file of current scene to the current directory.') cmd.do('saxsEnvelope Display SAXS envelope') cmd.do('sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.') cmd.do('sc222 Run Tom Holder's supercell script to generate three cells in all directions.') cmd.do('scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.') cmd.do('selectAllBut Select all nitrogen atom in a selelction except from lysine.') cmd.do('selectAtomsAround Select atoms within a radius around a ligand.') cmd.do('selectChain Select a chain.') cmd.do('selectElement Select atoms by elemnt.') cmd.do('selectHelices Select atoms by alpha helices.') cmd.do('selectLoops Select atoms by beta loops.') cmd.do('selectName Select atoms by name.') cmd.do('selectResi Select residues by a range of numbers.') cmd.do('selectResidues Select residues by name.') cmd.do('selectResiduesAround Select residues within a radius around a ligand.') cmd.do('selectStrands Select atoms by beta strands.') cmd.do('setcolor Set color name to a RGB code.') cmd.do('setpath Set additional path for PyMOL to search on startup') cmd.do('sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.') cmd.do('sigDigits Set number of decimals places to show in distance labels.') cmd.do('sigang Set angle labels to display 2 decimals places') cmd.do('sigdist set distance labels to display 2 decimals') cmd.do('solventRadius Set radius of ball used to make solvent accessible surface.') cmd.do('spng Save png flle with timestamp') cmd.do('spse Save pse flle with timestamp') cmd.do('stack Base-stacking figure.') cmd.do('stereoDraw Stereo draw.') cmd.do('stereoRay Stereo ray.') cmd.do('threeMaps Three electron density.') cmd.do('turnAboutAxis Turn about axis.') cmd.do('undoSelection Undo a selection.') cmd.do('volumeRamp Volume ramp.') cmd.do('writeCommandReference2HTML Write the command reference to html file in the present working directory."""') ${0} ''' 'Asp70-His31 salt-bridge from T4 lysozyme. ': 'prefix': 'his31asp70' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom (resi 31 or resi 70); ') cmd.do('preset.technical(selection='all'); ') cmd.do('bg_color gray70; ') cmd.do('clip slab, 7,(resi 31 or resi 70);') cmd.do('rock;') ${0} ''' 'triple water pentagon.': 'prefix': 'waterTriple' 'body': ''' cmd.do('fetch 1lw9, async=0; ') cmd.do('zoom resi 313; ') cmd.do('preset.technical(selection='all', mode=1);') ${0} ''' 'Make selection of ligand atoms.': 'prefix': 'ligandSelect' 'body': ''' cmd.do('select substrates, organic;') ${0} ''' 'Print url of README.md file of the pymolsnips repository.': 'prefix': 'github' 'body': ''' cmd.do('https://github.com/MooersLab/pymolsnips/blob/master/README.md') ${0} ''' 'Set dihedral labels to display 2 decimals places to the right of the decimal point.': 'prefix': 'sigdihedral' 'body': ''' cmd.do('set label_dihedral_digits, ${1:2};') ${0} ''' 'Select state 1 from a model with multiple states.': 'prefix': 'stateOne' 'body': ''' cmd.do('cmd.create('newobject', 'oldobject', '1', '1');') ${0} ''' 'Display all symmetry mates in two unit cells along the c axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc112' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cels along c. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc113' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates three three unit cells along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc311' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in three unit cells along b. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc131' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cell along a. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc211' 'body': ''' cmd.do('run $HOME/${1:Scripts/PyMOLscripts/supercell.py};') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in two unit cells along the b axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc121' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 1 x 2 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc122' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 2 x 2 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc221' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 1 x 2 arrays of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc212' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 1 x 3 x 3 array of unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc133' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 1 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc313' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 1 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc331' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 2 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc233' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in a 3 x 2 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc323' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 2 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc332' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in 3 x 3 x 3 array of unit cells. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc333' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long c-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc114' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long b-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc141' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Display all symmetry mates in four unit cells stacked long a-axis. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.': 'prefix': 'sc411' 'body': ''' cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;') cmd.do('supercell 1, 1, 1, , ${2:orange}, ${3:supercell1}, 1;') ${0} ''' 'Save aln flle with timestamp': 'prefix': 'saln' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd;') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT);') cmd.do('cmd.save(stemName+s+".aln");') cmd.do('end python;') ${0} ''' 'Save electron density map flle with timestamp': 'prefix': 'sccp4' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".ccp4"); ') cmd.do('end python;') ${0} ''' 'Save dae flle with timestamp': 'prefix': 'sdae' 'body': ''' cmd.do('python;') cmd.do('import datetime;') cmd.do('from pymol import cmd; ') cmd.do('DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");') cmd.do('s = str(DT); ') cmd.do('cmd.save(stemName+s+".dae"); ') cmd.do('end python;') ${0} ''' 'Carved isosurface representation of electron density. ': 'prefix': 'carvedIsosurface' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('isosurface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as an isosurface.': 'prefix': 'fetch2FoFcIsosurface' 'body': ''' cmd.do('fetch ${1:3nd4}_2fofc, type=2fofc, async=0;') cmd.do('isosurface 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as isosurface. ': 'prefix': 'threeMapsIsosurface' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('isosurface ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('isosurface ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('isosurface ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Carved volume representation of electron density. ': 'prefix': 'carvedVolume' 'body': ''' cmd.do('delete all;') cmd.do('fetch ${1:4dgr}, async=0;') cmd.do('fetch ${1:4dgr}, type=2fofc,async=0;') cmd.do('select ${2:LongGlycan}, resi ${3:469:477};') cmd.do('orient ${2:LongGlycan};') cmd.do('remove not ${2:LongGlycan};') cmd.do('remove name H*;') cmd.do('surface 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') cmd.do('color density, 2fofcmap; ') cmd.do('show sticks;') cmd.do('show spheres;') cmd.do('set stick_radius, .07;') cmd.do('set sphere_scale, .19;') cmd.do('set sphere_scale, .13, elem H;') cmd.do('set bg_rgb=[1, 1, 1];') cmd.do('set stick_quality, 50;') cmd.do('set sphere_quality, 4;') cmd.do('color gray85, elem C;') cmd.do('color red, elem O;') cmd.do('color slate, elem N;') cmd.do('color gray98, elem H;') cmd.do('set stick_color, gray50;') cmd.do('set ray_trace_mode, 1;') cmd.do('set ray_texture, 2;') cmd.do('set antialias, 3;') cmd.do('set ambient, 0.5;') cmd.do('set spec_count, 5;') cmd.do('set shininess, 50;') cmd.do('set specular, 1;') cmd.do('set reflect, .1;') cmd.do('set dash_gap, 0;') cmd.do('set dash_color, black;') cmd.do('set dash_gap, .15;') cmd.do('set dash_length, .05;') cmd.do('set dash_round_ends, 0;') cmd.do('set dash_radius, .05;') cmd.do('set_view (0.34,-0.72,0.61,0.8,0.56,0.22,-0.51,0.4,0.77,0.0,0.0,-81.31,44.64,-9.02,58.62,65.34,97.28,-20.0);') cmd.do('preset.ball_and_stick("all",mode=1);') cmd.do('draw;') ${0} ''' 'Fetch 2FoFc map as a volume.': 'prefix': 'fetch2FoFcVolume' 'body': ''' cmd.do('fetch ${1:3nd4}, type=2fofc, async=0;') cmd.do('volume 2fofcmap, ${1:3nd4}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;') ${0} ''' 'Three electron density as volumes. ': 'prefix': 'threeMapsVolume' 'body': ''' cmd.do('load ${1:4dgr}.pdb') cmd.do('# Make sure to rename map file so that ') cmd.do('# the root filename differs from pdb root filename') cmd.do('load ${1:4dgr}_2fofc.ccp4, 2fofc;') cmd.do('load ${1:4dgr}_fofc.ccp4, fofc;') cmd.do('select ${2:glycan}, resid 200 or (resid 469:477);') cmd.do('volume ${3:mesh1}, 2fofc, 1.0, ${2:glycan};') cmd.do('color density, ${3:mesh1};') cmd.do('volume ${4:mesh2}, fofc, 3.0, ${2:glycan};') cmd.do('color green, ${4:mesh2};') cmd.do('volume ${5:mesh3}, fofc, -3.0, ${2:glycan};') cmd.do('color red, ${5:mesh3};') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server ipymol in a jupuyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvi' 'body': ''' cmd.do('def rvj(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """') cmd.do(' rvj() is a modification of the the rv() function (aka the roundview.py) ') cmd.do(' so that it can run in Jupyter notebooks with the ipymol.viewer. ') cmd.do(' A set_view string is printed to the noteobook in a format that is ready ') cmd.do(' for reuse. ') cmd.do(' ') cmd.do(' The ipymol module was developed by PI:NAME:<NAME>END_PI:') cmd.do(' ') cmd.do(' https://github.com/cxhernandez/ipymol') cmd.do(' ') cmd.do(' The pre-requisites for installing ipymol are as follows:') cmd.do(' ') cmd.do(' 1. Make a jupyter notebook kernel for Python interpreter inside of ') cmd.do(' the Schrodinger PyMOL. See the PyMOL Snippets GitHub Page for ') cmd.do(' a description of how to make one.') cmd.do(' 2. Install the following build of ipymol at the PyMOL prompt.') cmd.do(' You need to log into your GitHub account first.') cmd.do(' ') cmd.do(' pip install git+pip install git+https://github.com/cxhernandez/ipymol.git@2a30d6ec1588434e6f0f72a1d572444f89ff535b') cmd.do(' ') cmd.do(' 3. Make a bash alias to this PyMOL app file.') cmd.do(' ') cmd.do(' 4. Launch the jupyter notebook and select the pymol.python kernel.') cmd.do(' ') cmd.do(' 5. Open a terminal instance from the File pulldown in jupyter notebook.') cmd.do(' ') cmd.do(' 6. Enter `pymol -Rq` to launch an interactive instance of PyMOL.') cmd.do(' ') cmd.do(' 7. Enter the following code to load ipymol and conmect to PyMOL') cmd.do(' ') cmd.do(' from ipymol import viewer as ipv') cmd.do(' ipv.start() # Start PyMOL RPC server') cmd.do(' ') cmd.do(' Now you can change the scene manually and send the display as static ') cmd.do(' image to a cell in the jupyter notebook.') cmd.do(' ') cmd.do(' It is assumed that the viewer class of the ipymol moduel has been ') cmd.do(' imported as ipv. ') cmd.do(' ') cmd.do(' I made the following modifications of roundview.py.') cmd.do(' The cmd.get_view was replaced with ipv.get_view.') cmd.do(' The cmd.extend was replaced with ipv.extend.') cmd.do(' The myRoundedList was returned for further processing.') cmd.do(' ') cmd.do(' MIT License') cmd.do(' ') cmd.do(' Copyright:') cmd.do(' PI:NAME:<NAME>END_PI and the OU Board of Regents') cmd.do(' Uniersity of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' ') cmd.do(' 29 April 2020') cmd.do(' ') cmd.do(' """') cmd.do(' ') cmd.do(' ') cmd.do(' StoredView = int(StoredView)') cmd.do(' decimal_places = int(decimal_places)') cmd.do(' ') cmd.do(' #call the get_view function') cmd.do(' ') cmd.do(' m = ipv.get_view(StoredView)') cmd.do(' ') cmd.do(' ') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' ') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9],') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' ') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' ') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' ') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' ') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' ') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' ') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a")') cmd.do(' myFile.write(x.format(*myRoundedList) + "")') cmd.do(' myFile.close()') cmd.do(' return myRoundedList') cmd.do('ipv.extend("rv", rv)') ${0} ''' 'Demo of the use of the RPC server with a drug compound via rdkit.': 'prefix': 'rdkrpcChem' 'body': ''' cmd.do('import os;') cmd.do('import rdkit;') cmd.do('from rdkit import Chem;') cmd.do('from rdkit.Chem import AllChem;') cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('s = PyMOL.MolViewer();') cmd.do('mol = Chem.MolFromSmiles \') cmd.do(' ('CCOCCn1c(C2CC[NH+](CCc3ccc(C(C)(C)C(=O)[O-])cc3)CC2)nc2ccccc21');') cmd.do('mol = AllChem.AddHs(mol);') cmd.do('AllChem.EmbedMolecule(mol);') cmd.do('AllChem.MMFFOptimizeMolecule(mol);') cmd.do('s.ShowMol(mol, name = 'bilastine', showOnly = False);') cmd.do('s.Zoom('bilastine');') cmd.do('s.SetDisplayStyle('bilastine', 'sticks');') cmd.do('s.GetPNG(preDelay=5);') ${0} ''' 'A kernel.json file for runnig PyMOL python interpreter in the Jupyter notebook. ': 'prefix': 'kernel' 'body': ''' cmd.do('framerule=2pt,') cmd.do('framesep=2mm,') cmd.do('framesep=2mm,') cmd.do('breaklines=True,') cmd.do('baselinestretch=1.2') cmd.do(']{bash}') cmd.do('{') cmd.do(' "argv": [') cmd.do(' "/Applications/PyMOL.app/Contents/bin/python",') cmd.do(' "-m",') cmd.do(' "ipykernel_launcher",') cmd.do(' "-f",') cmd.do(' "{connection_file}"') cmd.do(' ],') cmd.do(' "display_name": "pymol.python",') cmd.do(' "language": "python"') cmd.do('}') ${0} ''' 'Demo of the use of the RPC server with a protein via rdkit.': 'prefix': 'rdkrpcProtein' 'body': ''' cmd.do('from rdkit.Chem import PyMol;') cmd.do('') cmd.do('Usage=""""Start pymol from command line with -R flag.') cmd.do('Select the pymol.python kernel in Jupyter notebook. """;') cmd.do('') cmd.do('s = PyMol.MolViewer();') cmd.do('du = s.server.do;') cmd.do('du('rein; bg_color white; fetch 1lw9, type=pdb, async=0, show;nb_spheres; set_view (0.46,-0.28,-0.84,0.74,-0.41,0.54,-0.49,-0.87,0.02,0.0,0.0,\') cmd.do(' -155.16,35.13,11.48,9.72,122.33,187.99,-20.0);');') cmd.do('s.GetPNG(preDelay=3);') cmd.do('du('png T4L600dpi.png, dpi=600');') ${0} ''' 'Code to start the RPC server with ipymol.': 'prefix': 'ipymolStart' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') ${0} ''' 'Demo of the use of the RPC server with a protein via ipymol.': 'prefix': 'ipymolProtein' 'body': ''' cmd.do('# Start pymol in terminal with pymol -R;') cmd.do('# Select pymol.python as kernel in juptyer;') cmd.do('from ipymol import viewer as ipv;') cmd.do('ipv.start() # Start PyMOL RPC server;') cmd.do('') cmd.do('ipv.do('fetch 1lw9');') cmd.do('ipv.do('rv');') cmd.do('# The double parentheses are required when set_view is run this way.;') cmd.do('ipv.set_view((-0.13,-0.4,-0.91,0.89,-0.45,0.07,-0.44,-0.8,0.41,0.0,0.0,-182.47,35.13,11.48,9.72,149.64,215.3,-20.0));') cmd.do('ipv.do('AOD');') cmd.do('ipv.png('testipymolT4L.png');') ${0} ''' 'Return settings in rounded format while running PyMOL via the RCP server rdkit in a jupyter notebook. This is a modified version of the roundview.py script.': 'prefix': 'rvr' 'body': ''' cmd.do('def rvr(StoredView=0, decimal_places=2, outname="roundedview.txt"):') cmd.do(' """MIT License') cmd.do(' Copyright:') cmd.do(' PI:NAME:<NAME>END_PI and the OU Board of Regents') cmd.do(' University of Oklahoma Health Sciences Center') cmd.do(' Oklahoma City, OK 73104') cmd.do(' 30 April 2020') cmd.do(' ') cmd.do(' First run the following:') cmd.do(' ') cmd.do(' from rdkit.Chem import PyMol') cmd.do(' s = PyMol.MolViewer()') cmd.do(' du = s.server.do') cmd.do('') cmd.do(' """') cmd.do(' StoredView = int(StoredView) decimal_places = int(decimal_places)') cmd.do(' #call the get_view function') cmd.do(' m = s.get_view(StoredView)') cmd.do(' #Make a list of the elements in the orientation matrix.') cmd.do(' myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],m[7], m[8], m[9], ') cmd.do(' m[10], m[11], m[12], m[13], m[14],m[15], m[16], m[17]]') cmd.do(' #Round off the matrix elements to two decimal places (two fractional places)') cmd.do(' #This rounding approach solved the problem of unwanted') cmd.do(' #whitespaces when I tried to use a string format statement') cmd.do(' myRoundedList = [round(elem, decimal_places) for elem in myList]') cmd.do(' #x is the string template for the output. The whitespace is required') cmd.do(' #between the "set_view" and "("') cmd.do(' x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'') cmd.do(' # Print to the command history window.') cmd.do(' print(x.format(*myRoundedList))') cmd.do(' #Write to a text file.') cmd.do(' myFile = open("roundedview.txt", "a") myFile.write(x.format(*myRoundedList) + "") myFile.close()') cmd.do(' return myRoundedList') cmd.do('du.extend("rvr", rvr)') ${0} ''' 'Return to the command history window the docstrings for all of the functions in the cmd module.': 'prefix': 'cmddocs' 'body': ''' cmd.do('[help(i) for i in dir(cmd)];') ${0} ''' 'Return to the command history window the docstrings for all of the functions in a module.': 'prefix': 'pymoldocs' 'body': ''' cmd.do('[help(i) for i in dir(pymol)];') ${0} ''' 'Print the number of residues in a protein.': 'prefix': 'numResiProtein' 'body': ''' cmd.do('sel = 'polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in chain A of a protein.': 'prefix': 'numResiProteinChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.protein'; print(len(set([(i.chain, i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid (all chains).': 'prefix': 'numResiNucleic' 'body': ''' cmd.do('sel = 'polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Print the number of residues in a nulceic acid chain.': 'prefix': 'numResiNucleicChainA' 'body': ''' cmd.do('sel = 'chain A and polymer.nucleic'; print(len(set([(i.resi, i.resn) for i in cmd.get_model(sel).atom])));') ${0} ''' 'Create bonds between phosphorous and O3* atoms in a low resolution DNA structure that is 80 base pairs long.': 'prefix': 'brokenNucleicBackbone' 'body': ''' cmd.do('[cmd.bond(f"/5fur//E/{i}/O3'", f"/5fur//E/{i+1}/P") for i in range(${1:1}, ${2:80})]; ') cmd.do('[cmd.bond(f"/5fur//F/{i}/O3'", f"/5fur//F/{i+1}/P") for i in range(${3:81}, ${3:160})];') ${0} ''' 'To change stick color and radius for the bond between atom 2 and 3, use the set_bond command. ': 'prefix': 'oneBondThicknessColor' 'body': ''' cmd.do('# To change stick color and radius for the bond between atom 2 and 3;') cmd.do('set_bond stick_color, ${1:yellow}, index 2, index 3;') cmd.do('set_bond stick_radius, ${2:0.2}, index 2, index 3;') ${0} ''' 'Connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18. Note that this example requires the draw_links.py [http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py] by PI:NAME:<NAME>END_PI.': 'prefix': 'drawLinks' 'body': ''' cmd.do('# Requires draw_links.py http://pldserver1.biochem.queensu.ca/~rlc/work/pymol/draw_links.py by PI:NAME:<NAME>END_PI') cmd.do('# To connect the alpha carbons of residue 1 with 10, 6 with 16, 7 with 17 and 8 with 18.') cmd.do('draw_links ${1:mol1} & chain ${2:A} & name ${3:CA} & resi ${4:1+6+7+8}, ${5:mol1} & chain ${6:A}& name ${7:CA} & resi ${8:10+16+17+18} ') ${0} ''' 'Print the path to the currently used PyMOL binary.': 'prefix': 'printPath' 'body': ''' cmd.do('# Print the path to the current used PyMOL binary.') cmd.do('print pymol.__path__') ${0} ''' 'Turn on the ligand valence.': 'prefix': 'setLigandValenceOn' 'body': ''' cmd.do('#Set on the valence of the ligand only') cmd.do('set valence, on, resn ${1:RZS}; set valence, off, not resn ${2:RZS}') ${0} ''' 'Return the docustring for the preset submodule. The command help preset fails to return anything. The command help(pymol.preset) has the same effect as help(preset).': 'prefix': 'presetDocs' 'body': ''' cmd.do('help(preset)') ${0} ''' 'Return the docustring for the help submodule. The command help help is more concise.': 'prefix': 'helpDocs' 'body': ''' cmd.do('help(help)') ${0} ''' 'The amber trajectories have to be loaded into the same object.': 'prefix': 'loadAmberTrajs' 'body': ''' cmd.do('load file.top, protein;') cmd.do('load file.rst, protein') ${0} ''' 'Saves multiple objects into multiple files using an optional prefix name.': 'prefix': 'saveSep' 'body': ''' cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('import re') cmd.do('') cmd.do('def saveSep(prefix=''):') cmd.do(' """') cmd.do(' save_sep <prefix>') cmd.do('') cmd.do(' saves multiple objects into multiple files using an optional prefix name.') cmd.do('') cmd.do(' e.g. save_sep prefix') cmd.do(' """') cmd.do(' obj_list = cmd.get_names("all")') cmd.do('') cmd.do(' if obj_list:') cmd.do(' for i in range(len(obj_list)):') cmd.do(' obj_name = "%s%s.pdb" % (prefix, obj_list[i])') cmd.do(' cmd.save(obj_name, obj_list[i])') cmd.do(' print("Saving %s" % obj_name)') cmd.do(' else:') cmd.do(' print("No objects found")') cmd.do(' ') cmd.do('cmd.extend('saveSep',saveSep)') ${0} ''' 'OptiAlign.py by PI:NAME:<NAME>END_PI modified for aligning multiple RNA structures.': 'prefix': 'optAlignRNA' 'body': ''' cmd.do('#!python') cmd.do(' ') cmd.do('##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py. A python implementation of the optimal superposition') cmd.do('# of two sets of vectors as proposed by Kabsch 1976 & 1978.') cmd.do('#') cmd.do('# @AUTHOR: PI:NAME:<NAME>END_PI') cmd.do('# @COPYRIGHT: PI:NAME:<NAME>END_PI (C), 2005-2007') cmd.do('# @LICENSE: Released under GPL:') cmd.do('# This program is free software; you can redistribute it and/or modify') cmd.do('# it under the terms of the GNU General Public License as published by') cmd.do('# the Free Software Foundation; either version 2 of the License, or') cmd.do('# (at your option) any later version.') cmd.do('# This program is distributed in the hope that it will be useful, but WITHOUT') cmd.do('# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS') cmd.do('# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.') cmd.do('#') cmd.do('# You should have received a copy of the GNU General Public License along with') cmd.do('# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin') cmd.do('# Street, Fifth Floor, Boston, MA 02110-1301, USA ') cmd.do('#') cmd.do('# DATE : 2007-01-01') cmd.do('# REV : 2') cmd.do('# REQUIREMENTS: numpy') cmd.do('#') cmd.do('#') cmd.do('# Modified optAlign.py to use C1' carbon atoms of RNA for alignment.') cmd.do('# Jan. 29, 2020 ') cmd.do('# PI:NAME:<NAME>END_PI, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#############################################################################') cmd.do('from array import *') cmd.do(' ') cmd.do('# system stuff') cmd.do('import os') cmd.do('import copy') cmd.do(' ') cmd.do('# pretty printing') cmd.do('import pprint') cmd.do(' ') cmd.do('# for importing as a plugin into PyMol') cmd.do('from pymol import cmd') cmd.do('from pymol import stored') cmd.do('from pymol import selector') cmd.do(' ') cmd.do('# using numpy for linear algebra') cmd.do('import numpy') cmd.do(' ') cmd.do('def optAlignRNA( sel1, sel2 ):') cmd.do(' """') cmd.do(' optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections.') cmd.do(' Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1'') cmd.do(' ') cmd.do(' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from') cmd.do(' PyMOL based upon your selections.') cmd.do(' ') cmd.do(' This function can be run in a for loop to fit multiple structures with a common prefix name:') cmd.do(' ') cmd.do(' for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001")') cmd.do(' ') cmd.do(' or get the rmsds for all combinations, do the following:') cmd.do(' ') cmd.do(' [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do(' """') cmd.do(' cmd.reset()') cmd.do(' ') cmd.do(' # make the lists for holding coordinates') cmd.do(' # partial lists') cmd.do(' stored.sel1 = []') cmd.do(' stored.sel2 = []') cmd.do(' # full lists') cmd.do(' stored.mol1 = []') cmd.do(' stored.mol2 = []') cmd.do(' ') cmd.do(' # -- CUT HERE') cmd.do(' sel1 += " and N. C1'"') cmd.do(' sel2 += " and N. C1'"') cmd.do(' # -- CUT HERE') cmd.do(' ') cmd.do(' # Get the selected coordinates. We') cmd.do(' # align these coords.') cmd.do(' cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")') cmd.do(' ') cmd.do(' # get molecule name') cmd.do(' mol1 = cmd.identify(sel1,1)[0][0]') cmd.do(' mol2 = cmd.identify(sel2,1)[0][0]') cmd.do(' ') cmd.do(' # Get all molecule coords. We do this because') cmd.do(' # we have to rotate the whole molcule, not just') cmd.do(' # the aligned selection') cmd.do(' cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")') cmd.do(' ') cmd.do(' # check for consistency') cmd.do(' assert len(stored.sel1) == len(stored.sel2)') cmd.do(' L = len(stored.sel1)') cmd.do(' assert L > 0') cmd.do(' ') cmd.do(' # must alway center the two proteins to avoid') cmd.do(' # affine transformations. Center the two proteins') cmd.do(' # to their selections.') cmd.do(' COM1 = numpy.sum(stored.sel1,axis=0) / float(L)') cmd.do(' COM2 = numpy.sum(stored.sel2,axis=0) / float(L)') cmd.do(' stored.sel1 -= COM1') cmd.do(' stored.sel2 -= COM2') cmd.do(' ') cmd.do(' # Initial residual, see Kabsch.') cmd.do(' E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)') cmd.do(' ') cmd.do(' #') cmd.do(' # This beautiful step provides the answer. V and Wt are the orthonormal') cmd.do(' # bases that when multiplied by each other give us the rotation matrix, U.') cmd.do(' # S, (Sigma, from SVD) provides us with the error! Isn't SVD great!') cmd.do(' V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))') cmd.do(' ') cmd.do(' # we already have our solution, in the results from SVD.') cmd.do(' # we just need to check for reflections and then produce') cmd.do(' # the rotation. V and Wt are orthonormal, so their det's') cmd.do(' # are +/-1.') cmd.do(' reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))') cmd.do(' ') cmd.do(' if reflect == -1.0:') cmd.do(' S[-1] = -S[-1]') cmd.do(' V[:,-1] = -V[:,-1]') cmd.do(' ') cmd.do(' RMSD = E0 - (2.0 * sum(S))') cmd.do(' RMSD = numpy.sqrt(abs(RMSD / L))') cmd.do(' ') cmd.do(' #U is simply V*Wt') cmd.do(' U = numpy.dot(V, Wt)') cmd.do(' ') cmd.do(' # rotate and translate the molecule') cmd.do(' stored.sel2 = numpy.dot((stored.mol2 - COM2), U)') cmd.do(' stored.sel2 = stored.sel2.tolist()') cmd.do(' # center the molecule') cmd.do(' stored.sel1 = stored.mol1 - COM1') cmd.do(' stored.sel1 = stored.sel1.tolist()') cmd.do(' ') cmd.do(' # let PyMol know about the changes to the coordinates') cmd.do(' cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")') cmd.do(' cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")') cmd.do(' ') cmd.do(' #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD)') cmd.do(' print("% s, % s,% 5.3f" % (mol1, mol2, RMSD))') cmd.do(' ') cmd.do(' # make the alignment OBVIOUS') cmd.do(' cmd.hide('everything')') cmd.do(' cmd.show('ribbon', sel1 + ' or ' + sel2)') cmd.do(' cmd.color('gray70', mol1 )') cmd.do(' cmd.color('magenta', mol2 )') cmd.do(' cmd.color('red', 'visible')') cmd.do(' cmd.show('ribbon', 'not visible')') cmd.do(' cmd.center('visible')') cmd.do(' cmd.orient()') cmd.do(' cmd.zoom('visible')') cmd.do(' ') cmd.do('cmd.extend("optAlignRNA", optAlignRNA)') ${0} ''' 'Load into PyMOL multiple files with a common file stem. The is a script by PI:NAME:<NAME>END_PI that updated for Python3.': 'prefix': 'loadManyFiles' 'body': ''' cmd.do('# Copyright (c) 2004 PI:NAME:<NAME>END_PI') cmd.do('#') cmd.do('# Modified for use with Python3.') cmd.do('# Jan. 29, 2020 ') cmd.do('# PI:NAME:<NAME>END_PI, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#') cmd.do('from pymol import cmd') cmd.do('import glob') cmd.do('') cmd.do('def loadFiles(files):') cmd.do(' """') cmd.do(' load_files <files>') cmd.do('') cmd.do(' loads multiple files (using filename globbing)') cmd.do(' into a multiple objects named as the files are (e.g. collection of') cmd.do(' downloaded PDB files).') cmd.do('') cmd.do(' e.g. load_files prot_*.pdb') cmd.do(' """') cmd.do(' file_list = glob.glob(files)') cmd.do(' if file_list:') cmd.do(' file_list.sort()') cmd.do(' for i in file_list:') cmd.do(' #obj_name = i.replace('.pdb','')') cmd.do(' #cmd.load(file_list[i],obj_name)') cmd.do(' cmd.load(i)') cmd.do(' else:') cmd.do(' print("No files found for pattern %s" % files)') cmd.do('') cmd.do('cmd.extend('loadFiles',loadFiles)') ${0} ''' 'These are the instructions for loading and aligning multiple files.': 'prefix': 'loadAndAlignManyFiles' 'body': ''' cmd.do('To load a bunch of related files from inside PyMOL all at once:') cmd.do('') cmd.do('run loadFiles.py') cmd.do('loadFiles refine_*.pdb') cmd.do('') cmd.do('') cmd.do('To align all of the loaded RNA structures in all possible combinations by their C1' carbon atoms:') cmd.do('') cmd.do('run optAlignRNA.py') cmd.do('[[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do('(Yes, that construct is a list comprehension inside a list comprehension!)') cmd.do('') cmd.do('To save a multiple models in a file to separate pdb files,') cmd.do('') cmd.do('run saveSep.py') cmd.do('saveSep ') cmd.do('or ') cmd.do('saveSep prefix') ${0} ''' 'This is a two-fold nested list comprehension for any all parwise operation on the currently loaded objects. Replace optAlginRNA with any other function that operations on a pair of structrures.': 'prefix': 'allPairs' 'body': ''' cmd.do('[[${1:optAlignRNA}(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') ${0} ''' 'Combining DSSR block representation with regular PyMOL cartoons after loading the dssr_block.py script by PI:NAME:<NAME>END_PI.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('as cartoon;') cmd.do('set cartoon_ladder_radius, 0.1;') cmd.do('set cartoon_ladder_color, gray;') cmd.do('set cartoon_nucleic_acid_mode, 1;') cmd.do('dssr_block') ${0} ''' 'DSSR block representation with fused blocks after loading the dssr_block.py script by PI:NAME:<NAME>END_PI. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1ehz, async=0;') cmd.do('dssr_block block_file=wc') ${0} ''' 'DSSR block representation for a multi-state example after loading the dssr_block.py script by PI:NAME:<NAME>END_PI. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 2n2d, async=0;') cmd.do('dssr_block 2n2d, 0;') cmd.do('set all_states;') ${0} ''' 'DSSR block representation with custom coloring after loading the dssr_block.py script by PI:NAME:<NAME>END_PI. The x3dna-dssr executable needs to be in the PATH.': 'prefix': 'dssrBlock' 'body': ''' cmd.do('fetch 1msy, async=0;') cmd.do('dssr_block block_color=N red | minor 0.9 | major yellow;') ${0} ''' 'Settings for nucliec acid cartoon.': 'prefix': 'nucleicAcidCartoon' 'body': ''' cmd.do('set cartoon_ladder_color, ${1:density};') cmd.do('set cartoon_ladder_radius, ${2:0.2};') cmd.do('set cartoon_nucleic_acid_color, ${3:red};') cmd.do('set cartoon_ring_mode, ${4:2};') ${0} ''' 'Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. The set command as the syntax of setting_name [, setting_value [, selection [,state ]]] . In this case, the selection has to be global, object, object-state, or per-atom settings. It cannot be a named selection. This is a weak spot in PyMOL. Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands. Many double-stranded helices have one strand in the asymmetric unit. The second strand is in the biological unit. The coordinates for the second strand are in the pdb1 file type at the PDB. The second strand is in the second state, which is equivalent to the second model in the pdb file. The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting). The bases are colored differently too (via the cartoon_ladder_color setting). ': 'prefix': 'nucleicAcidCartoon2Strands' 'body': ''' cmd.do('# There is not support for applying different settings to different selections.') cmd.do('# Instead, this can be done for different objects.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# The set command as the syntax of setting_name [, setting_value [, selection [,state ]]]') cmd.do('# In this case, the selection has to be global, object, object-state, or per-atom settings.') cmd.do('# It cannot be a named selection.') cmd.do('# Coloring two strand differently of a double helix makes it easier to for the viewer to distinguish the two strands.') cmd.do('# Many double-stranded helices have one strand in the asymmetric unit.') cmd.do('# The second strand is in the biological unit.;') cmd.do('# The coordinates for the second strand are in the pdb1 file type at the PDB.;') cmd.do('# The second strand is in the second state, which is equivalent to the second model in the pdb file.;') cmd.do('# The strands are labeled chain A and B (via the cartoon_nucliec_acid_color setting).;') cmd.do('# The bases are colored differently too (via the cartoon_ladder_color setting).;') cmd.do('fetch ${1:3nd3}, ${2:3nd3}, type=${3:pdb1};') cmd.do('set all_states, on;') cmd.do('create chA, ${2:3nd3}, 1, 1;') cmd.do('create chB, ${2:3nd3}, 2, 1;') cmd.do('# colors only the backbone;') cmd.do('set cartoon_nucleic_acid_color, ${4:magenta}, chA;') cmd.do('set cartoon_nucleic_acid_color, ${5:orange}, chB;') cmd.do('# color the bases;') cmd.do('set cartoon_ladder_color, ${6:density}, chA;') cmd.do('set cartoon_ladder_color, ${7:yellow}, chB;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It could make a good shortcut.': 'prefix': 'nucleicAcidColorbySequence' 'body': ''' cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${1:yellow}, rna_A;') cmd.do('color ${2:red}, rna_C; ') cmd.do('color ${3:gray40}, rna_G;') cmd.do('color ${4:palecyan}, rna_U;') cmd.do('color ${5:brown}, dna_T;') ${0} ''' 'This code colors by the nucleotides by base seqence. It can be applied to any nucleic acid. It is dervied from the CR shortcut. The backcone is shown as a flatten ribbon.': 'prefix': 'nucleicAcidFlatRibbonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85};') cmd.do('set cartoon_oval_width, ${2:0.5};') cmd.do('cartoon oval;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval;') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'The code provides a cartoon of the loaded nucleic acid that has the ladder rungs replaced by filled rings that are colored by atom type. The code can be applied to any nucleic acid. It is derived from the FR shortuct.': 'prefix': 'nucleicAcidCartoonFilledRings' 'body': ''' cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set cartoon_ring_mode, 3;') cmd.do('set cartoon_ring_finder, 1;') cmd.do('set cartoon_ladder_mode, 1;') cmd.do('set cartoon_nucleic_acid_mode, 4;') cmd.do('set cartoon_ring_transparency, 0.5;') cmd.do('as cartoon;') ${0} ''' 'This code make as standard base stacking diagram with ball and stick representation. ': 'prefix': 'basePairStacking' 'body': ''' cmd.do('delete all;') cmd.do('fetch 4PCO, type=pdb, async=0;') cmd.do('select G2G3, ( ((resi 2 or resi 3) and chain A) or ((resi 8 or resi 9) and chain B));') cmd.do('remove not G2G3;') cmd.do('bg_color white;') cmd.do('show sticks;') cmd.do('set stick_radius=0.14;') cmd.do('set stick_ball, on; ') cmd.do('set stick_ball_ratio,1.9;') cmd.do('set_view (-0.75,0.09,0.66,-0.2,0.92,-0.35,-0.64,-0.39,-0.67,-0.0,-0.0,-43.7,7.24,9.55,11.78,29.46,57.91,-20.0);') cmd.do('remove name H*;') cmd.do('select carbon1, element C and (resi 3 or resi 8) ') cmd.do('# select lower base pair;') cmd.do('select carbon2, element C and (resi 2 or resi 9) ') cmd.do('#select upper base pair;') cmd.do('color gray70, carbon1;') cmd.do('color gray10, carbon2;') cmd.do('show sticks;') cmd.do('space cmyk;') cmd.do('distance hbond1, /4PCO//B/U`9/N3,/4PCO//A/G`2/O6;') cmd.do('distance hbond2, /4PCO//B/U`9/O2,/4PCO//A/G`2/N1;') cmd.do('distance hbond3, /4PCO//A/U`3/N3,/4PCO//B/G`8/O6;') cmd.do('distance hbond4, /4PCO//A/U`3/O2,/4PCO//B/G`8/N1;') cmd.do('color black, hbond1;') cmd.do('color black, hbond2;') cmd.do('color gray70, hbond3;') cmd.do('color gray70, hbond4;') cmd.do('show nb_spheres;') cmd.do('set nb_spheres_size, 0.35;') cmd.do('hide labels;') cmd.do('ray 1600,1000;') cmd.do('png 4PCO.png;') ${0} ''' 'This code colors by the nucleotides by base seqence. The backcone is shown as a flatten ribbon with rolled edges that give the dumbell effect. The code can be applied to any nucleic acid. The code is dervied from the CR and DU shortcuts. ': 'prefix': 'nucleicAcidDumbellCartoonColorbySequence' 'body': ''' cmd.do('bg_color white;') cmd.do('set cartoon_oval_length, ${1:1.85}') cmd.do('set cartoon_oval_width, ${2:0.5}') cmd.do('cartoon oval;') cmd.do('cartoon dumbbell;') cmd.do('set cartoon_dumbbell_width, 0.2;') cmd.do('set cartoon_dumbbell_radius, 0.4;') cmd.do('set cartoon_ring_mode, ${3:3};') cmd.do('# set the color of the backbone oval') cmd.do('set cartoon_nucleic_acid_color, ${4:blue};') cmd.do('select rna_A, resn A;') cmd.do('select rna_C, resn C;') cmd.do('select rna_G, resn G;') cmd.do('select rna_U, resn U;') cmd.do('select dna_T, resn T;') cmd.do('color ${5:yellow}, rna_A;') cmd.do('color ${6:red}, rna_C; ') cmd.do('color ${7:gray40}, rna_G;') cmd.do('color ${8:palecyan}, rna_U;') cmd.do('color ${9:brown}, dna_T;') cmd.do('as cartoon;') ${0} ''' 'Set keyboard shortcut by mapping F1 to stereo.': 'prefix': 'stereokb' 'body': ''' cmd.do('cmd.set_key('F1',lambda:cmd.stereo({'on':0,'off':1}[cmd.get('stereo')]));') ${0} ''' 'Print to the screen the settings and their current parameter values.': 'prefix': 'listSettings2' 'body': ''' cmd.do('list = setting.get_name_list();[print("%s => %s" % (name, setting.get_setting_text(name))) for name in list];') ${0} ''' 'Print to the screen the settings and their current parameter values. This is the more compact version.': 'prefix': 'listSettings' 'body': ''' cmd.do('[print("%s => %s" % (name, setting.get_setting_text(name))) for name in setting.get_name_list()];') ${0} ''' 'Print to the screen as labels that 21 font ids in their corresponding fonts in a grid. Each label is an object and appears in the internal gui. You can turn on and off the display of specific fonts.': 'prefix': 'displayFonts' 'body': ''' cmd.do('python;') cmd.do('from pymol import cmd;') cmd.do('for i in range(1,21):') cmd.do(' name = 'label%d' % i;') cmd.do(' cmd.pseudoatom(name, label='label font id %d' % i, pos=(0,0,0));') cmd.do(' cmd.set('label_font_id', i, name);') cmd.do('cmd.set('label_size', 50);') cmd.do('cmd.set('grid_mode');') cmd.do('python end;') ${0} ''' 'Print to disk a list of H-bond pairs and this H-bond length.': 'prefix': 'listHBonds' 'body': ''' cmd.do('Finish latter. See file listHBonds.py.;') ${0} ''' 'Create a list of objects in the internal gui and print this list to the screen.': 'prefix': 'listObjects' 'body': ''' cmd.do('objList = cmd.get_names("objects");print(objList);') ${0} ''' 'Print a list of protein--ligand distances. Code by PI:NAME:<NAME>END_PI. Updated for Python3.': 'prefix': 'listLigandProteinDistances' 'body': ''' cmd.do('from pymol import cmd') cmd.do('"""') cmd.do('Find all distances betwen all ligand atoms and all protein atoms. ') cmd.do('') cmd.do('Adapted and updated from script by PI:NAME:<NAME>END_PI posted here') cmd.do('https://sourceforge.net/p/pymol/mailman/message/10097804/') cmd.do('') cmd.do('There are probably better solutions like finding just the ') cmd.do('distances to proein atoms within a certain distance from ') cmd.do('the ligand.') cmd.do('') cmd.do('Due to the nested for loops, this script is takes several second') cmd.do('to run on a medium-sized human protein. This script is a ') cmd.do('good candidate for vectorization. ') cmd.do('') cmd.do('It is also a good candiate for becoming a function and a shortcut. ') cmd.do('') cmd.do('"""') cmd.do('') cmd.do('# customize these lines to your protein.') cmd.do('cmd.fetch("6NEC")') cmd.do('cmd.select("prot","not resn XIN and not resn HOH and not chain C")') cmd.do('cmd.select("lig", "resn XIN and not chain C")') cmd.do('') cmd.do('dist_list = {}') cmd.do('pro_atoms = cmd.get_model("prot")') cmd.do('lig_atoms = cmd.get_model("lig")') cmd.do('') cmd.do('for l_at in lig_atoms.atom:') cmd.do(' for p_at in pro_atoms.atom:') cmd.do(' dist_list[str(l_at.resn) +') cmd.do(' ":" +') cmd.do(' str(l_at.resi) +') cmd.do(' " " +') cmd.do(' l_at.name +') cmd.do(' " ---- " + ') cmd.do(' str(p_at.resn) +') cmd.do(' ":" +') cmd.do(' str(p_at.resi) +') cmd.do(' " " +') cmd.do(' p_at.name] = cmd.dist("foo", ') cmd.do(' "index " +') cmd.do(' str(l_at.index),"index " + str(p_at.index))') cmd.do(' cmd.delete("foo")') cmd.do('print("List of all pairwise ligand--protein atom-atom distances:")') cmd.do('# [print("Distance of " + d + " is " + str(dist_list[d])) for d in dist_list.keys()]') cmd.do('') cmd.do('# More compact print statement. Need an f-string format statement.') cmd.do('[print( d + " " + str(dist_list[d])) for d in dist_list.keys()]') ${0} ''' 'This code shows that cartoon backbone tube as 65% transparent. It hides the rungs of the cartoon. It shows all of the non-H atoms are sticks. The motivation is to have the cartoon highlight the backbone without dominanting the scene.': 'prefix': 'nucleicAcidBackboneTubesSticks' 'body': ''' cmd.do('set bg_rgb, white;') cmd.do('hide everything, all;') cmd.do('show cartoon, ${1:3nd3};') cmd.do('set cartoon_sampling,1;') cmd.do('set cartoon_tube_radius, 0.5;') cmd.do('set cartoon_ladder_mode, 0;') cmd.do('set cartoon_transparency, ${2:0.65};') cmd.do('set stick_radius ${3:0.12};') cmd.do('show sticks;') cmd.do('hide sticks, element H;') ${0} ''' 'The code expands the asymmetric unit. It like the generate symmetry mates command but it provides more control over the prefix name of the symmetry mates and the addition of unique segment identifiers for each symmetry mate. The usage: symexp prefix, object, (selection), cutoff, segidFlag. The cutoff is in Angstroms. The segidFlag set to 1 will add unique segids. For related functions, see SC***.': 'prefix': 'symexp' 'body': ''' cmd.do('symexp ${1:symm}, ${2:3fa0}, (${2:3fa0}), ${3:20},${4:1};') ${0} ''' 'Adds the function draw_axis(). Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.': 'prefix': 'addAxis' 'body': ''' cmd.do('from pymol.cgo import * # get constants') cmd.do('from pymol import cmd') cmd.do('') cmd.do('import math') cmd.do('') cmd.do('class Counter:') cmd.do(' """') cmd.do(' draw_line') cmd.do(' source https://www.pymolwiki.org/index.php/Symmetry_Axis') cmd.do(' ') cmd.do(' Pymol script copyright PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI 2007') cmd.do(' ') cmd.do(' Under GNU Free Documentation License 1.2') cmd.do(' ') cmd.do(' Example:') cmd.do(' ') cmd.do(' draw_axis(x=18.232, y=17.150, z=9.488,i=-.226639, j=0.708772, k=-.668039, r=1, b=0, g=0, width=1, length=100)') cmd.do(' ') cmd.do(' Updated 15 June 2020 ') cmd.do(' PI:NAME:<NAME>END_PI') cmd.do(' ') cmd.do(' Notes:') cmd.do(' 1) Could be useful for the adding a symmery axis, a ncs axis, or scale bar to a scene.') cmd.do(' 2) The postion (xyz) is the middle of the line, not one end as expected for a vector.') cmd.do(' 3) Another example: draw_axis(x=0, y=0, z=0,i=0, j=0, k=1, r=1, b=0, g=0, width=300, length=96) ') cmd.do(' 4) Changed print statement to Python3 print function.') cmd.do(' 5) Replaced cmd.extend() with function generator.') cmd.do(' """') cmd.do(' def __init__(self):') cmd.do(' self.state = 1') cmd.do('counter = Counter()') cmd.do('') cmd.do('@cmd.extend') cmd.do('def draw_axis(x=None, y=None, z=None, i=None, j=None, k=None, length=20.0, r=1.0, g=1.0, b=1.0, width=1.0 ):') cmd.do(' if x == None or y == None or z == None or i == None or j == None or k== None :') cmd.do(' print('Usage: draw_axis x,y,z, i,k,j, length, r,g,b, width')') cmd.do(' print('draw a line centered at (x,y,z) with the direction vector (i,j,k)')') cmd.do(' print('length, color (r,g,b), and width arguments are optional')') cmd.do('# print 'For a fun example of the command, run draw_axis_example'') cmd.do(' else :') cmd.do(' x,y,z = float(x), float(y), float(z)') cmd.do(' i,j,k = float(i), float(j), float(k)') cmd.do(' r,g,b = float(r), float(g), float(b)') cmd.do(' width = float(width)') cmd.do(' length = float(length) / 2.0') cmd.do('') cmd.do(' x1,y1,z1 = (x+i*length,y+j*length,z+k*length)') cmd.do(' x2,y2,z2 = (x-i*length,y-j*length,z-k*length)') cmd.do('') cmd.do(' obj = [') cmd.do(' LINEWIDTH, width,') cmd.do(' BEGIN, LINES,') cmd.do('') cmd.do(' COLOR, r, g, b,') cmd.do(' VERTEX, x1, y1, z1,') cmd.do(' VERTEX, x2, y2, z2,') cmd.do('') cmd.do(' END') cmd.do(' ]') cmd.do('') cmd.do(' cmd.load_cgo(obj,'axis'+str(counter.state))') cmd.do(' counter.state += 1') ${0} ''' 'Wait unitl all current commands have been executed. A timeout ensures that that command ecentually returns.': 'prefix': 'synch' 'body': ''' cmd.do('cmd.sync(timeout=${1:1.0},poll=${2:0.05});') ${0} ''' 'Add or substract a residue number offset.': 'prefix': 'renumResi' 'body': ''' cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;') ${0} ''' 'Add or substract a atom number offset.': 'prefix': 'renumAtoms' 'body': ''' cmd.do('alter {$1:3fa0}, ID=ID+${2:100};') cmd.do('sort;') ${0} ''' 'Rename a chain. ': 'prefix': 'renameChain' 'body': ''' cmd.do('alter ${1:3fa0} and chain ${2:A}, chain=${3:"C"};') cmd.do('sort;') ${0} ''' 'Print the atom number2 of a residue.': 'prefix': 'printAtomNumbers' 'body': ''' cmd.do('iterate (resi 1), print(name + " %i5" % ID);') ${0} ''' 'Print the atom names of a residue.': 'prefix': 'printAtomNames' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name);') ${0} ''' 'Print the bfactors of a residue.': 'prefix': 'printBfactors' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % b);') ${0} ''' 'Print the van Der Waals radii of the atoms in of a residue.': 'prefix': 'printVDWradii' 'body': ''' cmd.do('iterate (resi ${1:101}), print(name + " %.2f" % vdw);') ${0} ''' 'Print the coordinates of the atoms in a residue.': 'prefix': 'printCoordinates' 'body': ''' cmd.do('stored.coords = []; ') cmd.do('iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('[print(i) for i in stored.coords];') ${0} ''' 'Print the atom names and coordinates of the atoms in a residue.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]); ') cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101})), stored.coords.append([x,y,z]); ') cmd.do('[print(i,j) for i,j in zip(stored.names, stored.coords)];') ${0} ''' 'Print the atom names as tuples and coordinates of the atoms in a residue as a list.': 'prefix': 'printNamesCoordinates' 'body': ''' cmd.do('stored.coords = []; iterate_state 1, (resi ${1:101}), stored.coords.append([x,y,z]); ') cmd.do('stored.names = []; iterate_state 1, (resi ${1:101}), stored.names.append([name]);') cmd.do('stored.names3 = [tuple(i) for i in stored.names];') cmd.do('[print(i,j) for i,j in(zip(stored.names3, stored.coords)];') ${0} ''' 'Source block template in org-mode with emacs-jupyter package. ': 'prefix': 'emacsjupyterSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC jupyter-python :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') cmd.do('$0') ${0} ''' 'Source block template in org-mode with ob-ipython package. ': 'prefix': 'obipythonSourceBlock' 'body': ''' cmd.do('#+BEGIN_SRC ipython :session py :kernel pymol.python :exports both :results raw drawer ') cmd.do('from pymol import cmd') cmd.do('cmd.do("reinitialize")') cmd.do('cmd.bg_color("white")') cmd.do('cmd.do("fetch 6VXX")') cmd.do('cmd.do("zoom (resi 614 and chain A)")') cmd.do('cmd.label(selection="chain A and resi 614 and name CB", expression="'%s-%s' % (resn,resi)")') cmd.do('cmd.do("set label_color, black; set label_size, 48")') cmd.do('cmd.do("set stick_radius, 0.12")') cmd.do('cmd.do("hide cartoon; show sticks")') cmd.do('cmd.do("set ray_shadows, 0")') cmd.do('cmd.do("draw")') cmd.do('cmd.do("png /Users/blaine/D614Gipython3.png, 600, 360, dpi=600")') cmd.do('from IPython.display import Image') cmd.do('from IPython.core.display import HTML') cmd.do('PATH = "/Users/blaine/"') cmd.do('Image(filename = PATH + "D614Gipython3.png", width=600, unconfined=True)') cmd.do('#+END_SRC') cmd.do('') cmd.do('#+RESULTS:') ${0} '''
[ { "context": "erson details', ->\n it 'can fetch details about Adel Qalieh', (done) ->\n @directory.personDetails '4ad00", "end": 361, "score": 0.999812126159668, "start": 350, "tag": "NAME", "value": "Adel Qalieh" }, { "context": " result.result_data[0].list_name.should.equal \"QALIEH, ADEL \"\n done()\n\n describe 'Search', ->\n it ", "end": 519, "score": 0.9989638924598694, "start": 507, "tag": "NAME", "value": "QALIEH, ADEL" }, { "context": "()\n\n describe 'Search', ->\n it 'can search for Alex Wissmann', (done) ->\n @directory.search {last_name: '", "end": 598, "score": 0.9998127818107605, "start": 585, "tag": "NAME", "value": "Alex Wissmann" }, { "context": "', (done) ->\n @directory.search {last_name: 'Wissmann'}, (result) ->\n result.result_data.should.", "end": 656, "score": 0.9998368620872498, "start": 648, "tag": "NAME", "value": "Wissmann" }, { "context": " result.result_data[0].list_name.should.equal \"WISSMANN, ALEXANDER R\"\n done()\n", "end": 785, "score": 0.9941070079803467, "start": 777, "tag": "NAME", "value": "WISSMANN" }, { "context": "t.result_data[0].list_name.should.equal \"WISSMANN, ALEXANDER R\"\n done()\n", "end": 798, "score": 0.912183403968811, "start": 787, "tag": "NAME", "value": "ALEXANDER R" } ]
test/directory.coffee
pennlabs/penn-sdk-node
1
should = require "should" api = require "../lib" Directory = api.Directory API_USERNAME = process.env.DIRECTORY_API_USERNAME || "" API_PASSWORD = process.env.DIRECTORY_API_PASSWORD || "" describe 'Directory', -> before -> @directory = new Directory(API_USERNAME, API_PASSWORD) describe 'Person details', -> it 'can fetch details about Adel Qalieh', (done) -> @directory.personDetails '4ad00e45edffd2ec2180673dabf4aace', (result) -> result.result_data[0].list_name.should.equal "QALIEH, ADEL " done() describe 'Search', -> it 'can search for Alex Wissmann', (done) -> @directory.search {last_name: 'Wissmann'}, (result) -> result.result_data.should.have.lengthOf(1) result.result_data[0].list_name.should.equal "WISSMANN, ALEXANDER R" done()
101578
should = require "should" api = require "../lib" Directory = api.Directory API_USERNAME = process.env.DIRECTORY_API_USERNAME || "" API_PASSWORD = process.env.DIRECTORY_API_PASSWORD || "" describe 'Directory', -> before -> @directory = new Directory(API_USERNAME, API_PASSWORD) describe 'Person details', -> it 'can fetch details about <NAME>', (done) -> @directory.personDetails '4ad00e45edffd2ec2180673dabf4aace', (result) -> result.result_data[0].list_name.should.equal "<NAME> " done() describe 'Search', -> it 'can search for <NAME>', (done) -> @directory.search {last_name: '<NAME>'}, (result) -> result.result_data.should.have.lengthOf(1) result.result_data[0].list_name.should.equal "<NAME>, <NAME>" done()
true
should = require "should" api = require "../lib" Directory = api.Directory API_USERNAME = process.env.DIRECTORY_API_USERNAME || "" API_PASSWORD = process.env.DIRECTORY_API_PASSWORD || "" describe 'Directory', -> before -> @directory = new Directory(API_USERNAME, API_PASSWORD) describe 'Person details', -> it 'can fetch details about PI:NAME:<NAME>END_PI', (done) -> @directory.personDetails '4ad00e45edffd2ec2180673dabf4aace', (result) -> result.result_data[0].list_name.should.equal "PI:NAME:<NAME>END_PI " done() describe 'Search', -> it 'can search for PI:NAME:<NAME>END_PI', (done) -> @directory.search {last_name: 'PI:NAME:<NAME>END_PI'}, (result) -> result.result_data.should.have.lengthOf(1) result.result_data[0].list_name.should.equal "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" done()
[ { "context": "_id: _id\n permissions: []\n email: _id+'@email.com'\n anonymous: false\n name: _.string.huma", "end": 1231, "score": 0.996084988117218, "start": 1222, "tag": "EMAIL", "value": "email.com" }, { "context": "elCompleteAchievement()\n user = sources.user or @makeUser()\n attrs = _.extend({}, {\n _id,\n \"ac", "end": 3871, "score": 0.9394157528877258, "start": 3862, "tag": "USERNAME", "value": "@makeUser" }, { "context": " _id\n properties: {\n firstName: 'Mr'\n lastName: 'Professorson'\n name: '", "end": 5274, "score": 0.999545693397522, "start": 5272, "tag": "NAME", "value": "Mr" }, { "context": "ies: {\n firstName: 'Mr'\n lastName: 'Professorson'\n name: 'Mr Professorson'\n email: '", "end": 5307, "score": 0.999657928943634, "start": 5295, "tag": "NAME", "value": "Professorson" }, { "context": "'\n lastName: 'Professorson'\n name: 'Mr Professorson'\n email: 'an@email.com'\n phoneNumbe", "end": 5339, "score": 0.9874976277351379, "start": 5324, "tag": "NAME", "value": "Mr Professorson" }, { "context": "'\n name: 'Mr Professorson'\n email: 'an@email.com'\n phoneNumber: '555-555-5555'\n orga", "end": 5369, "score": 0.9999210238456726, "start": 5357, "tag": "EMAIL", "value": "an@email.com" } ]
test/app/factories.coffee
adamcsillag/codecombat
1
Level = require 'models/Level' Course = require 'models/Course' Courses = require 'collections/Courses' User = require 'models/User' Classroom = require 'models/Classroom' LevelSession = require 'models/LevelSession' CourseInstance = require 'models/CourseInstance' Achievement = require 'models/Achievement' EarnedAchievement = require 'models/EarnedAchievement' ThangType = require 'models/ThangType' Users = require 'collections/Users' Prepaid = require 'models/Prepaid' module.exports = { makeCourse: (attrs, sources={}) -> _id = _.uniqueId('course_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) }, attrs) attrs.campaignID ?= sources.campaign?.id or _.uniqueId('campaign_') return new Course(attrs) makeLevel: (attrs) -> _id = _.uniqueId('level_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) original: _id+'_original' version: major: 0 minor: 0 isLatestMajor: true isLatestMinor: true }, attrs) return new Level(attrs) makeUser: (attrs, sources={}) -> _id = _.uniqueId('user_') attrs = _.extend({ _id: _id permissions: [] email: _id+'@email.com' anonymous: false name: _.string.humanize(_id) }, attrs) if sources.prepaid and not attrs.coursePrepaid attrs.coursePrepaid = sources.prepaid.pick('_id', 'startDate', 'endDate') return new User(attrs) makeClassroom: (attrs, sources={}) -> levels = sources.levels or [] # array of Levels collections courses = sources.courses or new Courses() members = sources.members or new Users() _id = _.uniqueId('classroom_') attrs = _.extend({}, { _id: _id, name: _.string.humanize(_id) aceConfig: { language: 'python' } }, attrs) # populate courses if not attrs.courses courses = sources.courses or new Courses() attrs.courses = (course.pick('_id') for course in courses.models) # populate levels for [courseAttrs, levels] in _.zip(attrs.courses, levels) break if not courseAttrs course ?= @makeCourse() levels ?= new Levels() courseAttrs.levels = (level.pick('_id', 'slug', 'name', 'original', 'type') for level in levels.models) # populate members if not attrs.members members = members or new Users() attrs.members = (member.id for member in members.models) return new Classroom(attrs) makeLevelSession: (attrs, sources={}) -> level = sources.level or @makeLevel() creator = sources.creator or @makeUser() attrs = _.extend({}, { level: original: level.get('original'), creator: creator.id, }, attrs) return new LevelSession(attrs) makeCourseInstance: (attrs, sources={}) -> _id = _.uniqueId('course_instance_') course = sources.course or @makeCourse() classroom = sources.classroom or @makeClassroom() owner = sources.owner or @makeUser() members = sources.members or new Users() attrs = _.extend({}, { _id courseID: course.id classroomID: classroom.id ownerID: owner.id members: members.pluck('_id') }, attrs) return new CourseInstance(attrs) makeLevelCompleteAchievement: (attrs, sources={}) -> _id = _.uniqueId('achievement_') level = sources.level or @makeLevel() attrs = _.extend({}, { _id name: _.string.humanize(_id) query: { 'state.complete': true, 'level.original': level.get('original') } rewards: { gems: 10 } worth: 20 }, attrs) return new Achievement(attrs) makeEarnedAchievement: (attrs, sources={}) -> _id = _.uniqueId('earned_achievement_') achievement = sources.achievement or @makeLevelCompleteAchievement() user = sources.user or @makeUser() attrs = _.extend({}, { _id, "achievement": achievement.id, "user": user.id, "earnedRewards": _.clone(achievement.get('rewards')), "earnedPoints": achievement.get('worth'), "achievementName": achievement.get('name'), "notified": true }, attrs) return new EarnedAchievement(attrs) makeThangType: (attrs) -> _id = _.uniqueId('thang_type_') attrs = _.extend({}, { _id name: _.string.humanize(_id) }, attrs) return new ThangType(attrs) makePayment: (attrs, sources={}) -> _id = _.uniqueId('payment_') attrs = _.extend({}, { _id }, attrs) return new ThangType(attrs) makePrepaid: (attrs, sources={}) -> _id = _.uniqueId('prepaid_') attrs = _.extend({}, { _id type: 'course' maxRedeemers: 10 endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }, attrs) if not attrs.redeemers redeemers = sources.redeemers or new Users() attrs.redeemers = ({ userID: redeemer.id date: moment().subtract(1, 'month').toISOString() } for redeemer in redeemers.models) return new Prepaid(attrs) makeTrialRequest: (attrs, sources={}) -> _id = _.uniqueId('trial_request_') attrs = _.extend({}, { _id properties: { firstName: 'Mr' lastName: 'Professorson' name: 'Mr Professorson' email: 'an@email.com' phoneNumber: '555-555-5555' organization: 'Greendale' } }, attrs) }
73645
Level = require 'models/Level' Course = require 'models/Course' Courses = require 'collections/Courses' User = require 'models/User' Classroom = require 'models/Classroom' LevelSession = require 'models/LevelSession' CourseInstance = require 'models/CourseInstance' Achievement = require 'models/Achievement' EarnedAchievement = require 'models/EarnedAchievement' ThangType = require 'models/ThangType' Users = require 'collections/Users' Prepaid = require 'models/Prepaid' module.exports = { makeCourse: (attrs, sources={}) -> _id = _.uniqueId('course_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) }, attrs) attrs.campaignID ?= sources.campaign?.id or _.uniqueId('campaign_') return new Course(attrs) makeLevel: (attrs) -> _id = _.uniqueId('level_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) original: _id+'_original' version: major: 0 minor: 0 isLatestMajor: true isLatestMinor: true }, attrs) return new Level(attrs) makeUser: (attrs, sources={}) -> _id = _.uniqueId('user_') attrs = _.extend({ _id: _id permissions: [] email: _id+'@<EMAIL>' anonymous: false name: _.string.humanize(_id) }, attrs) if sources.prepaid and not attrs.coursePrepaid attrs.coursePrepaid = sources.prepaid.pick('_id', 'startDate', 'endDate') return new User(attrs) makeClassroom: (attrs, sources={}) -> levels = sources.levels or [] # array of Levels collections courses = sources.courses or new Courses() members = sources.members or new Users() _id = _.uniqueId('classroom_') attrs = _.extend({}, { _id: _id, name: _.string.humanize(_id) aceConfig: { language: 'python' } }, attrs) # populate courses if not attrs.courses courses = sources.courses or new Courses() attrs.courses = (course.pick('_id') for course in courses.models) # populate levels for [courseAttrs, levels] in _.zip(attrs.courses, levels) break if not courseAttrs course ?= @makeCourse() levels ?= new Levels() courseAttrs.levels = (level.pick('_id', 'slug', 'name', 'original', 'type') for level in levels.models) # populate members if not attrs.members members = members or new Users() attrs.members = (member.id for member in members.models) return new Classroom(attrs) makeLevelSession: (attrs, sources={}) -> level = sources.level or @makeLevel() creator = sources.creator or @makeUser() attrs = _.extend({}, { level: original: level.get('original'), creator: creator.id, }, attrs) return new LevelSession(attrs) makeCourseInstance: (attrs, sources={}) -> _id = _.uniqueId('course_instance_') course = sources.course or @makeCourse() classroom = sources.classroom or @makeClassroom() owner = sources.owner or @makeUser() members = sources.members or new Users() attrs = _.extend({}, { _id courseID: course.id classroomID: classroom.id ownerID: owner.id members: members.pluck('_id') }, attrs) return new CourseInstance(attrs) makeLevelCompleteAchievement: (attrs, sources={}) -> _id = _.uniqueId('achievement_') level = sources.level or @makeLevel() attrs = _.extend({}, { _id name: _.string.humanize(_id) query: { 'state.complete': true, 'level.original': level.get('original') } rewards: { gems: 10 } worth: 20 }, attrs) return new Achievement(attrs) makeEarnedAchievement: (attrs, sources={}) -> _id = _.uniqueId('earned_achievement_') achievement = sources.achievement or @makeLevelCompleteAchievement() user = sources.user or @makeUser() attrs = _.extend({}, { _id, "achievement": achievement.id, "user": user.id, "earnedRewards": _.clone(achievement.get('rewards')), "earnedPoints": achievement.get('worth'), "achievementName": achievement.get('name'), "notified": true }, attrs) return new EarnedAchievement(attrs) makeThangType: (attrs) -> _id = _.uniqueId('thang_type_') attrs = _.extend({}, { _id name: _.string.humanize(_id) }, attrs) return new ThangType(attrs) makePayment: (attrs, sources={}) -> _id = _.uniqueId('payment_') attrs = _.extend({}, { _id }, attrs) return new ThangType(attrs) makePrepaid: (attrs, sources={}) -> _id = _.uniqueId('prepaid_') attrs = _.extend({}, { _id type: 'course' maxRedeemers: 10 endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }, attrs) if not attrs.redeemers redeemers = sources.redeemers or new Users() attrs.redeemers = ({ userID: redeemer.id date: moment().subtract(1, 'month').toISOString() } for redeemer in redeemers.models) return new Prepaid(attrs) makeTrialRequest: (attrs, sources={}) -> _id = _.uniqueId('trial_request_') attrs = _.extend({}, { _id properties: { firstName: '<NAME>' lastName: '<NAME>' name: '<NAME>' email: '<EMAIL>' phoneNumber: '555-555-5555' organization: 'Greendale' } }, attrs) }
true
Level = require 'models/Level' Course = require 'models/Course' Courses = require 'collections/Courses' User = require 'models/User' Classroom = require 'models/Classroom' LevelSession = require 'models/LevelSession' CourseInstance = require 'models/CourseInstance' Achievement = require 'models/Achievement' EarnedAchievement = require 'models/EarnedAchievement' ThangType = require 'models/ThangType' Users = require 'collections/Users' Prepaid = require 'models/Prepaid' module.exports = { makeCourse: (attrs, sources={}) -> _id = _.uniqueId('course_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) }, attrs) attrs.campaignID ?= sources.campaign?.id or _.uniqueId('campaign_') return new Course(attrs) makeLevel: (attrs) -> _id = _.uniqueId('level_') attrs = _.extend({}, { _id: _id name: _.string.humanize(_id) original: _id+'_original' version: major: 0 minor: 0 isLatestMajor: true isLatestMinor: true }, attrs) return new Level(attrs) makeUser: (attrs, sources={}) -> _id = _.uniqueId('user_') attrs = _.extend({ _id: _id permissions: [] email: _id+'@PI:EMAIL:<EMAIL>END_PI' anonymous: false name: _.string.humanize(_id) }, attrs) if sources.prepaid and not attrs.coursePrepaid attrs.coursePrepaid = sources.prepaid.pick('_id', 'startDate', 'endDate') return new User(attrs) makeClassroom: (attrs, sources={}) -> levels = sources.levels or [] # array of Levels collections courses = sources.courses or new Courses() members = sources.members or new Users() _id = _.uniqueId('classroom_') attrs = _.extend({}, { _id: _id, name: _.string.humanize(_id) aceConfig: { language: 'python' } }, attrs) # populate courses if not attrs.courses courses = sources.courses or new Courses() attrs.courses = (course.pick('_id') for course in courses.models) # populate levels for [courseAttrs, levels] in _.zip(attrs.courses, levels) break if not courseAttrs course ?= @makeCourse() levels ?= new Levels() courseAttrs.levels = (level.pick('_id', 'slug', 'name', 'original', 'type') for level in levels.models) # populate members if not attrs.members members = members or new Users() attrs.members = (member.id for member in members.models) return new Classroom(attrs) makeLevelSession: (attrs, sources={}) -> level = sources.level or @makeLevel() creator = sources.creator or @makeUser() attrs = _.extend({}, { level: original: level.get('original'), creator: creator.id, }, attrs) return new LevelSession(attrs) makeCourseInstance: (attrs, sources={}) -> _id = _.uniqueId('course_instance_') course = sources.course or @makeCourse() classroom = sources.classroom or @makeClassroom() owner = sources.owner or @makeUser() members = sources.members or new Users() attrs = _.extend({}, { _id courseID: course.id classroomID: classroom.id ownerID: owner.id members: members.pluck('_id') }, attrs) return new CourseInstance(attrs) makeLevelCompleteAchievement: (attrs, sources={}) -> _id = _.uniqueId('achievement_') level = sources.level or @makeLevel() attrs = _.extend({}, { _id name: _.string.humanize(_id) query: { 'state.complete': true, 'level.original': level.get('original') } rewards: { gems: 10 } worth: 20 }, attrs) return new Achievement(attrs) makeEarnedAchievement: (attrs, sources={}) -> _id = _.uniqueId('earned_achievement_') achievement = sources.achievement or @makeLevelCompleteAchievement() user = sources.user or @makeUser() attrs = _.extend({}, { _id, "achievement": achievement.id, "user": user.id, "earnedRewards": _.clone(achievement.get('rewards')), "earnedPoints": achievement.get('worth'), "achievementName": achievement.get('name'), "notified": true }, attrs) return new EarnedAchievement(attrs) makeThangType: (attrs) -> _id = _.uniqueId('thang_type_') attrs = _.extend({}, { _id name: _.string.humanize(_id) }, attrs) return new ThangType(attrs) makePayment: (attrs, sources={}) -> _id = _.uniqueId('payment_') attrs = _.extend({}, { _id }, attrs) return new ThangType(attrs) makePrepaid: (attrs, sources={}) -> _id = _.uniqueId('prepaid_') attrs = _.extend({}, { _id type: 'course' maxRedeemers: 10 endDate: moment().add(1, 'month').toISOString() startDate: moment().subtract(1, 'month').toISOString() }, attrs) if not attrs.redeemers redeemers = sources.redeemers or new Users() attrs.redeemers = ({ userID: redeemer.id date: moment().subtract(1, 'month').toISOString() } for redeemer in redeemers.models) return new Prepaid(attrs) makeTrialRequest: (attrs, sources={}) -> _id = _.uniqueId('trial_request_') attrs = _.extend({}, { _id properties: { firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' phoneNumber: '555-555-5555' organization: 'Greendale' } }, attrs) }
[ { "context": "rl: 'http://localhost:5000'\n token:\n secret: 'IhoiUHyu6gt5HJHhjhhGfddsESEWsfgHJjhhjFDdsseseRDSTDfgghhjHJljklkjuiuyyUYUtytrRERerererERerererRTGHghj'\n", "end": 287, "score": 0.9997702240943909, "start": 187, "tag": "KEY", "value": "IhoiUHyu6gt5HJHhjhhGfddsESEWsfgHJjhhjFDdsseseRDSTDfgghhjHJljklkjuiuyyUYUtytrRERerererERerererRTGHghj" } ]
server/config/development.coffee
stevelacy/claru
0
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru' name: 'Claru' port: 5000 title: 'Claru' url: 'http://localhost:5000' token: secret: 'IhoiUHyu6gt5HJHhjhhGfddsESEWsfgHJjhhjFDdsseseRDSTDfgghhjHJljklkjuiuyyUYUtytrRERerererERerererRTGHghj'
210236
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru' name: 'Claru' port: 5000 title: 'Claru' url: 'http://localhost:5000' token: secret: '<KEY>'
true
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru' name: 'Claru' port: 5000 title: 'Claru' url: 'http://localhost:5000' token: secret: 'PI:KEY:<KEY>END_PI'
[ { "context": "ut fields', ->\n @template.should.containEql 'Spaeth'\n @template.should.containEql 'Craig'\n ", "end": 591, "score": 0.9990925192832947, "start": 585, "tag": "NAME", "value": "Spaeth" }, { "context": "inEql 'Spaeth'\n @template.should.containEql 'Craig'\n @template.should.containEql 'craigspaeth@g", "end": 633, "score": 0.9987009763717651, "start": 628, "tag": "NAME", "value": "Craig" }, { "context": "ainEql 'Craig'\n @template.should.containEql 'craigspaeth@gmail.com'\n\n describe 'for a logged out user', ->\n befo", "end": 691, "score": 0.9999220967292786, "start": 670, "tag": "EMAIL", "value": "craigspaeth@gmail.com" } ]
apps/gallery_insights/test/template.coffee
l2succes/force
1
jade = require 'jade' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Gallery Insights Form', -> describe 'for a logged in user', -> beforeEach -> @template = render('index')( sd: { CURRENT_USER: fabricate 'user' } asset: (->) ) it 'displays their email address and name in input fields', -> @template.should.containEql 'Spaeth' @template.should.containEql 'Craig' @template.should.containEql 'craigspaeth@gmail.com' describe 'for a logged out user', -> beforeEach -> @template = render('index')( sd: { } asset: (->) ) it 'displays empty inputs', -> @template.should.containEql '<input id="EMAIL" type="email" name="EMAIL" required value=""' @template.should.containEql '<input id="FNAME" type="text" name="FNAME" value=""' @template.should.containEql '<input id="LNAME" type="text" name="LNAME" value=""'
225578
jade = require 'jade' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Gallery Insights Form', -> describe 'for a logged in user', -> beforeEach -> @template = render('index')( sd: { CURRENT_USER: fabricate 'user' } asset: (->) ) it 'displays their email address and name in input fields', -> @template.should.containEql '<NAME>' @template.should.containEql '<NAME>' @template.should.containEql '<EMAIL>' describe 'for a logged out user', -> beforeEach -> @template = render('index')( sd: { } asset: (->) ) it 'displays empty inputs', -> @template.should.containEql '<input id="EMAIL" type="email" name="EMAIL" required value=""' @template.should.containEql '<input id="FNAME" type="text" name="FNAME" value=""' @template.should.containEql '<input id="LNAME" type="text" name="LNAME" value=""'
true
jade = require 'jade' path = require 'path' fs = require 'fs' { fabricate } = require 'antigravity' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Gallery Insights Form', -> describe 'for a logged in user', -> beforeEach -> @template = render('index')( sd: { CURRENT_USER: fabricate 'user' } asset: (->) ) it 'displays their email address and name in input fields', -> @template.should.containEql 'PI:NAME:<NAME>END_PI' @template.should.containEql 'PI:NAME:<NAME>END_PI' @template.should.containEql 'PI:EMAIL:<EMAIL>END_PI' describe 'for a logged out user', -> beforeEach -> @template = render('index')( sd: { } asset: (->) ) it 'displays empty inputs', -> @template.should.containEql '<input id="EMAIL" type="email" name="EMAIL" required value=""' @template.should.containEql '<input id="FNAME" type="text" name="FNAME" value=""' @template.should.containEql '<input id="LNAME" type="text" name="LNAME" value=""'
[ { "context": " password [String]\n #\n autoPassword = -> chance.hash()\n\n # Login to Kinvey with the given credent", "end": 3184, "score": 0.8707464337348938, "start": 3173, "tag": "PASSWORD", "value": "chance.hash" }, { "context": "username, password\n login({ username: username, password: password })\n else\n ", "end": 4454, "score": 0.9987399578094482, "start": 4446, "tag": "USERNAME", "value": "username" }, { "context": " login({ username: username, password: password })\n else\n logger.info 'No", "end": 4474, "score": 0.9988369345664978, "start": 4466, "tag": "PASSWORD", "value": "password" }, { "context": " try\n autoAccount username: autoUsername(), password: autoPassword()\n cat", "end": 4778, "score": 0.8419302701950073, "start": 4766, "tag": "USERNAME", "value": "autoUsername" } ]
lib/authorize_kinvey.coffee
logankoester/backbone-datarouter
1
# This custom authorizer should be injected into a Route to authorize # a user with the Kinvey service. # # Initializes the current user and triggers a route event when finished. # This event might be any of: # # * 'allow:user' # * 'allow:guest' # * 'allow:created' # * 'allow:offline' # * 'deny:user' # * 'deny:guest' # * 'deny:offline' # * 'deny:error' # # A nonspecific 'deny' or 'allow' route event is also triggered. # # Add the following options to your route instance: # # * kinvey [Object] Options hash to be passed into Kinvey.init() # * allowOffline [Boolean] Set true to resolve if the network is unreachable but a cached user exists. # * allowGuest [Boolean] Set true to resolve if no user is logged in. # * userClass [Function<Backbone.Model>] Your Kinvey User model. # * autoAccount [Boolean] If true, attempt to generate an account if online with no cached user. # # @param route [Object] A route object to authorize. # @return promise [Promise] A promise to resolve upon authorization, or reject if access is denied. # # @note To use autoAccount you will need "chance" on your global scope. # @see http://chancejs.com/#dice # define [ 'kinvey', 'chance' ], (Kinvey) -> (route) -> $.Deferred (deferred) -> # Inherit the route's logging function, if any if route && route.options && route.options.logger logger = route.options.logger else logger = console # Trigger a 'allow' route event and resolve the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # allow = (event) -> route.trigger event, route route.trigger 'allow', route deferred.resolve() # Trigger the 'deny' route event and reject the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # deny = (event) -> route.trigger event, route route.trigger 'deny', route deferred.reject() # Attempt to generate an account if online with no cached user. # # @param credentials [Object] An object containing username and password (string) properties. # autoAccount = (credentials) -> logger.info 'Creating new autogenerated account', credentials user.save credentials, success: (model, response, options) -> logger.info 'Account created successfully', response allow 'allow:created' error: (model, xhr, options) -> logger.error 'Failed to create account', xhr route.pushError xhr deny 'deny:error' # Return a username for the automatically generated user. # Attempts to read a uuid from the device (as in Cordova # environments), otherwise generate a random guid. # # @return username [String] # autoUsername = -> chance.guid() # Generate and return a secure password (a 40char hex hash) # # @return password [String] # autoPassword = -> chance.hash() # Login to Kinvey with the given credentials # # @param credentials [Object] An object containing username and password (string) properties. # login = (credentials) -> user.login(credentials).then -> if user.isLoggedIn() allow 'allow:user' else deny 'deny:user' , (error) -> logger.error 'Failed to login with credentials', error route.pushError error deny 'deny:error' # Ensure Kinvey is in online mode and then initialize it. # # If not logged in, attempt to log in with cached credentials. # # Otherwise either generate an account or deny, depending on route options. # online = -> Kinvey.Sync.online() Kinvey.init(route.options.kinvey).then (activeUser) => if activeUser logger.info 'Already logged in', activeUser allow 'allow:user' else cache = Kinvey.Backbone.User.accountCache username = cache.getUsername() password = cache.getPassword() if username && password logger.info 'Logging in with cached credentials', username, password login({ username: username, password: password }) else logger.info 'Not logged in, no cached credentials' if route.options.allowGuest allow 'allow:guest' else if route.options.autoAccount try autoAccount username: autoUsername(), password: autoPassword() catch error logger.trace(error) deny 'deny:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' # Ensure Kinvey is in offline mode, and deny if allowOffline is disabled. # # Otherwise, check for an active user. # offline = -> Kinvey.Sync.offline() if route.options.allowOffline options = _.clone(route.options.kinvey) options.online = false Kinvey.init(options).then (activeUser) => if Kinvey.Backbone.getActiveUser() allow 'allow:offline' else if route.options.allowGuest allow 'allow:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' else deny 'deny:offline' user = new Kinvey.Backbone.User if route.options.online() then online() else offline() .promise()
188135
# This custom authorizer should be injected into a Route to authorize # a user with the Kinvey service. # # Initializes the current user and triggers a route event when finished. # This event might be any of: # # * 'allow:user' # * 'allow:guest' # * 'allow:created' # * 'allow:offline' # * 'deny:user' # * 'deny:guest' # * 'deny:offline' # * 'deny:error' # # A nonspecific 'deny' or 'allow' route event is also triggered. # # Add the following options to your route instance: # # * kinvey [Object] Options hash to be passed into Kinvey.init() # * allowOffline [Boolean] Set true to resolve if the network is unreachable but a cached user exists. # * allowGuest [Boolean] Set true to resolve if no user is logged in. # * userClass [Function<Backbone.Model>] Your Kinvey User model. # * autoAccount [Boolean] If true, attempt to generate an account if online with no cached user. # # @param route [Object] A route object to authorize. # @return promise [Promise] A promise to resolve upon authorization, or reject if access is denied. # # @note To use autoAccount you will need "chance" on your global scope. # @see http://chancejs.com/#dice # define [ 'kinvey', 'chance' ], (Kinvey) -> (route) -> $.Deferred (deferred) -> # Inherit the route's logging function, if any if route && route.options && route.options.logger logger = route.options.logger else logger = console # Trigger a 'allow' route event and resolve the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # allow = (event) -> route.trigger event, route route.trigger 'allow', route deferred.resolve() # Trigger the 'deny' route event and reject the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # deny = (event) -> route.trigger event, route route.trigger 'deny', route deferred.reject() # Attempt to generate an account if online with no cached user. # # @param credentials [Object] An object containing username and password (string) properties. # autoAccount = (credentials) -> logger.info 'Creating new autogenerated account', credentials user.save credentials, success: (model, response, options) -> logger.info 'Account created successfully', response allow 'allow:created' error: (model, xhr, options) -> logger.error 'Failed to create account', xhr route.pushError xhr deny 'deny:error' # Return a username for the automatically generated user. # Attempts to read a uuid from the device (as in Cordova # environments), otherwise generate a random guid. # # @return username [String] # autoUsername = -> chance.guid() # Generate and return a secure password (a 40char hex hash) # # @return password [String] # autoPassword = -> <PASSWORD>() # Login to Kinvey with the given credentials # # @param credentials [Object] An object containing username and password (string) properties. # login = (credentials) -> user.login(credentials).then -> if user.isLoggedIn() allow 'allow:user' else deny 'deny:user' , (error) -> logger.error 'Failed to login with credentials', error route.pushError error deny 'deny:error' # Ensure Kinvey is in online mode and then initialize it. # # If not logged in, attempt to log in with cached credentials. # # Otherwise either generate an account or deny, depending on route options. # online = -> Kinvey.Sync.online() Kinvey.init(route.options.kinvey).then (activeUser) => if activeUser logger.info 'Already logged in', activeUser allow 'allow:user' else cache = Kinvey.Backbone.User.accountCache username = cache.getUsername() password = cache.getPassword() if username && password logger.info 'Logging in with cached credentials', username, password login({ username: username, password: <PASSWORD> }) else logger.info 'Not logged in, no cached credentials' if route.options.allowGuest allow 'allow:guest' else if route.options.autoAccount try autoAccount username: autoUsername(), password: autoPassword() catch error logger.trace(error) deny 'deny:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' # Ensure Kinvey is in offline mode, and deny if allowOffline is disabled. # # Otherwise, check for an active user. # offline = -> Kinvey.Sync.offline() if route.options.allowOffline options = _.clone(route.options.kinvey) options.online = false Kinvey.init(options).then (activeUser) => if Kinvey.Backbone.getActiveUser() allow 'allow:offline' else if route.options.allowGuest allow 'allow:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' else deny 'deny:offline' user = new Kinvey.Backbone.User if route.options.online() then online() else offline() .promise()
true
# This custom authorizer should be injected into a Route to authorize # a user with the Kinvey service. # # Initializes the current user and triggers a route event when finished. # This event might be any of: # # * 'allow:user' # * 'allow:guest' # * 'allow:created' # * 'allow:offline' # * 'deny:user' # * 'deny:guest' # * 'deny:offline' # * 'deny:error' # # A nonspecific 'deny' or 'allow' route event is also triggered. # # Add the following options to your route instance: # # * kinvey [Object] Options hash to be passed into Kinvey.init() # * allowOffline [Boolean] Set true to resolve if the network is unreachable but a cached user exists. # * allowGuest [Boolean] Set true to resolve if no user is logged in. # * userClass [Function<Backbone.Model>] Your Kinvey User model. # * autoAccount [Boolean] If true, attempt to generate an account if online with no cached user. # # @param route [Object] A route object to authorize. # @return promise [Promise] A promise to resolve upon authorization, or reject if access is denied. # # @note To use autoAccount you will need "chance" on your global scope. # @see http://chancejs.com/#dice # define [ 'kinvey', 'chance' ], (Kinvey) -> (route) -> $.Deferred (deferred) -> # Inherit the route's logging function, if any if route && route.options && route.options.logger logger = route.options.logger else logger = console # Trigger a 'allow' route event and resolve the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # allow = (event) -> route.trigger event, route route.trigger 'allow', route deferred.resolve() # Trigger the 'deny' route event and reject the deferred. # Also triggers a custom route event if passed as the first parameter. # # @param event [String] A custom route event to trigger # deny = (event) -> route.trigger event, route route.trigger 'deny', route deferred.reject() # Attempt to generate an account if online with no cached user. # # @param credentials [Object] An object containing username and password (string) properties. # autoAccount = (credentials) -> logger.info 'Creating new autogenerated account', credentials user.save credentials, success: (model, response, options) -> logger.info 'Account created successfully', response allow 'allow:created' error: (model, xhr, options) -> logger.error 'Failed to create account', xhr route.pushError xhr deny 'deny:error' # Return a username for the automatically generated user. # Attempts to read a uuid from the device (as in Cordova # environments), otherwise generate a random guid. # # @return username [String] # autoUsername = -> chance.guid() # Generate and return a secure password (a 40char hex hash) # # @return password [String] # autoPassword = -> PI:PASSWORD:<PASSWORD>END_PI() # Login to Kinvey with the given credentials # # @param credentials [Object] An object containing username and password (string) properties. # login = (credentials) -> user.login(credentials).then -> if user.isLoggedIn() allow 'allow:user' else deny 'deny:user' , (error) -> logger.error 'Failed to login with credentials', error route.pushError error deny 'deny:error' # Ensure Kinvey is in online mode and then initialize it. # # If not logged in, attempt to log in with cached credentials. # # Otherwise either generate an account or deny, depending on route options. # online = -> Kinvey.Sync.online() Kinvey.init(route.options.kinvey).then (activeUser) => if activeUser logger.info 'Already logged in', activeUser allow 'allow:user' else cache = Kinvey.Backbone.User.accountCache username = cache.getUsername() password = cache.getPassword() if username && password logger.info 'Logging in with cached credentials', username, password login({ username: username, password: PI:PASSWORD:<PASSWORD>END_PI }) else logger.info 'Not logged in, no cached credentials' if route.options.allowGuest allow 'allow:guest' else if route.options.autoAccount try autoAccount username: autoUsername(), password: autoPassword() catch error logger.trace(error) deny 'deny:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' # Ensure Kinvey is in offline mode, and deny if allowOffline is disabled. # # Otherwise, check for an active user. # offline = -> Kinvey.Sync.offline() if route.options.allowOffline options = _.clone(route.options.kinvey) options.online = false Kinvey.init(options).then (activeUser) => if Kinvey.Backbone.getActiveUser() allow 'allow:offline' else if route.options.allowGuest allow 'allow:guest' else deny 'deny:guest' , (error) => logger.error 'Kinvey init error', error route.pushError error deny 'deny:error' else deny 'deny:offline' user = new Kinvey.Backbone.User if route.options.online() then online() else offline() .promise()
[ { "context": " 1 # always 1st\n\t\t\tshow: true\n\t\t\tdisplayNameEng: 'Mt. Gox'\n\t\t\tgeo: \"JP\" # ISO 3166-1\n\t\t\tdefaultCurrenc", "end": 369, "score": 0.5069279670715332, "start": 367, "tag": "NAME", "value": "Mt" }, { "context": "y/ticker_fast' # REST api - https://bitbucket.org/nitrous/mtgox-api\n\t\t\t\trateLimit: 1005\n\t\t\tfetched:\n\t\t\t\tini", "end": 669, "score": 0.9979249835014343, "start": 662, "tag": "USERNAME", "value": "nitrous" }, { "context": "ce'\n\t\t\torder: 2\n\t\t\tshow: true\n\t\t\tdisplayNameEng: 'BTC-e'\n\t\t\tgeo: 'BG'\n\t\t\tdefaultCurrency: 'USD'\n\t\t\twebsit", "end": 1754, "score": 0.7344043850898743, "start": 1749, "tag": "NAME", "value": "BTC-e" }, { "context": "tched:\n\t\t\t\tinitialized: false\n\t\tbitfinex:\n\t\t\tid: 'bitfinex'\n\t\t\torder: 6\n\t\t\tshow: true\n\t\t\tdisplayNameEng: 'Bi", "end": 2651, "score": 0.9926396012306213, "start": 2643, "tag": "USERNAME", "value": "bitfinex" }, { "context": "ex'\n\t\t\torder: 6\n\t\t\tshow: true\n\t\t\tdisplayNameEng: 'Bitfinex'\n\t\t\tgeo: 'HK'\n\t\t\tdefaultCurrency: 'HKD'\n\t\t\twebsit", "end": 2707, "score": 0.5870943069458008, "start": 2699, "tag": "USERNAME", "value": "Bitfinex" } ]
public/js/app-data.coffee
rayshan/CoinArb
3
#fetched = # current: # last: null # spread: null # volume: null # updateTime: null # error: null # previous: # last: null # spread: null # volume: null # updateTime: null # error: null angular.module('CaApp').factory 'exchangeSvc', () -> data = mtgox: id: 'mtgox' # based on bitcoinaverage order: 1 # always 1st show: true displayNameEng: 'Mt. Gox' geo: "JP" # ISO 3166-1 defaultCurrency: 'USD' website: 'https://mtgox.com/' api: # type: 'ws' # uri: 'http://socketio.mtgox.com:80/mtgox?Currency=USD' type: 'REST' uri: 'https://data.mtgox.com/api/2/BTCUSD/money/ticker_fast' # REST api - https://bitbucket.org/nitrous/mtgox-api rateLimit: 1005 fetched: initialized: false btcchina: id: 'btcchina' order: 3 show: true displayNameEng: 'BTC China' displayNameLocal: '比特币中国' defaultCurrency: 'CNY' website: 'https://btcchina.com' api: type: 'REST' uri: 'https://data.btcchina.com/data/ticker' rateLimit: 1000 * 5 fetched: initialized: false localbitcoins: id: 'localbitcoins' order: 4 show: true displayNameEng: 'LocalBitcoins' defaultCurrency: 'USD' website: 'https://localbitcoins.com' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # appears to pull avg_3h # uri: 'https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/' # no CORS uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Flocalbitcoins.com%2Fbitcoinaverage%2Fticker-all-currencies%2F%22&format=json&callback=' # yql rateLimit: 1000 * 5 fetched: initialized: false btce: id: 'btce' order: 2 show: true displayNameEng: 'BTC-e' geo: 'BG' defaultCurrency: 'USD' website: 'https://btc-e.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # uri: 'https://btc-e.com/api/2/btc_usd/ticker' # no CORS no JSONP uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fbtc-e.com%2Fapi%2F2%2Fbtc_usd%2Fticker%22&format=json&callback=' # yql, no diagnostics rateLimit: 1000 * 5 # yql public 2k requests / hr fetched: initialized: false bitstamp: id: 'bitstamp' order: 5 show: true displayNameEng: 'Bitstamp' geo: 'GB' defaultCurrency: 'GBP' website: 'https://www.bitstamp.net/' api: type: 'REST' uri: 'https://api.bitcoinaverage.com/exchanges/USD' # no cors, 403 when pulled via yql rateLimit: 1001 * 60 fetched: initialized: false bitfinex: id: 'bitfinex' order: 6 show: true displayNameEng: 'Bitfinex' geo: 'HK' defaultCurrency: 'HKD' website: 'https://www.bitfinex.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fapi.bitfinex.com%2Fv1%2Fticker%2Fbtcusd%22&format=json&callback=' rateLimit: 1000 * 5 fetched: initialized: false data: data
29101
#fetched = # current: # last: null # spread: null # volume: null # updateTime: null # error: null # previous: # last: null # spread: null # volume: null # updateTime: null # error: null angular.module('CaApp').factory 'exchangeSvc', () -> data = mtgox: id: 'mtgox' # based on bitcoinaverage order: 1 # always 1st show: true displayNameEng: '<NAME>. Gox' geo: "JP" # ISO 3166-1 defaultCurrency: 'USD' website: 'https://mtgox.com/' api: # type: 'ws' # uri: 'http://socketio.mtgox.com:80/mtgox?Currency=USD' type: 'REST' uri: 'https://data.mtgox.com/api/2/BTCUSD/money/ticker_fast' # REST api - https://bitbucket.org/nitrous/mtgox-api rateLimit: 1005 fetched: initialized: false btcchina: id: 'btcchina' order: 3 show: true displayNameEng: 'BTC China' displayNameLocal: '比特币中国' defaultCurrency: 'CNY' website: 'https://btcchina.com' api: type: 'REST' uri: 'https://data.btcchina.com/data/ticker' rateLimit: 1000 * 5 fetched: initialized: false localbitcoins: id: 'localbitcoins' order: 4 show: true displayNameEng: 'LocalBitcoins' defaultCurrency: 'USD' website: 'https://localbitcoins.com' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # appears to pull avg_3h # uri: 'https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/' # no CORS uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Flocalbitcoins.com%2Fbitcoinaverage%2Fticker-all-currencies%2F%22&format=json&callback=' # yql rateLimit: 1000 * 5 fetched: initialized: false btce: id: 'btce' order: 2 show: true displayNameEng: '<NAME>' geo: 'BG' defaultCurrency: 'USD' website: 'https://btc-e.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # uri: 'https://btc-e.com/api/2/btc_usd/ticker' # no CORS no JSONP uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fbtc-e.com%2Fapi%2F2%2Fbtc_usd%2Fticker%22&format=json&callback=' # yql, no diagnostics rateLimit: 1000 * 5 # yql public 2k requests / hr fetched: initialized: false bitstamp: id: 'bitstamp' order: 5 show: true displayNameEng: 'Bitstamp' geo: 'GB' defaultCurrency: 'GBP' website: 'https://www.bitstamp.net/' api: type: 'REST' uri: 'https://api.bitcoinaverage.com/exchanges/USD' # no cors, 403 when pulled via yql rateLimit: 1001 * 60 fetched: initialized: false bitfinex: id: 'bitfinex' order: 6 show: true displayNameEng: 'Bitfinex' geo: 'HK' defaultCurrency: 'HKD' website: 'https://www.bitfinex.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fapi.bitfinex.com%2Fv1%2Fticker%2Fbtcusd%22&format=json&callback=' rateLimit: 1000 * 5 fetched: initialized: false data: data
true
#fetched = # current: # last: null # spread: null # volume: null # updateTime: null # error: null # previous: # last: null # spread: null # volume: null # updateTime: null # error: null angular.module('CaApp').factory 'exchangeSvc', () -> data = mtgox: id: 'mtgox' # based on bitcoinaverage order: 1 # always 1st show: true displayNameEng: 'PI:NAME:<NAME>END_PI. Gox' geo: "JP" # ISO 3166-1 defaultCurrency: 'USD' website: 'https://mtgox.com/' api: # type: 'ws' # uri: 'http://socketio.mtgox.com:80/mtgox?Currency=USD' type: 'REST' uri: 'https://data.mtgox.com/api/2/BTCUSD/money/ticker_fast' # REST api - https://bitbucket.org/nitrous/mtgox-api rateLimit: 1005 fetched: initialized: false btcchina: id: 'btcchina' order: 3 show: true displayNameEng: 'BTC China' displayNameLocal: '比特币中国' defaultCurrency: 'CNY' website: 'https://btcchina.com' api: type: 'REST' uri: 'https://data.btcchina.com/data/ticker' rateLimit: 1000 * 5 fetched: initialized: false localbitcoins: id: 'localbitcoins' order: 4 show: true displayNameEng: 'LocalBitcoins' defaultCurrency: 'USD' website: 'https://localbitcoins.com' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # appears to pull avg_3h # uri: 'https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/' # no CORS uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Flocalbitcoins.com%2Fbitcoinaverage%2Fticker-all-currencies%2F%22&format=json&callback=' # yql rateLimit: 1000 * 5 fetched: initialized: false btce: id: 'btce' order: 2 show: true displayNameEng: 'PI:NAME:<NAME>END_PI' geo: 'BG' defaultCurrency: 'USD' website: 'https://btc-e.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' # uri: 'https://btc-e.com/api/2/btc_usd/ticker' # no CORS no JSONP uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fbtc-e.com%2Fapi%2F2%2Fbtc_usd%2Fticker%22&format=json&callback=' # yql, no diagnostics rateLimit: 1000 * 5 # yql public 2k requests / hr fetched: initialized: false bitstamp: id: 'bitstamp' order: 5 show: true displayNameEng: 'Bitstamp' geo: 'GB' defaultCurrency: 'GBP' website: 'https://www.bitstamp.net/' api: type: 'REST' uri: 'https://api.bitcoinaverage.com/exchanges/USD' # no cors, 403 when pulled via yql rateLimit: 1001 * 60 fetched: initialized: false bitfinex: id: 'bitfinex' order: 6 show: true displayNameEng: 'Bitfinex' geo: 'HK' defaultCurrency: 'HKD' website: 'https://www.bitfinex.com/' api: type: 'REST' # uri: 'https://api.bitcoinaverage.com/exchanges/USD' uri: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22https%3A%2F%2Fapi.bitfinex.com%2Fv1%2Fticker%2Fbtcusd%22&format=json&callback=' rateLimit: 1000 * 5 fetched: initialized: false data: data
[ { "context": " {\n type: 'text'\n body: '<p>Bob Olsen</p>'\n }\n ]\n contributing_a", "end": 3063, "score": 0.9997871518135071, "start": 3054, "tag": "NAME", "value": "Bob Olsen" }, { "context": " artists: [{\n name: \"Govinda Sah 'Azad'\",\n slug: \"govinda-sah-aza", "end": 4075, "score": 0.9996369481086731, "start": 4064, "tag": "NAME", "value": "Govinda Sah" }, { "context": "artists: [{\n name: \"Govinda Sah 'Azad'\",\n slug: \"govinda-sah-azad\"\n ", "end": 4081, "score": 0.859329104423523, "start": 4077, "tag": "NAME", "value": "Azad" }, { "context": " },\n {\n name: \"Andy Warhol\",\n slug: \"andy-warhol\"\n ", "end": 4201, "score": 0.9997174739837646, "start": 4190, "tag": "NAME", "value": "Andy Warhol" }, { "context": "ame: \"Andy Warhol\",\n slug: \"andy-warhol\"\n }]\n },{\n ", "end": 4237, "score": 0.580159068107605, "start": 4234, "tag": "USERNAME", "value": "war" }, { "context": "ql '/october-gallery'\n html.should.containEql \"Govinda Sah 'Azad'\"\n html.should.containEql \"Andy Warhol\"\n", "end": 4859, "score": 0.9872739911079407, "start": 4848, "tag": "NAME", "value": "Govinda Sah" }, { "context": "gallery'\n html.should.containEql \"Govinda Sah 'Azad'\"\n html.should.containEql \"Andy Warhol\"\n ht", "end": 4865, "score": 0.7372286319732666, "start": 4861, "tag": "NAME", "value": "Azad" }, { "context": " \"Govinda Sah 'Azad'\"\n html.should.containEql \"Andy Warhol\"\n html.should.containEql '<p>Some cool art fro", "end": 4907, "score": 0.9957647919654846, "start": 4896, "tag": "NAME", "value": "Andy Warhol" } ]
src/desktop/components/article/test/templates.coffee
kanaabe/force
1
_ = require 'underscore' _s = require 'underscore.string' cheerio = require 'cheerio' embed = require 'particle' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' markdown = require '../../../components/util/markdown' Article = require '../../../models/article' Articles = require '../../../collections/articles' fixtures = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'article show template', -> it 'renders sectionless articles', -> html = render('index') article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.containEql 'hi' it 'renders hero section with static image', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image' url: 'http://image.jpg' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with multiple images', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image_collection' images: [ { type: 'image' url: 'http://image1.jpg' } { type: 'image' url: 'http://image2.jpg' } ] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image1.jpg"' html.should.containEql '<img src="http://image2.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with video', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'video' url: 'https://www.youtube.com/watch?v=Bv_5Zv5c-Ts' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> embed: embed html.should.containEql '<iframe src="//www.youtube.com/embed/Bv_5Zv5c-Ts' html.should.containEql 'class="article-large-format-video-container"' it 'can optionally exclude share buttons', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'text' body: '<p>Bob Olsen</p>' } ] contributing_authors: [] footerArticles: new Articles hideShare: true crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.not.containEql 'share' it 'renders image collections', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'image_collection', layout: 'overflow_fillwidth', images: [ { type: 'artwork' id: '5321b73dc9dc2458c4000196' slug: "govinda-sah-azad-in-between-1", date: "2015", title: "In Between", image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg", partner: { name: "October Gallery", slug: "october-gallery" }, artists: [{ name: "Govinda Sah 'Azad'", slug: "govinda-sah-azad" }, { name: "Andy Warhol", slug: "andy-warhol" }] },{ type: 'image' url: "http://artsy.net/image.jpg", caption: "<p>Some cool art from 2015</p>", } ] } ] contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '/artwork/govinda-sah-azad-in-between-1' html.should.containEql 'http://artsy.net/image.jpg' html.should.containEql '/october-gallery' html.should.containEql "Govinda Sah 'Azad'" html.should.containEql "Andy Warhol" html.should.containEql '<p>Some cool art from 2015</p>'
157657
_ = require 'underscore' _s = require 'underscore.string' cheerio = require 'cheerio' embed = require 'particle' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' markdown = require '../../../components/util/markdown' Article = require '../../../models/article' Articles = require '../../../collections/articles' fixtures = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'article show template', -> it 'renders sectionless articles', -> html = render('index') article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.containEql 'hi' it 'renders hero section with static image', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image' url: 'http://image.jpg' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with multiple images', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image_collection' images: [ { type: 'image' url: 'http://image1.jpg' } { type: 'image' url: 'http://image2.jpg' } ] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image1.jpg"' html.should.containEql '<img src="http://image2.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with video', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'video' url: 'https://www.youtube.com/watch?v=Bv_5Zv5c-Ts' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> embed: embed html.should.containEql '<iframe src="//www.youtube.com/embed/Bv_5Zv5c-Ts' html.should.containEql 'class="article-large-format-video-container"' it 'can optionally exclude share buttons', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'text' body: '<p><NAME></p>' } ] contributing_authors: [] footerArticles: new Articles hideShare: true crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.not.containEql 'share' it 'renders image collections', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'image_collection', layout: 'overflow_fillwidth', images: [ { type: 'artwork' id: '5321b73dc9dc2458c4000196' slug: "govinda-sah-azad-in-between-1", date: "2015", title: "In Between", image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg", partner: { name: "October Gallery", slug: "october-gallery" }, artists: [{ name: "<NAME> '<NAME>'", slug: "govinda-sah-azad" }, { name: "<NAME>", slug: "andy-warhol" }] },{ type: 'image' url: "http://artsy.net/image.jpg", caption: "<p>Some cool art from 2015</p>", } ] } ] contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '/artwork/govinda-sah-azad-in-between-1' html.should.containEql 'http://artsy.net/image.jpg' html.should.containEql '/october-gallery' html.should.containEql "<NAME> '<NAME>'" html.should.containEql "<NAME>" html.should.containEql '<p>Some cool art from 2015</p>'
true
_ = require 'underscore' _s = require 'underscore.string' cheerio = require 'cheerio' embed = require 'particle' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' markdown = require '../../../components/util/markdown' Article = require '../../../models/article' Articles = require '../../../collections/articles' fixtures = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'article show template', -> it 'renders sectionless articles', -> html = render('index') article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.containEql 'hi' it 'renders hero section with static image', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image' url: 'http://image.jpg' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with multiple images', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'image_collection' images: [ { type: 'image' url: 'http://image1.jpg' } { type: 'image' url: 'http://image2.jpg' } ] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '<img src="http://image1.jpg"' html.should.containEql '<img src="http://image2.jpg"' html.should.containEql 'class="article-large-format-image"' it 'renders hero section with video', -> html = render('index') article: new Article title: 'hi' sections: [] contributing_authors: [] hero_section: type: 'video' url: 'https://www.youtube.com/watch?v=Bv_5Zv5c-Ts' footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> embed: embed html.should.containEql '<iframe src="//www.youtube.com/embed/Bv_5Zv5c-Ts' html.should.containEql 'class="article-large-format-video-container"' it 'can optionally exclude share buttons', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'text' body: '<p>PI:NAME:<NAME>END_PI</p>' } ] contributing_authors: [] footerArticles: new Articles hideShare: true crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> html.should.not.containEql 'share' it 'renders image collections', -> html = render('index') article: new Article title: 'hi' sections: [ { type: 'image_collection', layout: 'overflow_fillwidth', images: [ { type: 'artwork' id: '5321b73dc9dc2458c4000196' slug: "govinda-sah-azad-in-between-1", date: "2015", title: "In Between", image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg", partner: { name: "October Gallery", slug: "october-gallery" }, artists: [{ name: "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'", slug: "govinda-sah-azad" }, { name: "PI:NAME:<NAME>END_PI", slug: "andy-warhol" }] },{ type: 'image' url: "http://artsy.net/image.jpg", caption: "<p>Some cool art from 2015</p>", } ] } ] contributing_authors: [] footerArticles: new Articles crop: (url) -> url resize: (u) -> u moment: moment sd: {} asset: -> _s: _s html.should.containEql '/artwork/govinda-sah-azad-in-between-1' html.should.containEql 'http://artsy.net/image.jpg' html.should.containEql '/october-gallery' html.should.containEql "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'" html.should.containEql "PI:NAME:<NAME>END_PI" html.should.containEql '<p>Some cool art from 2015</p>'
[ { "context": "###\n * https://github.com/jkuetemeier/gulp-tasks-common\n *\n * Copyright (c) 2014 Jörg K", "end": 37, "score": 0.9983522295951843, "start": 26, "tag": "USERNAME", "value": "jkuetemeier" }, { "context": "temeier/gulp-tasks-common\n *\n * Copyright (c) 2014 Jörg Kütemeier\n * Licensed under the MIT license.\n###\n\nmodule.ex", "end": 95, "score": 0.9998857975006104, "start": 81, "tag": "NAME", "value": "Jörg Kütemeier" } ]
test/tools/requireuncached.coffee
kuetemeier/gulp-tasks-common
0
### * https://github.com/jkuetemeier/gulp-tasks-common * * Copyright (c) 2014 Jörg Kütemeier * Licensed under the MIT license. ### module.exports = (module) -> delete require.cache[require.resolve(module)] return require module
89941
### * https://github.com/jkuetemeier/gulp-tasks-common * * Copyright (c) 2014 <NAME> * Licensed under the MIT license. ### module.exports = (module) -> delete require.cache[require.resolve(module)] return require module
true
### * https://github.com/jkuetemeier/gulp-tasks-common * * Copyright (c) 2014 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### module.exports = (module) -> delete require.cache[require.resolve(module)] return require module
[ { "context": "9036/ to try it out\n##\n## the password for test is asdf ;-)\n##\n##\n\ntry\n __SECRET = floyd.tools.files.r", "end": 384, "score": 0.9915915727615356, "start": 380, "tag": "PASSWORD", "value": "asdf" }, { "context": "T\n ##\n\n ##\n id: 'test'\n\n ## this method will be protected by", "end": 2044, "score": 0.5662358403205872, "start": 2040, "tag": "USERNAME", "value": "test" } ]
examples/auth/app.coffee
nero-networks/floyd
0
## ## auth demo... ## ## to run this demo successfull the following conditions must be met: ## ## 1. the private folder must be user/group readonly ## try `chmod -R o-rwx ./private` (also done via floyd build) ## ## 2. the whole thing must be started as root ## try `sudo floyd start` ## ## ## navigate to http://locathost:9036/ to try it out ## ## the password for test is asdf ;-) ## ## try __SECRET = floyd.tools.files.read './private/secret.txt' catch e console.warn e.message module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 GID: 33 ## data: port: 9036 debug: true ## bloated scripts and html but faster startup rewrite: '^/((index.html)|(boot.js))?$': '/login/$1' ## some sanity checks on boot and on start. ## and loggings to point you with your nose into ;-) booted: ()-> if process.getuid() isnt 0 @logger.error new Error 'FATAL: you are not root! run sudo floyd start' ## started: -> if _secret = floyd.tools.files.exists './private/secret.txt' @logger.error new Error 'FATAL: the file ./private/secret.txt is readable' if _users = floyd.tools.files.exists './private/users.data' @logger.error new Error 'FATAL: the file ./private/users.data is readable', if _secret then 'too!' else '' if !_secret && !_users @logger.info 'SUCCESS: userdata and secret are protected propperly.' children: [ ## ## configure the users DB to readonly from file ./private/users.data ## ## id: 'users' ## data: readonly: true, debug: false, type: 'file', path: './private', name: 'users' , ## ## add the backend client for protected access to __SECRET ## ## id: 'test' ## this method will be protected by the following permissionset secret: (fn)-> fn null, __SECRET ## permissions: ## the permissionset to be used by Controllable._permitAccess ## only users with the role tester may access the method secret secret: roles: 'tester' , ## ## define a gui context for /login/ (rewritten from "/") ## type: 'gui.HttpContext' ## data: route: '/login/' file: '/index.html' ## remote: ## type: 'dnode.Bridge' ## children: [ ## id: 'login' ## type: 'LoginForm' , ## type: 'gui.ViewContext' ## template: -> button style:'display: none', 'click for secret' ## running: -> @identity.on 'login', ()=> @__root.removeAttr 'style' ## wiring: -> @identity.on 'logout', ()=> @__root.hide() @__root.click => @lookup 'test', @identity, (err, test)-> test.secret (err, secret)-> return alert(err.message) if err alert secret ] ]
130787
## ## auth demo... ## ## to run this demo successfull the following conditions must be met: ## ## 1. the private folder must be user/group readonly ## try `chmod -R o-rwx ./private` (also done via floyd build) ## ## 2. the whole thing must be started as root ## try `sudo floyd start` ## ## ## navigate to http://locathost:9036/ to try it out ## ## the password for test is <PASSWORD> ;-) ## ## try __SECRET = floyd.tools.files.read './private/secret.txt' catch e console.warn e.message module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 GID: 33 ## data: port: 9036 debug: true ## bloated scripts and html but faster startup rewrite: '^/((index.html)|(boot.js))?$': '/login/$1' ## some sanity checks on boot and on start. ## and loggings to point you with your nose into ;-) booted: ()-> if process.getuid() isnt 0 @logger.error new Error 'FATAL: you are not root! run sudo floyd start' ## started: -> if _secret = floyd.tools.files.exists './private/secret.txt' @logger.error new Error 'FATAL: the file ./private/secret.txt is readable' if _users = floyd.tools.files.exists './private/users.data' @logger.error new Error 'FATAL: the file ./private/users.data is readable', if _secret then 'too!' else '' if !_secret && !_users @logger.info 'SUCCESS: userdata and secret are protected propperly.' children: [ ## ## configure the users DB to readonly from file ./private/users.data ## ## id: 'users' ## data: readonly: true, debug: false, type: 'file', path: './private', name: 'users' , ## ## add the backend client for protected access to __SECRET ## ## id: 'test' ## this method will be protected by the following permissionset secret: (fn)-> fn null, __SECRET ## permissions: ## the permissionset to be used by Controllable._permitAccess ## only users with the role tester may access the method secret secret: roles: 'tester' , ## ## define a gui context for /login/ (rewritten from "/") ## type: 'gui.HttpContext' ## data: route: '/login/' file: '/index.html' ## remote: ## type: 'dnode.Bridge' ## children: [ ## id: 'login' ## type: 'LoginForm' , ## type: 'gui.ViewContext' ## template: -> button style:'display: none', 'click for secret' ## running: -> @identity.on 'login', ()=> @__root.removeAttr 'style' ## wiring: -> @identity.on 'logout', ()=> @__root.hide() @__root.click => @lookup 'test', @identity, (err, test)-> test.secret (err, secret)-> return alert(err.message) if err alert secret ] ]
true
## ## auth demo... ## ## to run this demo successfull the following conditions must be met: ## ## 1. the private folder must be user/group readonly ## try `chmod -R o-rwx ./private` (also done via floyd build) ## ## 2. the whole thing must be started as root ## try `sudo floyd start` ## ## ## navigate to http://locathost:9036/ to try it out ## ## the password for test is PI:PASSWORD:<PASSWORD>END_PI ;-) ## ## try __SECRET = floyd.tools.files.read './private/secret.txt' catch e console.warn e.message module.exports = new floyd.Config 'config.gui.server', 'config.dnode.server', UID: 33 GID: 33 ## data: port: 9036 debug: true ## bloated scripts and html but faster startup rewrite: '^/((index.html)|(boot.js))?$': '/login/$1' ## some sanity checks on boot and on start. ## and loggings to point you with your nose into ;-) booted: ()-> if process.getuid() isnt 0 @logger.error new Error 'FATAL: you are not root! run sudo floyd start' ## started: -> if _secret = floyd.tools.files.exists './private/secret.txt' @logger.error new Error 'FATAL: the file ./private/secret.txt is readable' if _users = floyd.tools.files.exists './private/users.data' @logger.error new Error 'FATAL: the file ./private/users.data is readable', if _secret then 'too!' else '' if !_secret && !_users @logger.info 'SUCCESS: userdata and secret are protected propperly.' children: [ ## ## configure the users DB to readonly from file ./private/users.data ## ## id: 'users' ## data: readonly: true, debug: false, type: 'file', path: './private', name: 'users' , ## ## add the backend client for protected access to __SECRET ## ## id: 'test' ## this method will be protected by the following permissionset secret: (fn)-> fn null, __SECRET ## permissions: ## the permissionset to be used by Controllable._permitAccess ## only users with the role tester may access the method secret secret: roles: 'tester' , ## ## define a gui context for /login/ (rewritten from "/") ## type: 'gui.HttpContext' ## data: route: '/login/' file: '/index.html' ## remote: ## type: 'dnode.Bridge' ## children: [ ## id: 'login' ## type: 'LoginForm' , ## type: 'gui.ViewContext' ## template: -> button style:'display: none', 'click for secret' ## running: -> @identity.on 'login', ()=> @__root.removeAttr 'style' ## wiring: -> @identity.on 'logout', ()=> @__root.hide() @__root.click => @lookup 'test', @identity, (err, test)-> test.secret (err, secret)-> return alert(err.message) if err alert secret ] ]
[ { "context": "ions module unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\nTest.set \"/m", "end": 97, "score": 0.9998873472213745, "start": 80, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/test/element/manipulation_test.coffee
lovely-io/lovely.io-stl
2
# # The Element dom-manipulations module unit tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # {Test,should} = require('lovely') Test.set "/manipulations.html": """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test"></div> </body> </html> """ describe "Element Manipulations", -> $ = element = window = document = null beforeEach Test.load '/manipulations.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#clone()", -> it "should clone content and attributes", -> element._.innerHTML = "bla <b>bla</b> bla" clone = element.clone() clone._.innerHTML.should.eql element._.innerHTML clone._.id.should.eql element._.id it "should create a new instance of Element", -> element.clone().should.be.instanceOf $.Element it "should attach a new dom-element in it", -> element.clone()._.should.not.equal element._ describe "#clear()", -> it "should remove all the child elements", -> element._.innerHTML = 'some <b>content</b>' element.clear() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.clear().should.equal element describe "#empty()", -> it "should say 'true' for an empty element", -> element._.innerHTML = '' element.empty().should.be.true it "should say 'true' for an element with spaces only", -> element._.innerHTML = " \n\t\n " element.empty().should.be.true it "should say 'false' for an element with actual content", -> element._.innerHTML = '0' element.empty().should.be.false describe "#html()", -> it "should return the element's innerHTML", -> element._.innerHTML = 'some <b>content</b>' element.html().should.equal 'some <b>content</b>' describe "#html('content')", -> it "should assign the new content", -> element.html('some <b>new</b> content') element._.innerHTML.should.equal 'some <b>new</b> content' it "should return element itself back", -> element.html('boo hoo').should.equal element describe "#text()", -> it "should return the element's content as a text", -> element._.innerHTML = 'some <b>inner <u>text</u></b>' element.text().should.equal 'some inner text' it "should convert HTML escapees into normal chars", -> element._.innerHTML = 'Beevis &amp; Butthead' element.text().should.equal 'Beevis & Butthead' describe "#text('content')", -> it "should assign the text and escape special chars", -> element.text('<b>Beevis</b> & <u>Butthead</u>') element._.innerHTML.should.equal '&lt;b&gt;Beevis&lt;/b&gt; &amp; &lt;u&gt;Butthead&lt;/u&gt;' it "should return the element itself back", -> element.text('boo hoo').should.equal element describe "#remove()", -> it "should remove the element out of it's parent element", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' element._.appendChild(dummy._) dummy.remove() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.remove().should.equal element describe "#replace('some content')", -> it "should replace itself with a given content", -> dummy = new $.Element('div', html: 'dummy') element.clear()._.appendChild(dummy._) result = dummy.replace('some text') element._.innerHTML.should.equal 'some text' result.should.equal dummy describe "#update(...)", -> it "should replace all the element's content", -> element._.innerHTML = 'old content' element.update('new content') element._.innerHTML.should.equal 'new content' it "should accept dom-wrappers as an argument", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy._) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.update([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept numbers as values", -> element.update 888 element._.innerHTML.should.equal '888' it "should eval any embedded scripts", -> element.update """ bla bla bla <script>var test1 = 'test-1'</script> trololo <script type="text/javascript"> var test2 = 'test-2'; </script> it """ window.test1.should.equal 'test-1' window.test2.should.equal 'test-2' it "should cut out all the scripts when it updates an element", -> element.update """ bla bla bla <script> //<![CDATA[ Lovely(['dom'], function($) { $('#opinions a.add').emit('click'); }); //]]> </script> """ element._.innerHTML.should.equal """ bla bla bla """ it "should return the element itself back", -> element.update('text').should.equal element describe "#append(item, item, item)", -> it "should append elements to the end", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '<b>boo</b>' element.append dummy, new $.Element('div', html: 'new') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div><div>new</div>' it "should append strings to the end", -> element._.innerHTML = '<b>boo</b>' element.append '<i>eee</i>', '<u>uuu</u>' element._.innerHTML.should.equal '<b>boo</b><i>eee</i><u>uuu</u>' describe "#insertTo(...)", -> it "should insert it into the specified elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element._) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into elements by '#element-id'", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo('#test') element._.innerHTML.should.equal '<div>dummy</div>' it "should return the element itself back", -> dummy = new $.Element('div', html: 'dummy') dummy.insertTo('#test').should.be.equal dummy describe "#insert(...)", -> it "should insert dom-wrappers", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert plain html content", -> element.clear().insert('<b>dummy</b>') element._.innerHTML.should.equal '<b>dummy</b>' it "should insert numerical data", -> element.clear().insert 4.44 element._.innerHTML.should.equal '4.44' it "should return element itself back", -> element.insert('something').should.equal element it "should allow insert on top of the elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = "<b>boo</b>" element.insert(dummy, 'top') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert an element before another", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'before') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div>' it "should allow to insert things after the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'after') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert things instead of the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'instead') element._.innerHTML.should.equal '<b>boo</b>'
36023
# # The Element dom-manipulations module unit tests # # Copyright (C) 2011-2013 <NAME> # {Test,should} = require('lovely') Test.set "/manipulations.html": """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test"></div> </body> </html> """ describe "Element Manipulations", -> $ = element = window = document = null beforeEach Test.load '/manipulations.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#clone()", -> it "should clone content and attributes", -> element._.innerHTML = "bla <b>bla</b> bla" clone = element.clone() clone._.innerHTML.should.eql element._.innerHTML clone._.id.should.eql element._.id it "should create a new instance of Element", -> element.clone().should.be.instanceOf $.Element it "should attach a new dom-element in it", -> element.clone()._.should.not.equal element._ describe "#clear()", -> it "should remove all the child elements", -> element._.innerHTML = 'some <b>content</b>' element.clear() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.clear().should.equal element describe "#empty()", -> it "should say 'true' for an empty element", -> element._.innerHTML = '' element.empty().should.be.true it "should say 'true' for an element with spaces only", -> element._.innerHTML = " \n\t\n " element.empty().should.be.true it "should say 'false' for an element with actual content", -> element._.innerHTML = '0' element.empty().should.be.false describe "#html()", -> it "should return the element's innerHTML", -> element._.innerHTML = 'some <b>content</b>' element.html().should.equal 'some <b>content</b>' describe "#html('content')", -> it "should assign the new content", -> element.html('some <b>new</b> content') element._.innerHTML.should.equal 'some <b>new</b> content' it "should return element itself back", -> element.html('boo hoo').should.equal element describe "#text()", -> it "should return the element's content as a text", -> element._.innerHTML = 'some <b>inner <u>text</u></b>' element.text().should.equal 'some inner text' it "should convert HTML escapees into normal chars", -> element._.innerHTML = 'Beevis &amp; Butthead' element.text().should.equal 'Beevis & Butthead' describe "#text('content')", -> it "should assign the text and escape special chars", -> element.text('<b>Beevis</b> & <u>Butthead</u>') element._.innerHTML.should.equal '&lt;b&gt;Beevis&lt;/b&gt; &amp; &lt;u&gt;Butthead&lt;/u&gt;' it "should return the element itself back", -> element.text('boo hoo').should.equal element describe "#remove()", -> it "should remove the element out of it's parent element", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' element._.appendChild(dummy._) dummy.remove() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.remove().should.equal element describe "#replace('some content')", -> it "should replace itself with a given content", -> dummy = new $.Element('div', html: 'dummy') element.clear()._.appendChild(dummy._) result = dummy.replace('some text') element._.innerHTML.should.equal 'some text' result.should.equal dummy describe "#update(...)", -> it "should replace all the element's content", -> element._.innerHTML = 'old content' element.update('new content') element._.innerHTML.should.equal 'new content' it "should accept dom-wrappers as an argument", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy._) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.update([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept numbers as values", -> element.update 888 element._.innerHTML.should.equal '888' it "should eval any embedded scripts", -> element.update """ bla bla bla <script>var test1 = 'test-1'</script> trololo <script type="text/javascript"> var test2 = 'test-2'; </script> it """ window.test1.should.equal 'test-1' window.test2.should.equal 'test-2' it "should cut out all the scripts when it updates an element", -> element.update """ bla bla bla <script> //<![CDATA[ Lovely(['dom'], function($) { $('#opinions a.add').emit('click'); }); //]]> </script> """ element._.innerHTML.should.equal """ bla bla bla """ it "should return the element itself back", -> element.update('text').should.equal element describe "#append(item, item, item)", -> it "should append elements to the end", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '<b>boo</b>' element.append dummy, new $.Element('div', html: 'new') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div><div>new</div>' it "should append strings to the end", -> element._.innerHTML = '<b>boo</b>' element.append '<i>eee</i>', '<u>uuu</u>' element._.innerHTML.should.equal '<b>boo</b><i>eee</i><u>uuu</u>' describe "#insertTo(...)", -> it "should insert it into the specified elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element._) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into elements by '#element-id'", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo('#test') element._.innerHTML.should.equal '<div>dummy</div>' it "should return the element itself back", -> dummy = new $.Element('div', html: 'dummy') dummy.insertTo('#test').should.be.equal dummy describe "#insert(...)", -> it "should insert dom-wrappers", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert plain html content", -> element.clear().insert('<b>dummy</b>') element._.innerHTML.should.equal '<b>dummy</b>' it "should insert numerical data", -> element.clear().insert 4.44 element._.innerHTML.should.equal '4.44' it "should return element itself back", -> element.insert('something').should.equal element it "should allow insert on top of the elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = "<b>boo</b>" element.insert(dummy, 'top') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert an element before another", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'before') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div>' it "should allow to insert things after the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'after') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert things instead of the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'instead') element._.innerHTML.should.equal '<b>boo</b>'
true
# # The Element dom-manipulations module unit tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # {Test,should} = require('lovely') Test.set "/manipulations.html": """ <html> <head> <script src="/core.js"></script> <script src="/dom.js"></script> </head> <body> <div id="test"></div> </body> </html> """ describe "Element Manipulations", -> $ = element = window = document = null beforeEach Test.load '/manipulations.html', (dom, win)-> $ = dom window = win document = win.document element = new $.Element(document.getElementById('test')) describe "#clone()", -> it "should clone content and attributes", -> element._.innerHTML = "bla <b>bla</b> bla" clone = element.clone() clone._.innerHTML.should.eql element._.innerHTML clone._.id.should.eql element._.id it "should create a new instance of Element", -> element.clone().should.be.instanceOf $.Element it "should attach a new dom-element in it", -> element.clone()._.should.not.equal element._ describe "#clear()", -> it "should remove all the child elements", -> element._.innerHTML = 'some <b>content</b>' element.clear() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.clear().should.equal element describe "#empty()", -> it "should say 'true' for an empty element", -> element._.innerHTML = '' element.empty().should.be.true it "should say 'true' for an element with spaces only", -> element._.innerHTML = " \n\t\n " element.empty().should.be.true it "should say 'false' for an element with actual content", -> element._.innerHTML = '0' element.empty().should.be.false describe "#html()", -> it "should return the element's innerHTML", -> element._.innerHTML = 'some <b>content</b>' element.html().should.equal 'some <b>content</b>' describe "#html('content')", -> it "should assign the new content", -> element.html('some <b>new</b> content') element._.innerHTML.should.equal 'some <b>new</b> content' it "should return element itself back", -> element.html('boo hoo').should.equal element describe "#text()", -> it "should return the element's content as a text", -> element._.innerHTML = 'some <b>inner <u>text</u></b>' element.text().should.equal 'some inner text' it "should convert HTML escapees into normal chars", -> element._.innerHTML = 'Beevis &amp; Butthead' element.text().should.equal 'Beevis & Butthead' describe "#text('content')", -> it "should assign the text and escape special chars", -> element.text('<b>Beevis</b> & <u>Butthead</u>') element._.innerHTML.should.equal '&lt;b&gt;Beevis&lt;/b&gt; &amp; &lt;u&gt;Butthead&lt;/u&gt;' it "should return the element itself back", -> element.text('boo hoo').should.equal element describe "#remove()", -> it "should remove the element out of it's parent element", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' element._.appendChild(dummy._) dummy.remove() element._.innerHTML.should.equal '' it "should return the element itself back", -> element.remove().should.equal element describe "#replace('some content')", -> it "should replace itself with a given content", -> dummy = new $.Element('div', html: 'dummy') element.clear()._.appendChild(dummy._) result = dummy.replace('some text') element._.innerHTML.should.equal 'some text' result.should.equal dummy describe "#update(...)", -> it "should replace all the element's content", -> element._.innerHTML = 'old content' element.update('new content') element._.innerHTML.should.equal 'new content' it "should accept dom-wrappers as an argument", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.update(dummy._) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.update([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should accept numbers as values", -> element.update 888 element._.innerHTML.should.equal '888' it "should eval any embedded scripts", -> element.update """ bla bla bla <script>var test1 = 'test-1'</script> trololo <script type="text/javascript"> var test2 = 'test-2'; </script> it """ window.test1.should.equal 'test-1' window.test2.should.equal 'test-2' it "should cut out all the scripts when it updates an element", -> element.update """ bla bla bla <script> //<![CDATA[ Lovely(['dom'], function($) { $('#opinions a.add').emit('click'); }); //]]> </script> """ element._.innerHTML.should.equal """ bla bla bla """ it "should return the element itself back", -> element.update('text').should.equal element describe "#append(item, item, item)", -> it "should append elements to the end", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '<b>boo</b>' element.append dummy, new $.Element('div', html: 'new') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div><div>new</div>' it "should append strings to the end", -> element._.innerHTML = '<b>boo</b>' element.append '<i>eee</i>', '<u>uuu</u>' element._.innerHTML.should.equal '<b>boo</b><i>eee</i><u>uuu</u>' describe "#insertTo(...)", -> it "should insert it into the specified elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo(element._) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert it into elements by '#element-id'", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = '' dummy.insertTo('#test') element._.innerHTML.should.equal '<div>dummy</div>' it "should return the element itself back", -> dummy = new $.Element('div', html: 'dummy') dummy.insertTo('#test').should.be.equal dummy describe "#insert(...)", -> it "should insert dom-wrappers", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert raw dom-elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert arrays of elements", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert([dummy]) element._.innerHTML.should.equal '<div>dummy</div>' it "should insert plain html content", -> element.clear().insert('<b>dummy</b>') element._.innerHTML.should.equal '<b>dummy</b>' it "should insert numerical data", -> element.clear().insert 4.44 element._.innerHTML.should.equal '4.44' it "should return element itself back", -> element.insert('something').should.equal element it "should allow insert on top of the elements", -> dummy = new $.Element('div', html: 'dummy') element._.innerHTML = "<b>boo</b>" element.insert(dummy, 'top') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert an element before another", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'before') element._.innerHTML.should.equal '<b>boo</b><div>dummy</div>' it "should allow to insert things after the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'after') element._.innerHTML.should.equal '<div>dummy</div><b>boo</b>' it "should allow to insert things instead of the element", -> dummy = new $.Element('div', html: 'dummy') element.clear().insert(dummy) dummy.insert(new $.Element('b', html: 'boo'), 'instead') element._.innerHTML.should.equal '<b>boo</b>'
[ { "context": " =\n region: 'fakeRegion'\n accessKeyId: 'fakeAccessKeyId'\n secretAccessKey: 'fakeSecretAccessKey'\n ", "end": 903, "score": 0.9601938724517822, "start": 888, "tag": "KEY", "value": "fakeAccessKeyId" }, { "context": "sKeyId: 'fakeAccessKeyId'\n secretAccessKey: 'fakeSecretAccessKey'\n domain: 'fakeDomain'\n name: 'fakeWork", "end": 948, "score": 0.9690998196601868, "start": 929, "tag": "KEY", "value": "fakeSecretAccessKey" }, { "context": "\n beforeEach ->\n expectedToken = 'fakeToken'\n\n expectedInput =\n someKey: ", "end": 6924, "score": 0.9014980792999268, "start": 6915, "tag": "KEY", "value": "fakeToken" } ]
test/fulfillmentWorker.unit.coffee
balihoo/node-fulfillment-worker
0
'use strict' assert = require 'assert' aws = require 'aws-sdk' sinon = require 'sinon' Promise = require 'bluebird' FulfillmentWorker = require '../lib/fulfillmentWorker' activityStatus = require '../lib/activityStatus' error = require '../lib/error' mockDynamoDB = require './mocks/mockDynamoDB' mockSWF = require './mocks/mockSWF' mockSQS = require './mocks/mockSQS' config = undefined testRequiresConfigParameter = (config, propName) -> delete config[propName] try new FulfillmentWorker config assert.fail 'Expected a ConfigurationMissingError.' catch err assert err instanceof error.ConfigurationMissingError assert.deepEqual err.missingProperties, [propName] return fakeLogger = log: -> info: -> debug: -> warn: -> error: -> describe 'FulfillmentWorker unit tests', -> beforeEach -> config = region: 'fakeRegion' accessKeyId: 'fakeAccessKeyId' secretAccessKey: 'fakeSecretAccessKey' domain: 'fakeDomain' name: 'fakeWorkerName' version: 'fakeWorkerVersion' defaultTaskHeartbeatTimeout: 4000 defaultTaskScheduleToCloseTimeout: 400 defaultTaskScheduleToStartTimeout: 700 defaultTaskStartToCloseTimeout: 4700 workerStatusQueueName: "workerStatusTestQueue" updateIntervalMs: 1000 parameterSchema: {} resultSchema: {} logger: fakeLogger describe 'constructor', -> beforeEach -> sinon.stub aws, 'SQS', mockSQS afterEach -> aws.SQS.restore() it 'Requires a config', -> try new FulfillmentWorker() assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'undefined' it 'Requires that the config be an object', -> try new FulfillmentWorker('not an object') assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'string' it 'Requires config.region', -> testRequiresConfigParameter config, 'region' it 'Requires config.domain', -> testRequiresConfigParameter config, 'domain' it 'Requires config.workerName', -> testRequiresConfigParameter config, 'name' it 'Requires config.workerVersion', -> testRequiresConfigParameter config, 'version' context 'When a logger is supplied', -> it 'Uses the supplied logger', -> worker = new FulfillmentWorker config assert.strictEqual worker.logger, fakeLogger context 'When a logger is not supplied', -> it 'Uses console', -> delete config.logger worker = new FulfillmentWorker config assert.strictEqual worker.logger, console it 'Adds an API version to config', -> new FulfillmentWorker(config) assert.ok config.apiVersion assert typeof config.apiVersion is 'string' it 'Creates an instance ID', -> worker = new FulfillmentWorker(config) assert.ok worker.uuid assert typeof worker.uuid is 'string' it 'Creates an AWS SWF instance', -> sinon.stub aws, 'SWF', mockSWF worker = new FulfillmentWorker(config) expectedConfig = accessKeyId: config.accessKeyId secretAccessKey: config.secretAccessKey apiVersion: config.apiVersion region: config.region params: domain: config.domain name: config.name version: config.version assert aws.SWF.calledOnce assert.deepEqual expectedConfig, worker.swfAdapter.swf.config aws.SWF.restore() describe 'workAsync', -> worker = null beforeEach -> sinon.stub aws, 'DynamoDB', mockDynamoDB sinon.stub aws, 'SWF', mockSWF sinon.stub aws, 'SQS', mockSQS worker = new FulfillmentWorker(config) context 'prior to polling for work', -> it 'checks for an existing ActivityType', (done) -> expectedParams = activityType: name: config.name version: config.version worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.describeActivityType.calledOnce assert worker.swfAdapter.swf.describeActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when the activity type is not found', -> it 'registers the activity type', (done) -> expectedParams = defaultTaskHeartbeatTimeout: config.defaultTaskHeartbeatTimeout defaultTaskScheduleToCloseTimeout: config.defaultTaskScheduleToCloseTimeout defaultTaskScheduleToStartTimeout: config.defaultTaskScheduleToStartTimeout defaultTaskStartToCloseTimeout: config.defaultTaskStartToCloseTimeout worker.swfAdapter.swf.describeActivityType = sinon.spy -> err = Error('Loud noises!') err.cause = code: 'UnknownResourceFault' throw err worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.registerActivityType.calledOnce assert worker.swfAdapter.swf.registerActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when an error other than UnknownResourceFault occurs', -> it 'rejects the promise with the error', (done) -> fakeError = new Error('Loud noises!') worker.swfAdapter.swf.describeActivityType = sinon.spy -> throw fakeError promise = worker.workAsync -> {} promise .catch (err) -> assert.strictEqual fakeError, err done() context 'when polling for work', -> it 'uses worker name + version as the task list', (done) -> expectedParams = taskList: name: config.name + config.version worker.swfAdapter.swf.pollForActivityTask = sinon.spy (params) -> assert.deepEqual(expectedParams, params) worker.stop() .then -> done() worker.workAsync -> {} context 'when there is no work to be done', -> it 'polls again', (done) -> callCount = 0 worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callCount++ if callCount == 2 worker.stop() .then -> done() callback null, {} worker.workAsync -> {} context 'when there is work to be done', -> expectedInput = null expectedToken = null expectedResult = null expectedSwfResult = null err = null beforeEach -> expectedToken = 'fakeToken' expectedInput = someKey: 'someValue' anotherKey: aSubKey: 1 expectedResult = something: 'weeeee!' somethingElse: 5 expectedSwfResult = status: activityStatus.success result: expectedResult fakeTask = taskToken: expectedToken input: JSON.stringify expectedInput errorDetails = 'Some extra error details' err = new Error('Loud noises!') err.details = errorDetails worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callback null, fakeTask it 'invokes the provided worker function with the task input', (done) -> worker.workAsync (input) -> assert.deepEqual expectedInput, input worker.stop() .then -> done() context 'when the worker function returns a result', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual expectedToken, params.taskToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return expectedResult context 'when the worker function returns a promise that resolves', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual params.taskToken, expectedToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.resolve expectedResult context 'when the worker function returns a promise that rejects', -> it 'fails the task and logs the details of the failure', (done) -> sinon.stub fakeLogger, 'error', (e) -> assert.strictEqual e, err assert.strictEqual err.workerName, config.name assert.strictEqual err.workerVersion, config.version expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> assert fakeLogger.error.calledOnce fakeLogger.error.restore() done() worker.workAsync -> return Promise.reject err context 'when the worker function returns a promise that rejects with a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject failTaskError context 'when the worker returns a promise which rejects with a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject cancelTaskError context 'when the worker function throws an error', -> it 'fails the task', (done) -> expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw err context 'when the worker function throws a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw failTaskError context 'when the worker function throws a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw cancelTaskError afterEach -> aws.DynamoDB.restore() aws.SWF.restore() aws.SQS.restore()
73552
'use strict' assert = require 'assert' aws = require 'aws-sdk' sinon = require 'sinon' Promise = require 'bluebird' FulfillmentWorker = require '../lib/fulfillmentWorker' activityStatus = require '../lib/activityStatus' error = require '../lib/error' mockDynamoDB = require './mocks/mockDynamoDB' mockSWF = require './mocks/mockSWF' mockSQS = require './mocks/mockSQS' config = undefined testRequiresConfigParameter = (config, propName) -> delete config[propName] try new FulfillmentWorker config assert.fail 'Expected a ConfigurationMissingError.' catch err assert err instanceof error.ConfigurationMissingError assert.deepEqual err.missingProperties, [propName] return fakeLogger = log: -> info: -> debug: -> warn: -> error: -> describe 'FulfillmentWorker unit tests', -> beforeEach -> config = region: 'fakeRegion' accessKeyId: '<KEY>' secretAccessKey: '<KEY>' domain: 'fakeDomain' name: 'fakeWorkerName' version: 'fakeWorkerVersion' defaultTaskHeartbeatTimeout: 4000 defaultTaskScheduleToCloseTimeout: 400 defaultTaskScheduleToStartTimeout: 700 defaultTaskStartToCloseTimeout: 4700 workerStatusQueueName: "workerStatusTestQueue" updateIntervalMs: 1000 parameterSchema: {} resultSchema: {} logger: fakeLogger describe 'constructor', -> beforeEach -> sinon.stub aws, 'SQS', mockSQS afterEach -> aws.SQS.restore() it 'Requires a config', -> try new FulfillmentWorker() assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'undefined' it 'Requires that the config be an object', -> try new FulfillmentWorker('not an object') assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'string' it 'Requires config.region', -> testRequiresConfigParameter config, 'region' it 'Requires config.domain', -> testRequiresConfigParameter config, 'domain' it 'Requires config.workerName', -> testRequiresConfigParameter config, 'name' it 'Requires config.workerVersion', -> testRequiresConfigParameter config, 'version' context 'When a logger is supplied', -> it 'Uses the supplied logger', -> worker = new FulfillmentWorker config assert.strictEqual worker.logger, fakeLogger context 'When a logger is not supplied', -> it 'Uses console', -> delete config.logger worker = new FulfillmentWorker config assert.strictEqual worker.logger, console it 'Adds an API version to config', -> new FulfillmentWorker(config) assert.ok config.apiVersion assert typeof config.apiVersion is 'string' it 'Creates an instance ID', -> worker = new FulfillmentWorker(config) assert.ok worker.uuid assert typeof worker.uuid is 'string' it 'Creates an AWS SWF instance', -> sinon.stub aws, 'SWF', mockSWF worker = new FulfillmentWorker(config) expectedConfig = accessKeyId: config.accessKeyId secretAccessKey: config.secretAccessKey apiVersion: config.apiVersion region: config.region params: domain: config.domain name: config.name version: config.version assert aws.SWF.calledOnce assert.deepEqual expectedConfig, worker.swfAdapter.swf.config aws.SWF.restore() describe 'workAsync', -> worker = null beforeEach -> sinon.stub aws, 'DynamoDB', mockDynamoDB sinon.stub aws, 'SWF', mockSWF sinon.stub aws, 'SQS', mockSQS worker = new FulfillmentWorker(config) context 'prior to polling for work', -> it 'checks for an existing ActivityType', (done) -> expectedParams = activityType: name: config.name version: config.version worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.describeActivityType.calledOnce assert worker.swfAdapter.swf.describeActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when the activity type is not found', -> it 'registers the activity type', (done) -> expectedParams = defaultTaskHeartbeatTimeout: config.defaultTaskHeartbeatTimeout defaultTaskScheduleToCloseTimeout: config.defaultTaskScheduleToCloseTimeout defaultTaskScheduleToStartTimeout: config.defaultTaskScheduleToStartTimeout defaultTaskStartToCloseTimeout: config.defaultTaskStartToCloseTimeout worker.swfAdapter.swf.describeActivityType = sinon.spy -> err = Error('Loud noises!') err.cause = code: 'UnknownResourceFault' throw err worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.registerActivityType.calledOnce assert worker.swfAdapter.swf.registerActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when an error other than UnknownResourceFault occurs', -> it 'rejects the promise with the error', (done) -> fakeError = new Error('Loud noises!') worker.swfAdapter.swf.describeActivityType = sinon.spy -> throw fakeError promise = worker.workAsync -> {} promise .catch (err) -> assert.strictEqual fakeError, err done() context 'when polling for work', -> it 'uses worker name + version as the task list', (done) -> expectedParams = taskList: name: config.name + config.version worker.swfAdapter.swf.pollForActivityTask = sinon.spy (params) -> assert.deepEqual(expectedParams, params) worker.stop() .then -> done() worker.workAsync -> {} context 'when there is no work to be done', -> it 'polls again', (done) -> callCount = 0 worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callCount++ if callCount == 2 worker.stop() .then -> done() callback null, {} worker.workAsync -> {} context 'when there is work to be done', -> expectedInput = null expectedToken = null expectedResult = null expectedSwfResult = null err = null beforeEach -> expectedToken = '<KEY>' expectedInput = someKey: 'someValue' anotherKey: aSubKey: 1 expectedResult = something: 'weeeee!' somethingElse: 5 expectedSwfResult = status: activityStatus.success result: expectedResult fakeTask = taskToken: expectedToken input: JSON.stringify expectedInput errorDetails = 'Some extra error details' err = new Error('Loud noises!') err.details = errorDetails worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callback null, fakeTask it 'invokes the provided worker function with the task input', (done) -> worker.workAsync (input) -> assert.deepEqual expectedInput, input worker.stop() .then -> done() context 'when the worker function returns a result', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual expectedToken, params.taskToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return expectedResult context 'when the worker function returns a promise that resolves', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual params.taskToken, expectedToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.resolve expectedResult context 'when the worker function returns a promise that rejects', -> it 'fails the task and logs the details of the failure', (done) -> sinon.stub fakeLogger, 'error', (e) -> assert.strictEqual e, err assert.strictEqual err.workerName, config.name assert.strictEqual err.workerVersion, config.version expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> assert fakeLogger.error.calledOnce fakeLogger.error.restore() done() worker.workAsync -> return Promise.reject err context 'when the worker function returns a promise that rejects with a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject failTaskError context 'when the worker returns a promise which rejects with a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject cancelTaskError context 'when the worker function throws an error', -> it 'fails the task', (done) -> expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw err context 'when the worker function throws a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw failTaskError context 'when the worker function throws a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw cancelTaskError afterEach -> aws.DynamoDB.restore() aws.SWF.restore() aws.SQS.restore()
true
'use strict' assert = require 'assert' aws = require 'aws-sdk' sinon = require 'sinon' Promise = require 'bluebird' FulfillmentWorker = require '../lib/fulfillmentWorker' activityStatus = require '../lib/activityStatus' error = require '../lib/error' mockDynamoDB = require './mocks/mockDynamoDB' mockSWF = require './mocks/mockSWF' mockSQS = require './mocks/mockSQS' config = undefined testRequiresConfigParameter = (config, propName) -> delete config[propName] try new FulfillmentWorker config assert.fail 'Expected a ConfigurationMissingError.' catch err assert err instanceof error.ConfigurationMissingError assert.deepEqual err.missingProperties, [propName] return fakeLogger = log: -> info: -> debug: -> warn: -> error: -> describe 'FulfillmentWorker unit tests', -> beforeEach -> config = region: 'fakeRegion' accessKeyId: 'PI:KEY:<KEY>END_PI' secretAccessKey: 'PI:KEY:<KEY>END_PI' domain: 'fakeDomain' name: 'fakeWorkerName' version: 'fakeWorkerVersion' defaultTaskHeartbeatTimeout: 4000 defaultTaskScheduleToCloseTimeout: 400 defaultTaskScheduleToStartTimeout: 700 defaultTaskStartToCloseTimeout: 4700 workerStatusQueueName: "workerStatusTestQueue" updateIntervalMs: 1000 parameterSchema: {} resultSchema: {} logger: fakeLogger describe 'constructor', -> beforeEach -> sinon.stub aws, 'SQS', mockSQS afterEach -> aws.SQS.restore() it 'Requires a config', -> try new FulfillmentWorker() assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'undefined' it 'Requires that the config be an object', -> try new FulfillmentWorker('not an object') assert.fail 'Expected a ConfigurationMustBeObjectError.' catch err assert err instanceof error.ConfigurationMustBeObjectError assert.strictEqual err.suppliedType, 'string' it 'Requires config.region', -> testRequiresConfigParameter config, 'region' it 'Requires config.domain', -> testRequiresConfigParameter config, 'domain' it 'Requires config.workerName', -> testRequiresConfigParameter config, 'name' it 'Requires config.workerVersion', -> testRequiresConfigParameter config, 'version' context 'When a logger is supplied', -> it 'Uses the supplied logger', -> worker = new FulfillmentWorker config assert.strictEqual worker.logger, fakeLogger context 'When a logger is not supplied', -> it 'Uses console', -> delete config.logger worker = new FulfillmentWorker config assert.strictEqual worker.logger, console it 'Adds an API version to config', -> new FulfillmentWorker(config) assert.ok config.apiVersion assert typeof config.apiVersion is 'string' it 'Creates an instance ID', -> worker = new FulfillmentWorker(config) assert.ok worker.uuid assert typeof worker.uuid is 'string' it 'Creates an AWS SWF instance', -> sinon.stub aws, 'SWF', mockSWF worker = new FulfillmentWorker(config) expectedConfig = accessKeyId: config.accessKeyId secretAccessKey: config.secretAccessKey apiVersion: config.apiVersion region: config.region params: domain: config.domain name: config.name version: config.version assert aws.SWF.calledOnce assert.deepEqual expectedConfig, worker.swfAdapter.swf.config aws.SWF.restore() describe 'workAsync', -> worker = null beforeEach -> sinon.stub aws, 'DynamoDB', mockDynamoDB sinon.stub aws, 'SWF', mockSWF sinon.stub aws, 'SQS', mockSQS worker = new FulfillmentWorker(config) context 'prior to polling for work', -> it 'checks for an existing ActivityType', (done) -> expectedParams = activityType: name: config.name version: config.version worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.describeActivityType.calledOnce assert worker.swfAdapter.swf.describeActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when the activity type is not found', -> it 'registers the activity type', (done) -> expectedParams = defaultTaskHeartbeatTimeout: config.defaultTaskHeartbeatTimeout defaultTaskScheduleToCloseTimeout: config.defaultTaskScheduleToCloseTimeout defaultTaskScheduleToStartTimeout: config.defaultTaskScheduleToStartTimeout defaultTaskStartToCloseTimeout: config.defaultTaskStartToCloseTimeout worker.swfAdapter.swf.describeActivityType = sinon.spy -> err = Error('Loud noises!') err.cause = code: 'UnknownResourceFault' throw err worker.swfAdapter.swf.pollForActivityTask = -> assert worker.swfAdapter.swf.registerActivityType.calledOnce assert worker.swfAdapter.swf.registerActivityType.calledWith expectedParams worker.stop() .then -> done() worker.workAsync -> {} context 'when an error other than UnknownResourceFault occurs', -> it 'rejects the promise with the error', (done) -> fakeError = new Error('Loud noises!') worker.swfAdapter.swf.describeActivityType = sinon.spy -> throw fakeError promise = worker.workAsync -> {} promise .catch (err) -> assert.strictEqual fakeError, err done() context 'when polling for work', -> it 'uses worker name + version as the task list', (done) -> expectedParams = taskList: name: config.name + config.version worker.swfAdapter.swf.pollForActivityTask = sinon.spy (params) -> assert.deepEqual(expectedParams, params) worker.stop() .then -> done() worker.workAsync -> {} context 'when there is no work to be done', -> it 'polls again', (done) -> callCount = 0 worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callCount++ if callCount == 2 worker.stop() .then -> done() callback null, {} worker.workAsync -> {} context 'when there is work to be done', -> expectedInput = null expectedToken = null expectedResult = null expectedSwfResult = null err = null beforeEach -> expectedToken = 'PI:KEY:<KEY>END_PI' expectedInput = someKey: 'someValue' anotherKey: aSubKey: 1 expectedResult = something: 'weeeee!' somethingElse: 5 expectedSwfResult = status: activityStatus.success result: expectedResult fakeTask = taskToken: expectedToken input: JSON.stringify expectedInput errorDetails = 'Some extra error details' err = new Error('Loud noises!') err.details = errorDetails worker.swfAdapter.swf.pollForActivityTask = (params, callback) -> callback null, fakeTask it 'invokes the provided worker function with the task input', (done) -> worker.workAsync (input) -> assert.deepEqual expectedInput, input worker.stop() .then -> done() context 'when the worker function returns a result', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual expectedToken, params.taskToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return expectedResult context 'when the worker function returns a promise that resolves', -> it 'returns the result to simple workflow', (done) -> worker.swfAdapter.swf.respondActivityTaskCompleted = (params) -> assert.strictEqual params.taskToken, expectedToken assert.strictEqual params.result, JSON.stringify expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.resolve expectedResult context 'when the worker function returns a promise that rejects', -> it 'fails the task and logs the details of the failure', (done) -> sinon.stub fakeLogger, 'error', (e) -> assert.strictEqual e, err assert.strictEqual err.workerName, config.name assert.strictEqual err.workerVersion, config.version expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> assert fakeLogger.error.calledOnce fakeLogger.error.restore() done() worker.workAsync -> return Promise.reject err context 'when the worker function returns a promise that rejects with a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject failTaskError context 'when the worker returns a promise which rejects with a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> return Promise.reject cancelTaskError context 'when the worker function throws an error', -> it 'fails the task', (done) -> expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.error notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw err context 'when the worker function throws a FailTaskError', -> it 'fails the task', (done) -> failTaskError = new error.FailTaskError err.message, err.details, err.stack expectedSwfResult = taskToken: expectedToken reason: '' details: JSON.stringify status: activityStatus.fatal notes: [] reason: err.message result: err.message trace: err.stack.split "\n" worker.swfAdapter.swf.respondActivityTaskFailed = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw failTaskError context 'when the worker function throws a CancelTaskError', -> it 'cancels the task', (done) -> cancelTaskError = new error.CancelTaskError err.message, err.details expectedSwfResult = taskToken: expectedToken details: JSON.stringify status: activityStatus.defer notes: [] reason: err.message result: err.message trace: [] worker.swfAdapter.swf.respondActivityTaskCanceled = (params) -> assert.deepEqual params, expectedSwfResult worker.stop() .then -> done() worker.workAsync -> throw cancelTaskError afterEach -> aws.DynamoDB.restore() aws.SWF.restore() aws.SQS.restore()
[ { "context": "ow).scrollTop(scrollKeys[i])\n\t\t\t)(i)\n\t\tkeyMap[\"Cmd-D\"] = \"download\"\n\t\tkeyMap[\"Shift-Cmd-N\"] = \"findNex", "end": 1216, "score": 0.9422038793563843, "start": 1215, "tag": "KEY", "value": "D" }, { "context": "llTop(scrollKeys[i])\n\t\t\t)(i)\n\t\tkeyMap[\"Cmd-D\"] = \"download\"\n\t\tkeyMap[\"Shift-Cmd-N\"] = \"findNext\"\n\t\tkeyMap[\"S", "end": 1230, "score": 0.5586075186729431, "start": 1222, "tag": "KEY", "value": "download" }, { "context": "\n\t\t\t)(i)\n\t\tkeyMap[\"Cmd-D\"] = \"download\"\n\t\tkeyMap[\"Shift-Cmd-N\"] = \"findNext\"\n\t\tkeyMap[\"Shift-Cmd-P\"] = \"findPre", "end": 1253, "score": 0.9218398332595825, "start": 1242, "tag": "KEY", "value": "Shift-Cmd-N" }, { "context": "[\"Cmd-D\"] = \"download\"\n\t\tkeyMap[\"Shift-Cmd-N\"] = \"findNext\"\n\t\tkeyMap[\"Shift-Cmd-P\"] = \"findPrev\"\n\t\tkeyMap[\"S", "end": 1267, "score": 0.7890831828117371, "start": 1259, "tag": "KEY", "value": "findNext" }, { "context": "d\"\n\t\tkeyMap[\"Shift-Cmd-N\"] = \"findNext\"\n\t\tkeyMap[\"Shift-Cmd-P\"] = \"findPrev\"\n\t\tkeyMap[\"Shift-Cmd-R\"] = \"replace", "end": 1290, "score": 0.9462603330612183, "start": 1279, "tag": "KEY", "value": "Shift-Cmd-P" }, { "context": "t-Cmd-N\"] = \"findNext\"\n\t\tkeyMap[\"Shift-Cmd-P\"] = \"findPrev\"\n\t\tkeyMap[\"Shift-Cmd-R\"] = \"replace\"\n\t\tkeyMap[\"Sh", "end": 1304, "score": 0.810263991355896, "start": 1296, "tag": "KEY", "value": "findPrev" }, { "context": "t\"\n\t\tkeyMap[\"Shift-Cmd-P\"] = \"findPrev\"\n\t\tkeyMap[\"Shift-Cmd-R\"] = \"replace\"\n\t\tkeyMap[\"Shift-Cmd-/\"] = -> consol", "end": 1327, "score": 0.9584356546401978, "start": 1316, "tag": "KEY", "value": "Shift-Cmd-R" }, { "context": "t-Cmd-P\"] = \"findPrev\"\n\t\tkeyMap[\"Shift-Cmd-R\"] = \"replace\"\n\t\tkeyMap[\"Shift-Cmd-/\"] = -> console.log keyMap\n", "end": 1340, "score": 0.7321354150772095, "start": 1333, "tag": "KEY", "value": "replace" }, { "context": "\tkeyMap[\"Shift-Cmd-R\"] = \"replace\"\n\t\tkeyMap[\"Shift-Cmd-/\"] = -> console.log keyMap\n\t\t\n\t\tCodeMirror.command", "end": 1363, "score": 0.9424033761024475, "start": 1358, "tag": "KEY", "value": "Cmd-/" } ]
reflection.coffee
mwmessin/Reflection
3
$ -> $.get "reflection.coffee", (reflection) -> new class constructor: -> state = localStorage.getItem("state") @editor = CodeMirror(document.body, lineNumbers: true autofocus: true value: state or reflection onCursorActivity: => @editor.matchHighlight "CodeMirror-matchhighlight" onChange: @reflect ) @width = 80 @windowHeight = $(window).height() @height = Math.max(@windowHeight, @editor.lineCount()) @canvas = $("<canvas>") .attr('id', 'scroll') .attr("width", @width) .attr("height", @height) .appendTo(".CodeMirror") @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: scrollTop).line @bottom = @editor.coordsChar(x: null, y: scrollTop + @windowHeight).line + 1 @reflect() scrollKeys = [] keyMap = CodeMirror.keyMap["default"] for i in [0..9] ((i) -> keyMap["Shift-Ctrl-" + i] = -> console.log i + ": " + $(window).scrollTop() scrollKeys[i] = $(window).scrollTop() keyMap["Ctrl-" + i] = -> console.log i + "> " + scrollKeys[i] $(window).scrollTop(scrollKeys[i]) )(i) keyMap["Cmd-D"] = "download" keyMap["Shift-Cmd-N"] = "findNext" keyMap["Shift-Cmd-P"] = "findPrev" keyMap["Shift-Cmd-R"] = "replace" keyMap["Shift-Cmd-/"] = -> console.log keyMap CodeMirror.commands.save = => localStorage.setItem("state", @editor.getValue()) CodeMirror.commands.download = => @downloadAs("name.coffee") @dragging = false @down = false $(window) .scroll(@scroll) .resize(@resize) .mousedown( => @down = true) .mousemove( => @dragging = true if @down) .mouseleave( => @down = @dragging = false) .mouseup( => @down = @dragging = false) @canvas .mouseup(({clientY}) => if not @dragging then @scrollTo(clientY)) .mousemove(({clientY}) => if @dragging then @scrollTo(clientY)) $(document.body).append("<footer><code>MWM</code></footer>") reflect: (editor, change) => t0 = (+new Date) @lines = @editor.lineCount() @codeHeight = $(".CodeMirror").height() if not change x = col = 0 y = 0 end = @lines else x = col = change.from.ch y = change.from.line linesChanged = change.to.line + 1 - y if linesChanged is change.text.length end = y + linesChanged + 1 else end = Math.max(@lines, y + linesChanged + 1) while y < end line = @editor.getLine(y) while col < @width ch = line?.charAt(col) if ch if /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 else token = @editor.getTokenAt(line: y, ch: col + 1).className switch token when "operator", "keyword" then @setPixel x, y, 0, 0, 255, @charAlpha(ch) when "number" then @setPixel x, y, 255, 0, 0, 255 when "punctuation" then @setPixel x, y, 150, 150, 150, 255 when "string" then @setPixel x, y, 136, 85, 0, @charAlpha(ch) when "string-2" then @setPixel x, y, 136, 0, 255, @charAlpha(ch) when "comment" then @setPixel x, y, 0, 128, 0, @charAlpha(ch) when "variable" then @setPixel x, y, 50, 50, 50, @charAlpha(ch) when "atom" then @setPixel x, y, 50, 25, 150, @charAlpha(ch) else @setPixel x, y, 0, 0, 0, 255 else if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 ++x ++col col = x = 0 ++y @context.putImageData(@frame, 0, 0) console.log (+new Date) - t0 + "ms", 'reflect' scroll: => t0 = (+new Date) top = @top bottom = @bottom @scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: @scrollTop).line @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 heightLines = @bottom - @top y = Math.min(top, @top) end = Math.max(bottom, @bottom) while y < end x = col = 0 while x < @width ch = @editor.getLine(y)?.charAt(col) if ch and /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if not ch or /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 255, 255, 255, 125 ++x ++col ++y @context.putImageData @frame, 0, 0 if @lines > @windowHeight @offset = -(@top / (@lines - heightLines) * (@lines - @windowHeight)) | 0 $("#scroll").css('top', @offset + 'px') #console.log (+new Date) - t0 + "ms", 'scroll' scrollTo: (y) -> y -= 20 if @lines > @windowHeight top = y / @windowHeight * @codeHeight | 0 else top = @editor.charCoords( line: Math.max(0, y) ch: 0 ).y $(window).scrollTop(top) resize: => @windowHeight = $(window).height() if (@windowHeight > @lines) @height = @windowHeight @canvas = $("#scroll").attr("height", @height) @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 downloadAs: (name) -> raw = @editor.getValue() window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, (fs) -> console.log('webkitRequestFileSystem') fs.root.getFile(name, {create: true}, (fileEntry) -> fileEntry.createWriter((fileWriter) -> builder = new WebKitBlobBuilder() builder.append(raw) fileWriter.onwriteend = -> location.href = fileEntry.toURL() fileWriter.write(builder.getBlob()) , ->) , ->) , (e) -> console.error(e)) charAlpha: (ch) -> if /[._'"\-]/.test(ch) 150 else if /[flyg]/.test(ch) 225 else if /[a-z]/.test(ch) 200 else 255 setPixel: (x, y, r, g, b, a) -> index = (x + y * @width) * 4 @data[index + 0] = r @data[index + 1] = g @data[index + 2] = b @data[index + 3] = a
112043
$ -> $.get "reflection.coffee", (reflection) -> new class constructor: -> state = localStorage.getItem("state") @editor = CodeMirror(document.body, lineNumbers: true autofocus: true value: state or reflection onCursorActivity: => @editor.matchHighlight "CodeMirror-matchhighlight" onChange: @reflect ) @width = 80 @windowHeight = $(window).height() @height = Math.max(@windowHeight, @editor.lineCount()) @canvas = $("<canvas>") .attr('id', 'scroll') .attr("width", @width) .attr("height", @height) .appendTo(".CodeMirror") @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: scrollTop).line @bottom = @editor.coordsChar(x: null, y: scrollTop + @windowHeight).line + 1 @reflect() scrollKeys = [] keyMap = CodeMirror.keyMap["default"] for i in [0..9] ((i) -> keyMap["Shift-Ctrl-" + i] = -> console.log i + ": " + $(window).scrollTop() scrollKeys[i] = $(window).scrollTop() keyMap["Ctrl-" + i] = -> console.log i + "> " + scrollKeys[i] $(window).scrollTop(scrollKeys[i]) )(i) keyMap["Cmd-<KEY>"] = "<KEY>" keyMap["<KEY>"] = "<KEY>" keyMap["<KEY>"] = "<KEY>" keyMap["<KEY>"] = "<KEY>" keyMap["Shift-<KEY>"] = -> console.log keyMap CodeMirror.commands.save = => localStorage.setItem("state", @editor.getValue()) CodeMirror.commands.download = => @downloadAs("name.coffee") @dragging = false @down = false $(window) .scroll(@scroll) .resize(@resize) .mousedown( => @down = true) .mousemove( => @dragging = true if @down) .mouseleave( => @down = @dragging = false) .mouseup( => @down = @dragging = false) @canvas .mouseup(({clientY}) => if not @dragging then @scrollTo(clientY)) .mousemove(({clientY}) => if @dragging then @scrollTo(clientY)) $(document.body).append("<footer><code>MWM</code></footer>") reflect: (editor, change) => t0 = (+new Date) @lines = @editor.lineCount() @codeHeight = $(".CodeMirror").height() if not change x = col = 0 y = 0 end = @lines else x = col = change.from.ch y = change.from.line linesChanged = change.to.line + 1 - y if linesChanged is change.text.length end = y + linesChanged + 1 else end = Math.max(@lines, y + linesChanged + 1) while y < end line = @editor.getLine(y) while col < @width ch = line?.charAt(col) if ch if /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 else token = @editor.getTokenAt(line: y, ch: col + 1).className switch token when "operator", "keyword" then @setPixel x, y, 0, 0, 255, @charAlpha(ch) when "number" then @setPixel x, y, 255, 0, 0, 255 when "punctuation" then @setPixel x, y, 150, 150, 150, 255 when "string" then @setPixel x, y, 136, 85, 0, @charAlpha(ch) when "string-2" then @setPixel x, y, 136, 0, 255, @charAlpha(ch) when "comment" then @setPixel x, y, 0, 128, 0, @charAlpha(ch) when "variable" then @setPixel x, y, 50, 50, 50, @charAlpha(ch) when "atom" then @setPixel x, y, 50, 25, 150, @charAlpha(ch) else @setPixel x, y, 0, 0, 0, 255 else if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 ++x ++col col = x = 0 ++y @context.putImageData(@frame, 0, 0) console.log (+new Date) - t0 + "ms", 'reflect' scroll: => t0 = (+new Date) top = @top bottom = @bottom @scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: @scrollTop).line @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 heightLines = @bottom - @top y = Math.min(top, @top) end = Math.max(bottom, @bottom) while y < end x = col = 0 while x < @width ch = @editor.getLine(y)?.charAt(col) if ch and /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if not ch or /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 255, 255, 255, 125 ++x ++col ++y @context.putImageData @frame, 0, 0 if @lines > @windowHeight @offset = -(@top / (@lines - heightLines) * (@lines - @windowHeight)) | 0 $("#scroll").css('top', @offset + 'px') #console.log (+new Date) - t0 + "ms", 'scroll' scrollTo: (y) -> y -= 20 if @lines > @windowHeight top = y / @windowHeight * @codeHeight | 0 else top = @editor.charCoords( line: Math.max(0, y) ch: 0 ).y $(window).scrollTop(top) resize: => @windowHeight = $(window).height() if (@windowHeight > @lines) @height = @windowHeight @canvas = $("#scroll").attr("height", @height) @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 downloadAs: (name) -> raw = @editor.getValue() window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, (fs) -> console.log('webkitRequestFileSystem') fs.root.getFile(name, {create: true}, (fileEntry) -> fileEntry.createWriter((fileWriter) -> builder = new WebKitBlobBuilder() builder.append(raw) fileWriter.onwriteend = -> location.href = fileEntry.toURL() fileWriter.write(builder.getBlob()) , ->) , ->) , (e) -> console.error(e)) charAlpha: (ch) -> if /[._'"\-]/.test(ch) 150 else if /[flyg]/.test(ch) 225 else if /[a-z]/.test(ch) 200 else 255 setPixel: (x, y, r, g, b, a) -> index = (x + y * @width) * 4 @data[index + 0] = r @data[index + 1] = g @data[index + 2] = b @data[index + 3] = a
true
$ -> $.get "reflection.coffee", (reflection) -> new class constructor: -> state = localStorage.getItem("state") @editor = CodeMirror(document.body, lineNumbers: true autofocus: true value: state or reflection onCursorActivity: => @editor.matchHighlight "CodeMirror-matchhighlight" onChange: @reflect ) @width = 80 @windowHeight = $(window).height() @height = Math.max(@windowHeight, @editor.lineCount()) @canvas = $("<canvas>") .attr('id', 'scroll') .attr("width", @width) .attr("height", @height) .appendTo(".CodeMirror") @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: scrollTop).line @bottom = @editor.coordsChar(x: null, y: scrollTop + @windowHeight).line + 1 @reflect() scrollKeys = [] keyMap = CodeMirror.keyMap["default"] for i in [0..9] ((i) -> keyMap["Shift-Ctrl-" + i] = -> console.log i + ": " + $(window).scrollTop() scrollKeys[i] = $(window).scrollTop() keyMap["Ctrl-" + i] = -> console.log i + "> " + scrollKeys[i] $(window).scrollTop(scrollKeys[i]) )(i) keyMap["Cmd-PI:KEY:<KEY>END_PI"] = "PI:KEY:<KEY>END_PI" keyMap["PI:KEY:<KEY>END_PI"] = "PI:KEY:<KEY>END_PI" keyMap["PI:KEY:<KEY>END_PI"] = "PI:KEY:<KEY>END_PI" keyMap["PI:KEY:<KEY>END_PI"] = "PI:KEY:<KEY>END_PI" keyMap["Shift-PI:KEY:<KEY>END_PI"] = -> console.log keyMap CodeMirror.commands.save = => localStorage.setItem("state", @editor.getValue()) CodeMirror.commands.download = => @downloadAs("name.coffee") @dragging = false @down = false $(window) .scroll(@scroll) .resize(@resize) .mousedown( => @down = true) .mousemove( => @dragging = true if @down) .mouseleave( => @down = @dragging = false) .mouseup( => @down = @dragging = false) @canvas .mouseup(({clientY}) => if not @dragging then @scrollTo(clientY)) .mousemove(({clientY}) => if @dragging then @scrollTo(clientY)) $(document.body).append("<footer><code>MWM</code></footer>") reflect: (editor, change) => t0 = (+new Date) @lines = @editor.lineCount() @codeHeight = $(".CodeMirror").height() if not change x = col = 0 y = 0 end = @lines else x = col = change.from.ch y = change.from.line linesChanged = change.to.line + 1 - y if linesChanged is change.text.length end = y + linesChanged + 1 else end = Math.max(@lines, y + linesChanged + 1) while y < end line = @editor.getLine(y) while col < @width ch = line?.charAt(col) if ch if /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 else token = @editor.getTokenAt(line: y, ch: col + 1).className switch token when "operator", "keyword" then @setPixel x, y, 0, 0, 255, @charAlpha(ch) when "number" then @setPixel x, y, 255, 0, 0, 255 when "punctuation" then @setPixel x, y, 150, 150, 150, 255 when "string" then @setPixel x, y, 136, 85, 0, @charAlpha(ch) when "string-2" then @setPixel x, y, 136, 0, 255, @charAlpha(ch) when "comment" then @setPixel x, y, 0, 128, 0, @charAlpha(ch) when "variable" then @setPixel x, y, 50, 50, 50, @charAlpha(ch) when "atom" then @setPixel x, y, 50, 25, 150, @charAlpha(ch) else @setPixel x, y, 0, 0, 0, 255 else if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 ++x ++col col = x = 0 ++y @context.putImageData(@frame, 0, 0) console.log (+new Date) - t0 + "ms", 'reflect' scroll: => t0 = (+new Date) top = @top bottom = @bottom @scrollTop = $(window).scrollTop() @top = @editor.coordsChar(x: null, y: @scrollTop).line @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 heightLines = @bottom - @top y = Math.min(top, @top) end = Math.max(bottom, @bottom) while y < end x = col = 0 while x < @width ch = @editor.getLine(y)?.charAt(col) if ch and /\t/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 @setPixel x + 1, y, 200, 225, 255, 125 else @setPixel x, y, 0, 0, 0, 0 @setPixel x + 1, y, 0, 0, 0, 0 ++x else if not ch or /\s/.test(ch) if @top < y < @bottom @setPixel x, y, 200, 225, 255, 125 else @setPixel x, y, 255, 255, 255, 125 ++x ++col ++y @context.putImageData @frame, 0, 0 if @lines > @windowHeight @offset = -(@top / (@lines - heightLines) * (@lines - @windowHeight)) | 0 $("#scroll").css('top', @offset + 'px') #console.log (+new Date) - t0 + "ms", 'scroll' scrollTo: (y) -> y -= 20 if @lines > @windowHeight top = y / @windowHeight * @codeHeight | 0 else top = @editor.charCoords( line: Math.max(0, y) ch: 0 ).y $(window).scrollTop(top) resize: => @windowHeight = $(window).height() if (@windowHeight > @lines) @height = @windowHeight @canvas = $("#scroll").attr("height", @height) @context = @canvas[0].getContext("2d") @frame = {@data} = @context.createImageData(@width, @height) @bottom = @editor.coordsChar(x: null, y: @scrollTop + @windowHeight).line + 1 downloadAs: (name) -> raw = @editor.getValue() window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, (fs) -> console.log('webkitRequestFileSystem') fs.root.getFile(name, {create: true}, (fileEntry) -> fileEntry.createWriter((fileWriter) -> builder = new WebKitBlobBuilder() builder.append(raw) fileWriter.onwriteend = -> location.href = fileEntry.toURL() fileWriter.write(builder.getBlob()) , ->) , ->) , (e) -> console.error(e)) charAlpha: (ch) -> if /[._'"\-]/.test(ch) 150 else if /[flyg]/.test(ch) 225 else if /[a-z]/.test(ch) 200 else 255 setPixel: (x, y, r, g, b, a) -> index = (x + y * @width) * 4 @data[index + 0] = r @data[index + 1] = g @data[index + 2] = b @data[index + 3] = a
[ { "context": "j\"\n and: \"i\"\n back: \"powrót\"\n changePassword: \"Zmień hasło\"\n choosePassword: \"Wybierz hasło\"\n clickAgree: ", "end": 118, "score": 0.9829081296920776, "start": 107, "tag": "PASSWORD", "value": "Zmień hasło" }, { "context": "createAccount: \"Utwórz konto\"\n currentPassword: \"Aktualne hasło\"\n dontHaveAnAccount: \"Nie masz konta?\"\n email: ", "end": 311, "score": 0.9774507284164429, "start": 297, "tag": "PASSWORD", "value": "Aktualne hasło" }, { "context": "ail z linkiem do zmiany hasła\"\n forgotPassword: \"Zapomniałeś hasła?\"\n ifYouAlreadyHaveAnAccount: \"Jeżeli już masz k", "end": 494, "score": 0.9241305589675903, "start": 477, "tag": "PASSWORD", "value": "Zapomniałeś hasła" }, { "context": "nAccount: \"Jeżeli już masz konto\"\n newPassword: \"Nowe hasło\"\n newPasswordAgain: \"Nowe hasło (powtórz)\"\n opt", "end": 576, "score": 0.9317856431007385, "start": 566, "tag": "PASSWORD", "value": "Nowe hasło" }, { "context": "\n newPassword: \"Nowe hasło\"\n newPasswordAgain: \"Nowe hasło (powtórz)\"\n optional: \"Nieobowiązkowe\"\n O", "end": 603, "score": 0.6152303218841553, "start": 599, "tag": "PASSWORD", "value": "Nowe" }, { "context": "tional: \"Nieobowiązkowe\"\n OR: \"LUB\"\n password: \"Hasło\"\n passwordAgain: \"Hasło (powtórz)\"\n privacyPoli", "end": 680, "score": 0.9844026565551758, "start": 675, "tag": "PASSWORD", "value": "Hasło" }, { "context": " OR: \"LUB\"\n password: \"Hasło\"\n passwordAgain: \"Hasło (powtórz)\"\n privacyPolicy: \"polityką prywatności", "end": 705, "score": 0.7589215040206909, "start": 700, "tag": "PASSWORD", "value": "Hasło" }, { "context": " password: \"Hasło\"\n passwordAgain: \"Hasło (powtórz)\"\n privacyPolicy: \"polityką prywatności\"\n remov", "end": 714, "score": 0.6347823143005371, "start": 712, "tag": "PASSWORD", "value": "rz" }, { "context": "\"\n remove: \"usuń\"\n resetYourPassword: \"Ustaw nowe hasło\"\n setPassword: \"Ustaw hasło\"\n sign: \"Podpisz\"", "end": 810, "score": 0.676573634147644, "start": 805, "tag": "PASSWORD", "value": "e has" }, { "context": "tYourPassword: \"Ustaw nowe hasło\"\n setPassword: \"Ustaw hasło\"\n sign: \"Podpisz\"\n signIn: \"Zaloguj się\"\n sign", "end": 841, "score": 0.9707826375961304, "start": 830, "tag": "PASSWORD", "value": "Ustaw hasło" }, { "context": "ami korzystania z serwisu\"\n updateYourPassword: \"Zaktualizuj swoje hasło\"\n username: \"Nazwa użytkownika\"\n ", "end": 1139, "score": 0.656294584274292, "start": 1130, "tag": "PASSWORD", "value": "Zaktualiz" }, { "context": "ia z serwisu\"\n updateYourPassword: \"Zaktualizuj swoje hasło\"\n username: \"Nazwa użytkownika\"\n username", "end": 1147, "score": 0.6955412030220032, "start": 1143, "tag": "PASSWORD", "value": "woje" }, { "context": "rPassword: \"Zaktualizuj swoje hasło\"\n username: \"Nazwa użytkownika\"\n usernameOrEmail: \"Nazwa użytkownika lub email\"", "end": 1185, "score": 0.9770551919937134, "start": 1168, "tag": "USERNAME", "value": "Nazwa użytkownika" }, { "context": "username: \"Nazwa użytkownika\"\n usernameOrEmail: \"Nazwa użytkownika lub email\"\n with: \"z\"\n \n info:\n emailSent: ", "end": 1224, "score": 0.8158191442489624, "start": 1207, "tag": "USERNAME", "value": "Nazwa użytkownika" }, { "context": "\"Adres email zweryfikowany\"\n passwordChanged: \"Hasło zmienione\"\n passwordReset: \"Hasło wyzerowane\"\n \n err", "end": 1380, "score": 0.9854170680046082, "start": 1365, "tag": "PASSWORD", "value": "Hasło zmienione" }, { "context": "ordChanged: \"Hasło zmienione\"\n passwordReset: \"Hasło wyzerowane\"\n \n error:\n emailRequired: \"Wymagany jest ", "end": 1418, "score": 0.9834068417549133, "start": 1402, "tag": "PASSWORD", "value": "Hasło wyzerowane" }, { "context": " usernameIsEmail: \"Adres email nie może być nazwą użytkownika.\"\n usernameRequired: \"Wymagana jest nazwa użyt", "end": 1927, "score": 0.9225306510925293, "start": 1916, "tag": "NAME", "value": "użytkownika" }, { "context": "wnika.\"\n usernameRequired: \"Wymagana jest nazwa użytkownika.\"\n\n accounts:\n\n #---- accounts-base\n ", "end": 1984, "score": 0.9073421955108643, "start": 1973, "tag": "NAME", "value": "użytkownika" }, { "context": " \"User validation failed\": \"Niepoprawna nazwa użytkownika\"\n \"Username already exists.\": \"Nazwa użytkow", "end": 2629, "score": 0.9516417980194092, "start": 2618, "tag": "NAME", "value": "użytkownika" }, { "context": "\n \"Username already exists.\": \"Nazwa użytkownika już istnieje.\"\n \"You are not logged in.\": \"N", "end": 2683, "score": 0.8360850811004639, "start": 2680, "tag": "NAME", "value": "ika" }, { "context": "-- accounts-password\n \"Incorrect password\": \"Niepoprawne hasło\"\n \"Invalid email\": \"Błędny adres email\"\n ", "end": 3302, "score": 0.9987913966178894, "start": 3285, "tag": "PASSWORD", "value": "Niepoprawne hasło" }, { "context": "t a username or email\": \"Wymagane ustawienie nazwy użytkownika lub adresu email\"\n \"old password format\": \"s", "end": 3478, "score": 0.6995809674263, "start": 3467, "tag": "NAME", "value": "użytkownika" } ]
t9n/pl.coffee
tnedich/meteor-accounts-t9n
0
#Language: Polish #Translators: pwldp pl = add: "dodaj" and: "i" back: "powrót" changePassword: "Zmień hasło" choosePassword: "Wybierz hasło" clickAgree: "Klikając na Zarejestruj się zgadzasz się z naszą" configure: "Konfiguruj" createAccount: "Utwórz konto" currentPassword: "Aktualne hasło" dontHaveAnAccount: "Nie masz konta?" email: "Email" emailAddress: "Adres email" emailResetLink: "Wyślij email z linkiem do zmiany hasła" forgotPassword: "Zapomniałeś hasła?" ifYouAlreadyHaveAnAccount: "Jeżeli już masz konto" newPassword: "Nowe hasło" newPasswordAgain: "Nowe hasło (powtórz)" optional: "Nieobowiązkowe" OR: "LUB" password: "Hasło" passwordAgain: "Hasło (powtórz)" privacyPolicy: "polityką prywatności" remove: "usuń" resetYourPassword: "Ustaw nowe hasło" setPassword: "Ustaw hasło" sign: "Podpisz" signIn: "Zaloguj się" signin: "zaloguj się" signOut: "Wyloguj się" signUp: "Zarejestruj się" signupCode: "Kod rejestracji" signUpWithYourEmailAddress: "Zarejestruj się używając adresu email" terms: "warunkami korzystania z serwisu" updateYourPassword: "Zaktualizuj swoje hasło" username: "Nazwa użytkownika" usernameOrEmail: "Nazwa użytkownika lub email" with: "z" info: emailSent: "Adres email wysłany" emailVerified: "Adres email zweryfikowany" passwordChanged: "Hasło zmienione" passwordReset: "Hasło wyzerowane" error: emailRequired: "Wymagany jest adres email." minChar: "7 znaków to minimalna długość hasła." pwdsDontMatch: "Hasła są różne" pwOneDigit: "Hasło musi zawierać przynajmniej jedną cyfrę." pwOneLetter: "Hasło musi zawierać 1 literę." signInRequired: "Musisz być zalogowany, aby to zrobić." signupCodeIncorrect: "Kod rejestracji jest nieprawidłowy." signupCodeRequired: "Wymagany jest kod rejestracji." usernameIsEmail: "Adres email nie może być nazwą użytkownika." usernameRequired: "Wymagana jest nazwa użytkownika." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "Adres email już istnieje." "Email doesn't match the criteria.": "Adres email nie spełnia kryteriów." "Invalid login token": "Błędny token logowania" "Login forbidden": "Logowanie zabronione" #"Service " + options.service + " already configured": "Service unknown": "Nieznana usługa" "Unrecognized options for login request": "Nieznane parametry w żądaniu logowania." "User validation failed": "Niepoprawna nazwa użytkownika" "Username already exists.": "Nazwa użytkownika już istnieje." "You are not logged in.": "Nie jesteś zalogowany." "You've been logged out by the server. Please log in again.": "Zostałeś wylogowane przez serwer. Zaloguj się ponownie." "Your session has expired. Please log in again.": "Twoja sesja wygasła. Zaloguj się ponownie." #---- accounts-oauth "No matching login attempt found": "Nie dopasowano danych logowania." #---- accounts-password-client "Password is old. Please reset your password.": "Hasło jest stare. Proszę wyzerować hasło." #---- accounts-password "Incorrect password": "Niepoprawne hasło" "Invalid email": "Błędny adres email" "Must be logged in": "Musisz być zalogowany" "Need to set a username or email": "Wymagane ustawienie nazwy użytkownika lub adresu email" "old password format": "stary format hasła" "Password may not be empty": "Hasło nie może być puste" "Signups forbidden": "Rejestracja zabroniona" "Token expired": "Token wygasł" "Token has invalid email address": "Token ma niewłaściwy adres email" "User has no password set": "Użytkownik nie ma ustawionego hasła" "User not found": "Nie znaleziono użytkownika" "Verify email link expired": "Link weryfikacyjny wygasł" "Verify email link is for unknown address": "Link weryfikacyjny jest dla nieznanego adresu" #---- match "Match failed": "Błędne dopasowanie" #---- Misc... "Unknown error": "Nieznany błąd" T9n.map "pl", pl
102910
#Language: Polish #Translators: pwldp pl = add: "dodaj" and: "i" back: "powrót" changePassword: "<PASSWORD>" choosePassword: "Wybierz hasło" clickAgree: "Klikając na Zarejestruj się zgadzasz się z naszą" configure: "Konfiguruj" createAccount: "Utwórz konto" currentPassword: "<PASSWORD>" dontHaveAnAccount: "Nie masz konta?" email: "Email" emailAddress: "Adres email" emailResetLink: "Wyślij email z linkiem do zmiany hasła" forgotPassword: "<PASSWORD>?" ifYouAlreadyHaveAnAccount: "Jeżeli już masz konto" newPassword: "<PASSWORD>" newPasswordAgain: "<PASSWORD> hasło (powtórz)" optional: "Nieobowiązkowe" OR: "LUB" password: "<PASSWORD>" passwordAgain: "<PASSWORD> (powtó<PASSWORD>)" privacyPolicy: "polityką prywatności" remove: "usuń" resetYourPassword: "Ustaw now<PASSWORD>ło" setPassword: "<PASSWORD>" sign: "Podpisz" signIn: "Zaloguj się" signin: "zaloguj się" signOut: "Wyloguj się" signUp: "Zarejestruj się" signupCode: "Kod rejestracji" signUpWithYourEmailAddress: "Zarejestruj się używając adresu email" terms: "warunkami korzystania z serwisu" updateYourPassword: "<PASSWORD>uj s<PASSWORD> hasło" username: "Nazwa użytkownika" usernameOrEmail: "Nazwa użytkownika lub email" with: "z" info: emailSent: "Adres email wysłany" emailVerified: "Adres email zweryfikowany" passwordChanged: "<PASSWORD>" passwordReset: "<PASSWORD>" error: emailRequired: "Wymagany jest adres email." minChar: "7 znaków to minimalna długość hasła." pwdsDontMatch: "Hasła są różne" pwOneDigit: "Hasło musi zawierać przynajmniej jedną cyfrę." pwOneLetter: "Hasło musi zawierać 1 literę." signInRequired: "Musisz być zalogowany, aby to zrobić." signupCodeIncorrect: "Kod rejestracji jest nieprawidłowy." signupCodeRequired: "Wymagany jest kod rejestracji." usernameIsEmail: "Adres email nie może być nazwą <NAME>." usernameRequired: "Wymagana jest nazwa <NAME>." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "Adres email już istnieje." "Email doesn't match the criteria.": "Adres email nie spełnia kryteriów." "Invalid login token": "Błędny token logowania" "Login forbidden": "Logowanie zabronione" #"Service " + options.service + " already configured": "Service unknown": "Nieznana usługa" "Unrecognized options for login request": "Nieznane parametry w żądaniu logowania." "User validation failed": "Niepoprawna nazwa <NAME>" "Username already exists.": "Nazwa użytkown<NAME> już istnieje." "You are not logged in.": "Nie jesteś zalogowany." "You've been logged out by the server. Please log in again.": "Zostałeś wylogowane przez serwer. Zaloguj się ponownie." "Your session has expired. Please log in again.": "Twoja sesja wygasła. Zaloguj się ponownie." #---- accounts-oauth "No matching login attempt found": "Nie dopasowano danych logowania." #---- accounts-password-client "Password is old. Please reset your password.": "Hasło jest stare. Proszę wyzerować hasło." #---- accounts-password "Incorrect password": "<PASSWORD>" "Invalid email": "Błędny adres email" "Must be logged in": "Musisz być zalogowany" "Need to set a username or email": "Wymagane ustawienie nazwy <NAME> lub adresu email" "old password format": "stary format hasła" "Password may not be empty": "Hasło nie może być puste" "Signups forbidden": "Rejestracja zabroniona" "Token expired": "Token wygasł" "Token has invalid email address": "Token ma niewłaściwy adres email" "User has no password set": "Użytkownik nie ma ustawionego hasła" "User not found": "Nie znaleziono użytkownika" "Verify email link expired": "Link weryfikacyjny wygasł" "Verify email link is for unknown address": "Link weryfikacyjny jest dla nieznanego adresu" #---- match "Match failed": "Błędne dopasowanie" #---- Misc... "Unknown error": "Nieznany błąd" T9n.map "pl", pl
true
#Language: Polish #Translators: pwldp pl = add: "dodaj" and: "i" back: "powrót" changePassword: "PI:PASSWORD:<PASSWORD>END_PI" choosePassword: "Wybierz hasło" clickAgree: "Klikając na Zarejestruj się zgadzasz się z naszą" configure: "Konfiguruj" createAccount: "Utwórz konto" currentPassword: "PI:PASSWORD:<PASSWORD>END_PI" dontHaveAnAccount: "Nie masz konta?" email: "Email" emailAddress: "Adres email" emailResetLink: "Wyślij email z linkiem do zmiany hasła" forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?" ifYouAlreadyHaveAnAccount: "Jeżeli już masz konto" newPassword: "PI:PASSWORD:<PASSWORD>END_PI" newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI hasło (powtórz)" optional: "Nieobowiązkowe" OR: "LUB" password: "PI:PASSWORD:<PASSWORD>END_PI" passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI (powtóPI:PASSWORD:<PASSWORD>END_PI)" privacyPolicy: "polityką prywatności" remove: "usuń" resetYourPassword: "Ustaw nowPI:PASSWORD:<PASSWORD>END_PIło" setPassword: "PI:PASSWORD:<PASSWORD>END_PI" sign: "Podpisz" signIn: "Zaloguj się" signin: "zaloguj się" signOut: "Wyloguj się" signUp: "Zarejestruj się" signupCode: "Kod rejestracji" signUpWithYourEmailAddress: "Zarejestruj się używając adresu email" terms: "warunkami korzystania z serwisu" updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PIuj sPI:PASSWORD:<PASSWORD>END_PI hasło" username: "Nazwa użytkownika" usernameOrEmail: "Nazwa użytkownika lub email" with: "z" info: emailSent: "Adres email wysłany" emailVerified: "Adres email zweryfikowany" passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI" passwordReset: "PI:PASSWORD:<PASSWORD>END_PI" error: emailRequired: "Wymagany jest adres email." minChar: "7 znaków to minimalna długość hasła." pwdsDontMatch: "Hasła są różne" pwOneDigit: "Hasło musi zawierać przynajmniej jedną cyfrę." pwOneLetter: "Hasło musi zawierać 1 literę." signInRequired: "Musisz być zalogowany, aby to zrobić." signupCodeIncorrect: "Kod rejestracji jest nieprawidłowy." signupCodeRequired: "Wymagany jest kod rejestracji." usernameIsEmail: "Adres email nie może być nazwą PI:NAME:<NAME>END_PI." usernameRequired: "Wymagana jest nazwa PI:NAME:<NAME>END_PI." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "Adres email już istnieje." "Email doesn't match the criteria.": "Adres email nie spełnia kryteriów." "Invalid login token": "Błędny token logowania" "Login forbidden": "Logowanie zabronione" #"Service " + options.service + " already configured": "Service unknown": "Nieznana usługa" "Unrecognized options for login request": "Nieznane parametry w żądaniu logowania." "User validation failed": "Niepoprawna nazwa PI:NAME:<NAME>END_PI" "Username already exists.": "Nazwa użytkownPI:NAME:<NAME>END_PI już istnieje." "You are not logged in.": "Nie jesteś zalogowany." "You've been logged out by the server. Please log in again.": "Zostałeś wylogowane przez serwer. Zaloguj się ponownie." "Your session has expired. Please log in again.": "Twoja sesja wygasła. Zaloguj się ponownie." #---- accounts-oauth "No matching login attempt found": "Nie dopasowano danych logowania." #---- accounts-password-client "Password is old. Please reset your password.": "Hasło jest stare. Proszę wyzerować hasło." #---- accounts-password "Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI" "Invalid email": "Błędny adres email" "Must be logged in": "Musisz być zalogowany" "Need to set a username or email": "Wymagane ustawienie nazwy PI:NAME:<NAME>END_PI lub adresu email" "old password format": "stary format hasła" "Password may not be empty": "Hasło nie może być puste" "Signups forbidden": "Rejestracja zabroniona" "Token expired": "Token wygasł" "Token has invalid email address": "Token ma niewłaściwy adres email" "User has no password set": "Użytkownik nie ma ustawionego hasła" "User not found": "Nie znaleziono użytkownika" "Verify email link expired": "Link weryfikacyjny wygasł" "Verify email link is for unknown address": "Link weryfikacyjny jest dla nieznanego adresu" #---- match "Match failed": "Błędne dopasowanie" #---- Misc... "Unknown error": "Nieznany błąd" T9n.map "pl", pl
[ { "context": "#####################################\n# Created by Jordan Robert Dobson on 05 OCT 2015\n# Updated by Jordan Robert Dobson ", "end": 117, "score": 0.9998868107795715, "start": 97, "tag": "NAME", "value": "Jordan Robert Dobson" }, { "context": "y Jordan Robert Dobson on 05 OCT 2015\n# Updated by Jordan Robert Dobson on 14 SEP 2016\n#\n# Use to add font files and refe", "end": 166, "score": 0.999883234500885, "start": 146, "tag": "NAME", "value": "Jordan Robert Dobson" } ]
FontFace.coffee
Seattle-Framer/modules-Seattle
12
################################################################################### # Created by Jordan Robert Dobson on 05 OCT 2015 # Updated by Jordan Robert Dobson on 14 SEP 2016 # # Use to add font files and reference them in your CSS style settings. # # To Get Started... # # 1. Place the FontFace.coffee file in Framer Studio modules directory # # 2. In your project include: # {FontFace} = require "FontFace" # # 3. To add a font face: # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", weight: 400 # # 4. It checks that the font was loaded. Errors can be suppressed like so... # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", hideErrors: true # ################################################################################### class exports.FontFace TEST = face: "monospace" text: "foo" time: .01 maxLoadAttempts: 200 hideErrorMessages: true TEST.style = width: "auto" fontSize: "150px" fontFamily: TEST.face TEST.layer = new Layer name: ".FontFace Tester" width: 0 height: 1 maxX: -(Screen.width) visible: false html: TEST.text style: TEST.style # SETUP FOR EVERY INSTANCE constructor: (options) -> @name = @file = @testLayer = @isLoaded = @loadFailed = @loadAttempts = @originalSize = @hideErrors = null if options? @name = options.name or null @file = options.file or null @weight = options.weight or 400 @style = options.style or "normal" return missingArgumentError() unless @name? and @file? @testLayer = TEST.layer.copy() @testLayer.style = TEST.style @testLayer.maxX = -(Screen.width) @testLayer.visible = true @isLoaded = false @loadFailed = false @loadAttempts = 0 @hideErrors = options.hideErrors return addFontFace @ ############################################################################## # Private Helper Methods ##################################################### addFontFace = (self) -> # Create our Element & Node styleTag = document.createElement 'style' faceCSS = document.createTextNode """ @font-face { font-family:"#{self.name }"; src: url("#{self.file }") format("truetype"); font-weight: #{self.weight}; font-style: #{self.style }; }""" # Add the Element & Node to the document styleTag.appendChild faceCSS document.head.appendChild styleTag # Test out the Font to see if it changed testNewFace self.name, self ############################################################################## removeTestLayer = (self) -> self.testLayer.destroy() self.testLayer = null ############################################################################## testNewFace = (name, self) -> initialWidth = self.testLayer._element.getBoundingClientRect().width # Check to see if it's ready yet if initialWidth is 0 if self.hideErrors is false or TEST.hideErrorMessages is false print "Load testing failed. Attempting again." return Utils.delay TEST.time, -> testNewFace name, self self.loadAttempts++ if self.originalSize is null self.originalSize = initialWidth self.testLayer.style = fontFamily: "#{name}, #{TEST.face}" widthUpdate = self.testLayer._element.getBoundingClientRect().width if self.originalSize is widthUpdate # If we can attempt to check again... Do it if self.loadAttempts < TEST.maxLoadAttempts return Utils.delay TEST.time, -> testNewFace name, self print "⚠️ Failed loading FontFace: #{name} #{self.weight}" unless self.hideErrors console.log "⚠️ Failed loading FontFace: #{name} #{self.weight}" self.isLoaded = false self.loadFailed = true loadTestingFileError self unless self.hideErrors return else print "LOADED: #{name} #{self.weight}" unless self.hideErrors is false or TEST.hideErrorMessages console.log "FONT FACE - LOADED: #{name} #{self.weight}" self.isLoaded = true self.loadFailed = false removeTestLayer self return name ############################################################################## # Error Handler Methods ###################################################### missingArgumentError = -> error """<b>FontFace</b> Missing Name and/or File: See Console""" console.error """ Error: You must pass name & file properites when creating a new FontFace. \n Example: myFace = new FontFace name:\"Gotham\", file:\"gotham.ttf\" \n""" loadTestingFileError = (self) -> error """<b>FontFace</b> Loading Error: See Console""" console.error """ Error: Couldn't detect the font: \"#{self.name}\" and file: \"#{self.file}\" was loaded. \n Either the file couldn't be found or your browser doesn't support the file type that was provided. \n Suppress this message by adding \"hideErrors: true\" when creating a new FontFace. \n""" error = (message) -> Framer.Extras.ErrorDisplay.enable() throw Error message
196191
################################################################################### # Created by <NAME> on 05 OCT 2015 # Updated by <NAME> on 14 SEP 2016 # # Use to add font files and reference them in your CSS style settings. # # To Get Started... # # 1. Place the FontFace.coffee file in Framer Studio modules directory # # 2. In your project include: # {FontFace} = require "FontFace" # # 3. To add a font face: # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", weight: 400 # # 4. It checks that the font was loaded. Errors can be suppressed like so... # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", hideErrors: true # ################################################################################### class exports.FontFace TEST = face: "monospace" text: "foo" time: .01 maxLoadAttempts: 200 hideErrorMessages: true TEST.style = width: "auto" fontSize: "150px" fontFamily: TEST.face TEST.layer = new Layer name: ".FontFace Tester" width: 0 height: 1 maxX: -(Screen.width) visible: false html: TEST.text style: TEST.style # SETUP FOR EVERY INSTANCE constructor: (options) -> @name = @file = @testLayer = @isLoaded = @loadFailed = @loadAttempts = @originalSize = @hideErrors = null if options? @name = options.name or null @file = options.file or null @weight = options.weight or 400 @style = options.style or "normal" return missingArgumentError() unless @name? and @file? @testLayer = TEST.layer.copy() @testLayer.style = TEST.style @testLayer.maxX = -(Screen.width) @testLayer.visible = true @isLoaded = false @loadFailed = false @loadAttempts = 0 @hideErrors = options.hideErrors return addFontFace @ ############################################################################## # Private Helper Methods ##################################################### addFontFace = (self) -> # Create our Element & Node styleTag = document.createElement 'style' faceCSS = document.createTextNode """ @font-face { font-family:"#{self.name }"; src: url("#{self.file }") format("truetype"); font-weight: #{self.weight}; font-style: #{self.style }; }""" # Add the Element & Node to the document styleTag.appendChild faceCSS document.head.appendChild styleTag # Test out the Font to see if it changed testNewFace self.name, self ############################################################################## removeTestLayer = (self) -> self.testLayer.destroy() self.testLayer = null ############################################################################## testNewFace = (name, self) -> initialWidth = self.testLayer._element.getBoundingClientRect().width # Check to see if it's ready yet if initialWidth is 0 if self.hideErrors is false or TEST.hideErrorMessages is false print "Load testing failed. Attempting again." return Utils.delay TEST.time, -> testNewFace name, self self.loadAttempts++ if self.originalSize is null self.originalSize = initialWidth self.testLayer.style = fontFamily: "#{name}, #{TEST.face}" widthUpdate = self.testLayer._element.getBoundingClientRect().width if self.originalSize is widthUpdate # If we can attempt to check again... Do it if self.loadAttempts < TEST.maxLoadAttempts return Utils.delay TEST.time, -> testNewFace name, self print "⚠️ Failed loading FontFace: #{name} #{self.weight}" unless self.hideErrors console.log "⚠️ Failed loading FontFace: #{name} #{self.weight}" self.isLoaded = false self.loadFailed = true loadTestingFileError self unless self.hideErrors return else print "LOADED: #{name} #{self.weight}" unless self.hideErrors is false or TEST.hideErrorMessages console.log "FONT FACE - LOADED: #{name} #{self.weight}" self.isLoaded = true self.loadFailed = false removeTestLayer self return name ############################################################################## # Error Handler Methods ###################################################### missingArgumentError = -> error """<b>FontFace</b> Missing Name and/or File: See Console""" console.error """ Error: You must pass name & file properites when creating a new FontFace. \n Example: myFace = new FontFace name:\"Gotham\", file:\"gotham.ttf\" \n""" loadTestingFileError = (self) -> error """<b>FontFace</b> Loading Error: See Console""" console.error """ Error: Couldn't detect the font: \"#{self.name}\" and file: \"#{self.file}\" was loaded. \n Either the file couldn't be found or your browser doesn't support the file type that was provided. \n Suppress this message by adding \"hideErrors: true\" when creating a new FontFace. \n""" error = (message) -> Framer.Extras.ErrorDisplay.enable() throw Error message
true
################################################################################### # Created by PI:NAME:<NAME>END_PI on 05 OCT 2015 # Updated by PI:NAME:<NAME>END_PI on 14 SEP 2016 # # Use to add font files and reference them in your CSS style settings. # # To Get Started... # # 1. Place the FontFace.coffee file in Framer Studio modules directory # # 2. In your project include: # {FontFace} = require "FontFace" # # 3. To add a font face: # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", weight: 400 # # 4. It checks that the font was loaded. Errors can be suppressed like so... # gotham = new FontFace name: "Gotham", file: "Gotham.ttf", hideErrors: true # ################################################################################### class exports.FontFace TEST = face: "monospace" text: "foo" time: .01 maxLoadAttempts: 200 hideErrorMessages: true TEST.style = width: "auto" fontSize: "150px" fontFamily: TEST.face TEST.layer = new Layer name: ".FontFace Tester" width: 0 height: 1 maxX: -(Screen.width) visible: false html: TEST.text style: TEST.style # SETUP FOR EVERY INSTANCE constructor: (options) -> @name = @file = @testLayer = @isLoaded = @loadFailed = @loadAttempts = @originalSize = @hideErrors = null if options? @name = options.name or null @file = options.file or null @weight = options.weight or 400 @style = options.style or "normal" return missingArgumentError() unless @name? and @file? @testLayer = TEST.layer.copy() @testLayer.style = TEST.style @testLayer.maxX = -(Screen.width) @testLayer.visible = true @isLoaded = false @loadFailed = false @loadAttempts = 0 @hideErrors = options.hideErrors return addFontFace @ ############################################################################## # Private Helper Methods ##################################################### addFontFace = (self) -> # Create our Element & Node styleTag = document.createElement 'style' faceCSS = document.createTextNode """ @font-face { font-family:"#{self.name }"; src: url("#{self.file }") format("truetype"); font-weight: #{self.weight}; font-style: #{self.style }; }""" # Add the Element & Node to the document styleTag.appendChild faceCSS document.head.appendChild styleTag # Test out the Font to see if it changed testNewFace self.name, self ############################################################################## removeTestLayer = (self) -> self.testLayer.destroy() self.testLayer = null ############################################################################## testNewFace = (name, self) -> initialWidth = self.testLayer._element.getBoundingClientRect().width # Check to see if it's ready yet if initialWidth is 0 if self.hideErrors is false or TEST.hideErrorMessages is false print "Load testing failed. Attempting again." return Utils.delay TEST.time, -> testNewFace name, self self.loadAttempts++ if self.originalSize is null self.originalSize = initialWidth self.testLayer.style = fontFamily: "#{name}, #{TEST.face}" widthUpdate = self.testLayer._element.getBoundingClientRect().width if self.originalSize is widthUpdate # If we can attempt to check again... Do it if self.loadAttempts < TEST.maxLoadAttempts return Utils.delay TEST.time, -> testNewFace name, self print "⚠️ Failed loading FontFace: #{name} #{self.weight}" unless self.hideErrors console.log "⚠️ Failed loading FontFace: #{name} #{self.weight}" self.isLoaded = false self.loadFailed = true loadTestingFileError self unless self.hideErrors return else print "LOADED: #{name} #{self.weight}" unless self.hideErrors is false or TEST.hideErrorMessages console.log "FONT FACE - LOADED: #{name} #{self.weight}" self.isLoaded = true self.loadFailed = false removeTestLayer self return name ############################################################################## # Error Handler Methods ###################################################### missingArgumentError = -> error """<b>FontFace</b> Missing Name and/or File: See Console""" console.error """ Error: You must pass name & file properites when creating a new FontFace. \n Example: myFace = new FontFace name:\"Gotham\", file:\"gotham.ttf\" \n""" loadTestingFileError = (self) -> error """<b>FontFace</b> Loading Error: See Console""" console.error """ Error: Couldn't detect the font: \"#{self.name}\" and file: \"#{self.file}\" was loaded. \n Either the file couldn't be found or your browser doesn't support the file type that was provided. \n Suppress this message by adding \"hideErrors: true\" when creating a new FontFace. \n""" error = (message) -> Framer.Extras.ErrorDisplay.enable() throw Error message
[ { "context": "\nC = ModelInterface.Attribute\n\n# **Epic props** to rythos42 for saving me having to research and type all thi", "end": 140, "score": 0.9993699789047241, "start": 132, "tag": "USERNAME", "value": "rythos42" }, { "context": " research and type all this!\n# https://github.com/rythos42/MalifauxModels-Web/blob/master/js/app/Mappers/Mod", "end": 222, "score": 0.9996730089187622, "start": 214, "tag": "USERNAME", "value": "rythos42" }, { "context": "/Mappers/ModelList.js\n\nModelList = [\n new Model('Lady Justice', [C.Guild], [C.Master, C.Living, C.GuildMarshal,", "end": 322, "score": 0.9034483432769775, "start": 310, "tag": "NAME", "value": "Lady Justice" }, { "context": "ildMarshal, C.Wave1], undefined, 4),\n new Model('Sonnia Criid', [C.Guild], [C.Master, C.Living, C.WitchHunter, ", "end": 423, "score": 0.9718247652053833, "start": 411, "tag": "NAME", "value": "Sonnia Criid" }, { "context": "itchHunter, C.Wave1], undefined, 3),\n new Model('Perdita Ortega', [C.Guild], [C.Master, C.Living, C.Family, C.Wav", "end": 525, "score": 0.9990918636322021, "start": 511, "tag": "NAME", "value": "Perdita Ortega" }, { "context": ", C.Family, C.Wave1], undefined, 2),\n new Model('Franscisco Ortega', [C.Guild], [C.Henchman, C.Living, C.Family, C.W", "end": 625, "score": 0.9995667338371277, "start": 608, "tag": "NAME", "value": "Franscisco Ortega" }, { "context": "C.Living, C.Family, C.Wave1], 8, 5),\n new Model('Samael Hopkins', [C.Guild], [C.Henchman, C.Living, C.WitchHunter", "end": 716, "score": 0.9996457695960999, "start": 702, "tag": "NAME", "value": "Samael Hopkins" }, { "context": "C.WitchHunter, C.Wave1], 9, 4),\n new Model('The Judge', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Gu", "end": 807, "score": 0.5835471153259277, "start": 803, "tag": "NAME", "value": "udge" }, { "context": "Purifying Flame', [C.Guild], [C.Peon, C.TotemFor('Sonnia Criid'), C.Spirit, C.Wave1], 3),\n new Model('Enslaved ", "end": 1066, "score": 0.8607693910598755, "start": 1054, "tag": "NAME", "value": "Sonnia Criid" }, { "context": "slaved Nephilim', [C.Guild], [C.Peon, C.TotemFor('Perdita Ortega'), C.Nephilim, C.Wave1], 3),\n new Model('Governo", "end": 1173, "score": 0.8487486839294434, "start": 1159, "tag": "NAME", "value": "Perdita Ortega" }, { "context": "Living, C.WitchHunter, C.Wave1], 5),\n new Model('Nino Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Fa", "end": 1961, "score": 0.9998370409011841, "start": 1950, "tag": "NAME", "value": "Nino Ortega" }, { "context": "ng, C.Rare1, C.Family, C.Wave1], 7),\n new Model('Papa Loco', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Fa", "end": 2053, "score": 0.9473727345466614, "start": 2044, "tag": "NAME", "value": "Papa Loco" }, { "context": "C.Family, C.Tormented, C.Wave1], 7),\n new Model('Santiago Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Fa", "end": 2164, "score": 0.9998202323913574, "start": 2149, "tag": "NAME", "value": "Santiago Ortega" }, { "context": " C.Rare1, C.Family, C.Wave1], 7),\n \n new Model('C. Hoffman', [C.Guild], [C.Master, C.Living, C.Construct, C.", "end": 2260, "score": 0.9998346567153931, "start": 2250, "tag": "NAME", "value": "C. Hoffman" }, { "context": "uct, C.Msu, C.Wave2], undefined, 3),\n new Model('Ryle', [C.Guild], [C.Henchman, C.Construct, C.Rare1, C", "end": 2357, "score": 0.9969162940979004, "start": 2353, "tag": "NAME", "value": "Ryle" }, { "context": "nt', [C.Guild], [C.Peon, C.Construct, C.TotemFor('C. Hoffman'), C.Wave2], 2),\n new Model('Guardian', [C.Guild", "end": 2522, "score": 0.995398998260498, "start": 2512, "tag": "NAME", "value": "C. Hoffman" }, { "context": "otemFor('C. Hoffman'), C.Wave2], 2),\n new Model('Guardian', [C.Guild], [C.Minion, C.Construct, C.Wave2], 8)", "end": 2561, "score": 0.9767652750015259, "start": 2553, "tag": "NAME", "value": "Guardian" }, { "context": "C.Minion, C.Construct, C.Wave2], 8),\n new Model('Lucius', [C.Guild, C.Neverborn], [C.Master, C.Living, C.", "end": 2632, "score": 0.9992274641990662, "start": 2626, "tag": "NAME", "value": "Lucius" }, { "context": "g, C.Mimic, C.Wave2], undefined, 4),\n new Model('Captain Dashel', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Gu", "end": 2741, "score": 0.9953445196151733, "start": 2727, "tag": "NAME", "value": "Captain Dashel" }, { "context": "ild, C.Neverborn], [C.Peon, C.Living, C.TotemFor('Lucius'), C.Wave2], 2),\n new Model('Abuela Ortega', [C.", "end": 2904, "score": 0.9982028007507324, "start": 2898, "tag": "NAME", "value": "Lucius" }, { "context": " C.TotemFor('Lucius'), C.Wave2], 2),\n new Model('Abuela Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Fa", "end": 2948, "score": 0.999437153339386, "start": 2935, "tag": "NAME", "value": "Abuela Ortega" }, { "context": " C.Rare2, C.Guardsman, C.Wave2], 6),\n new Model('Hunter', [C.Guild], [C.Minion, C.Construct, C.Rare2, C.W", "end": 3250, "score": 0.9031147360801697, "start": 3244, "tag": "NAME", "value": "Hunter" }, { "context": "Living, C.Wave1], undefined, 3),\n new Model('McMourning', [C.Resurrectionist, C.Guild], [C.Master, C.Livi", "end": 4453, "score": 0.5637755990028381, "start": 4447, "tag": "NAME", "value": "urning" }, { "context": ", C.Living, C.Wave1], undefined, 4),\n new Model('Nicodem', [C.Resurrectionist], [C.Master, C.Living, C.Wav", "end": 4552, "score": 0.7567930221557617, "start": 4545, "tag": "NAME", "value": "Nicodem" }, { "context": ", C.Living, C.Wave1], undefined, 3),\n new Model('Madam Sybelle', [C.Resurrectionist], [C.Henchman, C.Undead, C.R", "end": 4648, "score": 0.9998332858085632, "start": 4635, "tag": "NAME", "value": "Madam Sybelle" }, { "context": " C.Undead, C.Rare1, C.Wave1], 8, 5),\n new Model('Sebastian', [C.Resurrectionist], [C.Henchman, C.Living, C.R", "end": 4743, "score": 0.999398410320282, "start": 4734, "tag": "NAME", "value": "Sebastian" }, { "context": "1, C.Horror, C.Spirit, C.Wave2], 2),\n new Model('Kirai Ankoku', [C.Resurrectionist], [C.Master, C.Living, C.Wav", "end": 6821, "score": 0.9093265533447266, "start": 6809, "tag": "NAME", "value": "Kirai Ankoku" }, { "context": "i Ankoku'), C.Spirit, C.Wave2], 4),\n new Model('Datsue Ba', [C.Resurrectionist], [C.Henchman, C.Undead", "end": 7200, "score": 0.5286519527435303, "start": 7197, "tag": "NAME", "value": "ats" }, { "context": " C.Spirit, C.Retainer, C.Wave2], 5),\n new Model('Shikome', [C.Resurrectionist], [C.Minion, C.Undead, C.Rar", "end": 7681, "score": 0.6072567105293274, "start": 7674, "tag": "NAME", "value": "Shikome" }, { "context": "C.Spirit, C.Tormented, C.Wave2], 6),\n new Model('Jaakuna Ubume', [C.Resurrectionist], [C.Enforcer, C.", "end": 8088, "score": 0.529625654220581, "start": 8086, "tag": "NAME", "value": "Ja" }, { "context": "er, C.Living, C.Rare1, C.Wave2], 7),\n new Model('Carrion Effigy', [C.Resurrectionist], [C.Minion, C.Construct, C.", "end": 8298, "score": 0.9978618621826172, "start": 8284, "tag": "NAME", "value": "Carrion Effigy" }, { "context": "1, C.Puppet, C.Effigy, C.Wave2], 4),\n new Model('Ashigaru', [C.Resurrectionist], [C.Minion, C.Undead, C.Ret", "end": 8410, "score": 0.9812080264091492, "start": 8402, "tag": "NAME", "value": "Ashigaru" }, { "context": " C.Undead, C.Retainer, C.Wave2], 5),\n new Model('Philip and the Nanny', [C.Resurrectionist], [C.Henchman, C.U", "end": 8504, "score": 0.8383582234382629, "start": 8494, "tag": "NAME", "value": "Philip and" }, { "context": "etainer, C.Wave2], 5),\n new Model('Philip and the Nanny', [C.Resurrectionist], [C.Henchman, C.Undead, C.R", "end": 8514, "score": 0.9935756921768188, "start": 8509, "tag": "NAME", "value": "Nanny" }, { "context": "C.Horror, C.Wave2], 8, 5),\n new Model('Student of Sinew', [C.Resurrectionist], [C.Minion, C.Construct, C.", "end": 8636, "score": 0.91214919090271, "start": 8631, "tag": "NAME", "value": "Sinew" }, { "context": " C.Academic, C.Wave2], 7),\n new Model('Student of Steel', [C.Resurrectionist], [C.Minion, C.Construct, C.", "end": 8759, "score": 0.8028450012207031, "start": 8754, "tag": "NAME", "value": "Steel" }, { "context": " C.Academic, C.Wave2], 7),\n new Model('Student of Viscera', [C.Resurrectionist], [C.Minion, C.Construct, C.", "end": 8884, "score": 0.9336612820625305, "start": 8877, "tag": "NAME", "value": "Viscera" }, { "context": "Horror, C.Academic, C.Wave2], 8),\n new Model('The Valedictorian', [C.Resurrectionist], [C.Henchman, C", "end": 8996, "score": 0.5868222713470459, "start": 8995, "tag": "NAME", "value": "V" }, { "context": ", C.Academic, C.Wave2], 8),\n new Model('The Valedictorian', [C.Resurrectionist], [C.Henchman, C.Construct, ", "end": 9008, "score": 0.5907509922981262, "start": 9000, "tag": "NAME", "value": "ictorian" }, { "context": "ademic, C.Wave2], 10, 3),\n \n new Model('Rasputina', [C.Arcanist], [C.Master, C.Living, C.Wave1], un", "end": 9150, "score": 0.9995496273040771, "start": 9141, "tag": "NAME", "value": "Rasputina" }, { "context": ", C.Living, C.Wave1], undefined, 3),\n new Model('Marcus', [C.Arcanist], [C.Master, C.Living, C.Beast, C.W", "end": 9232, "score": 0.9995995163917542, "start": 9226, "tag": "NAME", "value": "Marcus" }, { "context": "g, C.Beast, C.Wave1], undefined, 4),\n new Model('Ramos', [C.Arcanist], [C.Master, C.Living, C.Construct,", "end": 9322, "score": 0.9992985725402832, "start": 9317, "tag": "NAME", "value": "Ramos" }, { "context": "uct, C.Msu, C.Wave1], undefined, 3),\n new Model('Myranda', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C", "end": 9425, "score": 0.9893739223480225, "start": 9418, "tag": "NAME", "value": "Myranda" }, { "context": ", C.Rare1, C.Beast, C.Wave1], 8, 5),\n new Model('Joss', [C.Arcanist], [C.Henchman, C.Living, C.Construc", "end": 9517, "score": 0.9973593354225159, "start": 9513, "tag": "NAME", "value": "Joss" }, { "context": "t, C.Rare1, C.Msu, C.Wave1], 10, 3),\n new Model('Cojo', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C", "end": 9621, "score": 0.9977504014968872, "start": 9617, "tag": "NAME", "value": "Cojo" }, { "context": ", C.Rare1, C.Beast, C.Wave1], 8),\n new Model('Ice Golem', [C.Arcanist], [C.Enforcer, C.Construct, C.Wave1", "end": 9715, "score": 0.6275904178619385, "start": 9710, "tag": "NAME", "value": "Golem" }, { "context": "nforcer, C.Construct, C.Wave1], 10),\n new Model('Wendigo', [C.Arcanist], [C.Minion, C.Living, C.TotemFor('", "end": 9793, "score": 0.9978496432304382, "start": 9786, "tag": "NAME", "value": "Wendigo" }, { "context": "TotemFor('Rasputina'), C.Wave1], 3),\n new Model('Jackalope', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Ma", "end": 9892, "score": 0.9988810420036316, "start": 9883, "tag": "NAME", "value": "Jackalope" }, { "context": "pe', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Marcus'), C.Beast, C.Wave1], 2),\n new Model('Brass Arac", "end": 9946, "score": 0.9952355027198792, "start": 9940, "tag": "NAME", "value": "Marcus" }, { "context": "or('Marcus'), C.Beast, C.Wave1], 2),\n new Model('Brass Arachnid', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor(", "end": 10000, "score": 0.7937206029891968, "start": 9986, "tag": "NAME", "value": "Brass Arachnid" }, { "context": ", [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Ramos'), C.Msu, C.Wave1], 4),\n new Model('Essence of P", "end": 10056, "score": 0.9337799549102783, "start": 10051, "tag": "NAME", "value": "Ramos" }, { "context": ", C.Totem, C.Spirit, C.Wave1], 3),\n new Model('December Acolyte', [C.Arcanist], [C.Minion, C.Living, C.Wave1], 7)", "end": 10198, "score": 0.8499085307121277, "start": 10184, "tag": "NAME", "value": "cember Acolyte" }, { "context": " [C.Peon, C.Construct, C.Wave1], 4),\n new Model('Hoarcat Pride', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.S", "end": 10359, "score": 0.761517345905304, "start": 10346, "tag": "NAME", "value": "Hoarcat Pride" }, { "context": "ing, C.Beast, C.Swarm, C.Wave1], 5),\n new Model('Howard Langston', [C.Arcanist], [C.Enforcer, C.Construct, C.Livin", "end": 10457, "score": 0.9984899163246155, "start": 10442, "tag": "NAME", "value": "Howard Langston" }, { "context": "min, C.Msu, C.Foundry, C.Wave1], 4),\n new Model('Moleman', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.W", "end": 10753, "score": 0.9224985241889954, "start": 10746, "tag": "NAME", "value": "Moleman" }, { "context": "te Du Bois'), C.Rare3, C.Wave2], 2),\n new Model('Cassandra', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C", "end": 11845, "score": 0.9907881617546082, "start": 11836, "tag": "NAME", "value": "Cassandra" }, { "context": ".Rare1, C.Showgirl, C.Wave2], 8, 5),\n new Model('Coryphee', [C.Arcanist], [C.Minion, C.Construct, C.Rare2, ", "end": 11944, "score": 0.9922540783882141, "start": 11936, "tag": "NAME", "value": "Coryphee" }, { "context": " C.Showgirl, C.Puppet, C.Wave2], 7),\n new Model('Coryphee Duet', [C.Arcanist], [C.Enforcer, C.Construct, C.Showg", "end": 12056, "score": 0.970779538154602, "start": 12043, "tag": "NAME", "value": "Coryphee Duet" }, { "context": " C.Showgirl, C.Puppet, C.Wave2], 0),\n new Model('Performer', [C.Arcanist], [C.Minion, C.Living, C.Mercenary,", "end": 12157, "score": 0.8983749151229858, "start": 12148, "tag": "NAME", "value": "Performer" }, { "context": "Mercenary, C.Showgirl, C.Wave2], 5),\n new Model('Mannequin', [C.Arcanist], [C.Peon, C.Construct, C.Showgirl,", "end": 12256, "score": 0.9914964437484741, "start": 12247, "tag": "NAME", "value": "Mannequin" }, { "context": " C.Showgirl, C.Puppet, C.Wave2], 4),\n new Model('Kaeris', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wav", "end": 12350, "score": 0.9918391108512878, "start": 12344, "tag": "NAME", "value": "Kaeris" }, { "context": "mFor('Kaeris'), C.Msu, C.Wave2], 2),\n new Model('Gunsmith', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wav", "end": 12650, "score": 0.9916446208953857, "start": 12642, "tag": "NAME", "value": "Gunsmith" }, { "context": "ct, C.Rare1, C.Msu, C.Wave2], 3),\n \n new Model('Lilith', ['Neverborn'], [C.Master, C.Living, C.Nephilim,", "end": 14143, "score": 0.8414816856384277, "start": 14137, "tag": "NAME", "value": "Lilith" }, { "context": "C.Nephilim, C.Wave1], undefined, 4),\n new Model('Pandora', ['Neverborn'], [C.Master, C.Living, C.Woe, C.Wa", "end": 14239, "score": 0.7451474070549011, "start": 14232, "tag": "NAME", "value": "Pandora" }, { "context": "ing, C.Woe, C.Wave1], undefined, 3),\n new Model('Zoraida', ['Neverborn', C.Gremlin], [C.Master, C.Living, ", "end": 14330, "score": 0.6900224685668945, "start": 14323, "tag": "NAME", "value": "Zoraida" }, { "context": "Swampfiend, C.Wave1], undefined, 4),\n new Model('Barbaros', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, ", "end": 14440, "score": 0.8018297553062439, "start": 14432, "tag": "NAME", "value": "Barbaros" }, { "context": "Rare1, C.Nephilim, C.Wave1], 10, 3),\n new Model('Candy', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, ", "end": 14538, "score": 0.9796656370162964, "start": 14533, "tag": "NAME", "value": "Candy" }, { "context": "C.Mimic, C.Lost, C.Wave1], 9, 4),\n new Model('Bad Juju', ['Neverborn'], [C.Henchman, C.Rare1, C.Swampfie", "end": 14650, "score": 0.6803867220878601, "start": 14646, "tag": "NAME", "value": "Juju" }, { "context": "are1, C.Swampfiend, C.Wave1], 8, 5),\n new Model('Cherub', ['Neverborn'], [C.Peon, C.Living, C.TotemFor('L", "end": 14740, "score": 0.9592485427856445, "start": 14734, "tag": "NAME", "value": "Cherub" }, { "context": "ra'), C.Woe, C.Spirit, C.Wave1], 5),\n new Model('Voodoo Doll', ['Neverborn', C.Gremlin], [C.Peon, C.Construct,", "end": 14956, "score": 0.8599982261657715, "start": 14945, "tag": "NAME", "value": "Voodoo Doll" }, { "context": ".Rare3, C.Nightmare, C.Wave2], 2),\n new Model('Alp', [C.Neverborn], [C.Peon, C.Nightmare, C.Wave2], ", "end": 16430, "score": 0.8498632311820984, "start": 16429, "tag": "NAME", "value": "p" }, { "context": " [C.Peon, C.Nightmare, C.Wave2], 3),\n new Model('Coppelius', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmar", "end": 16506, "score": 0.8640411496162415, "start": 16497, "tag": "NAME", "value": "Coppelius" }, { "context": " C.Rare1, C.Nightmare, C.Wave2], 8),\n new Model('Lelu', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmar", "end": 16590, "score": 0.9450175762176514, "start": 16586, "tag": "NAME", "value": "Lelu" }, { "context": "re, C.Nephilim, C.Woe, C.Wave2], 7),\n new Model('Lilitu', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmar", "end": 16695, "score": 0.9483709931373596, "start": 16689, "tag": "NAME", "value": "Lilitu" }, { "context": ", C.Rare2, C.Nephilim, C.Wave2], 7),\n new Model('Nekima', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, ", "end": 17102, "score": 0.8395368456840515, "start": 17096, "tag": "NAME", "value": "Nekima" }, { "context": "Rare1, C.Nephilim, C.Wave2], 13, 0),\n new Model('Collodi', [C.Neverborn], [C.Master, C.Construct, C.Puppet", "end": 17202, "score": 0.9895763397216797, "start": 17195, "tag": "NAME", "value": "Collodi" }, { "context": ", C.Puppet, C.Wave2], undefined, 3),\n new Model('Marionette', [C.Neverborn], [C.Minion, C.Construct, C.TotemF", "end": 17302, "score": 0.9416907429695129, "start": 17292, "tag": "NAME", "value": "Marionette" }, { "context": "Rare1, C.Horseman, C.Wave2], 12),\n \n new Model('Von Schill', [C.Outcast], [C.Master, C.Living, C.Freikorps, ", "end": 18469, "score": 0.9995572566986084, "start": 18459, "tag": "NAME", "value": "Von Schill" }, { "context": ".Freikorps, C.Wave1], undefined, 1),\n new Model('Tara', [C.Outcast, C.Resurrectionist], [C.Master, C.Un", "end": 18561, "score": 0.9985678195953369, "start": 18557, "tag": "NAME", "value": "Tara" }, { "context": ", C.Sister, C.Wave1], undefined, 1),\n new Model('Hannah', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.", "end": 18763, "score": 0.9995551109313965, "start": 18757, "tag": "NAME", "value": "Hannah" }, { "context": " C.Rare1, C.Sister, C.Wave1], 0, 3),\n new Model('Taelor', [C.Outcast], [C.Henchman, C.Living, C.Mercenary", "end": 19062, "score": 0.9995377063751221, "start": 19056, "tag": "NAME", "value": "Taelor" }, { "context": "', [C.Outcast], [C.Peon, C.Construct, C.TotemFor('Von Schill'), C.Wave1], 3),\n new Model('Karina', [C.Outcast", "end": 19225, "score": 0.9948580265045166, "start": 19215, "tag": "NAME", "value": "Von Schill" }, { "context": "otemFor('Von Schill'), C.Wave1], 3),\n new Model('Karina', [C.Outcast, C.Resurrectionist], [C.Enforcer, C.", "end": 19262, "score": 0.9996087551116943, "start": 19256, "tag": "NAME", "value": "Karina" }, { "context": "urrectionist], [C.Enforcer, C.Living, C.TotemFor('Tara'), C.Wave1], 5),\n new Model('Student of Conflict", "end": 19336, "score": 0.9822431802749634, "start": 19332, "tag": "NAME", "value": "Tara" }, { "context": ", C.Mercenary, C.Lost, C.Wave1], 2),\n new Model('Bishop', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary", "end": 19592, "score": 0.9931150078773499, "start": 19586, "tag": "NAME", "value": "Bishop" }, { "context": "C.Mercenary, C.Rare1, C.Wave1], 10),\n new Model('Convict Gunslinger', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary", "end": 19699, "score": 0.9989827275276184, "start": 19681, "tag": "NAME", "value": "Convict Gunslinger" }, { "context": "Mercenary, C.Rare2, C.Wave1], 7),\n new Model('Desperate Mercenary', [C.Outcast], [C.Minion, C.Living, C.Mer", "end": 19798, "score": 0.6378806233406067, "start": 19790, "tag": "NAME", "value": "perate M" }, { "context": "ercenary, C.Freikorps, C.Wave1], 8),\n new Model('Freikorpsman', [C.Outcast], [C.Living, C.Minion, C.Mercenary, ", "end": 20007, "score": 0.9983938932418823, "start": 19995, "tag": "NAME", "value": "Freikorpsman" }, { "context": "ercenary, C.Freikorps, C.Wave1], 5),\n new Model('Hans', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary", "end": 20101, "score": 0.9995152950286865, "start": 20097, "tag": "NAME", "value": "Hans" }, { "context": " C.Mercenary, C.Rare1, C.Wave1], 8),\n new Model('Johan', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary", "end": 20194, "score": 0.9996359944343567, "start": 20189, "tag": "NAME", "value": "Johan" }, { "context": "enary, C.Rare1, C.Msu, C.Wave1], 6),\n new Model('Killjoy', [C.Outcast], [C.Enforcer, C.Undead, C.Mercenary", "end": 20296, "score": 0.7809256315231323, "start": 20289, "tag": "NAME", "value": "Killjoy" }, { "context": "y, C.Rare1, C.Horror, C.Wave1], 12),\n new Model('Ronin', [C.Outcast], [C.Minion, C.Living, C.Mercenary, ", "end": 20400, "score": 0.9992157816886902, "start": 20395, "tag": "NAME", "value": "Ronin" }, { "context": "ving, C.Mercenary, C.Wave1], 6),\n new Model('Void Wretch', [C.Outcast], [C.Minion, C.Wave1], 4),\n \n new ", "end": 20488, "score": 0.9757195711135864, "start": 20482, "tag": "NAME", "value": "Wretch" }, { "context": "utcast], [C.Minion, C.Wave1], 4),\n \n new Model('Jack Daw', [C.Outcast], [C.Master, C.Undead, C.Tormented, ", "end": 20553, "score": 0.9996321797370911, "start": 20545, "tag": "NAME", "value": "Jack Daw" }, { "context": "C.Undead, C.Tormented, C.Wave2], 5),\n new Model('Montresor', [C.Outcast], [C.Henchman, C.Undead, C.Rare1, C.", "end": 20757, "score": 0.9995575547218323, "start": 20748, "tag": "NAME", "value": "Montresor" }, { "context": "Rare1, C.Tormented, C.Wave2], 9, 4),\n new Model('Lady Ligeia', [C.Outcast], [C.Peon, C.TotemFor('Jack Daw'), C", "end": 20859, "score": 0.9997329711914062, "start": 20848, "tag": "NAME", "value": "Lady Ligeia" }, { "context": "('Lady Ligeia', [C.Outcast], [C.Peon, C.TotemFor('Jack Daw'), C.Tormented, C.Spirit, C.Wave2], 4),\n new Mod", "end": 20904, "score": 0.9997820854187012, "start": 20896, "tag": "NAME", "value": "Jack Daw" }, { "context": "C.Tormented, C.Spirit, C.Wave2], 4),\n new Model('Hamelin', [C.Outcast], [C.Master, C.Tyrant, C.Nihilist, C", "end": 20965, "score": 0.9996984601020813, "start": 20958, "tag": "NAME", "value": "Hamelin" }, { "context": "C.Nihilist, C.Wave2], undefined, 1),\n new Model('Nix', [C.Outcast], [C.Henchman, C.Rare1, C.Nihilist, ", "end": 21055, "score": 0.9981197714805603, "start": 21052, "tag": "NAME", "value": "Nix" }, { "context": ", C.Rare2, C.Nihilist, C.Wave2], 6),\n new Model('Malifaux Rat', [C.Outcast], [C.Peon, C.Vermin, C.Wave2]", "end": 21346, "score": 0.6590205430984497, "start": 21341, "tag": "NAME", "value": "Malif" }, { "context": "2, C.Nihilist, C.Wave2], 6),\n new Model('Malifaux Rat', [C.Outcast], [C.Peon, C.Vermin, C.Wave2], 2),\n ", "end": 21353, "score": 0.7661603689193726, "start": 21350, "tag": "NAME", "value": "Rat" }, { "context": "len', [C.Outcast], [C.Peon, C.Living, C.TotemFor('Hamelin'), C.Rare3, C.Nihilist, C.Lost, C.Wave2], 2),\n n", "end": 21560, "score": 0.9990790486335754, "start": 21553, "tag": "NAME", "value": "Hamelin" }, { "context": ", C.Living, C.Wave2], undefined, 2),\n new Model('Rusty Alyce', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.", "end": 22891, "score": 0.9996590614318848, "start": 22880, "tag": "NAME", "value": "Rusty Alyce" }, { "context": "C.Living, C.Rare1, C.Wave2], 10, 3),\n new Model('Hollow Waif', [C.Outcast], [C.Peon, C.Undead, C.TotemFor('Lev", "end": 22981, "score": 0.8997901082038879, "start": 22970, "tag": "NAME", "value": "Hollow Waif" }, { "context": ", C.Rare1, C.Wave2], 13),\n \n new Model('Som\\'er Teeth Jones', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 23301, "score": 0.9997552037239075, "start": 23282, "tag": "NAME", "value": "Som\\'er Teeth Jones" }, { "context": " C.Gremlin, C.Wave1], undefined, 4),\n new Model('Ophelia LaCroix', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 23402, "score": 0.9998494386672974, "start": 23387, "tag": "NAME", "value": "Ophelia LaCroix" }, { "context": ", C.TriChi, C.Wave1], undefined, 3),\n new Model('Francois LaCroix', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.", "end": 23636, "score": 0.9998404383659363, "start": 23620, "tag": "NAME", "value": "Francois LaCroix" }, { "context": "Gremlin, C.TriChi, C.Wave1], 10, 3),\n new Model('Lenny', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.", "end": 23844, "score": 0.9997773170471191, "start": 23839, "tag": "NAME", "value": "Lenny" }, { "context": "t, C.Rare1, C.TriChi, C.Wave1], 10),\n new Model('Skeeter', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Som", "end": 24039, "score": 0.970268964767456, "start": 24032, "tag": "NAME", "value": "Skeeter" }, { "context": "er', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Som\\'er Teeth Jones'), C.Wave1], 2),\n new Model('Young LaCroix', [C.", "end": 24105, "score": 0.9038834571838379, "start": 24087, "tag": "NAME", "value": "om\\'er Teeth Jones" }, { "context": "Som\\'er Teeth Jones'), C.Wave1], 2),\n new Model('Young LaCroix', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Oph", "end": 24149, "score": 0.9760370254516602, "start": 24136, "tag": "NAME", "value": "Young LaCroix" }, { "context": "x', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Ophelia LaCroix'), C.Gremlin, C.Kin, C.Wave1], 2),\n new Model('A", "end": 24211, "score": 0.9282469749450684, "start": 24198, "tag": "NAME", "value": "helia LaCroix" }, { "context": "x'), C.Gremlin, C.Kin, C.Wave1], 2),\n new Model('Apprentice Wesley', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('T", "end": 24277, "score": 0.9611866474151611, "start": 24260, "tag": "NAME", "value": "Apprentice Wesley" }, { "context": ".Gremlin, C.TriChi, C.Wave1], 3),\n new Model('Bayou Gremlin', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.", "end": 24405, "score": 0.7375435829162598, "start": 24395, "tag": "NAME", "value": "ou Gremlin" }, { "context": "re1, C.Gremlin, C.Kin, C.Wave1], 6),\n new Model('Rami LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.", "end": 25146, "score": 0.9996886253356934, "start": 25134, "tag": "NAME", "value": "Rami LaCroix" }, { "context": "re1, C.Gremlin, C.Kin, C.Wave1], 7),\n new Model('Raphael LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.", "end": 25254, "score": 0.9998344779014587, "start": 25239, "tag": "NAME", "value": "Raphael LaCroix" }, { "context": ", C.Gremlin, C.Kin, C.Wave1], 7),\n \n new Model('Ulix', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 25354, "score": 0.9934245347976685, "start": 25350, "tag": "NAME", "value": "Ulix" }, { "context": "ope', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Ulix'), C.Hound, C.Wave2], 2),\n new Model('The Sow', ", "end": 25499, "score": 0.9768962860107422, "start": 25495, "tag": "NAME", "value": "Ulix" }, { "context": "ndead, C.Rare6, C.Pig, C.Wave2], 2),\n new Model('Gremlin Taxidermist', [C.Gremlin], [C.Enforcer, C.Living, C.Rare2, C.", "end": 25939, "score": 0.8897926807403564, "start": 25920, "tag": "NAME", "value": "Gremlin Taxidermist" }, { "context": "g, C.Rare2, C.Gremlin, C.Wave2], 7),\n new Model('Mah Tucket', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 26035, "score": 0.9900223016738892, "start": 26025, "tag": "NAME", "value": "Mah Tucket" }, { "context": "h Tucket'), C.Gremlin, C.Wave2], 4),\n new Model('Trixiebelle', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.", "end": 26246, "score": 0.9815554618835449, "start": 26235, "tag": "NAME", "value": "Trixiebelle" }, { "context": "C.Rare1, C.Gremlin, C.Wave2], 8, 5),\n new Model('Bayou Bushwhacker', [C.Gremlin], [C.Minion, C.Living, C.Rare3, C.Gr", "end": 26352, "score": 0.9580777287483215, "start": 26335, "tag": "NAME", "value": "Bayou Bushwhacker" }, { "context": "g, C.Rare3, C.Gremlin, C.Wave2], 6),\n new Model('McTavish', [C.Gremlin], [C.Henchman, C.Living, C.Mercenary", "end": 26444, "score": 0.9989438056945801, "start": 26436, "tag": "NAME", "value": "McTavish" }, { "context": "re1, C.Swampfiend, C.Wave2], 10, 3),\n new Model('Mancha Roja', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.", "end": 26561, "score": 0.9998717308044434, "start": 26550, "tag": "NAME", "value": "Mancha Roja" }, { "context": ".Rare1, C.Gremlin, C.Wave2], 10, 3),\n new Model('Burt Jebsen', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary", "end": 26662, "score": 0.9998748898506165, "start": 26651, "tag": "NAME", "value": "Burt Jebsen" }, { "context": "y, C.Rare1, C.Gremlin, C.Wave2], 7),\n new Model('Gracie', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary", "end": 26767, "score": 0.9980290532112122, "start": 26761, "tag": "NAME", "value": "Gracie" }, { "context": "nary, C.Rare1, C.Pig, C.Wave2], 10),\n new Model('Merris LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.", "end": 26877, "score": 0.999701201915741, "start": 26863, "tag": "NAME", "value": "Merris LaCroix" }, { "context": "1, C.Puppet, C.Effigy, C.Wave2], 4),\n new Model('Wong', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 27185, "score": 0.5855576992034912, "start": 27181, "tag": "NAME", "value": "Wong" }, { "context": ", C.Living, C.Gremlin, C.Wave2], 5),\n new Model('Bayou Gator', [C.Gremlin], [C.Minion, C.Living, C.Swampfiend,", "end": 27491, "score": 0.9986798167228699, "start": 27480, "tag": "NAME", "value": "Bayou Gator" }, { "context": ".Living, C.Swampfiend, C.Wave2], 5),\n new Model('Sammy LaCroix', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.", "end": 27582, "score": 0.9998847842216492, "start": 27569, "tag": "NAME", "value": "Sammy LaCroix" }, { "context": ", C.Gremlin, C.Kin, C.Wave2], 7, 6),\n new Model('Old Cranky', [C.Gremlin], [C.Peon, C.Living, C.Totem, C.Grem", "end": 27688, "score": 0.9753745198249817, "start": 27678, "tag": "NAME", "value": "Old Cranky" }, { "context": " C.Gremlin, C.Wave2], 4),\n \n new Model('Misaki', [C.TenThunders, C.Outcast], [C.Master, C.Living", "end": 27787, "score": 0.9994818568229675, "start": 27781, "tag": "NAME", "value": "Misaki" }, { "context": "astBlossom, C.Wave1], undefined, 2),\n new Model('Mei Feng', [C.TenThunders, C.Arcanist], [C.Master, C.Livin", "end": 27900, "score": 0.9997265338897705, "start": 27892, "tag": "NAME", "value": "Mei Feng" }, { "context": " C.Foundry, C.Wave1], undefined, 3),\n new Model('Jakob Lynch', [C.TenThunders, C.Neverborn], [C.Master, C.Livi", "end": 28013, "score": 0.9998593330383301, "start": 28002, "tag": "NAME", "value": "Jakob Lynch" }, { "context": "C.Darkened, C.Wave1], undefined, 1),\n new Model('Ototo', [C.TenThunders], [C.Henchman, C.Living, C.Rare1", "end": 28122, "score": 0.9995888471603394, "start": 28117, "tag": "NAME", "value": "Ototo" }, { "context": "e1, C.LastBlossom, C.Wave1], 10, 3),\n new Model('Kang', [C.TenThunders], [C.Henchman, C.Living, C.Rare1", "end": 28224, "score": 0.9983848333358765, "start": 28220, "tag": "NAME", "value": "Kang" }, { "context": "C.Rare1, C.Foundry, C.Wave1], 9, 4),\n new Model('Yamaziko', [C.TenThunders], [C.Henchman, C.Living, C.Rare1", "end": 28325, "score": 0.9957351088523865, "start": 28317, "tag": "NAME", "value": "Yamaziko" }, { "context": "re1, C.LastBlossom, C.Wave1], 7, 6),\n new Model('Shang', [C.TenThunders, C.Outcast], [C.Peon, C.Living, ", "end": 28427, "score": 0.9914309978485107, "start": 28422, "tag": "NAME", "value": "Shang" }, { "context": "nders, C.Outcast], [C.Peon, C.Living, C.TotemFor('Misaki'), C.Wave1], 3),\n new Model('Emberling', [C.TenT", "end": 28495, "score": 0.9664175510406494, "start": 28489, "tag": "NAME", "value": "Misaki" }, { "context": " C.TotemFor('Misaki'), C.Wave1], 3),\n new Model('Emberling', [C.TenThunders, C.Arcanist], [C.Minion, C.Totem", "end": 28535, "score": 0.990279495716095, "start": 28526, "tag": "NAME", "value": "Emberling" }, { "context": ".TenThunders, C.Arcanist], [C.Minion, C.TotemFor('Mei Feng'), C.Spirit, C.Wave1], 3),\n new Model('Hungering", "end": 28598, "score": 0.9949764609336853, "start": 28590, "tag": "NAME", "value": "Mei Feng" }, { "context": "nThunders, C.Neverborn], [C.Henchman, C.TotemFor('Jakob Lynch'), C.Rare1, C.Spirit, C.Darkened, C.Wave1], 0, 5)", "end": 28726, "score": 0.9997664093971252, "start": 28715, "tag": "NAME", "value": "Jakob Lynch" }, { "context": "pirit, C.Darkened, C.Wave1], 0, 5),\n new Model('Dawn Serpent', [C.TenThunders], [C.Minion, C.Living, C.Rare1, ", "end": 28803, "score": 0.764665424823761, "start": 28792, "tag": "NAME", "value": "awn Serpent" }, { "context": "ng, C.Rare1, C.Beast, C.Wave1], 10),\n new Model('Fuhatsu', [C.TenThunders], [C.Henchman, C.Living, C.Rare1", "end": 28897, "score": 0.9937620759010315, "start": 28890, "tag": "NAME", "value": "Fuhatsu" }, { "context": "on, C.Living, C.Rare3, C.Wave1], 4),\n new Model('Oiran', [C.TenThunders], [C.Minion, C.Living, C.Mercena", "end": 29079, "score": 0.9924125671386719, "start": 29074, "tag": "NAME", "value": "Oiran" }, { "context": ", [C.Minion, C.Living, C.Wave1], 7),\n new Model('Torakage', [C.TenThunders], [C.Minion, C.Living, C.Mercena", "end": 29502, "score": 0.98880535364151, "start": 29494, "tag": "NAME", "value": "Torakage" }, { "context": "cenary, C.LastBlossom, C.Wave1], 6),\n new Model('Samurai', [C.TenThunders], [C.Enforcer, C.Living, C.Wave1", "end": 29605, "score": 0.9956839680671692, "start": 29598, "tag": "NAME", "value": "Samurai" }, { "context": "Enforcer, C.Living, C.Wave1], 8),\n \n new Model('Lucas McCabe', [C.TenThunders, C.Guild], [C.Master, C.Living, ", "end": 29690, "score": 0.9977504014968872, "start": 29678, "tag": "NAME", "value": "Lucas McCabe" }, { "context": "BlackSheep, C.Wave2], undefined, 2),\n new Model('Dismounted McCabe', [C.TenThunders, C.Guild], [C.Master, C.Living, ", "end": 29809, "score": 0.9648586511611938, "start": 29792, "tag": "NAME", "value": "Dismounted McCabe" }, { "context": "BlackSheep, C.Wave2], undefined, 0),\n new Model('Sidir Alchibal', [C.TenThunders, C.Guild], [C.Henchman, C.Living", "end": 29925, "score": 0.9989327788352966, "start": 29911, "tag": "NAME", "value": "Sidir Alchibal" }, { "context": "are1, C.BlackSheep, C.Wave2], 9, 4),\n new Model('Luna', [C.TenThunders, C.Guild], [C.Minion, C.Living, ", "end": 30034, "score": 0.9882854223251343, "start": 30030, "tag": "NAME", "value": "Luna" }, { "context": "nders, C.Guild], [C.Minion, C.Living, C.TotemFor('Lucas McCabe'), C.Beast, C.Hound, C.Wave2], 4),\n new Model('W", "end": 30108, "score": 0.9604222178459167, "start": 30096, "tag": "NAME", "value": "Lucas McCabe" }, { "context": "e'), C.Beast, C.Hound, C.Wave2], 4),\n new Model('Wastrel', [C.TenThunders, C.Guild], [C.Minion, C.Living, ", "end": 30164, "score": 0.9883993268013, "start": 30157, "tag": "NAME", "value": "Wastrel" }, { "context": ".Living, C.BlackSheep, C.Wave2], 4),\n new Model('Yan Lo', [C.TenThunders, C.Resurrectionist], [C.Master, ", "end": 30261, "score": 0.9774314761161804, "start": 30255, "tag": "NAME", "value": "Yan Lo" }, { "context": ".Ancestor, C.Wave2], undefined, 4),\n new Model('Soul Porter', [C.TenThunders, C.Resurrectionist], [C.Peon, ", "end": 30380, "score": 0.5884225368499756, "start": 30372, "tag": "NAME", "value": "oul Port" }, { "context": "r('Yan Lo'), C.Spirit, C.Wave2], 3),\n new Model('Chiaki the Niece', [C.TenThunders, C.Resurrectionist], [C.En", "end": 30499, "score": 0.6608421206474304, "start": 30489, "tag": "NAME", "value": "Chiaki the" }, { "context": "C.Minion, C.Living, C.Wave2], 5),\n new Model('Mr. Graves', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Li", "end": 31118, "score": 0.9202146530151367, "start": 31112, "tag": "NAME", "value": "Graves" }, { "context": ".Darkened, C.Mimic, C.Wave2], 8),\n new Model('Mr. Tannen', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Li", "end": 31253, "score": 0.9791402816772461, "start": 31247, "tag": "NAME", "value": "Tannen" }, { "context": " C.Living, C.Rare1, C.Wave2], 9, 4),\n new Model('Shenlong', [C.TenThunders], [C.Master, C.Living, C.Tyrant,", "end": 31685, "score": 0.8352381587028503, "start": 31677, "tag": "NAME", "value": "Shenlong" }, { "context": ", [C.TenThunders], [C.Peon, C.Living, C.TotemFor('Shenlong'), C.Rare2, C.Wave2], 2),\n new Model('Fermented ", "end": 31840, "score": 0.6556376814842224, "start": 31832, "tag": "NAME", "value": "Shenlong" }, { "context": "irit, C.Oni, C.Wave2], 4),\n new Model('Katanaka Sniper', [C.TenThunders], [C.Minion, C.Living, C.Rare", "end": 32346, "score": 0.7403373122215271, "start": 32344, "tag": "NAME", "value": "ni" }, { "context": "n, C.BlackSheep, C.Wave3], 7, 6),\n new Model('Dr. Grimwell', [C.Guild], [C.Henchman, C.Living, C.Mercenary, ", "end": 32653, "score": 0.9941067695617676, "start": 32645, "tag": "NAME", "value": "Grimwell" }, { "context": "ercenary, C.Rare1, C.Wave3], 9, 4),\n new Model('Sloth', [C.Resurrectionist], [C.Enforcer, C.Undead, C", "end": 33513, "score": 0.5143094062805176, "start": 33511, "tag": "NAME", "value": "lo" }, { "context": "er, C.Living, C.Rare1, C.Wave3], 7),\n new Model('Hayreddin', [C.Resurrectionist], [C.Enforcer, C.Living, C.R", "end": 33766, "score": 0.9810889959335327, "start": 33757, "tag": "NAME", "value": "Hayreddin" }, { "context": ", [C.Minion, C.Oni, C.Wave3], 6),\n new Model('Jorogumo', [C.TenThunders], [C.Minion, C.Oni, C.LastBloss", "end": 36711, "score": 0.579882025718689, "start": 36707, "tag": "NAME", "value": "ogum" }, { "context": "Oni, C.LastBlossom, C.Wave3], 9),\n \n new Model('Nellie Cochrane', [C.Guild], [C.Master, C.Living, C.Journalist, C", "end": 36810, "score": 0.9930815696716309, "start": 36795, "tag": "NAME", "value": "Nellie Cochrane" }, { "context": "ss', [C.Guild], [C.Peon, C.Construct, C.TotemFor('Nellie Cochrane'), C.Journalist, C.Wave4], 3),\n new Model('Phion", "end": 36978, "score": 0.8891021609306335, "start": 36963, "tag": "NAME", "value": "Nellie Cochrane" }, { "context": "hrane'), C.Journalist, C.Wave4], 3),\n new Model('Phiona Gage', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Jo", "end": 37034, "score": 0.996955394744873, "start": 37023, "tag": "NAME", "value": "Phiona Gage" }, { "context": "Rare2, C.GuildMarshal, C.Wave4], 7),\n new Model('Witchling Thrall', [C.Guild], [C.Minion, C.Living, C.WitchHunter, ", "end": 37444, "score": 0.6864361763000488, "start": 37428, "tag": "NAME", "value": "Witchling Thrall" }, { "context": "ing, C.WitchHunter, C.Wave4], 9),\n \n new Model('Reva', [C.Resurrectionist], [C.Master, C.Living, C.Rev", "end": 37528, "score": 0.8937450647354126, "start": 37524, "tag": "NAME", "value": "Reva" }, { "context": "C.Revenant, C.Wave4], undefined, 4),\n new Model('Corpse Candle', [C.Resurrectionist], [C.Peon, C.Undead, C.Totem", "end": 37636, "score": 0.5615026950836182, "start": 37623, "tag": "NAME", "value": "Corpse Candle" }, { "context": " C.Spirit, C.Revenant, C.Wave4], 2),\n new Model('Vincent St. Clair', [C.Resurrectionist], [C.Henchman, C.Living, C.R", "end": 37765, "score": 0.9650882482528687, "start": 37748, "tag": "NAME", "value": "Vincent St. Clair" }, { "context": ".Rare1, C.Revenant, C.Wave4], 8, 5),\n new Model('Archie', [C.Resurrectionist], [C.Henchman, C.Undead, C.R", "end": 37869, "score": 0.9780369400978088, "start": 37863, "tag": "NAME", "value": "Archie" }, { "context": "1, C.Horror, C.Wave4], 13, 0),\n new Model('Shieldbearer', [C.Resurrectionist], [C.Minion, C.Living, C.Rev", "end": 37978, "score": 0.5743445158004761, "start": 37972, "tag": "NAME", "value": "bearer" }, { "context": " C.Living, C.Revenant, C.Wave4], 6),\n new Model('Draugr', [C.Resurrectionist], [C.Minion, C.Undead, C.Rev", "end": 38068, "score": 0.9290618896484375, "start": 38062, "tag": "NAME", "value": "Draugr" }, { "context": " C.Revenant, C.Horror, C.Wave4], 8),\n new Model('Goryo', [C.Resurrectionist], [C.Minion, C.Spirit, C.Ret", "end": 38167, "score": 0.9645007252693176, "start": 38162, "tag": "NAME", "value": "Goryo" }, { "context": "Spirit, C.Retainer, C.Wave4], 7),\n \n new Model('Sandeep Desai', [C.Arcanist], [C.Master, C.Living, C.Academic, ", "end": 38267, "score": 0.9991756677627563, "start": 38254, "tag": "NAME", "value": "Sandeep Desai" }, { "context": "pse Candle', [C.Arcanist], [C.Minion, C.TotemFor('Sandeep Desai'), C.Rare1, C.Gamin, C.Wave4], 8),\n new Model('K", "end": 38421, "score": 0.999836802482605, "start": 38408, "tag": "NAME", "value": "Sandeep Desai" }, { "context": "i'), C.Rare1, C.Gamin, C.Wave4], 8),\n new Model('Kudra', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C", "end": 38475, "score": 0.9991604685783386, "start": 38470, "tag": "NAME", "value": "Kudra" }, { "context": ".Rare1, C.Academic, C.Wave4], 7, 6),\n new Model('Amina Naidu', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C", "end": 38577, "score": 0.9998459815979004, "start": 38566, "tag": "NAME", "value": "Amina Naidu" }, { "context": " C.Msu, C.Academic, C.Wave4], 9, 4),\n new Model('Carlos Vasquez', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C", "end": 38689, "score": 0.9998407363891602, "start": 38675, "tag": "NAME", "value": "Carlos Vasquez" }, { "context": ".Rare1, C.Showgirl, C.Wave4], 9, 4),\n new Model('Poison Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, ", "end": 38792, "score": 0.997647225856781, "start": 38780, "tag": "NAME", "value": "Poison Gamin" }, { "context": "uct, C.Gamin, C.Beast, C.Wave4], 5),\n new Model('Shastar Vidiya Guard', [C.Arcanist], [C.Enforcer, C.Living, C.Msu, C.A", "end": 38898, "score": 0.9941629767417908, "start": 38878, "tag": "NAME", "value": "Shastar Vidiya Guard" }, { "context": " C.Msu, C.Academic, C.Wave4], 8),\n \n new Model('Titania', [C.Neverborn], [C.Master, C.Undead, C.Fae, C.Wa", "end": 38994, "score": 0.9934207797050476, "start": 38987, "tag": "NAME", "value": "Titania" }, { "context": "C.Fae, C.Wave4], undefined, 4),\n new Model('The Gorare', [C.Neverborn], [C.Peon, C.Living, C.TotemFor('T", "end": 39088, "score": 0.858554482460022, "start": 39083, "tag": "NAME", "value": "orare" }, { "context": "For('Titania'), C.Fae, C.Wave4], 3),\n new Model('Aeslin', [C.Neverborn], [C.Henchman, C.Undead, C.Rare1, ", "end": 39188, "score": 0.9996945261955261, "start": 39182, "tag": "NAME", "value": "Aeslin" }, { "context": "ndead, C.Rare1, C.Fae, C.Wave4], 7),\n new Model('Bandersnatch', [C.Neverborn], [C.Minion, C.Living, C.Rare1", "end": 39555, "score": 0.5293363928794861, "start": 39547, "tag": "NAME", "value": "Bandersn" }, { "context": "ad, C.Fae, C.Beast, C.Wave4], 8),\n \n new Model('Parker Barrows', [C.Outcast], [C.Master, C.Living, C.Bandit, C.W", "end": 39877, "score": 0.9949286580085754, "start": 39863, "tag": "NAME", "value": "Parker Barrows" }, { "context": ", C.Bandit, C.Wave4], undefined, 4),\n new Model('Doc Mitchell', [C.Outcast], [C.Minion, C.Living, C.TotemFor('P", "end": 39974, "score": 0.9972309470176697, "start": 39962, "tag": "NAME", "value": "Doc Mitchell" }, { "context": "l', [C.Outcast], [C.Minion, C.Living, C.TotemFor('Parker Barrows'), C.Wave4], 3),\n new Model('Mad Dog Brackett', ", "end": 40037, "score": 0.9912627935409546, "start": 40023, "tag": "NAME", "value": "Parker Barrows" }, { "context": " C.Rare1, C.Bandit, C.Wave4], 9, 4),\n new Model('Aionus', [C.Outcast], [C.Henchman, C.Mercenary, C.Rare1,", "end": 40178, "score": 0.9474957585334778, "start": 40172, "tag": "NAME", "value": "Aionus" }, { "context": "ercenary, C.Rare1, C.Wave4], 12, 1),\n new Model('Bandido', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.W", "end": 40267, "score": 0.9841746687889099, "start": 40260, "tag": "NAME", "value": "Bandido" }, { "context": "C.Bandit, C.Tormented, C.Wave4], 6),\n new Model('Wokou Raider', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.L", "end": 40452, "score": 0.9710159301757812, "start": 40440, "tag": "NAME", "value": "Wokou Raider" }, { "context": "dit, C.LastBlossom, C.Wave4], 8),\n \n new Model('Zipp', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.", "end": 40548, "score": 0.9950243234634399, "start": 40544, "tag": "NAME", "value": "Zipp" }, { "context": ".SkyPirate, C.Wave4], undefined, 4),\n new Model('Earl Burns', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('Z", "end": 40657, "score": 0.9630207419395447, "start": 40647, "tag": "NAME", "value": "Earl Burns" }, { "context": "s', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('Zipp'), C.Wave4], 3),\n new Model('The First Mate', [C", "end": 40710, "score": 0.9285041689872742, "start": 40706, "tag": "NAME", "value": "Zipp" }, { "context": "fiend, C.SkyPirate, C.Wave4], 9, 4),\n new Model('Iron Skeeter', [C.Gremlin], [C.Enforcer, C.Living, C.Construct", "end": 40872, "score": 0.9783704876899719, "start": 40860, "tag": "NAME", "value": "Iron Skeeter" }, { "context": ".Gremlin, C.SkyPirate, C.Wave4], 6),\n new Model('Akaname', [C.Gremlin, C.TenThunders], [C.Minion, C.Rare3,", "end": 40982, "score": 0.8379404544830322, "start": 40975, "tag": "NAME", "value": "Akaname" }, { "context": "are3, C.Oni, C.TriChi, C.Wave4], 4),\n new Model('Banjonista', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.", "end": 41087, "score": 0.9421666264533997, "start": 41077, "tag": "NAME", "value": "Banjonista" }, { "context": "C.Rare2, C.Gremlin, C.Wave4], 7),\n \n new Model('Asami Tanaka', [C.TenThunders], [C.Master, C.Living, C.Oni, C.", "end": 41273, "score": 0.9508346319198608, "start": 41261, "tag": "NAME", "value": "Asami Tanaka" }, { "context": "ing, C.Oni, C.Wave4], undefined, 3),\n new Model('Amanjaku', [C.TenThunders], [C.Peon, C.TotemFor('Asami Tan", "end": 41367, "score": 0.9747380018234253, "start": 41359, "tag": "NAME", "value": "Amanjaku" }, { "context": "'Amanjaku', [C.TenThunders], [C.Peon, C.TotemFor('Asami Tanaka'), C.Oni, C.Wave4], 3),\n new Model('Ohaguro Bett", "end": 41420, "score": 0.8752321004867554, "start": 41408, "tag": "NAME", "value": "Asami Tanaka" }, { "context": "Asami Tanaka'), C.Oni, C.Wave4], 3),\n new Model('Ohaguro Bettari', [C.TenThunders], [C.Henchman, C.Rare1, C.Oni, C", "end": 41473, "score": 0.9949657917022705, "start": 41458, "tag": "NAME", "value": "Ohaguro Bettari" }, { "context": "uct, C.Rare3, C.Mimic, C.Wave4], 5),\n new Model('Sun Quiang', [C.TenThunders], [C.Enforcer, C.Rare1, C.Living", "end": 41739, "score": 0.9988642334938049, "start": 41729, "tag": "NAME", "value": "Sun Quiang" } ]
proto/data/ModelList.coffee
AppSynergy/malifaux-crew-explorer
0
import ModelInterface from './ModelInterface.coffee' Model = ModelInterface.Model C = ModelInterface.Attribute # **Epic props** to rythos42 for saving me having to research and type all this! # https://github.com/rythos42/MalifauxModels-Web/blob/master/js/app/Mappers/ModelList.js ModelList = [ new Model('Lady Justice', [C.Guild], [C.Master, C.Living, C.GuildMarshal, C.Wave1], undefined, 4), new Model('Sonnia Criid', [C.Guild], [C.Master, C.Living, C.WitchHunter, C.Wave1], undefined, 3), new Model('Perdita Ortega', [C.Guild], [C.Master, C.Living, C.Family, C.Wave1], undefined, 2), new Model('Franscisco Ortega', [C.Guild], [C.Henchman, C.Living, C.Family, C.Wave1], 8, 5), new Model('Samael Hopkins', [C.Guild], [C.Henchman, C.Living, C.WitchHunter, C.Wave1], 9, 4), new Model('The Judge', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 9, 4), new Model('Scales of Justice', [C.Guild], [C.Peon, C.Living, C.TotemFor('Lady Justice'), C.Wave1], 3), new Model('Purifying Flame', [C.Guild], [C.Peon, C.TotemFor('Sonnia Criid'), C.Spirit, C.Wave1], 3), new Model('Enslaved Nephilim', [C.Guild], [C.Peon, C.TotemFor('Perdita Ortega'), C.Nephilim, C.Wave1], 3), new Model('Governor\'s Proxy', [C.Guild], [C.Peon, C.Totem, C.Living, C.Wave1], 3), new Model('Death Marshal', [C.Guild], [C.Minion, C.Living, C.GuildMarshal, C.Wave1], 6), new Model('Executioner', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Wave1], 9), new Model('Guild Austringer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Guardsman, C.Wave1], 6), new Model('Guild Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave1], 4), new Model('Peacekeeper', [C.Guild], [C.Enforcer, C.Construct, C.Rare1, C.Wave1], 11), new Model('The Lone Marshal', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 8), new Model('Witchling Stalker', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave1], 5), new Model('Nino Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('Papa Loco', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Tormented, C.Wave1], 7), new Model('Santiago Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('C. Hoffman', [C.Guild], [C.Master, C.Living, C.Construct, C.Msu, C.Wave2], undefined, 3), new Model('Ryle', [C.Guild], [C.Henchman, C.Construct, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Mechanical Attendant', [C.Guild], [C.Peon, C.Construct, C.TotemFor('C. Hoffman'), C.Wave2], 2), new Model('Guardian', [C.Guild], [C.Minion, C.Construct, C.Wave2], 8), new Model('Lucius', [C.Guild, C.Neverborn], [C.Master, C.Living, C.Mimic, C.Wave2], undefined, 4), new Model('Captain Dashel', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.Wave2], 9, 4), new Model('The Scribe', [C.Guild, C.Neverborn], [C.Peon, C.Living, C.TotemFor('Lucius'), C.Wave2], 2), new Model('Abuela Ortega', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave2], 7), new Model('Guild Hound', [C.Guild], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Guardsman, C.Wave2], 3), new Model('Guard Sergeant', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Guardsman, C.Wave2], 6), new Model('Hunter', [C.Guild], [C.Minion, C.Construct, C.Rare2, C.Wave2], 7), new Model('Guild Lawyer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Mimic, C.Wave2], 6), new Model('Watcher', [C.Guild], [C.Minion, C.Construct, C.Wave2], 4), new Model('Exorcist', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave2], 7), new Model('Pistolero De Latigo', [C.Guild], [C.Minion, C.Living, C.Family, C.Wave2], 5), new Model('Pale Rider', [C.Guild], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Warden', [C.Guild], [C.Minion, C.Construct, C.Guardsman, C.Wave2], 6), new Model('Witchling Handler', [C.Guild], [C.Enforcer, C.Living, C.WitchHunter, C.Wave2], 8), new Model('Brutal Effigy', [C.Guild], [C.Minion, C.Construct, C.Puppet, C.Effigy, C.Rare1, C.Wave2], 4), new Model('Guild Rifleman', [C.Guild], [C.Minion, C.Living, C.Rare3, C.Guardsman, C.Wave2], 5), new Model('Clockwork Trap', [C.Guild, C.TenThunders], [C.Peon, C.Rare4, C.Wave2], 2), new Model('Guild Pathfinder', [C.Guild, C.TenThunders], [C.Minion, C.Living, C.Guardsman, C.Wave2], 6), new Model('Seamus', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('McMourning', [C.Resurrectionist, C.Guild], [C.Master, C.Living, C.Wave1], undefined, 4), new Model('Nicodem', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('Madam Sybelle', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Wave1], 8, 5), new Model('Sebastian', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 7, 6), new Model('Mortimer', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 9, 4), new Model('Copycat Killer', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Seamus'), C.Wave1], 3), new Model('Zombie Chihuahua', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('McMourning'), C.Beast, C.Wave1], 2), new Model('Vulture', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Nicodem'), C.Beast, C.Wave1], 3), new Model('Graveyard Spirit', [C.Resurrectionist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('Bete Noire', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Wave1], 8), new Model('Canine Remains', [C.Resurrectionist], [C.Minion, C.Undead, C.Beast, C.Hound, C.Wave1], 4), new Model('Crooked Man', [C.Resurrectionist], [C.Minion, C.Undead, C.Tormented, C.Wave1], 5), new Model('Flesh Construct', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 6), new Model('Mindless Zombie', [C.Resurrectionist], [C.Peon, C.Undead, C.Wave1], 2), new Model('Necropunk', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 5), new Model('Nurse', [C.Resurrectionist], [C.Minion, C.Living, C.Tormented, C.Wave1], 5), new Model('Punk Zombie', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave1], 7), new Model('Rotten Belle', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave1], 5), new Model('The Hanged', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Spirit, C.Tormented, C.Wave1], 9), new Model('Molly Squidpiddge', [C.Resurrectionist], [C.Master, C.Undead, C.Belle, C.Horror, C.Wave2], undefined, 3), new Model('Rogue Necromancy', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Construct, C.Beast, C.Horror, C.Wave2], 10), new Model('Guild Autopsy', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave2], 4), new Model('Necrotic Machine', [C.Resurrectionist], [C.Minion, C.Construct, C.TotemFor('Molly Squidpiddge'), C.Rare1, C.Horror, C.Spirit, C.Wave2], 2), new Model('Kirai Ankoku', [C.Resurrectionist], [C.Master, C.Living, C.Wave2], undefined, 3), new Model('Ikiryo', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.Spirit, C.Wave2], 0), new Model('Seishin', [C.Resurrectionist], [C.Peon, C.Rare5, C.Spirit, C.Wave2], 0), new Model('Lost Love', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Kirai Ankoku'), C.Spirit, C.Wave2], 4), new Model('Datsue Ba', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Wave2], 8, 5), new Model('Dead Rider', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Gaki', [C.Resurrectionist], [C.Minion, C.Spirit, C.Wave2], 4), new Model('Night Terror', [C.Resurrectionist], [C.Minion, C.Rare4, C.Beast, C.Spirit, C.Wave2], 3), new Model('Onryo', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave2], 5), new Model('Shikome', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Beast, C.Spirit, C.Wave2], 8), new Model('Crooligan', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Lost, C.Wave2], 4), new Model('Dead Doxy', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave2], 6), new Model('The Drowned', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Spirit, C.Tormented, C.Wave2], 6), new Model('Jaakuna Ubume', [C.Resurrectionist], [C.Enforcer, C.Spirit, C.Tormented, C.Rare1, C.Wave2], 6), new Model('Rafkin', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 7), new Model('Carrion Effigy', [C.Resurrectionist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Ashigaru', [C.Resurrectionist], [C.Minion, C.Undead, C.Retainer, C.Wave2], 5), new Model('Philip and the Nanny', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Horror, C.Wave2], 8, 5), new Model('Student of Sinew', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of Steel', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of Viscera', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 8), new Model('The Valedictorian', [C.Resurrectionist], [C.Henchman, C.Construct, C.Undead, C.Rare1, C.Horror, C.Academic, C.Wave2], 10, 3), new Model('Rasputina', [C.Arcanist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('Marcus', [C.Arcanist], [C.Master, C.Living, C.Beast, C.Wave1], undefined, 4), new Model('Ramos', [C.Arcanist], [C.Master, C.Living, C.Construct, C.Msu, C.Wave1], undefined, 3), new Model('Myranda', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Beast, C.Wave1], 8, 5), new Model('Joss', [C.Arcanist], [C.Henchman, C.Living, C.Construct, C.Rare1, C.Msu, C.Wave1], 10, 3), new Model('Cojo', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave1], 8), new Model('Ice Golem', [C.Arcanist], [C.Enforcer, C.Construct, C.Wave1], 10), new Model('Wendigo', [C.Arcanist], [C.Minion, C.Living, C.TotemFor('Rasputina'), C.Wave1], 3), new Model('Jackalope', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Marcus'), C.Beast, C.Wave1], 2), new Model('Brass Arachnid', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Ramos'), C.Msu, C.Wave1], 4), new Model('Essence of Power', [C.Arcanist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('December Acolyte', [C.Arcanist], [C.Minion, C.Living, C.Wave1], 7), new Model('Electric Creation', [C.Arcanist], [C.Peon, C.Construct, C.Wave1], 4), new Model('Hoarcat Pride', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Swarm, C.Wave1], 5), new Model('Howard Langston', [C.Arcanist], [C.Enforcer, C.Construct, C.Living, C.Rare1, C.Msu, C.Wave1], 12), new Model('Ice Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave1], 4), new Model('Metal Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Msu, C.Foundry, C.Wave1], 4), new Model('Moleman', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 4), new Model('Rail Golem', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Foundry, C.Wave1], 11), new Model('Razorspine Rattler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 7), new Model('Sabertooth Cerberus', [C.Arcanist], [C.Enforcer, C.Living, C.Beast, C.Wave1], 9), new Model('Steam Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave1], 4), new Model('Steam Arachnid Swarm', [C.Arcanist], [C.Minion, C.Construct, C.Swarm, C.Msu, C.Wave1], 8), new Model('Ironsides', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 5), new Model('Oxfordian Mage', [C.Arcanist], [C.Enforcer, C.Living, C.Rare3, C.Academic, C.Msu, C.Wave2], 6), new Model('Mouse', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Ironsides'), C.Msu, C.Wave2], 4), new Model('Colette Du Bois', [C.Arcanist], [C.Master, C.Living, C.Showgirl, C.Wave2], undefined, 2), new Model('Mechanical Dove', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Colette Du Bois'), C.Rare3, C.Wave2], 2), new Model('Cassandra', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave2], 8, 5), new Model('Coryphee', [C.Arcanist], [C.Minion, C.Construct, C.Rare2, C.Showgirl, C.Puppet, C.Wave2], 7), new Model('Coryphee Duet', [C.Arcanist], [C.Enforcer, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 0), new Model('Performer', [C.Arcanist], [C.Minion, C.Living, C.Mercenary, C.Showgirl, C.Wave2], 5), new Model('Mannequin', [C.Arcanist], [C.Peon, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 4), new Model('Kaeris', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 4), new Model('The Firestarter', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 7, 6), new Model('Eternal Flame', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Kaeris'), C.Msu, C.Wave2], 2), new Model('Gunsmith', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 7), new Model('Large Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('Malifaux Raptor', [C.Arcanist], [C.Peon, C.Living, C.Rare3, C.Beast, C.Wave2], 3), new Model('Mechanical Rider', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Silent One', [C.Arcanist], [C.Minion, C.Living, C.Wave2], 6), new Model('Snow Storm', [C.Arcanist], [C.Henchman, C.Rare1, C.Spirit, C.Wave2], 11, 2), new Model('Soulstone Miner', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('The Captain', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Angelica', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Showgirl, C.Wave2], 6), new Model('Blessed of December', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave2], 9), new Model('Fire Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave2], 4), new Model('Slate Ridge Mauler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave2], 8), new Model('Union Miner', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 5), new Model('Willie', [C.Arcanist], [C.Minion, C.Living, C.Rare1, C.Msu, C.Foundry, C.Wave2], 6), new Model('Arcane Effigy', [C.Arcanist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Mobile Toolkit', [C.Arcanist], [C.Peon, C.Construct, C.Rare1, C.Msu, C.Wave2], 3), new Model('Lilith', ['Neverborn'], [C.Master, C.Living, C.Nephilim, C.Wave1], undefined, 4), new Model('Pandora', ['Neverborn'], [C.Master, C.Living, C.Woe, C.Wave1], undefined, 3), new Model('Zoraida', ['Neverborn', C.Gremlin], [C.Master, C.Living, C.Swampfiend, C.Wave1], undefined, 4), new Model('Barbaros', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave1], 10, 3), new Model('Candy', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Woe, C.Mimic, C.Lost, C.Wave1], 9, 4), new Model('Bad Juju', ['Neverborn'], [C.Henchman, C.Rare1, C.Swampfiend, C.Wave1], 8, 5), new Model('Cherub', ['Neverborn'], [C.Peon, C.Living, C.TotemFor('Lilith'), C.Nephilim, C.Wave1], 3), new Model('Poltergeist', ['Neverborn'], [C.Minion, C.TotemFor('Pandora'), C.Woe, C.Spirit, C.Wave1], 5), new Model('Voodoo Doll', ['Neverborn', C.Gremlin], [C.Peon, C.Construct, C.TotemFor('Zoraida'), C.Puppet, C.Wave1], 3), new Model('Primordial Magic', ['Neverborn'], [C.Peon, C.Totem, C.Spirit, C.Wave1], 2), new Model('Baby Kade', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave1], 7), new Model('Teddy', ['Neverborn'], [C.Enforcer, C.Construct, C.Nightmare, C.Wave1], 11), new Model('Beckoner', ['Neverborn'], [C.Minion, C.Living, C.Rare2, C.Brilliance, C.Darkened, C.Mimic, C.Wave1], 7), new Model('Doppleganger', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Mimic, C.Wave1], 7), new Model('Mature Nephilim', ['Neverborn'], [C.Enforcer, C.Living, C.Nephilim, C.Wave1], 11), new Model('Silurid', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 7), new Model('Sorrow', ['Neverborn'], [C.Minion, C.Woe, C.Spirit, C.Wave1], 5), new Model('Terror Tot', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 4), new Model('Waldgeist', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 6), new Model('Young Nephilim', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 6), new Model('The Dreamer', [C.Neverborn], [C.Master, C.Spirit, C.Wave2], undefined, 3), new Model('Lord Chompy Bits', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Tyrant, C.Wave2], 0), new Model('Daydream', [C.Neverborn], [C.Peon, C.TotemFor('The Dreamer'), C.Rare3, C.Nightmare, C.Wave2], 2), new Model('Alp', [C.Neverborn], [C.Peon, C.Nightmare, C.Wave2], 3), new Model('Coppelius', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Wave2], 8), new Model('Lelu', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('Lilitu', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('Insidious Madness', [C.Neverborn], [C.Minion, C.Rare3, C.Nightmare, C.Woe, C.Wave2], 5), new Model('Widow Weaver', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Wave2], 8, 5), new Model('Black Blood Shaman', [C.Neverborn], [C.Minion, C.Living, C.Rare2, C.Nephilim, C.Wave2], 7), new Model('Nekima', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave2], 13, 0), new Model('Collodi', [C.Neverborn], [C.Master, C.Construct, C.Puppet, C.Wave2], undefined, 3), new Model('Marionette', [C.Neverborn], [C.Minion, C.Construct, C.TotemFor('Collodi'), C.Rare4, C.Puppet, C.Wave2], 3), new Model('Stitched Together', [C.Neverborn], [C.Minion, C.Construct, C.Nightmare, C.Puppet, C.Darkened, C.Wave2], 6), new Model('Wicked Doll', [C.Neverborn], [C.Minion, C.Construct, C.Puppet, C.Wave2], 4), new Model('Vasilisa', [C.Neverborn], [C.Henchman, C.Construct, C.Rare1, C.Puppet, C.Wave2], 9, 4), new Model('Iggy', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave2], 5), new Model('Spawn Mother', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.Beast, C.Wave2], 9, 4), new Model('Gupps', [C.Neverborn], [C.Minion, C.Living, C.Swampfiend, C.Beast, C.Swarm, C.Wave2], 4), new Model('Tuco', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave2], 7), new Model('Mysterious Effigy', [C.Neverborn], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('The Depleted', [C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Darkened, C.Wave2], 4), new Model('Hooded Rider', [C.Neverborn], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Von Schill', [C.Outcast], [C.Master, C.Living, C.Freikorps, C.Wave1], undefined, 1), new Model('Tara', [C.Outcast, C.Resurrectionist], [C.Master, C.Undead, C.Wave1], undefined, 4), new Model('Viktoria of Ashes', [C.Outcast], [C.Master, C.Living, C.Sister, C.Wave1], undefined, 1), new Model('Hannah', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Mercenary, C.Freikorps, C.Wave1], 10, 3), new Model('The Nothing Beast', [C.Outcast], [C.Enforcer, C.Rare1, C.Wave1], 10), new Model('Viktoria of Blood', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Sister, C.Wave1], 0, 3), new Model('Taelor', [C.Outcast], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10, 3), new Model('Steam Trunk', [C.Outcast], [C.Peon, C.Construct, C.TotemFor('Von Schill'), C.Wave1], 3), new Model('Karina', [C.Outcast, C.Resurrectionist], [C.Enforcer, C.Living, C.TotemFor('Tara'), C.Wave1], 5), new Model('Student of Conflict', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Sister, C.Wave1], 4), new Model('Malifaux Child', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Lost, C.Wave1], 2), new Model('Bishop', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10), new Model('Convict Gunslinger', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare2, C.Wave1], 7), new Model('Desperate Mercenary', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 4), new Model('Freikorps Specialist', [C.Outcast], [C.Living, C.Enforcer, C.Mercenary, C.Freikorps, C.Wave1], 8), new Model('Freikorpsman', [C.Outcast], [C.Living, C.Minion, C.Mercenary, C.Freikorps, C.Wave1], 5), new Model('Hans', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 8), new Model('Johan', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Msu, C.Wave1], 6), new Model('Killjoy', [C.Outcast], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.Horror, C.Wave1], 12), new Model('Ronin', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 6), new Model('Void Wretch', [C.Outcast], [C.Minion, C.Wave1], 4), new Model('Jack Daw', [C.Outcast], [C.Master, C.Undead, C.Tormented, C.Spirit, C.Cursed, C.Wave2], undefined, 2), new Model('The Guilty', [C.Outcast], [C.Minion, C.Undead, C.Tormented, C.Wave2], 5), new Model('Montresor', [C.Outcast], [C.Henchman, C.Undead, C.Rare1, C.Tormented, C.Wave2], 9, 4), new Model('Lady Ligeia', [C.Outcast], [C.Peon, C.TotemFor('Jack Daw'), C.Tormented, C.Spirit, C.Wave2], 4), new Model('Hamelin', [C.Outcast], [C.Master, C.Tyrant, C.Nihilist, C.Wave2], undefined, 1), new Model('Nix', [C.Outcast], [C.Henchman, C.Rare1, C.Nihilist, C.Spirit, C.Wave2], 8, 5), new Model('Obediant Wretch', [C.Outcast], [C.Minion, C.Living, C.Rare1, C.Nihilist, C.Wave2], 4), new Model('Rat Catcher', [C.Outcast], [C.Minion, C.Living, C.Rare2, C.Nihilist, C.Wave2], 6), new Model('Malifaux Rat', [C.Outcast], [C.Peon, C.Vermin, C.Wave2], 2), new Model('Rat King', [C.Outcast], [C.Minion, C.Vermin, C.Swarm, C.Wave2], 8), new Model('The Stolen', [C.Outcast], [C.Peon, C.Living, C.TotemFor('Hamelin'), C.Rare3, C.Nihilist, C.Lost, C.Wave2], 2), new Model('Ashes and Dust', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 13), new Model('Ashen Core', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 0), new Model('Dust Storm', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 6), new Model('Freikorps Librarian', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Academic, C.Freikorps, C.Wave2], 7), new Model('Freikorps Trapper', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Freikorps, C.Wave2], 6), new Model('Lazarus', [C.Outcast], [C.Enforcer, C.Construct, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Sue', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave2], 8), new Model('Hodgepodge Effigy', [C.Outcast], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Ama No Zako', [C.Outcast, C.TenThunders], [C.Henchman, C.Mercenary, C.Rare1, C.Oni, C.Wave2], 9, 4), new Model('Strongarm Suit', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Vanessa', [C.Outcast], [C.Enforcer, C.Living, C.Rare1, C.Sister, C.Wave2], 8), new Model('Leveticus', [C.Outcast], [C.Master, C.Living, C.Wave2], undefined, 2), new Model('Rusty Alyce', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Wave2], 10, 3), new Model('Hollow Waif', [C.Outcast], [C.Peon, C.Undead, C.TotemFor('Leveticus'), C.Rare3, C.Wave2], 0), new Model('Abomination', [C.Outcast], [C.Minion, C.Construct, C.Undead, C.Wave2], 4), new Model('Desolation Engine', [C.Outcast], [C.Enforcer, C.Undead, C.Construct, C.Rare1, C.Wave2], 13), new Model('Som\'er Teeth Jones', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave1], undefined, 4), new Model('Ophelia LaCroix', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Kin, C.Wave1], undefined, 3), new Model('The Brewmaster', [C.Gremlin, C.TenThunders], [C.Master, C.Living, C.Gremlin, C.TriChi, C.Wave1], undefined, 3), new Model('Francois LaCroix', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7, 6), new Model('Fingers', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.TriChi, C.Wave1], 10, 3), new Model('Lenny', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Wave1], 9), new Model('Whiskey Golem', [C.Gremlin], [C.Enforcer, C.Construct, C.Rare1, C.TriChi, C.Wave1], 10), new Model('Skeeter', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Som\'er Teeth Jones'), C.Wave1], 2), new Model('Young LaCroix', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Ophelia LaCroix'), C.Gremlin, C.Kin, C.Wave1], 2), new Model('Apprentice Wesley', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('The Brewmaster'), C.Gremlin, C.TriChi, C.Wave1], 3), new Model('Bayou Gremlin', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 3), new Model('Hog Whisperer', [C.Gremlin], [C.Minion, C.Living, C.Mercenary, C.Gremlin, C.Wave1], 5), new Model('Moon Shinobi', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.TriChi, C.Wave1], 6), new Model('Pigapult', [C.Gremlin], [C.Peon, C.Construct, C.Rare1, C.Gremlin, C.Wave1], 8), new Model('Piglet', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 4), new Model('Slop Hauler', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 5), new Model('War Pig', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 9), new Model('Pere Ravage', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 6), new Model('Rami LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('Raphael LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('Ulix', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('Penelope', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Ulix'), C.Hound, C.Wave2], 2), new Model('The Sow', [C.Gremlin], [C.Minion, C.Living, C.Rare1, C.Beast, C.Pig, C.Wave2], 8), new Model('Old Major', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Pig, C.Wave2], 9, 4), new Model('Rooster Rider', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Rooster, C.Wave2], 6), new Model('Stuffed Piglet', [C.Gremlin], [C.Peon, C.Undead, C.Rare6, C.Pig, C.Wave2], 2), new Model('Gremlin Taxidermist', [C.Gremlin], [C.Enforcer, C.Living, C.Rare2, C.Gremlin, C.Wave2], 7), new Model('Mah Tucket', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('The Little Lass', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Mah Tucket'), C.Gremlin, C.Wave2], 4), new Model('Trixiebelle', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 8, 5), new Model('Bayou Bushwhacker', [C.Gremlin], [C.Minion, C.Living, C.Rare3, C.Gremlin, C.Wave2], 6), new Model('McTavish', [C.Gremlin], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Swampfiend, C.Wave2], 10, 3), new Model('Mancha Roja', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 10, 3), new Model('Burt Jebsen', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Gremlin, C.Wave2], 7), new Model('Gracie', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Pig, C.Wave2], 10), new Model('Merris LaCroix', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 6), new Model('Wild Boar', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Swampfiend, C.Wave2], 6), new Model('Lucky Effigy', [C.Gremlin], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Wong', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 3), new Model('Lovely Assistant', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Wong'), C.Gremlin, C.Showgirl, C.Wave2], 3), new Model('Lightning Bug', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave2], 5), new Model('Bayou Gator', [C.Gremlin], [C.Minion, C.Living, C.Swampfiend, C.Wave2], 5), new Model('Sammy LaCroix', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 7, 6), new Model('Old Cranky', [C.Gremlin], [C.Peon, C.Living, C.Totem, C.Gremlin, C.Wave2], 4), new Model('Misaki', [C.TenThunders, C.Outcast], [C.Master, C.Living, C.LastBlossom, C.Wave1], undefined, 2), new Model('Mei Feng', [C.TenThunders, C.Arcanist], [C.Master, C.Living, C.Foundry, C.Wave1], undefined, 3), new Model('Jakob Lynch', [C.TenThunders, C.Neverborn], [C.Master, C.Living, C.Darkened, C.Wave1], undefined, 1), new Model('Ototo', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 10, 3), new Model('Kang', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Foundry, C.Wave1], 9, 4), new Model('Yamaziko', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 7, 6), new Model('Shang', [C.TenThunders, C.Outcast], [C.Peon, C.Living, C.TotemFor('Misaki'), C.Wave1], 3), new Model('Emberling', [C.TenThunders, C.Arcanist], [C.Minion, C.TotemFor('Mei Feng'), C.Spirit, C.Wave1], 3), new Model('Hungering Darkness', [C.TenThunders, C.Neverborn], [C.Henchman, C.TotemFor('Jakob Lynch'), C.Rare1, C.Spirit, C.Darkened, C.Wave1], 0, 5), new Model('Dawn Serpent', [C.TenThunders], [C.Minion, C.Living, C.Rare1, C.Beast, C.Wave1], 10), new Model('Fuhatsu', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave1], 10, 3), new Model('Monk of Low River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave1], 4), new Model('Oiran', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Showgirl, C.Wave1], 5), new Model('Rail Worker', [C.TenThunders, C.Arcanist], [C.Minion, C.Living, C.Construct, C.Foundry, C.Wave1], 5), new Model('The Illuminated', [C.TenThunders, C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Wave1], 7), new Model('Thunder Archer', [C.TenThunders], [C.Minion, C.Living, C.Wave1], 7), new Model('Torakage', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Wave1], 6), new Model('Samurai', [C.TenThunders], [C.Enforcer, C.Living, C.Wave1], 8), new Model('Lucas McCabe', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 2), new Model('Dismounted McCabe', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 0), new Model('Sidir Alchibal', [C.TenThunders, C.Guild], [C.Henchman, C.Living, C.Rare1, C.BlackSheep, C.Wave2], 9, 4), new Model('Luna', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.TotemFor('Lucas McCabe'), C.Beast, C.Hound, C.Wave2], 4), new Model('Wastrel', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.BlackSheep, C.Wave2], 4), new Model('Yan Lo', [C.TenThunders, C.Resurrectionist], [C.Master, C.Living, C.Ancestor, C.Wave2], undefined, 4), new Model('Soul Porter', [C.TenThunders, C.Resurrectionist], [C.Peon, C.TotemFor('Yan Lo'), C.Spirit, C.Wave2], 3), new Model('Chiaki the Niece', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Ancestor, C.Wave2], 6), new Model('Izamu the Armor', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Spirit, C.Wave2], 10), new Model('Toshiro the Daimyo', [C.TenThunders, C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Ancestor, C.Wave2], 9, 4), new Model('Yin the Penangalan', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Horror, C.Wave2], 8), new Model('Ten Thunders Brother', [C.TenThunders], [C.Minion, C.Living, C.Wave2], 5), new Model('Mr. Graves', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Darkened, C.Mimic, C.Wave2], 8), new Model('Mr. Tannen', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Darkened, C.Mimic, C.Wave2], 6), new Model('Shadow Effigy', [C.TenThunders], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Komainu', [C.TenThunders], [C.Minion, C.Construct, C.Spirit, C.Retainer, C.Wave2], 5), new Model('Sensei Yu', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave2], 9, 4), new Model('Shenlong', [C.TenThunders], [C.Master, C.Living, C.Tyrant, C.Wave2], undefined, 2), new Model('Peasant', [C.TenThunders], [C.Peon, C.Living, C.TotemFor('Shenlong'), C.Rare2, C.Wave2], 2), new Model('Fermented River Monk', [C.TenThunders], [C.Minion, C.Living, C.TriChi, C.Wave2], 5), new Model('Monk of High River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave2], 6), new Model('The Lone Swordsman', [C.TenThunders], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 8), new Model('Kamaitachi', [C.TenThunders], [C.Minion, C.Totem, C.Oni, C.Wave2], 4), new Model('Tengu', [C.TenThunders], [C.Minion, C.Spirit, C.Oni, C.Wave2], 4), new Model('Katanaka Sniper', [C.TenThunders], [C.Minion, C.Living, C.Rare2, C.Wave2], 7), new Model('Brutal Emissary', [C.Guild], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Master Queeg', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.BlackSheep, C.Wave3], 7, 6), new Model('Dr. Grimwell', [C.Guild], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 9, 4), new Model('Nurse Heartsbane', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 8), new Model('Greed', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Sanctioned Spellcaster', [C.Guild], [C.Minion, C.Living, C.Academic, C.Wave3], 5), new Model('Orderly', [C.Guild], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.WitchHunter, C.Wave3], 5), new Model('Mounted Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave3], 7), new Model('Carrion Emissary', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Anna Lovelace', [C.Resurrectionist], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave3], 9, 4), new Model('Sloth', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Horror, C.Wave3], 8), new Model('The Forgotten Marshal', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave3], 7), new Model('Hayreddin', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave3], 7), new Model('Arcane Emissary', [C.Arcanist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wind Gamin', [C.Arcanist], [C.Minion, C.Living, C.Gamin, C.Wave3], 4), new Model('The Scorpius', [C.Arcanist], [C.Minion, C.Living, C.Construct, C.Rare1, C.Beast, C.Wave3], 6), new Model('Ice Dancer', [C.Arcanist], [C.Minion, C.Living, C.Showgirl, C.Wave3], 6), new Model('Envy', [C.Arcanist], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Mysterious Emissary', [C.Neverborn], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wrath', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8, 5), new Model('Angel Eyes', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 9, 4), new Model('Scion of Black Blood', [C.Neverborn], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 8), new Model('Corrupted Hound', [C.Neverborn], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Wave3], 3), new Model('Changeling', [C.Neverborn], [C.Minion, C.Living, C.Rare3, C.Mimic, C.Wave3], 4), new Model('Bloodwretch', [C.Neverborn], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Nephilim, C.Wave3], 5), new Model('Bunraku', [C.Neverborn, C.TenThunders], [C.Minion, C.Construct, C.Puppet, C.Wave3], 6), new Model('Hodgepodge Emissary', [C.Outcast], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Cursed, C.Wave3], 10), new Model('Scion of the Void', [C.Outcast], [C.Henchman, C.Rare1, C.Wave3], 8, 5), new Model('Pride', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Big Jake', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave3], 5), new Model('The Winged Plague', [C.Outcast], [C.Minion, C.Living, C.Vermin, C.Wave3], 4), new Model('Lucky Emissary', [C.Gremlin], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Sparks', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Foundry, C.Wave3], 7, 6), new Model('Gluttony', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Survivor', [C.Gremlin], [C.Minion, C.Living, C.Construct, C.Gremlin, C.Wave3], 5), new Model('Mechanized Porkchop', [C.Gremlin], [C.Minion, C.Construct, C.Pig, C.Foundry, C.Wave3], 7), new Model('Shadow Emissary', [C.TenThunders], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Lust', [C.TenThunders], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Wandering River Monk', [C.TenThunders], [C.Minion, C.Living, C.Wave3], 7), new Model('Obsidian Oni', [C.TenThunders], [C.Minion, C.Oni, C.Wave3], 6), new Model('Jorogumo', [C.TenThunders], [C.Minion, C.Oni, C.LastBlossom, C.Wave3], 9), new Model('Nellie Cochrane', [C.Guild], [C.Master, C.Living, C.Journalist, C.Wave4], undefined, 4), new Model('The Printing Press', [C.Guild], [C.Peon, C.Construct, C.TotemFor('Nellie Cochrane'), C.Journalist, C.Wave4], 3), new Model('Phiona Gage', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Allison Dade', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Field Reporter', [C.Guild], [C.Minion, C.Living, C.Journalist, C.Wave4], 4), new Model('Death Marshal Recruiter', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave4], 7), new Model('Witchling Thrall', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave4], 9), new Model('Reva', [C.Resurrectionist], [C.Master, C.Living, C.Revenant, C.Wave4], undefined, 4), new Model('Corpse Candle', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Reva'), C.Spirit, C.Revenant, C.Wave4], 2), new Model('Vincent St. Clair', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Revenant, C.Wave4], 8, 5), new Model('Archie', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Horror, C.Wave4], 13, 0), new Model('Shieldbearer', [C.Resurrectionist], [C.Minion, C.Living, C.Revenant, C.Wave4], 6), new Model('Draugr', [C.Resurrectionist], [C.Minion, C.Undead, C.Revenant, C.Horror, C.Wave4], 8), new Model('Goryo', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave4], 7), new Model('Sandeep Desai', [C.Arcanist], [C.Master, C.Living, C.Academic, C.Wave4], undefined, 4), new Model('Corpse Candle', [C.Arcanist], [C.Minion, C.TotemFor('Sandeep Desai'), C.Rare1, C.Gamin, C.Wave4], 8), new Model('Kudra', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Academic, C.Wave4], 7, 6), new Model('Amina Naidu', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Academic, C.Wave4], 9, 4), new Model('Carlos Vasquez', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave4], 9, 4), new Model('Poison Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Beast, C.Wave4], 5), new Model('Shastar Vidiya Guard', [C.Arcanist], [C.Enforcer, C.Living, C.Msu, C.Academic, C.Wave4], 8), new Model('Titania', [C.Neverborn], [C.Master, C.Undead, C.Fae, C.Wave4], undefined, 4), new Model('The Gorare', [C.Neverborn], [C.Peon, C.Living, C.TotemFor('Titania'), C.Fae, C.Wave4], 3), new Model('Aeslin', [C.Neverborn], [C.Henchman, C.Undead, C.Rare1, C.Fae, C.Wave4], 9, 4), new Model('The Tooth', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Claw', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Thorn', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('Bandersnatch', [C.Neverborn], [C.Minion, C.Living, C.Rare1, C.Fae, C.Nightmare, C.Spirit, C.Wave4], 5), new Model('Will O\' the Wisp', [C.Neverborn], [C.Minion, C.Rare3, C.Spirit, C.Swampfiend, C.Wave4], 3), new Model('Rougarou', [C.Neverborn], [C.Minion, C.Undead, C.Fae, C.Beast, C.Wave4], 8), new Model('Parker Barrows', [C.Outcast], [C.Master, C.Living, C.Bandit, C.Wave4], undefined, 4), new Model('Doc Mitchell', [C.Outcast], [C.Minion, C.Living, C.TotemFor('Parker Barrows'), C.Wave4], 3), new Model('Mad Dog Brackett', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Bandit, C.Wave4], 9, 4), new Model('Aionus', [C.Outcast], [C.Henchman, C.Mercenary, C.Rare1, C.Wave4], 12, 1), new Model('Bandido', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.Wave4], 5), new Model('Dead Outland', [C.Outcast], [C.Minion, C.Undead, C.Bandit, C.Tormented, C.Wave4], 6), new Model('Wokou Raider', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.LastBlossom, C.Wave4], 8), new Model('Zipp', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.SkyPirate, C.Wave4], undefined, 4), new Model('Earl Burns', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('Zipp'), C.Wave4], 3), new Model('The First Mate', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.SkyPirate, C.Wave4], 9, 4), new Model('Iron Skeeter', [C.Gremlin], [C.Enforcer, C.Living, C.Construct, C.Gremlin, C.SkyPirate, C.Wave4], 6), new Model('Akaname', [C.Gremlin, C.TenThunders], [C.Minion, C.Rare3, C.Oni, C.TriChi, C.Wave4], 4), new Model('Banjonista', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave4], 5), new Model('Swine-Cursed', [C.Gremlin], [C.Minion, C.Living, C.Rare2, C.Gremlin, C.Wave4], 7), new Model('Asami Tanaka', [C.TenThunders], [C.Master, C.Living, C.Oni, C.Wave4], undefined, 3), new Model('Amanjaku', [C.TenThunders], [C.Peon, C.TotemFor('Asami Tanaka'), C.Oni, C.Wave4], 3), new Model('Ohaguro Bettari', [C.TenThunders], [C.Henchman, C.Rare1, C.Oni, C.Wave4], 8, 5), new Model('Yokai', [C.TenThunders], [C.Minion, C.Oni, C.Wave4], 5), new Model('Terracotta Warrior', [C.TenThunders], [C.Minion, C.Construct, C.Rare3, C.Mimic, C.Wave4], 5), new Model('Sun Quiang', [C.TenThunders], [C.Enforcer, C.Rare1, C.Living, C.Retainer, C.Wave4], 8) ] export default ModelList
145372
import ModelInterface from './ModelInterface.coffee' Model = ModelInterface.Model C = ModelInterface.Attribute # **Epic props** to rythos42 for saving me having to research and type all this! # https://github.com/rythos42/MalifauxModels-Web/blob/master/js/app/Mappers/ModelList.js ModelList = [ new Model('<NAME>', [C.Guild], [C.Master, C.Living, C.GuildMarshal, C.Wave1], undefined, 4), new Model('<NAME>', [C.Guild], [C.Master, C.Living, C.WitchHunter, C.Wave1], undefined, 3), new Model('<NAME>', [C.Guild], [C.Master, C.Living, C.Family, C.Wave1], undefined, 2), new Model('<NAME>', [C.Guild], [C.Henchman, C.Living, C.Family, C.Wave1], 8, 5), new Model('<NAME>', [C.Guild], [C.Henchman, C.Living, C.WitchHunter, C.Wave1], 9, 4), new Model('The J<NAME>', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 9, 4), new Model('Scales of Justice', [C.Guild], [C.Peon, C.Living, C.TotemFor('Lady Justice'), C.Wave1], 3), new Model('Purifying Flame', [C.Guild], [C.Peon, C.TotemFor('<NAME>'), C.Spirit, C.Wave1], 3), new Model('Enslaved Nephilim', [C.Guild], [C.Peon, C.TotemFor('<NAME>'), C.Nephilim, C.Wave1], 3), new Model('Governor\'s Proxy', [C.Guild], [C.Peon, C.Totem, C.Living, C.Wave1], 3), new Model('Death Marshal', [C.Guild], [C.Minion, C.Living, C.GuildMarshal, C.Wave1], 6), new Model('Executioner', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Wave1], 9), new Model('Guild Austringer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Guardsman, C.Wave1], 6), new Model('Guild Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave1], 4), new Model('Peacekeeper', [C.Guild], [C.Enforcer, C.Construct, C.Rare1, C.Wave1], 11), new Model('The Lone Marshal', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 8), new Model('Witchling Stalker', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave1], 5), new Model('<NAME>', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('<NAME>', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Tormented, C.Wave1], 7), new Model('<NAME>', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('<NAME>', [C.Guild], [C.Master, C.Living, C.Construct, C.Msu, C.Wave2], undefined, 3), new Model('<NAME>', [C.Guild], [C.Henchman, C.Construct, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Mechanical Attendant', [C.Guild], [C.Peon, C.Construct, C.TotemFor('<NAME>'), C.Wave2], 2), new Model('<NAME>', [C.Guild], [C.Minion, C.Construct, C.Wave2], 8), new Model('<NAME>', [C.Guild, C.Neverborn], [C.Master, C.Living, C.Mimic, C.Wave2], undefined, 4), new Model('<NAME>', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.Wave2], 9, 4), new Model('The Scribe', [C.Guild, C.Neverborn], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Wave2], 2), new Model('<NAME>', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave2], 7), new Model('Guild Hound', [C.Guild], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Guardsman, C.Wave2], 3), new Model('Guard Sergeant', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Guardsman, C.Wave2], 6), new Model('<NAME>', [C.Guild], [C.Minion, C.Construct, C.Rare2, C.Wave2], 7), new Model('Guild Lawyer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Mimic, C.Wave2], 6), new Model('Watcher', [C.Guild], [C.Minion, C.Construct, C.Wave2], 4), new Model('Exorcist', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave2], 7), new Model('Pistolero De Latigo', [C.Guild], [C.Minion, C.Living, C.Family, C.Wave2], 5), new Model('Pale Rider', [C.Guild], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Warden', [C.Guild], [C.Minion, C.Construct, C.Guardsman, C.Wave2], 6), new Model('Witchling Handler', [C.Guild], [C.Enforcer, C.Living, C.WitchHunter, C.Wave2], 8), new Model('Brutal Effigy', [C.Guild], [C.Minion, C.Construct, C.Puppet, C.Effigy, C.Rare1, C.Wave2], 4), new Model('Guild Rifleman', [C.Guild], [C.Minion, C.Living, C.Rare3, C.Guardsman, C.Wave2], 5), new Model('Clockwork Trap', [C.Guild, C.TenThunders], [C.Peon, C.Rare4, C.Wave2], 2), new Model('Guild Pathfinder', [C.Guild, C.TenThunders], [C.Minion, C.Living, C.Guardsman, C.Wave2], 6), new Model('Seamus', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('McMo<NAME>', [C.Resurrectionist, C.Guild], [C.Master, C.Living, C.Wave1], undefined, 4), new Model('<NAME>', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('<NAME>', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Wave1], 8, 5), new Model('<NAME>', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 7, 6), new Model('Mortimer', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 9, 4), new Model('Copycat Killer', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Seamus'), C.Wave1], 3), new Model('Zombie Chihuahua', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('McMourning'), C.Beast, C.Wave1], 2), new Model('Vulture', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Nicodem'), C.Beast, C.Wave1], 3), new Model('Graveyard Spirit', [C.Resurrectionist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('Bete Noire', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Wave1], 8), new Model('Canine Remains', [C.Resurrectionist], [C.Minion, C.Undead, C.Beast, C.Hound, C.Wave1], 4), new Model('Crooked Man', [C.Resurrectionist], [C.Minion, C.Undead, C.Tormented, C.Wave1], 5), new Model('Flesh Construct', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 6), new Model('Mindless Zombie', [C.Resurrectionist], [C.Peon, C.Undead, C.Wave1], 2), new Model('Necropunk', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 5), new Model('Nurse', [C.Resurrectionist], [C.Minion, C.Living, C.Tormented, C.Wave1], 5), new Model('Punk Zombie', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave1], 7), new Model('Rotten Belle', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave1], 5), new Model('The Hanged', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Spirit, C.Tormented, C.Wave1], 9), new Model('Molly Squidpiddge', [C.Resurrectionist], [C.Master, C.Undead, C.Belle, C.Horror, C.Wave2], undefined, 3), new Model('Rogue Necromancy', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Construct, C.Beast, C.Horror, C.Wave2], 10), new Model('Guild Autopsy', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave2], 4), new Model('Necrotic Machine', [C.Resurrectionist], [C.Minion, C.Construct, C.TotemFor('Molly Squidpiddge'), C.Rare1, C.Horror, C.Spirit, C.Wave2], 2), new Model('<NAME>', [C.Resurrectionist], [C.Master, C.Living, C.Wave2], undefined, 3), new Model('Ikiryo', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.Spirit, C.Wave2], 0), new Model('Seishin', [C.Resurrectionist], [C.Peon, C.Rare5, C.Spirit, C.Wave2], 0), new Model('Lost Love', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Kirai Ankoku'), C.Spirit, C.Wave2], 4), new Model('D<NAME>ue Ba', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Wave2], 8, 5), new Model('Dead Rider', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Gaki', [C.Resurrectionist], [C.Minion, C.Spirit, C.Wave2], 4), new Model('Night Terror', [C.Resurrectionist], [C.Minion, C.Rare4, C.Beast, C.Spirit, C.Wave2], 3), new Model('Onryo', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave2], 5), new Model('<NAME>', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Beast, C.Spirit, C.Wave2], 8), new Model('Crooligan', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Lost, C.Wave2], 4), new Model('Dead Doxy', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave2], 6), new Model('The Drowned', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Spirit, C.Tormented, C.Wave2], 6), new Model('<NAME>akuna Ubume', [C.Resurrectionist], [C.Enforcer, C.Spirit, C.Tormented, C.Rare1, C.Wave2], 6), new Model('Rafkin', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 7), new Model('<NAME>', [C.Resurrectionist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('<NAME>', [C.Resurrectionist], [C.Minion, C.Undead, C.Retainer, C.Wave2], 5), new Model('<NAME> the <NAME>', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Horror, C.Wave2], 8, 5), new Model('Student of <NAME>', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of <NAME>', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of <NAME>', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 8), new Model('The <NAME>aled<NAME>', [C.Resurrectionist], [C.Henchman, C.Construct, C.Undead, C.Rare1, C.Horror, C.Academic, C.Wave2], 10, 3), new Model('<NAME>', [C.Arcanist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('<NAME>', [C.Arcanist], [C.Master, C.Living, C.Beast, C.Wave1], undefined, 4), new Model('<NAME>', [C.Arcanist], [C.Master, C.Living, C.Construct, C.Msu, C.Wave1], undefined, 3), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Beast, C.Wave1], 8, 5), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Construct, C.Rare1, C.Msu, C.Wave1], 10, 3), new Model('<NAME>', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave1], 8), new Model('Ice <NAME>', [C.Arcanist], [C.Enforcer, C.Construct, C.Wave1], 10), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Living, C.TotemFor('Rasputina'), C.Wave1], 3), new Model('<NAME>', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Beast, C.Wave1], 2), new Model('<NAME>', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('<NAME>'), C.Msu, C.Wave1], 4), new Model('Essence of Power', [C.Arcanist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('De<NAME>', [C.Arcanist], [C.Minion, C.Living, C.Wave1], 7), new Model('Electric Creation', [C.Arcanist], [C.Peon, C.Construct, C.Wave1], 4), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Swarm, C.Wave1], 5), new Model('<NAME>', [C.Arcanist], [C.Enforcer, C.Construct, C.Living, C.Rare1, C.Msu, C.Wave1], 12), new Model('Ice Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave1], 4), new Model('Metal Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Msu, C.Foundry, C.Wave1], 4), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 4), new Model('Rail Golem', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Foundry, C.Wave1], 11), new Model('Razorspine Rattler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 7), new Model('Sabertooth Cerberus', [C.Arcanist], [C.Enforcer, C.Living, C.Beast, C.Wave1], 9), new Model('Steam Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave1], 4), new Model('Steam Arachnid Swarm', [C.Arcanist], [C.Minion, C.Construct, C.Swarm, C.Msu, C.Wave1], 8), new Model('Ironsides', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 5), new Model('Oxfordian Mage', [C.Arcanist], [C.Enforcer, C.Living, C.Rare3, C.Academic, C.Msu, C.Wave2], 6), new Model('Mouse', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Ironsides'), C.Msu, C.Wave2], 4), new Model('Colette Du Bois', [C.Arcanist], [C.Master, C.Living, C.Showgirl, C.Wave2], undefined, 2), new Model('Mechanical Dove', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Colette Du Bois'), C.Rare3, C.Wave2], 2), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave2], 8, 5), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Construct, C.Rare2, C.Showgirl, C.Puppet, C.Wave2], 7), new Model('<NAME>', [C.Arcanist], [C.Enforcer, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 0), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Living, C.Mercenary, C.Showgirl, C.Wave2], 5), new Model('<NAME>', [C.Arcanist], [C.Peon, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 4), new Model('<NAME>', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 4), new Model('The Firestarter', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 7, 6), new Model('Eternal Flame', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Kaeris'), C.Msu, C.Wave2], 2), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 7), new Model('Large Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('Malifaux Raptor', [C.Arcanist], [C.Peon, C.Living, C.Rare3, C.Beast, C.Wave2], 3), new Model('Mechanical Rider', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Silent One', [C.Arcanist], [C.Minion, C.Living, C.Wave2], 6), new Model('Snow Storm', [C.Arcanist], [C.Henchman, C.Rare1, C.Spirit, C.Wave2], 11, 2), new Model('Soulstone Miner', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('The Captain', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Angelica', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Showgirl, C.Wave2], 6), new Model('Blessed of December', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave2], 9), new Model('Fire Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave2], 4), new Model('Slate Ridge Mauler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave2], 8), new Model('Union Miner', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 5), new Model('Willie', [C.Arcanist], [C.Minion, C.Living, C.Rare1, C.Msu, C.Foundry, C.Wave2], 6), new Model('Arcane Effigy', [C.Arcanist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Mobile Toolkit', [C.Arcanist], [C.Peon, C.Construct, C.Rare1, C.Msu, C.Wave2], 3), new Model('<NAME>', ['Neverborn'], [C.Master, C.Living, C.Nephilim, C.Wave1], undefined, 4), new Model('<NAME>', ['Neverborn'], [C.Master, C.Living, C.Woe, C.Wave1], undefined, 3), new Model('<NAME>', ['Neverborn', C.Gremlin], [C.Master, C.Living, C.Swampfiend, C.Wave1], undefined, 4), new Model('<NAME>', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave1], 10, 3), new Model('<NAME>', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Woe, C.Mimic, C.Lost, C.Wave1], 9, 4), new Model('Bad <NAME>', ['Neverborn'], [C.Henchman, C.Rare1, C.Swampfiend, C.Wave1], 8, 5), new Model('<NAME>', ['Neverborn'], [C.Peon, C.Living, C.TotemFor('Lilith'), C.Nephilim, C.Wave1], 3), new Model('Poltergeist', ['Neverborn'], [C.Minion, C.TotemFor('Pandora'), C.Woe, C.Spirit, C.Wave1], 5), new Model('<NAME>', ['Neverborn', C.Gremlin], [C.Peon, C.Construct, C.TotemFor('Zoraida'), C.Puppet, C.Wave1], 3), new Model('Primordial Magic', ['Neverborn'], [C.Peon, C.Totem, C.Spirit, C.Wave1], 2), new Model('Baby Kade', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave1], 7), new Model('Teddy', ['Neverborn'], [C.Enforcer, C.Construct, C.Nightmare, C.Wave1], 11), new Model('Beckoner', ['Neverborn'], [C.Minion, C.Living, C.Rare2, C.Brilliance, C.Darkened, C.Mimic, C.Wave1], 7), new Model('Doppleganger', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Mimic, C.Wave1], 7), new Model('Mature Nephilim', ['Neverborn'], [C.Enforcer, C.Living, C.Nephilim, C.Wave1], 11), new Model('Silurid', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 7), new Model('Sorrow', ['Neverborn'], [C.Minion, C.Woe, C.Spirit, C.Wave1], 5), new Model('Terror Tot', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 4), new Model('Waldgeist', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 6), new Model('Young Nephilim', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 6), new Model('The Dreamer', [C.Neverborn], [C.Master, C.Spirit, C.Wave2], undefined, 3), new Model('Lord Chompy Bits', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Tyrant, C.Wave2], 0), new Model('Daydream', [C.Neverborn], [C.Peon, C.TotemFor('The Dreamer'), C.Rare3, C.Nightmare, C.Wave2], 2), new Model('Al<NAME>', [C.Neverborn], [C.Peon, C.Nightmare, C.Wave2], 3), new Model('<NAME>', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Wave2], 8), new Model('<NAME>', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('<NAME>', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('Insidious Madness', [C.Neverborn], [C.Minion, C.Rare3, C.Nightmare, C.Woe, C.Wave2], 5), new Model('Widow Weaver', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Wave2], 8, 5), new Model('Black Blood Shaman', [C.Neverborn], [C.Minion, C.Living, C.Rare2, C.Nephilim, C.Wave2], 7), new Model('<NAME>', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave2], 13, 0), new Model('<NAME>', [C.Neverborn], [C.Master, C.Construct, C.Puppet, C.Wave2], undefined, 3), new Model('<NAME>', [C.Neverborn], [C.Minion, C.Construct, C.TotemFor('Collodi'), C.Rare4, C.Puppet, C.Wave2], 3), new Model('Stitched Together', [C.Neverborn], [C.Minion, C.Construct, C.Nightmare, C.Puppet, C.Darkened, C.Wave2], 6), new Model('Wicked Doll', [C.Neverborn], [C.Minion, C.Construct, C.Puppet, C.Wave2], 4), new Model('Vasilisa', [C.Neverborn], [C.Henchman, C.Construct, C.Rare1, C.Puppet, C.Wave2], 9, 4), new Model('Iggy', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave2], 5), new Model('Spawn Mother', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.Beast, C.Wave2], 9, 4), new Model('Gupps', [C.Neverborn], [C.Minion, C.Living, C.Swampfiend, C.Beast, C.Swarm, C.Wave2], 4), new Model('Tuco', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave2], 7), new Model('Mysterious Effigy', [C.Neverborn], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('The Depleted', [C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Darkened, C.Wave2], 4), new Model('Hooded Rider', [C.Neverborn], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('<NAME>', [C.Outcast], [C.Master, C.Living, C.Freikorps, C.Wave1], undefined, 1), new Model('<NAME>', [C.Outcast, C.Resurrectionist], [C.Master, C.Undead, C.Wave1], undefined, 4), new Model('Viktoria of Ashes', [C.Outcast], [C.Master, C.Living, C.Sister, C.Wave1], undefined, 1), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Mercenary, C.Freikorps, C.Wave1], 10, 3), new Model('The Nothing Beast', [C.Outcast], [C.Enforcer, C.Rare1, C.Wave1], 10), new Model('Viktoria of Blood', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Sister, C.Wave1], 0, 3), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10, 3), new Model('Steam Trunk', [C.Outcast], [C.Peon, C.Construct, C.TotemFor('<NAME>'), C.Wave1], 3), new Model('<NAME>', [C.Outcast, C.Resurrectionist], [C.Enforcer, C.Living, C.TotemFor('<NAME>'), C.Wave1], 5), new Model('Student of Conflict', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Sister, C.Wave1], 4), new Model('Malifaux Child', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Lost, C.Wave1], 2), new Model('<NAME>', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10), new Model('<NAME>', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare2, C.Wave1], 7), new Model('Des<NAME>ercenary', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 4), new Model('Freikorps Specialist', [C.Outcast], [C.Living, C.Enforcer, C.Mercenary, C.Freikorps, C.Wave1], 8), new Model('<NAME>', [C.Outcast], [C.Living, C.Minion, C.Mercenary, C.Freikorps, C.Wave1], 5), new Model('<NAME>', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 8), new Model('<NAME>', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Msu, C.Wave1], 6), new Model('<NAME>', [C.Outcast], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.Horror, C.Wave1], 12), new Model('<NAME>', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 6), new Model('Void <NAME>', [C.Outcast], [C.Minion, C.Wave1], 4), new Model('<NAME>', [C.Outcast], [C.Master, C.Undead, C.Tormented, C.Spirit, C.Cursed, C.Wave2], undefined, 2), new Model('The Guilty', [C.Outcast], [C.Minion, C.Undead, C.Tormented, C.Wave2], 5), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Undead, C.Rare1, C.Tormented, C.Wave2], 9, 4), new Model('<NAME>', [C.Outcast], [C.Peon, C.TotemFor('<NAME>'), C.Tormented, C.Spirit, C.Wave2], 4), new Model('<NAME>', [C.Outcast], [C.Master, C.Tyrant, C.Nihilist, C.Wave2], undefined, 1), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Rare1, C.Nihilist, C.Spirit, C.Wave2], 8, 5), new Model('Obediant Wretch', [C.Outcast], [C.Minion, C.Living, C.Rare1, C.Nihilist, C.Wave2], 4), new Model('Rat Catcher', [C.Outcast], [C.Minion, C.Living, C.Rare2, C.Nihilist, C.Wave2], 6), new Model('<NAME>aux <NAME>', [C.Outcast], [C.Peon, C.Vermin, C.Wave2], 2), new Model('Rat King', [C.Outcast], [C.Minion, C.Vermin, C.Swarm, C.Wave2], 8), new Model('The Stolen', [C.Outcast], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Rare3, C.Nihilist, C.Lost, C.Wave2], 2), new Model('Ashes and Dust', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 13), new Model('Ashen Core', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 0), new Model('Dust Storm', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 6), new Model('Freikorps Librarian', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Academic, C.Freikorps, C.Wave2], 7), new Model('Freikorps Trapper', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Freikorps, C.Wave2], 6), new Model('Lazarus', [C.Outcast], [C.Enforcer, C.Construct, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Sue', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave2], 8), new Model('Hodgepodge Effigy', [C.Outcast], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Ama No Zako', [C.Outcast, C.TenThunders], [C.Henchman, C.Mercenary, C.Rare1, C.Oni, C.Wave2], 9, 4), new Model('Strongarm Suit', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Vanessa', [C.Outcast], [C.Enforcer, C.Living, C.Rare1, C.Sister, C.Wave2], 8), new Model('Leveticus', [C.Outcast], [C.Master, C.Living, C.Wave2], undefined, 2), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Wave2], 10, 3), new Model('<NAME>', [C.Outcast], [C.Peon, C.Undead, C.TotemFor('Leveticus'), C.Rare3, C.Wave2], 0), new Model('Abomination', [C.Outcast], [C.Minion, C.Construct, C.Undead, C.Wave2], 4), new Model('Desolation Engine', [C.Outcast], [C.Enforcer, C.Undead, C.Construct, C.Rare1, C.Wave2], 13), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave1], undefined, 4), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Kin, C.Wave1], undefined, 3), new Model('The Brewmaster', [C.Gremlin, C.TenThunders], [C.Master, C.Living, C.Gremlin, C.TriChi, C.Wave1], undefined, 3), new Model('<NAME>', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7, 6), new Model('Fingers', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.TriChi, C.Wave1], 10, 3), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Wave1], 9), new Model('Whiskey Golem', [C.Gremlin], [C.Enforcer, C.Construct, C.Rare1, C.TriChi, C.Wave1], 10), new Model('<NAME>', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('S<NAME>'), C.Wave1], 2), new Model('<NAME>', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Op<NAME>'), C.Gremlin, C.Kin, C.Wave1], 2), new Model('<NAME>', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('The Brewmaster'), C.Gremlin, C.TriChi, C.Wave1], 3), new Model('Bay<NAME>', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 3), new Model('Hog Whisperer', [C.Gremlin], [C.Minion, C.Living, C.Mercenary, C.Gremlin, C.Wave1], 5), new Model('Moon Shinobi', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.TriChi, C.Wave1], 6), new Model('Pigapult', [C.Gremlin], [C.Peon, C.Construct, C.Rare1, C.Gremlin, C.Wave1], 8), new Model('Piglet', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 4), new Model('Slop Hauler', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 5), new Model('War Pig', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 9), new Model('Pere Ravage', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 6), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('Penelope', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Hound, C.Wave2], 2), new Model('The Sow', [C.Gremlin], [C.Minion, C.Living, C.Rare1, C.Beast, C.Pig, C.Wave2], 8), new Model('Old Major', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Pig, C.Wave2], 9, 4), new Model('Rooster Rider', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Rooster, C.Wave2], 6), new Model('Stuffed Piglet', [C.Gremlin], [C.Peon, C.Undead, C.Rare6, C.Pig, C.Wave2], 2), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Rare2, C.Gremlin, C.Wave2], 7), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('The Little Lass', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Mah Tucket'), C.Gremlin, C.Wave2], 4), new Model('<NAME>', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 8, 5), new Model('<NAME>', [C.Gremlin], [C.Minion, C.Living, C.Rare3, C.Gremlin, C.Wave2], 6), new Model('<NAME>', [C.Gremlin], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Swampfiend, C.Wave2], 10, 3), new Model('<NAME>', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 10, 3), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Gremlin, C.Wave2], 7), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Pig, C.Wave2], 10), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 6), new Model('Wild Boar', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Swampfiend, C.Wave2], 6), new Model('Lucky Effigy', [C.Gremlin], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 3), new Model('Lovely Assistant', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Wong'), C.Gremlin, C.Showgirl, C.Wave2], 3), new Model('Lightning Bug', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave2], 5), new Model('<NAME>', [C.Gremlin], [C.Minion, C.Living, C.Swampfiend, C.Wave2], 5), new Model('<NAME>', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 7, 6), new Model('<NAME>', [C.Gremlin], [C.Peon, C.Living, C.Totem, C.Gremlin, C.Wave2], 4), new Model('<NAME>', [C.TenThunders, C.Outcast], [C.Master, C.Living, C.LastBlossom, C.Wave1], undefined, 2), new Model('<NAME>', [C.TenThunders, C.Arcanist], [C.Master, C.Living, C.Foundry, C.Wave1], undefined, 3), new Model('<NAME>', [C.TenThunders, C.Neverborn], [C.Master, C.Living, C.Darkened, C.Wave1], undefined, 1), new Model('<NAME>', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 10, 3), new Model('<NAME>', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Foundry, C.Wave1], 9, 4), new Model('<NAME>', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 7, 6), new Model('<NAME>', [C.TenThunders, C.Outcast], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Wave1], 3), new Model('<NAME>', [C.TenThunders, C.Arcanist], [C.Minion, C.TotemFor('<NAME>'), C.Spirit, C.Wave1], 3), new Model('Hungering Darkness', [C.TenThunders, C.Neverborn], [C.Henchman, C.TotemFor('<NAME>'), C.Rare1, C.Spirit, C.Darkened, C.Wave1], 0, 5), new Model('D<NAME>', [C.TenThunders], [C.Minion, C.Living, C.Rare1, C.Beast, C.Wave1], 10), new Model('<NAME>', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave1], 10, 3), new Model('Monk of Low River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave1], 4), new Model('<NAME>', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Showgirl, C.Wave1], 5), new Model('Rail Worker', [C.TenThunders, C.Arcanist], [C.Minion, C.Living, C.Construct, C.Foundry, C.Wave1], 5), new Model('The Illuminated', [C.TenThunders, C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Wave1], 7), new Model('Thunder Archer', [C.TenThunders], [C.Minion, C.Living, C.Wave1], 7), new Model('<NAME>', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Wave1], 6), new Model('<NAME>', [C.TenThunders], [C.Enforcer, C.Living, C.Wave1], 8), new Model('<NAME>', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 2), new Model('<NAME>', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 0), new Model('<NAME>', [C.TenThunders, C.Guild], [C.Henchman, C.Living, C.Rare1, C.BlackSheep, C.Wave2], 9, 4), new Model('<NAME>', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.TotemFor('<NAME>'), C.Beast, C.Hound, C.Wave2], 4), new Model('<NAME>', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.BlackSheep, C.Wave2], 4), new Model('<NAME>', [C.TenThunders, C.Resurrectionist], [C.Master, C.Living, C.Ancestor, C.Wave2], undefined, 4), new Model('S<NAME>er', [C.TenThunders, C.Resurrectionist], [C.Peon, C.TotemFor('Yan Lo'), C.Spirit, C.Wave2], 3), new Model('<NAME> Niece', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Ancestor, C.Wave2], 6), new Model('Izamu the Armor', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Spirit, C.Wave2], 10), new Model('Toshiro the Daimyo', [C.TenThunders, C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Ancestor, C.Wave2], 9, 4), new Model('Yin the Penangalan', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Horror, C.Wave2], 8), new Model('Ten Thunders Brother', [C.TenThunders], [C.Minion, C.Living, C.Wave2], 5), new Model('Mr. <NAME>', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Darkened, C.Mimic, C.Wave2], 8), new Model('Mr. <NAME>', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Darkened, C.Mimic, C.Wave2], 6), new Model('Shadow Effigy', [C.TenThunders], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Komainu', [C.TenThunders], [C.Minion, C.Construct, C.Spirit, C.Retainer, C.Wave2], 5), new Model('Sensei Yu', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave2], 9, 4), new Model('<NAME>', [C.TenThunders], [C.Master, C.Living, C.Tyrant, C.Wave2], undefined, 2), new Model('Peasant', [C.TenThunders], [C.Peon, C.Living, C.TotemFor('<NAME>'), C.Rare2, C.Wave2], 2), new Model('Fermented River Monk', [C.TenThunders], [C.Minion, C.Living, C.TriChi, C.Wave2], 5), new Model('Monk of High River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave2], 6), new Model('The Lone Swordsman', [C.TenThunders], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 8), new Model('Kamaitachi', [C.TenThunders], [C.Minion, C.Totem, C.Oni, C.Wave2], 4), new Model('Tengu', [C.TenThunders], [C.Minion, C.Spirit, C.Oni, C.Wave2], 4), new Model('Katanaka S<NAME>per', [C.TenThunders], [C.Minion, C.Living, C.Rare2, C.Wave2], 7), new Model('Brutal Emissary', [C.Guild], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Master Queeg', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.BlackSheep, C.Wave3], 7, 6), new Model('Dr. <NAME>', [C.Guild], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 9, 4), new Model('Nurse Heartsbane', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 8), new Model('Greed', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Sanctioned Spellcaster', [C.Guild], [C.Minion, C.Living, C.Academic, C.Wave3], 5), new Model('Orderly', [C.Guild], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.WitchHunter, C.Wave3], 5), new Model('Mounted Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave3], 7), new Model('Carrion Emissary', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Anna Lovelace', [C.Resurrectionist], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave3], 9, 4), new Model('S<NAME>th', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Horror, C.Wave3], 8), new Model('The Forgotten Marshal', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave3], 7), new Model('<NAME>', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave3], 7), new Model('Arcane Emissary', [C.Arcanist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wind Gamin', [C.Arcanist], [C.Minion, C.Living, C.Gamin, C.Wave3], 4), new Model('The Scorpius', [C.Arcanist], [C.Minion, C.Living, C.Construct, C.Rare1, C.Beast, C.Wave3], 6), new Model('Ice Dancer', [C.Arcanist], [C.Minion, C.Living, C.Showgirl, C.Wave3], 6), new Model('Envy', [C.Arcanist], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Mysterious Emissary', [C.Neverborn], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wrath', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8, 5), new Model('Angel Eyes', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 9, 4), new Model('Scion of Black Blood', [C.Neverborn], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 8), new Model('Corrupted Hound', [C.Neverborn], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Wave3], 3), new Model('Changeling', [C.Neverborn], [C.Minion, C.Living, C.Rare3, C.Mimic, C.Wave3], 4), new Model('Bloodwretch', [C.Neverborn], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Nephilim, C.Wave3], 5), new Model('Bunraku', [C.Neverborn, C.TenThunders], [C.Minion, C.Construct, C.Puppet, C.Wave3], 6), new Model('Hodgepodge Emissary', [C.Outcast], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Cursed, C.Wave3], 10), new Model('Scion of the Void', [C.Outcast], [C.Henchman, C.Rare1, C.Wave3], 8, 5), new Model('Pride', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Big Jake', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave3], 5), new Model('The Winged Plague', [C.Outcast], [C.Minion, C.Living, C.Vermin, C.Wave3], 4), new Model('Lucky Emissary', [C.Gremlin], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Sparks', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Foundry, C.Wave3], 7, 6), new Model('Gluttony', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Survivor', [C.Gremlin], [C.Minion, C.Living, C.Construct, C.Gremlin, C.Wave3], 5), new Model('Mechanized Porkchop', [C.Gremlin], [C.Minion, C.Construct, C.Pig, C.Foundry, C.Wave3], 7), new Model('Shadow Emissary', [C.TenThunders], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Lust', [C.TenThunders], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Wandering River Monk', [C.TenThunders], [C.Minion, C.Living, C.Wave3], 7), new Model('Obsidian Oni', [C.TenThunders], [C.Minion, C.Oni, C.Wave3], 6), new Model('Jor<NAME>o', [C.TenThunders], [C.Minion, C.Oni, C.LastBlossom, C.Wave3], 9), new Model('<NAME>', [C.Guild], [C.Master, C.Living, C.Journalist, C.Wave4], undefined, 4), new Model('The Printing Press', [C.Guild], [C.Peon, C.Construct, C.TotemFor('<NAME>'), C.Journalist, C.Wave4], 3), new Model('<NAME>', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Allison Dade', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Field Reporter', [C.Guild], [C.Minion, C.Living, C.Journalist, C.Wave4], 4), new Model('Death Marshal Recruiter', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave4], 7), new Model('<NAME>', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave4], 9), new Model('<NAME>', [C.Resurrectionist], [C.Master, C.Living, C.Revenant, C.Wave4], undefined, 4), new Model('<NAME>', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Reva'), C.Spirit, C.Revenant, C.Wave4], 2), new Model('<NAME>', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Revenant, C.Wave4], 8, 5), new Model('<NAME>', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Horror, C.Wave4], 13, 0), new Model('Shield<NAME>', [C.Resurrectionist], [C.Minion, C.Living, C.Revenant, C.Wave4], 6), new Model('<NAME>', [C.Resurrectionist], [C.Minion, C.Undead, C.Revenant, C.Horror, C.Wave4], 8), new Model('<NAME>', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave4], 7), new Model('<NAME>', [C.Arcanist], [C.Master, C.Living, C.Academic, C.Wave4], undefined, 4), new Model('Corpse Candle', [C.Arcanist], [C.Minion, C.TotemFor('<NAME>'), C.Rare1, C.Gamin, C.Wave4], 8), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Academic, C.Wave4], 7, 6), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Academic, C.Wave4], 9, 4), new Model('<NAME>', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave4], 9, 4), new Model('<NAME>', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Beast, C.Wave4], 5), new Model('<NAME>', [C.Arcanist], [C.Enforcer, C.Living, C.Msu, C.Academic, C.Wave4], 8), new Model('<NAME>', [C.Neverborn], [C.Master, C.Undead, C.Fae, C.Wave4], undefined, 4), new Model('The G<NAME>', [C.Neverborn], [C.Peon, C.Living, C.TotemFor('Titania'), C.Fae, C.Wave4], 3), new Model('<NAME>', [C.Neverborn], [C.Henchman, C.Undead, C.Rare1, C.Fae, C.Wave4], 9, 4), new Model('The Tooth', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Claw', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Thorn', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('<NAME>atch', [C.Neverborn], [C.Minion, C.Living, C.Rare1, C.Fae, C.Nightmare, C.Spirit, C.Wave4], 5), new Model('Will O\' the Wisp', [C.Neverborn], [C.Minion, C.Rare3, C.Spirit, C.Swampfiend, C.Wave4], 3), new Model('Rougarou', [C.Neverborn], [C.Minion, C.Undead, C.Fae, C.Beast, C.Wave4], 8), new Model('<NAME>', [C.Outcast], [C.Master, C.Living, C.Bandit, C.Wave4], undefined, 4), new Model('<NAME>', [C.Outcast], [C.Minion, C.Living, C.TotemFor('<NAME>'), C.Wave4], 3), new Model('Mad Dog Brackett', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Bandit, C.Wave4], 9, 4), new Model('<NAME>', [C.Outcast], [C.Henchman, C.Mercenary, C.Rare1, C.Wave4], 12, 1), new Model('<NAME>', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.Wave4], 5), new Model('Dead Outland', [C.Outcast], [C.Minion, C.Undead, C.Bandit, C.Tormented, C.Wave4], 6), new Model('<NAME>', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.LastBlossom, C.Wave4], 8), new Model('<NAME>', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.SkyPirate, C.Wave4], undefined, 4), new Model('<NAME>', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('<NAME>'), C.Wave4], 3), new Model('The First Mate', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.SkyPirate, C.Wave4], 9, 4), new Model('<NAME>', [C.Gremlin], [C.Enforcer, C.Living, C.Construct, C.Gremlin, C.SkyPirate, C.Wave4], 6), new Model('<NAME>', [C.Gremlin, C.TenThunders], [C.Minion, C.Rare3, C.Oni, C.TriChi, C.Wave4], 4), new Model('<NAME>', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave4], 5), new Model('Swine-Cursed', [C.Gremlin], [C.Minion, C.Living, C.Rare2, C.Gremlin, C.Wave4], 7), new Model('<NAME>', [C.TenThunders], [C.Master, C.Living, C.Oni, C.Wave4], undefined, 3), new Model('<NAME>', [C.TenThunders], [C.Peon, C.TotemFor('<NAME>'), C.Oni, C.Wave4], 3), new Model('<NAME>', [C.TenThunders], [C.Henchman, C.Rare1, C.Oni, C.Wave4], 8, 5), new Model('Yokai', [C.TenThunders], [C.Minion, C.Oni, C.Wave4], 5), new Model('Terracotta Warrior', [C.TenThunders], [C.Minion, C.Construct, C.Rare3, C.Mimic, C.Wave4], 5), new Model('<NAME>', [C.TenThunders], [C.Enforcer, C.Rare1, C.Living, C.Retainer, C.Wave4], 8) ] export default ModelList
true
import ModelInterface from './ModelInterface.coffee' Model = ModelInterface.Model C = ModelInterface.Attribute # **Epic props** to rythos42 for saving me having to research and type all this! # https://github.com/rythos42/MalifauxModels-Web/blob/master/js/app/Mappers/ModelList.js ModelList = [ new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Master, C.Living, C.GuildMarshal, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Master, C.Living, C.WitchHunter, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Master, C.Living, C.Family, C.Wave1], undefined, 2), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.Family, C.Wave1], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.WitchHunter, C.Wave1], 9, 4), new Model('The JPI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 9, 4), new Model('Scales of Justice', [C.Guild], [C.Peon, C.Living, C.TotemFor('Lady Justice'), C.Wave1], 3), new Model('Purifying Flame', [C.Guild], [C.Peon, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Spirit, C.Wave1], 3), new Model('Enslaved Nephilim', [C.Guild], [C.Peon, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Nephilim, C.Wave1], 3), new Model('Governor\'s Proxy', [C.Guild], [C.Peon, C.Totem, C.Living, C.Wave1], 3), new Model('Death Marshal', [C.Guild], [C.Minion, C.Living, C.GuildMarshal, C.Wave1], 6), new Model('Executioner', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Wave1], 9), new Model('Guild Austringer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Guardsman, C.Wave1], 6), new Model('Guild Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave1], 4), new Model('Peacekeeper', [C.Guild], [C.Enforcer, C.Construct, C.Rare1, C.Wave1], 11), new Model('The Lone Marshal', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.GuildMarshal, C.Wave1], 8), new Model('Witchling Stalker', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave1], 5), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Tormented, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Master, C.Living, C.Construct, C.Msu, C.Wave2], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Construct, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Mechanical Attendant', [C.Guild], [C.Peon, C.Construct, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Minion, C.Construct, C.Wave2], 8), new Model('PI:NAME:<NAME>END_PI', [C.Guild, C.Neverborn], [C.Master, C.Living, C.Mimic, C.Wave2], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.Wave2], 9, 4), new Model('The Scribe', [C.Guild, C.Neverborn], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Enforcer, C.Living, C.Rare1, C.Family, C.Wave2], 7), new Model('Guild Hound', [C.Guild], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Guardsman, C.Wave2], 3), new Model('Guard Sergeant', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.Guardsman, C.Wave2], 6), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Minion, C.Construct, C.Rare2, C.Wave2], 7), new Model('Guild Lawyer', [C.Guild], [C.Minion, C.Living, C.Rare2, C.Mimic, C.Wave2], 6), new Model('Watcher', [C.Guild], [C.Minion, C.Construct, C.Wave2], 4), new Model('Exorcist', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave2], 7), new Model('Pistolero De Latigo', [C.Guild], [C.Minion, C.Living, C.Family, C.Wave2], 5), new Model('Pale Rider', [C.Guild], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Warden', [C.Guild], [C.Minion, C.Construct, C.Guardsman, C.Wave2], 6), new Model('Witchling Handler', [C.Guild], [C.Enforcer, C.Living, C.WitchHunter, C.Wave2], 8), new Model('Brutal Effigy', [C.Guild], [C.Minion, C.Construct, C.Puppet, C.Effigy, C.Rare1, C.Wave2], 4), new Model('Guild Rifleman', [C.Guild], [C.Minion, C.Living, C.Rare3, C.Guardsman, C.Wave2], 5), new Model('Clockwork Trap', [C.Guild, C.TenThunders], [C.Peon, C.Rare4, C.Wave2], 2), new Model('Guild Pathfinder', [C.Guild, C.TenThunders], [C.Minion, C.Living, C.Guardsman, C.Wave2], 6), new Model('Seamus', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('McMoPI:NAME:<NAME>END_PI', [C.Resurrectionist, C.Guild], [C.Master, C.Living, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Wave1], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 7, 6), new Model('Mortimer', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Wave1], 9, 4), new Model('Copycat Killer', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Seamus'), C.Wave1], 3), new Model('Zombie Chihuahua', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('McMourning'), C.Beast, C.Wave1], 2), new Model('Vulture', [C.Resurrectionist], [C.Peon, C.Living, C.TotemFor('Nicodem'), C.Beast, C.Wave1], 3), new Model('Graveyard Spirit', [C.Resurrectionist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('Bete Noire', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Wave1], 8), new Model('Canine Remains', [C.Resurrectionist], [C.Minion, C.Undead, C.Beast, C.Hound, C.Wave1], 4), new Model('Crooked Man', [C.Resurrectionist], [C.Minion, C.Undead, C.Tormented, C.Wave1], 5), new Model('Flesh Construct', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 6), new Model('Mindless Zombie', [C.Resurrectionist], [C.Peon, C.Undead, C.Wave1], 2), new Model('Necropunk', [C.Resurrectionist], [C.Minion, C.Undead, C.Construct, C.Wave1], 5), new Model('Nurse', [C.Resurrectionist], [C.Minion, C.Living, C.Tormented, C.Wave1], 5), new Model('Punk Zombie', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave1], 7), new Model('Rotten Belle', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave1], 5), new Model('The Hanged', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Spirit, C.Tormented, C.Wave1], 9), new Model('Molly Squidpiddge', [C.Resurrectionist], [C.Master, C.Undead, C.Belle, C.Horror, C.Wave2], undefined, 3), new Model('Rogue Necromancy', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Construct, C.Beast, C.Horror, C.Wave2], 10), new Model('Guild Autopsy', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Wave2], 4), new Model('Necrotic Machine', [C.Resurrectionist], [C.Minion, C.Construct, C.TotemFor('Molly Squidpiddge'), C.Rare1, C.Horror, C.Spirit, C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Master, C.Living, C.Wave2], undefined, 3), new Model('Ikiryo', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.Spirit, C.Wave2], 0), new Model('Seishin', [C.Resurrectionist], [C.Peon, C.Rare5, C.Spirit, C.Wave2], 0), new Model('Lost Love', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Kirai Ankoku'), C.Spirit, C.Wave2], 4), new Model('DPI:NAME:<NAME>END_PIue Ba', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Wave2], 8, 5), new Model('Dead Rider', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Gaki', [C.Resurrectionist], [C.Minion, C.Spirit, C.Wave2], 4), new Model('Night Terror', [C.Resurrectionist], [C.Minion, C.Rare4, C.Beast, C.Spirit, C.Wave2], 3), new Model('Onryo', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Undead, C.Rare2, C.Beast, C.Spirit, C.Wave2], 8), new Model('Crooligan', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Lost, C.Wave2], 4), new Model('Dead Doxy', [C.Resurrectionist], [C.Minion, C.Undead, C.Belle, C.Wave2], 6), new Model('The Drowned', [C.Resurrectionist], [C.Minion, C.Undead, C.Horror, C.Spirit, C.Tormented, C.Wave2], 6), new Model('PI:NAME:<NAME>END_PIakuna Ubume', [C.Resurrectionist], [C.Enforcer, C.Spirit, C.Tormented, C.Rare1, C.Wave2], 6), new Model('Rafkin', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Undead, C.Retainer, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI the PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Spirit, C.Horror, C.Wave2], 8, 5), new Model('Student of PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 7), new Model('Student of PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Construct, C.Undead, C.Horror, C.Academic, C.Wave2], 8), new Model('The PI:NAME:<NAME>END_PIaledPI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Construct, C.Undead, C.Rare1, C.Horror, C.Academic, C.Wave2], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Master, C.Living, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Master, C.Living, C.Beast, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Master, C.Living, C.Construct, C.Msu, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Beast, C.Wave1], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Construct, C.Rare1, C.Msu, C.Wave1], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave1], 8), new Model('Ice PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Enforcer, C.Construct, C.Wave1], 10), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.TotemFor('Rasputina'), C.Wave1], 3), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Beast, C.Wave1], 2), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Msu, C.Wave1], 4), new Model('Essence of Power', [C.Arcanist], [C.Peon, C.Totem, C.Spirit, C.Wave1], 3), new Model('DePI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.Wave1], 7), new Model('Electric Creation', [C.Arcanist], [C.Peon, C.Construct, C.Wave1], 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Swarm, C.Wave1], 5), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Enforcer, C.Construct, C.Living, C.Rare1, C.Msu, C.Wave1], 12), new Model('Ice Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave1], 4), new Model('Metal Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Msu, C.Foundry, C.Wave1], 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 4), new Model('Rail Golem', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Foundry, C.Wave1], 11), new Model('Razorspine Rattler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave1], 7), new Model('Sabertooth Cerberus', [C.Arcanist], [C.Enforcer, C.Living, C.Beast, C.Wave1], 9), new Model('Steam Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave1], 4), new Model('Steam Arachnid Swarm', [C.Arcanist], [C.Minion, C.Construct, C.Swarm, C.Msu, C.Wave1], 8), new Model('Ironsides', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 5), new Model('Oxfordian Mage', [C.Arcanist], [C.Enforcer, C.Living, C.Rare3, C.Academic, C.Msu, C.Wave2], 6), new Model('Mouse', [C.Arcanist], [C.Peon, C.Living, C.TotemFor('Ironsides'), C.Msu, C.Wave2], 4), new Model('Colette Du Bois', [C.Arcanist], [C.Master, C.Living, C.Showgirl, C.Wave2], undefined, 2), new Model('Mechanical Dove', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Colette Du Bois'), C.Rare3, C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave2], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Construct, C.Rare2, C.Showgirl, C.Puppet, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Enforcer, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 0), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.Mercenary, C.Showgirl, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Peon, C.Construct, C.Showgirl, C.Puppet, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Master, C.Living, C.Msu, C.Wave2], undefined, 4), new Model('The Firestarter', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 7, 6), new Model('Eternal Flame', [C.Arcanist], [C.Peon, C.Construct, C.TotemFor('Kaeris'), C.Msu, C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 7), new Model('Large Arachnid', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('Malifaux Raptor', [C.Arcanist], [C.Peon, C.Living, C.Rare3, C.Beast, C.Wave2], 3), new Model('Mechanical Rider', [C.Arcanist], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('Silent One', [C.Arcanist], [C.Minion, C.Living, C.Wave2], 6), new Model('Snow Storm', [C.Arcanist], [C.Henchman, C.Rare1, C.Spirit, C.Wave2], 11, 2), new Model('Soulstone Miner', [C.Arcanist], [C.Minion, C.Construct, C.Msu, C.Wave2], 6), new Model('The Captain', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Wave2], 10, 3), new Model('Angelica', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Showgirl, C.Wave2], 6), new Model('Blessed of December', [C.Arcanist], [C.Enforcer, C.Living, C.Rare1, C.Beast, C.Wave2], 9), new Model('Fire Gamin', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Wave2], 4), new Model('Slate Ridge Mauler', [C.Arcanist], [C.Minion, C.Living, C.Beast, C.Wave2], 8), new Model('Union Miner', [C.Arcanist], [C.Minion, C.Living, C.Msu, C.Wave2], 5), new Model('Willie', [C.Arcanist], [C.Minion, C.Living, C.Rare1, C.Msu, C.Foundry, C.Wave2], 6), new Model('Arcane Effigy', [C.Arcanist], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Mobile Toolkit', [C.Arcanist], [C.Peon, C.Construct, C.Rare1, C.Msu, C.Wave2], 3), new Model('PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Master, C.Living, C.Nephilim, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Master, C.Living, C.Woe, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', ['Neverborn', C.Gremlin], [C.Master, C.Living, C.Swampfiend, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave1], 10, 3), new Model('PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Henchman, C.Living, C.Rare1, C.Woe, C.Mimic, C.Lost, C.Wave1], 9, 4), new Model('Bad PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Henchman, C.Rare1, C.Swampfiend, C.Wave1], 8, 5), new Model('PI:NAME:<NAME>END_PI', ['Neverborn'], [C.Peon, C.Living, C.TotemFor('Lilith'), C.Nephilim, C.Wave1], 3), new Model('Poltergeist', ['Neverborn'], [C.Minion, C.TotemFor('Pandora'), C.Woe, C.Spirit, C.Wave1], 5), new Model('PI:NAME:<NAME>END_PI', ['Neverborn', C.Gremlin], [C.Peon, C.Construct, C.TotemFor('Zoraida'), C.Puppet, C.Wave1], 3), new Model('Primordial Magic', ['Neverborn'], [C.Peon, C.Totem, C.Spirit, C.Wave1], 2), new Model('Baby Kade', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave1], 7), new Model('Teddy', ['Neverborn'], [C.Enforcer, C.Construct, C.Nightmare, C.Wave1], 11), new Model('Beckoner', ['Neverborn'], [C.Minion, C.Living, C.Rare2, C.Brilliance, C.Darkened, C.Mimic, C.Wave1], 7), new Model('Doppleganger', ['Neverborn'], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Mimic, C.Wave1], 7), new Model('Mature Nephilim', ['Neverborn'], [C.Enforcer, C.Living, C.Nephilim, C.Wave1], 11), new Model('Silurid', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 7), new Model('Sorrow', ['Neverborn'], [C.Minion, C.Woe, C.Spirit, C.Wave1], 5), new Model('Terror Tot', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 4), new Model('Waldgeist', ['Neverborn'], [C.Minion, C.Living, C.Beast, C.Swampfiend, C.Wave1], 6), new Model('Young Nephilim', ['Neverborn'], [C.Minion, C.Living, C.Nephilim, C.Wave1], 6), new Model('The Dreamer', [C.Neverborn], [C.Master, C.Spirit, C.Wave2], undefined, 3), new Model('Lord Chompy Bits', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Tyrant, C.Wave2], 0), new Model('Daydream', [C.Neverborn], [C.Peon, C.TotemFor('The Dreamer'), C.Rare3, C.Nightmare, C.Wave2], 2), new Model('AlPI:NAME:<NAME>END_PI', [C.Neverborn], [C.Peon, C.Nightmare, C.Wave2], 3), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Wave2], 8), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Enforcer, C.Rare1, C.Nightmare, C.Nephilim, C.Woe, C.Wave2], 7), new Model('Insidious Madness', [C.Neverborn], [C.Minion, C.Rare3, C.Nightmare, C.Woe, C.Wave2], 5), new Model('Widow Weaver', [C.Neverborn], [C.Henchman, C.Rare1, C.Nightmare, C.Wave2], 8, 5), new Model('Black Blood Shaman', [C.Neverborn], [C.Minion, C.Living, C.Rare2, C.Nephilim, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Nephilim, C.Wave2], 13, 0), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Master, C.Construct, C.Puppet, C.Wave2], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Minion, C.Construct, C.TotemFor('Collodi'), C.Rare4, C.Puppet, C.Wave2], 3), new Model('Stitched Together', [C.Neverborn], [C.Minion, C.Construct, C.Nightmare, C.Puppet, C.Darkened, C.Wave2], 6), new Model('Wicked Doll', [C.Neverborn], [C.Minion, C.Construct, C.Puppet, C.Wave2], 4), new Model('Vasilisa', [C.Neverborn], [C.Henchman, C.Construct, C.Rare1, C.Puppet, C.Wave2], 9, 4), new Model('Iggy', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Lost, C.Wave2], 5), new Model('Spawn Mother', [C.Neverborn], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.Beast, C.Wave2], 9, 4), new Model('Gupps', [C.Neverborn], [C.Minion, C.Living, C.Swampfiend, C.Beast, C.Swarm, C.Wave2], 4), new Model('Tuco', [C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave2], 7), new Model('Mysterious Effigy', [C.Neverborn], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('The Depleted', [C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Darkened, C.Wave2], 4), new Model('Hooded Rider', [C.Neverborn], [C.Enforcer, C.Construct, C.Rare1, C.Horseman, C.Wave2], 12), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Master, C.Living, C.Freikorps, C.Wave1], undefined, 1), new Model('PI:NAME:<NAME>END_PI', [C.Outcast, C.Resurrectionist], [C.Master, C.Undead, C.Wave1], undefined, 4), new Model('Viktoria of Ashes', [C.Outcast], [C.Master, C.Living, C.Sister, C.Wave1], undefined, 1), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Mercenary, C.Freikorps, C.Wave1], 10, 3), new Model('The Nothing Beast', [C.Outcast], [C.Enforcer, C.Rare1, C.Wave1], 10), new Model('Viktoria of Blood', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Sister, C.Wave1], 0, 3), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10, 3), new Model('Steam Trunk', [C.Outcast], [C.Peon, C.Construct, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave1], 3), new Model('PI:NAME:<NAME>END_PI', [C.Outcast, C.Resurrectionist], [C.Enforcer, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave1], 5), new Model('Student of Conflict', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Sister, C.Wave1], 4), new Model('Malifaux Child', [C.Outcast], [C.Peon, C.Living, C.Totem, C.Mercenary, C.Lost, C.Wave1], 2), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 10), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare2, C.Wave1], 7), new Model('DesPI:NAME:<NAME>END_PIercenary', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 4), new Model('Freikorps Specialist', [C.Outcast], [C.Living, C.Enforcer, C.Mercenary, C.Freikorps, C.Wave1], 8), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Living, C.Minion, C.Mercenary, C.Freikorps, C.Wave1], 5), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave1], 8), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Msu, C.Wave1], 6), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.Horror, C.Wave1], 12), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Wave1], 6), new Model('Void PI:NAME:<NAME>END_PI', [C.Outcast], [C.Minion, C.Wave1], 4), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Master, C.Undead, C.Tormented, C.Spirit, C.Cursed, C.Wave2], undefined, 2), new Model('The Guilty', [C.Outcast], [C.Minion, C.Undead, C.Tormented, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Undead, C.Rare1, C.Tormented, C.Wave2], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Peon, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Tormented, C.Spirit, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Master, C.Tyrant, C.Nihilist, C.Wave2], undefined, 1), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Rare1, C.Nihilist, C.Spirit, C.Wave2], 8, 5), new Model('Obediant Wretch', [C.Outcast], [C.Minion, C.Living, C.Rare1, C.Nihilist, C.Wave2], 4), new Model('Rat Catcher', [C.Outcast], [C.Minion, C.Living, C.Rare2, C.Nihilist, C.Wave2], 6), new Model('PI:NAME:<NAME>END_PIaux PI:NAME:<NAME>END_PI', [C.Outcast], [C.Peon, C.Vermin, C.Wave2], 2), new Model('Rat King', [C.Outcast], [C.Minion, C.Vermin, C.Swarm, C.Wave2], 8), new Model('The Stolen', [C.Outcast], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Rare3, C.Nihilist, C.Lost, C.Wave2], 2), new Model('Ashes and Dust', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 13), new Model('Ashen Core', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 0), new Model('Dust Storm', [C.Outcast], [C.Enforcer, C.Construct, C.Undead, C.Rare1, C.Wave2], 6), new Model('Freikorps Librarian', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Academic, C.Freikorps, C.Wave2], 7), new Model('Freikorps Trapper', [C.Outcast], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Freikorps, C.Wave2], 6), new Model('Lazarus', [C.Outcast], [C.Enforcer, C.Construct, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Sue', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave2], 8), new Model('Hodgepodge Effigy', [C.Outcast], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Ama No Zako', [C.Outcast, C.TenThunders], [C.Henchman, C.Mercenary, C.Rare1, C.Oni, C.Wave2], 9, 4), new Model('Strongarm Suit', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Freikorps, C.Wave2], 10), new Model('Vanessa', [C.Outcast], [C.Enforcer, C.Living, C.Rare1, C.Sister, C.Wave2], 8), new Model('Leveticus', [C.Outcast], [C.Master, C.Living, C.Wave2], undefined, 2), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Wave2], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Peon, C.Undead, C.TotemFor('Leveticus'), C.Rare3, C.Wave2], 0), new Model('Abomination', [C.Outcast], [C.Minion, C.Construct, C.Undead, C.Wave2], 4), new Model('Desolation Engine', [C.Outcast], [C.Enforcer, C.Undead, C.Construct, C.Rare1, C.Wave2], 13), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave1], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Kin, C.Wave1], undefined, 3), new Model('The Brewmaster', [C.Gremlin, C.TenThunders], [C.Master, C.Living, C.Gremlin, C.TriChi, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7, 6), new Model('Fingers', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.TriChi, C.Wave1], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Wave1], 9), new Model('Whiskey Golem', [C.Gremlin], [C.Enforcer, C.Construct, C.Rare1, C.TriChi, C.Wave1], 10), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('SPI:NAME:<NAME>END_PI'), C.Wave1], 2), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('OpPI:NAME:<NAME>END_PI'), C.Gremlin, C.Kin, C.Wave1], 2), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('The Brewmaster'), C.Gremlin, C.TriChi, C.Wave1], 3), new Model('BayPI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 3), new Model('Hog Whisperer', [C.Gremlin], [C.Minion, C.Living, C.Mercenary, C.Gremlin, C.Wave1], 5), new Model('Moon Shinobi', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.TriChi, C.Wave1], 6), new Model('Pigapult', [C.Gremlin], [C.Peon, C.Construct, C.Rare1, C.Gremlin, C.Wave1], 8), new Model('Piglet', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 4), new Model('Slop Hauler', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave1], 5), new Model('War Pig', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Wave1], 9), new Model('Pere Ravage', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 6), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('Penelope', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Hound, C.Wave2], 2), new Model('The Sow', [C.Gremlin], [C.Minion, C.Living, C.Rare1, C.Beast, C.Pig, C.Wave2], 8), new Model('Old Major', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Pig, C.Wave2], 9, 4), new Model('Rooster Rider', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Rooster, C.Wave2], 6), new Model('Stuffed Piglet', [C.Gremlin], [C.Peon, C.Undead, C.Rare6, C.Pig, C.Wave2], 2), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Rare2, C.Gremlin, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 4), new Model('The Little Lass', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Mah Tucket'), C.Gremlin, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.Rare3, C.Gremlin, C.Wave2], 6), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Swampfiend, C.Wave2], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Wave2], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Gremlin, C.Wave2], 7), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Pig, C.Wave2], 10), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 6), new Model('Wild Boar', [C.Gremlin], [C.Minion, C.Living, C.Beast, C.Pig, C.Swampfiend, C.Wave2], 6), new Model('Lucky Effigy', [C.Gremlin], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.Wave2], undefined, 3), new Model('Lovely Assistant', [C.Gremlin], [C.Peon, C.Living, C.TotemFor('Wong'), C.Gremlin, C.Showgirl, C.Wave2], 3), new Model('Lightning Bug', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.Swampfiend, C.Wave2], 5), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Kin, C.Wave2], 7, 6), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Peon, C.Living, C.Totem, C.Gremlin, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Outcast], [C.Master, C.Living, C.LastBlossom, C.Wave1], undefined, 2), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Arcanist], [C.Master, C.Living, C.Foundry, C.Wave1], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Neverborn], [C.Master, C.Living, C.Darkened, C.Wave1], undefined, 1), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 10, 3), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Foundry, C.Wave1], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.LastBlossom, C.Wave1], 7, 6), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Outcast], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave1], 3), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Arcanist], [C.Minion, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Spirit, C.Wave1], 3), new Model('Hungering Darkness', [C.TenThunders, C.Neverborn], [C.Henchman, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Rare1, C.Spirit, C.Darkened, C.Wave1], 0, 5), new Model('DPI:NAME:<NAME>END_PI', [C.TenThunders], [C.Minion, C.Living, C.Rare1, C.Beast, C.Wave1], 10), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave1], 10, 3), new Model('Monk of Low River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave1], 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Showgirl, C.Wave1], 5), new Model('Rail Worker', [C.TenThunders, C.Arcanist], [C.Minion, C.Living, C.Construct, C.Foundry, C.Wave1], 5), new Model('The Illuminated', [C.TenThunders, C.Neverborn], [C.Minion, C.Living, C.Brilliance, C.Wave1], 7), new Model('Thunder Archer', [C.TenThunders], [C.Minion, C.Living, C.Wave1], 7), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Minion, C.Living, C.Mercenary, C.LastBlossom, C.Wave1], 6), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Enforcer, C.Living, C.Wave1], 8), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 2), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Guild], [C.Master, C.Living, C.BlackSheep, C.Wave2], undefined, 0), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Guild], [C.Henchman, C.Living, C.Rare1, C.BlackSheep, C.Wave2], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Beast, C.Hound, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Guild], [C.Minion, C.Living, C.BlackSheep, C.Wave2], 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders, C.Resurrectionist], [C.Master, C.Living, C.Ancestor, C.Wave2], undefined, 4), new Model('SPI:NAME:<NAME>END_PIer', [C.TenThunders, C.Resurrectionist], [C.Peon, C.TotemFor('Yan Lo'), C.Spirit, C.Wave2], 3), new Model('PI:NAME:<NAME>END_PI Niece', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Ancestor, C.Wave2], 6), new Model('Izamu the Armor', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Spirit, C.Wave2], 10), new Model('Toshiro the Daimyo', [C.TenThunders, C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Ancestor, C.Wave2], 9, 4), new Model('Yin the Penangalan', [C.TenThunders, C.Resurrectionist], [C.Enforcer, C.Undead, C.Rare1, C.Ancestor, C.Horror, C.Wave2], 8), new Model('Ten Thunders Brother', [C.TenThunders], [C.Minion, C.Living, C.Wave2], 5), new Model('Mr. PI:NAME:<NAME>END_PI', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Darkened, C.Mimic, C.Wave2], 8), new Model('Mr. PI:NAME:<NAME>END_PI', [C.TenThunders, C.Neverborn], [C.Enforcer, C.Living, C.Rare1, C.Woe, C.Darkened, C.Mimic, C.Wave2], 6), new Model('Shadow Effigy', [C.TenThunders], [C.Minion, C.Construct, C.Rare1, C.Puppet, C.Effigy, C.Wave2], 4), new Model('Komainu', [C.TenThunders], [C.Minion, C.Construct, C.Spirit, C.Retainer, C.Wave2], 5), new Model('Sensei Yu', [C.TenThunders], [C.Henchman, C.Living, C.Rare1, C.Wave2], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Master, C.Living, C.Tyrant, C.Wave2], undefined, 2), new Model('Peasant', [C.TenThunders], [C.Peon, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Rare2, C.Wave2], 2), new Model('Fermented River Monk', [C.TenThunders], [C.Minion, C.Living, C.TriChi, C.Wave2], 5), new Model('Monk of High River', [C.TenThunders], [C.Minion, C.Living, C.Rare3, C.Wave2], 6), new Model('The Lone Swordsman', [C.TenThunders], [C.Enforcer, C.Living, C.Rare1, C.Wave2], 8), new Model('Kamaitachi', [C.TenThunders], [C.Minion, C.Totem, C.Oni, C.Wave2], 4), new Model('Tengu', [C.TenThunders], [C.Minion, C.Spirit, C.Oni, C.Wave2], 4), new Model('Katanaka SPI:NAME:<NAME>END_PIper', [C.TenThunders], [C.Minion, C.Living, C.Rare2, C.Wave2], 7), new Model('Brutal Emissary', [C.Guild], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Master Queeg', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Guardsman, C.BlackSheep, C.Wave3], 7, 6), new Model('Dr. PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 9, 4), new Model('Nurse Heartsbane', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.WitchHunter, C.Wave3], 8), new Model('Greed', [C.Guild], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Sanctioned Spellcaster', [C.Guild], [C.Minion, C.Living, C.Academic, C.Wave3], 5), new Model('Orderly', [C.Guild], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.WitchHunter, C.Wave3], 5), new Model('Mounted Guard', [C.Guild], [C.Minion, C.Living, C.Guardsman, C.Wave3], 7), new Model('Carrion Emissary', [C.Resurrectionist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Anna Lovelace', [C.Resurrectionist], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Wave3], 9, 4), new Model('SPI:NAME:<NAME>END_PIth', [C.Resurrectionist], [C.Enforcer, C.Undead, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Horror, C.Wave3], 8), new Model('The Forgotten Marshal', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Wave3], 7), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Enforcer, C.Living, C.Rare1, C.Nephilim, C.Wave3], 7), new Model('Arcane Emissary', [C.Arcanist], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wind Gamin', [C.Arcanist], [C.Minion, C.Living, C.Gamin, C.Wave3], 4), new Model('The Scorpius', [C.Arcanist], [C.Minion, C.Living, C.Construct, C.Rare1, C.Beast, C.Wave3], 6), new Model('Ice Dancer', [C.Arcanist], [C.Minion, C.Living, C.Showgirl, C.Wave3], 6), new Model('Envy', [C.Arcanist], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Mysterious Emissary', [C.Neverborn], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Wrath', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8, 5), new Model('Angel Eyes', [C.Neverborn], [C.Henchman, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 9, 4), new Model('Scion of Black Blood', [C.Neverborn], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Nephilim, C.Wave3], 8), new Model('Corrupted Hound', [C.Neverborn], [C.Minion, C.Living, C.Rare4, C.Beast, C.Hound, C.Wave3], 3), new Model('Changeling', [C.Neverborn], [C.Minion, C.Living, C.Rare3, C.Mimic, C.Wave3], 4), new Model('Bloodwretch', [C.Neverborn], [C.Minion, C.Living, C.Mercenary, C.Rare2, C.Nephilim, C.Wave3], 5), new Model('Bunraku', [C.Neverborn, C.TenThunders], [C.Minion, C.Construct, C.Puppet, C.Wave3], 6), new Model('Hodgepodge Emissary', [C.Outcast], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Cursed, C.Wave3], 10), new Model('Scion of the Void', [C.Outcast], [C.Henchman, C.Rare1, C.Wave3], 8, 5), new Model('Pride', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Big Jake', [C.Outcast], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.Wave3], 5), new Model('The Winged Plague', [C.Outcast], [C.Minion, C.Living, C.Vermin, C.Wave3], 4), new Model('Lucky Emissary', [C.Gremlin], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Sparks', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Gremlin, C.Foundry, C.Wave3], 7, 6), new Model('Gluttony', [C.Gremlin], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Survivor', [C.Gremlin], [C.Minion, C.Living, C.Construct, C.Gremlin, C.Wave3], 5), new Model('Mechanized Porkchop', [C.Gremlin], [C.Minion, C.Construct, C.Pig, C.Foundry, C.Wave3], 7), new Model('Shadow Emissary', [C.TenThunders], [C.Enforcer, C.Rare1, C.EmissaryOfFate, C.Wave3], 10), new Model('Lust', [C.TenThunders], [C.Enforcer, C.Living, C.Mercenary, C.Rare1, C.CrossroadsSeven, C.Tormented, C.Wave3], 8), new Model('Wandering River Monk', [C.TenThunders], [C.Minion, C.Living, C.Wave3], 7), new Model('Obsidian Oni', [C.TenThunders], [C.Minion, C.Oni, C.Wave3], 6), new Model('JorPI:NAME:<NAME>END_PIo', [C.TenThunders], [C.Minion, C.Oni, C.LastBlossom, C.Wave3], 9), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Master, C.Living, C.Journalist, C.Wave4], undefined, 4), new Model('The Printing Press', [C.Guild], [C.Peon, C.Construct, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Journalist, C.Wave4], 3), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Allison Dade', [C.Guild], [C.Henchman, C.Living, C.Rare1, C.Journalist, C.Wave4], 8, 5), new Model('Field Reporter', [C.Guild], [C.Minion, C.Living, C.Journalist, C.Wave4], 4), new Model('Death Marshal Recruiter', [C.Guild], [C.Enforcer, C.Living, C.Rare2, C.GuildMarshal, C.Wave4], 7), new Model('PI:NAME:<NAME>END_PI', [C.Guild], [C.Minion, C.Living, C.WitchHunter, C.Wave4], 9), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Master, C.Living, C.Revenant, C.Wave4], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Peon, C.Undead, C.TotemFor('Reva'), C.Spirit, C.Revenant, C.Wave4], 2), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Living, C.Rare1, C.Revenant, C.Wave4], 8, 5), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Henchman, C.Undead, C.Rare1, C.Horror, C.Wave4], 13, 0), new Model('ShieldPI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Living, C.Revenant, C.Wave4], 6), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Undead, C.Revenant, C.Horror, C.Wave4], 8), new Model('PI:NAME:<NAME>END_PI', [C.Resurrectionist], [C.Minion, C.Spirit, C.Retainer, C.Wave4], 7), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Master, C.Living, C.Academic, C.Wave4], undefined, 4), new Model('Corpse Candle', [C.Arcanist], [C.Minion, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Rare1, C.Gamin, C.Wave4], 8), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Academic, C.Wave4], 7, 6), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Msu, C.Academic, C.Wave4], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Henchman, C.Living, C.Rare1, C.Showgirl, C.Wave4], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Minion, C.Construct, C.Gamin, C.Beast, C.Wave4], 5), new Model('PI:NAME:<NAME>END_PI', [C.Arcanist], [C.Enforcer, C.Living, C.Msu, C.Academic, C.Wave4], 8), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Master, C.Undead, C.Fae, C.Wave4], undefined, 4), new Model('The GPI:NAME:<NAME>END_PI', [C.Neverborn], [C.Peon, C.Living, C.TotemFor('Titania'), C.Fae, C.Wave4], 3), new Model('PI:NAME:<NAME>END_PI', [C.Neverborn], [C.Henchman, C.Undead, C.Rare1, C.Fae, C.Wave4], 9, 4), new Model('The Tooth', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Claw', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('The Thorn', [C.Neverborn], [C.Minion, C.Undead, C.Rare1, C.Fae, C.Wave4], 7), new Model('PI:NAME:<NAME>END_PIatch', [C.Neverborn], [C.Minion, C.Living, C.Rare1, C.Fae, C.Nightmare, C.Spirit, C.Wave4], 5), new Model('Will O\' the Wisp', [C.Neverborn], [C.Minion, C.Rare3, C.Spirit, C.Swampfiend, C.Wave4], 3), new Model('Rougarou', [C.Neverborn], [C.Minion, C.Undead, C.Fae, C.Beast, C.Wave4], 8), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Master, C.Living, C.Bandit, C.Wave4], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Minion, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave4], 3), new Model('Mad Dog Brackett', [C.Outcast], [C.Henchman, C.Living, C.Rare1, C.Bandit, C.Wave4], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Henchman, C.Mercenary, C.Rare1, C.Wave4], 12, 1), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.Wave4], 5), new Model('Dead Outland', [C.Outcast], [C.Minion, C.Undead, C.Bandit, C.Tormented, C.Wave4], 6), new Model('PI:NAME:<NAME>END_PI', [C.Outcast], [C.Minion, C.Living, C.Bandit, C.LastBlossom, C.Wave4], 8), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Master, C.Living, C.Gremlin, C.SkyPirate, C.Wave4], undefined, 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Wave4], 3), new Model('The First Mate', [C.Gremlin], [C.Henchman, C.Living, C.Rare1, C.Swampfiend, C.SkyPirate, C.Wave4], 9, 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Enforcer, C.Living, C.Construct, C.Gremlin, C.SkyPirate, C.Wave4], 6), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin, C.TenThunders], [C.Minion, C.Rare3, C.Oni, C.TriChi, C.Wave4], 4), new Model('PI:NAME:<NAME>END_PI', [C.Gremlin], [C.Minion, C.Living, C.Gremlin, C.Wave4], 5), new Model('Swine-Cursed', [C.Gremlin], [C.Minion, C.Living, C.Rare2, C.Gremlin, C.Wave4], 7), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Master, C.Living, C.Oni, C.Wave4], undefined, 3), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Peon, C.TotemFor('PI:NAME:<NAME>END_PI'), C.Oni, C.Wave4], 3), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Henchman, C.Rare1, C.Oni, C.Wave4], 8, 5), new Model('Yokai', [C.TenThunders], [C.Minion, C.Oni, C.Wave4], 5), new Model('Terracotta Warrior', [C.TenThunders], [C.Minion, C.Construct, C.Rare3, C.Mimic, C.Wave4], 5), new Model('PI:NAME:<NAME>END_PI', [C.TenThunders], [C.Enforcer, C.Rare1, C.Living, C.Retainer, C.Wave4], 8) ] export default ModelList
[ { "context": "esetPassword.from = \"Application Admin Email <admin@application.com>\"\n\n# Set a subject for the reset password email.\n", "end": 296, "score": 0.9999276399612427, "start": 275, "tag": "EMAIL", "value": "admin@application.com" }, { "context": "u feel something is wrong, please contact support: admin@application.com.\"\n", "end": 926, "score": 0.9999276399612427, "start": 905, "tag": "EMAIL", "value": "admin@application.com" } ]
app/server/email/templates/reset-password.coffee
chrisdamba/offer-market
1
### Reset Password Email Template Override Meteor defaults when sending a reset password email. ### # Set name and from email. Accounts.emailTemplates.resetPassword.siteName = "Application Name" Accounts.emailTemplates.resetPassword.from = "Application Admin Email <admin@application.com>" # Set a subject for the reset password email. Accounts.emailTemplates.resetPassword.subject = (user) -> "[Application Name] Reset Your Password" # Set the body of the reset password email. Accounts.emailTemplates.resetPassword.text = (user, url) -> email = user.emails[0].address removeHash = url.replace('#/', '') "A password reset has been requested for the account related to this address(#{email}). To reset the password, visit the following link:\n\n #{removeHash}\n\n If you did not request this reset, please ignore this email. If you feel something is wrong, please contact support: admin@application.com."
209003
### Reset Password Email Template Override Meteor defaults when sending a reset password email. ### # Set name and from email. Accounts.emailTemplates.resetPassword.siteName = "Application Name" Accounts.emailTemplates.resetPassword.from = "Application Admin Email <<EMAIL>>" # Set a subject for the reset password email. Accounts.emailTemplates.resetPassword.subject = (user) -> "[Application Name] Reset Your Password" # Set the body of the reset password email. Accounts.emailTemplates.resetPassword.text = (user, url) -> email = user.emails[0].address removeHash = url.replace('#/', '') "A password reset has been requested for the account related to this address(#{email}). To reset the password, visit the following link:\n\n #{removeHash}\n\n If you did not request this reset, please ignore this email. If you feel something is wrong, please contact support: <EMAIL>."
true
### Reset Password Email Template Override Meteor defaults when sending a reset password email. ### # Set name and from email. Accounts.emailTemplates.resetPassword.siteName = "Application Name" Accounts.emailTemplates.resetPassword.from = "Application Admin Email <PI:EMAIL:<EMAIL>END_PI>" # Set a subject for the reset password email. Accounts.emailTemplates.resetPassword.subject = (user) -> "[Application Name] Reset Your Password" # Set the body of the reset password email. Accounts.emailTemplates.resetPassword.text = (user, url) -> email = user.emails[0].address removeHash = url.replace('#/', '') "A password reset has been requested for the account related to this address(#{email}). To reset the password, visit the following link:\n\n #{removeHash}\n\n If you did not request this reset, please ignore this email. If you feel something is wrong, please contact support: PI:EMAIL:<EMAIL>END_PI."
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999145269393921, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "\n scope.setUser id: currentUser.id, username: currentUser.username\n", "end": 1176, "score": 0.9415374398231506, "start": 1156, "tag": "USERNAME", "value": "currentUser.username" } ]
resources/assets/coffee/_classes/current-user-observer.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @CurrentUserObserver constructor: -> @covers = document.getElementsByClassName('js-current-user-cover') @avatars = document.getElementsByClassName('js-current-user-avatar') $.subscribe 'user:update', @setData $(document).on 'turbolinks:load', @reinit $.subscribe 'osu:page:change', @reinit reinit: => @setAvatars() @setCovers() @setSentryUser() setAvatars: (elements) => elements ?= @avatars bgImage = osu.urlPresence(currentUser.avatar_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setCovers: (elements) => elements ?= @covers bgImage = osu.urlPresence(currentUser.cover_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setData: (_e, data) => window.currentUser = data @reinit() setSentryUser: -> return unless Sentry? Sentry.configureScope (scope) -> scope.setUser id: currentUser.id, username: currentUser.username
189511
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @CurrentUserObserver constructor: -> @covers = document.getElementsByClassName('js-current-user-cover') @avatars = document.getElementsByClassName('js-current-user-avatar') $.subscribe 'user:update', @setData $(document).on 'turbolinks:load', @reinit $.subscribe 'osu:page:change', @reinit reinit: => @setAvatars() @setCovers() @setSentryUser() setAvatars: (elements) => elements ?= @avatars bgImage = osu.urlPresence(currentUser.avatar_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setCovers: (elements) => elements ?= @covers bgImage = osu.urlPresence(currentUser.cover_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setData: (_e, data) => window.currentUser = data @reinit() setSentryUser: -> return unless Sentry? Sentry.configureScope (scope) -> scope.setUser id: currentUser.id, username: currentUser.username
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @CurrentUserObserver constructor: -> @covers = document.getElementsByClassName('js-current-user-cover') @avatars = document.getElementsByClassName('js-current-user-avatar') $.subscribe 'user:update', @setData $(document).on 'turbolinks:load', @reinit $.subscribe 'osu:page:change', @reinit reinit: => @setAvatars() @setCovers() @setSentryUser() setAvatars: (elements) => elements ?= @avatars bgImage = osu.urlPresence(currentUser.avatar_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setCovers: (elements) => elements ?= @covers bgImage = osu.urlPresence(currentUser.cover_url) if currentUser.id? for el in elements el.style.backgroundImage = bgImage setData: (_e, data) => window.currentUser = data @reinit() setSentryUser: -> return unless Sentry? Sentry.configureScope (scope) -> scope.setUser id: currentUser.id, username: currentUser.username
[ { "context": "##############################################\n#\n# Markus 1/23/2017\n#\n#####################################", "end": 75, "score": 0.9990363121032715, "start": 69, "tag": "NAME", "value": "Markus" } ]
server/methods/fields.coffee
agottschalk10/worklearn
0
################################################################ # # Markus 1/23/2017 # ################################################################ ################################################################ Meteor.methods set_field: (collection_name, item_id, field, data)-> collection = get_collection_save collection_name return modify_field collection, item_id, field, data upload_file: (collection_name, item_id, field, data, type)-> collection = get_collection_save collection_name return upload_file collection, item_id, field, data, type download_file: (collection_name, item_id, field)-> collection = get_collection_save collection_name return download_file collection, item_id, field
61223
################################################################ # # <NAME> 1/23/2017 # ################################################################ ################################################################ Meteor.methods set_field: (collection_name, item_id, field, data)-> collection = get_collection_save collection_name return modify_field collection, item_id, field, data upload_file: (collection_name, item_id, field, data, type)-> collection = get_collection_save collection_name return upload_file collection, item_id, field, data, type download_file: (collection_name, item_id, field)-> collection = get_collection_save collection_name return download_file collection, item_id, field
true
################################################################ # # PI:NAME:<NAME>END_PI 1/23/2017 # ################################################################ ################################################################ Meteor.methods set_field: (collection_name, item_id, field, data)-> collection = get_collection_save collection_name return modify_field collection, item_id, field, data upload_file: (collection_name, item_id, field, data, type)-> collection = get_collection_save collection_name return upload_file collection, item_id, field, data, type download_file: (collection_name, item_id, field)-> collection = get_collection_save collection_name return download_file collection, item_id, field
[ { "context": "} = require '../lib/user'\nalice = users().lookup 'test_alice'\nbob = users().lookup 'test_bob'\n\nexports.id_0 = ", "end": 72, "score": 0.9988288879394531, "start": 62, "tag": "USERNAME", "value": "test_alice" }, { "context": "users().lookup 'test_alice'\nbob = users().lookup 'test_bob'\n\nexports.id_0 = (T,cb) ->\n await bob.id alice, ", "end": 104, "score": 0.998617947101593, "start": 96, "tag": "USERNAME", "value": "test_bob" }, { "context": ")\n\nexports.follow_0 = (T,cb) ->\n await bob.follow alice, {remote : true }, defer err\n T.no_error err\n c", "end": 242, "score": 0.4806903302669525, "start": 237, "tag": "NAME", "value": "alice" }, { "context": ")\n\nexports.follow_1 = (T,cb) ->\n await bob.follow alice, {remote : true }, defer err\n T.no_error err\n c", "end": 444, "score": 0.5855087637901306, "start": 439, "tag": "NAME", "value": "alice" } ]
test/files/2_follow.iced
substack/keybase-client
1
{users,User} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' exports.id_0 = (T,cb) -> await bob.id alice, defer err T.no_error err cb() exports.follow_0 = (T,cb) -> await bob.follow alice, {remote : true }, defer err T.no_error err cb() exports.unfollow_1 = (T,cb) -> await bob.unfollow alice, defer err T.no_error err cb() exports.follow_1 = (T,cb) -> await bob.follow alice, {remote : true }, defer err T.no_error err cb()
173255
{users,User} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' exports.id_0 = (T,cb) -> await bob.id alice, defer err T.no_error err cb() exports.follow_0 = (T,cb) -> await bob.follow <NAME>, {remote : true }, defer err T.no_error err cb() exports.unfollow_1 = (T,cb) -> await bob.unfollow alice, defer err T.no_error err cb() exports.follow_1 = (T,cb) -> await bob.follow <NAME>, {remote : true }, defer err T.no_error err cb()
true
{users,User} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' exports.id_0 = (T,cb) -> await bob.id alice, defer err T.no_error err cb() exports.follow_0 = (T,cb) -> await bob.follow PI:NAME:<NAME>END_PI, {remote : true }, defer err T.no_error err cb() exports.unfollow_1 = (T,cb) -> await bob.unfollow alice, defer err T.no_error err cb() exports.follow_1 = (T,cb) -> await bob.follow PI:NAME:<NAME>END_PI, {remote : true }, defer err T.no_error err cb()
[ { "context": "\n @expectedInitialTasksList = [\n name: 'test1'\n departure_point: 'from_test'\n des", "end": 946, "score": 0.990178108215332, "start": 941, "tag": "NAME", "value": "test1" }, { "context": " resource_uri: 'fake1'\n ,\n name: 'test2'\n departure_point: 'from_test'\n des", "end": 1111, "score": 0.9901770353317261, "start": 1106, "tag": "NAME", "value": "test2" }, { "context": " resource_uri: 'fake2'\n ,\n name: 'test3'\n departure_point: 'from_test'\n des", "end": 1276, "score": 0.9924184679985046, "start": 1271, "tag": "NAME", "value": "test3" }, { "context": " resource_uri: 'fake3'\n ,\n name: 'test4'\n departure_point: 'from_test'\n des", "end": 1441, "score": 0.994530200958252, "start": 1436, "tag": "NAME", "value": "test4" }, { "context": " resource_uri: 'fake4'\n ,\n name: 'test5'\n departure_point: 'from_test'\n des", "end": 1606, "score": 0.9905211925506592, "start": 1601, "tag": "NAME", "value": "test5" }, { "context": " resource_uri: 'fake5'\n ,\n name: 'test6'\n departure_point: 'from_test'\n des", "end": 1771, "score": 0.9827743768692017, "start": 1766, "tag": "NAME", "value": "test6" }, { "context": "point: 'from_test'\n destination_point: 'to_test'\n somefield: 'test data'\n resource_", "end": 1845, "score": 0.8686805963516235, "start": 1841, "tag": "NAME", "value": "test" }, { "context": " resource_uri: 'fake6'\n ,\n name: 'test7'\n departure_point: 'from_test'\n des", "end": 1936, "score": 0.974818229675293, "start": 1931, "tag": "NAME", "value": "test7" }, { "context": " resource_uri: 'fake7'\n ,\n name: 'test8'\n departure_point: 'from_test'\n des", "end": 2101, "score": 0.9790548086166382, "start": 2096, "tag": "NAME", "value": "test8" }, { "context": " @expectedTasksList = [\n [\n name: 'test1'\n departure_point: 'from_test'\n ", "end": 2302, "score": 0.9855608344078064, "start": 2297, "tag": "NAME", "value": "test1" }, { "context": " resource_uri: 'fake1'\n ,\n name: 'test2'\n departure_point: 'from_test'\n ", "end": 2479, "score": 0.9888685941696167, "start": 2474, "tag": "NAME", "value": "test2" }, { "context": " resource_uri: 'fake2'\n ,\n name: 'test3'\n departure_point: 'from_test'\n ", "end": 2656, "score": 0.9873228073120117, "start": 2651, "tag": "NAME", "value": "test3" }, { "context": " resource_uri: 'fake3'\n ,\n name: 'test4'\n departure_point: 'from_test'\n ", "end": 2833, "score": 0.9852466583251953, "start": 2828, "tag": "NAME", "value": "test4" }, { "context": "ce_uri: 'fake4'\n ],\n [\n name: 'test5'\n departure_point: 'from_test'\n ", "end": 3017, "score": 0.9877803325653076, "start": 3012, "tag": "NAME", "value": "test5" }, { "context": " resource_uri: 'fake5'\n ,\n name: 'test6'\n departure_point: 'from_test'\n ", "end": 3194, "score": 0.9860490560531616, "start": 3189, "tag": "NAME", "value": "test6" }, { "context": " resource_uri: 'fake6'\n ,\n name: 'test7'\n departure_point: 'from_test'\n ", "end": 3371, "score": 0.9715282917022705, "start": 3366, "tag": "NAME", "value": "test7" }, { "context": " resource_uri: 'fake7'\n ,\n name: 'test8'\n departure_point: 'from_test'\n ", "end": 3548, "score": 0.984070360660553, "start": 3543, "tag": "NAME", "value": "test8" }, { "context": "\n # be enough\n testObj =\n name: 'test name'\n resource_uri: 'fake_task_resource'\n\n ", "end": 6090, "score": 0.9964747428894043, "start": 6081, "tag": "NAME", "value": "test name" }, { "context": "is is a new object\n testObj =\n name: 'test name'\n somefield: 'test data'\n resource_", "end": 6879, "score": 0.9958592653274536, "start": 6870, "tag": "NAME", "value": "test name" }, { "context": "_uri: ''\n\n extInitialTasksList = angular.copy(@expectedInitialTasksList)\n extTasksList = angular.copy(@expectedTasks", "end": 7004, "score": 0.9612289667129517, "start": 6979, "tag": "USERNAME", "value": "@expectedInitialTasksList" }, { "context": "tialTasksList)\n extTasksList = angular.copy(@expectedTasksList)\n\n extInitialTasksList.push(testObj)\n e", "end": 7058, "score": 0.9647021293640137, "start": 7041, "tag": "USERNAME", "value": "expectedTasksList" }, { "context": "urnValue(@$q.when())\n\n task =\n name: 'test'\n resource_uri: 'test'\n is_active: ", "end": 7967, "score": 0.9978249073028564, "start": 7963, "tag": "NAME", "value": "test" }, { "context": " p.promise\n )\n\n task =\n name: 'test'\n resource_uri: 'test'\n is_active: ", "end": 8453, "score": 0.9993879795074463, "start": 8449, "tag": "NAME", "value": "test" }, { "context": "urnValue(@$q.when())\n\n task =\n name: 'test'\n resource_uri: 'test'\n is_active: ", "end": 8913, "score": 0.9995050430297852, "start": 8909, "tag": "NAME", "value": "test" }, { "context": " p.promise\n )\n\n task =\n name: 'test'\n resource_uri: 'test'\n is_active: ", "end": 9395, "score": 0.999453067779541, "start": 9391, "tag": "NAME", "value": "test" }, { "context": "rnValue(@$q.when(\n data:[\n name: 'test1'\n full_name: 'test1 full'\n code", "end": 13622, "score": 0.9981811046600342, "start": 13617, "tag": "NAME", "value": "test1" }, { "context": "a:[\n name: 'test1'\n full_name: 'test1 full'\n code: '0'\n ,\n name: 't", "end": 13656, "score": 0.9948329329490662, "start": 13646, "tag": "NAME", "value": "test1 full" }, { "context": "l'\n code: '0'\n ,\n name: 'test2'\n full_name: 'test2 full'\n code", "end": 13710, "score": 0.9984334707260132, "start": 13705, "tag": "NAME", "value": "test2" }, { "context": " ,\n name: 'test2'\n full_name: 'test2 full'\n code: '1'\n ,\n name: 't", "end": 13744, "score": 0.9817565083503723, "start": 13734, "tag": "NAME", "value": "test2 full" }, { "context": "l'\n code: '1'\n ,\n name: 'test3'\n full_name: 'test3 full'\n code", "end": 13798, "score": 0.9977457523345947, "start": 13793, "tag": "NAME", "value": "test3" }, { "context": " ,\n name: 'test3'\n full_name: 'test3 full'\n code: '2'\n ]\n ))\n\n re", "end": 13832, "score": 0.9835155606269836, "start": 13822, "tag": "NAME", "value": "test3 full" }, { "context": "()\n\n expect(result).toEqual([\n name: 'test1'\n full_name: 'test1 full'\n code: '0", "end": 14075, "score": 0.9985053539276123, "start": 14070, "tag": "NAME", "value": "test1" }, { "context": "Equal([\n name: 'test1'\n full_name: 'test1 full'\n code: '0'\n ,\n name: 'test2'\n", "end": 14107, "score": 0.9884462356567383, "start": 14097, "tag": "NAME", "value": "test1 full" }, { "context": "t1 full'\n code: '0'\n ,\n name: 'test2'\n full_name: 'test2 full'\n code: '1", "end": 14155, "score": 0.9979824423789978, "start": 14150, "tag": "NAME", "value": "test2" }, { "context": " ,\n name: 'test2'\n full_name: 'test2 full'\n code: '1'\n ,\n name: 'test3'\n", "end": 14187, "score": 0.9846377968788147, "start": 14177, "tag": "NAME", "value": "test2 full" }, { "context": "t2 full'\n code: '1'\n ,\n name: 'test3'\n full_name: 'test3 full'\n code: '2", "end": 14235, "score": 0.9962248802185059, "start": 14230, "tag": "NAME", "value": "test3" }, { "context": " ,\n name: 'test3'\n full_name: 'test3 full'\n code: '2'\n ])\n\n describe 'controll", "end": 14267, "score": 0.9833285212516785, "start": 14257, "tag": "NAME", "value": "test3 full" }, { "context": "ue(@$q.when(\n data:[\n full_name: '123B HOMIEL-MINSK'\n code: '123B'\n ,\n full_", "end": 14495, "score": 0.9717757701873779, "start": 14478, "tag": "NAME", "value": "123B HOMIEL-MINSK" }, { "context": " code: '123B'\n ,\n full_name: '333C BREST-MINSK'\n code: '333C'\n ,\n full_", "end": 14568, "score": 0.9993182420730591, "start": 14552, "tag": "NAME", "value": "333C BREST-MINSK" }, { "context": " code: '333C'\n ,\n full_name: '232A MINSK-GRODNO'\n code: '232A'\n ]\n ", "end": 14629, "score": 0.99607253074646, "start": 14625, "tag": "NAME", "value": "232A" }, { "context": " code: '333C'\n ,\n full_name: '232A MINSK-GRODNO'\n code: '232A'\n ]\n ))\n\n ", "end": 14642, "score": 0.9914992451667786, "start": 14630, "tag": "NAME", "value": "MINSK-GRODNO" }, { "context": " expect(result).toEqual([\n full_name: '123B HOMIEL-MINSK'\n code: '123B'\n ,\n full_name: ", "end": 15020, "score": 0.9818586707115173, "start": 15003, "tag": "NAME", "value": "123B HOMIEL-MINSK" }, { "context": "\n code: '123B'\n ,\n full_name: '333C BREST-MINSK'\n code: '333C'\n ,\n full_name: ", "end": 15087, "score": 0.9995526075363159, "start": 15071, "tag": "NAME", "value": "333C BREST-MINSK" }, { "context": "\n code: '333C'\n ,\n full_name: '232A MINSK-GRODNO'\n code: '232A'\n ])\n", "end": 15142, "score": 0.9964948892593384, "start": 15138, "tag": "NAME", "value": "232A" }, { "context": " code: '333C'\n ,\n full_name: '232A MINSK-GRODNO'\n code: '232A'\n ])\n", "end": 15155, "score": 0.9893441796302795, "start": 15143, "tag": "NAME", "value": "MINSK-GRODNO" } ]
src/app/pages/tasks/pages.tasks.spec.coffee
pavelkuchin/tracktrains-ui
0
describe 'PagesTasksCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, DataService, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @stubSession = user: resource_uri: 'not_real_user_resource_uri_just_for_test', tasks_limit: 4 @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubDialogsService = jasmine.createSpyObj('DialogsService', ['confirmation']) @stubDataService = jasmine.createSpyObj('DataService', [ 'getTasks', 'saveTask', 'disableTask', 'enableTask', 'deleteTask', 'getStation', 'getTrain' ]) @expectedInitialTasksList = [ name: 'test1' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: 'test2' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: 'test3' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: 'test4' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' , name: 'test5' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: 'test6' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake6' , name: 'test7' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: 'test8' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] @expectedTasksList = [ [ name: 'test1' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: 'test2' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: 'test3' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: 'test4' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' ], [ name: 'test5' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: 'test6' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake6' , name: 'test7' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: 'test8' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] ] @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: @expectedInitialTasksList )) @scope = $rootScope.$new() @controller = $controller('PagesTasksCtrl', $scope: @scope AlertsService: @stubAlertsService DataService: @stubDataService DialogsService: @stubDialogsService session: @stubSession ) )) describe 'controller.constructor', () => it 'tasksList and initialTasksList are empty arrays before answer from server', () => expect(@controller.initialTasksList).toEqual([]) expect(@controller.tasksList).toEqual([]) it 'after server answered the initialTasksList has the data from server and tasksList has the data chunked by 4', () => @$rootScope.$digest() expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(@expectedInitialTasksList) expect(@controller.tasksList).toEqual(@expectedTasksList) describe 'controller.createTask', () => it 'controller.newTask is a properly initialized task object', () => @controller.createTask() expect(@controller.newTask).toEqual( resource_uri: '' departure_date: '' departure_point: '' destination_point: '' train: '' car: 'ANY' seat: 'ANY' is_active: true owner: @stubSession.user.resource_uri ) it 'controller.createNewTask is setted to true', () => @controller.createTask() expect(@controller.createNewTask).toEqual(true) it 'controller.createNewTask shows and error if tasks count exceed the limit', () => @$rootScope.$digest() @controller.createTask() expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "Sorry, but the current system limitation is no more then 4 tasks per user.", @ALERTS_TYPE.ERROR, 3000 ) expect(@controller.createNewTask).toEqual(false) describe 'controller.save', () => it 'dataService.saveTask(task) was called for edit and alert showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough testObj = name: 'test name' resource_uri: 'fake_task_resource' @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) it 'dataService.saveTask(task) was called for creating a new item and alert was showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough, resource_uri is empty string because this is a new object testObj = name: 'test name' somefield: 'test data' resource_uri: '' extInitialTasksList = angular.copy(@expectedInitialTasksList) extTasksList = angular.copy(@expectedTasksList) extInitialTasksList.push(testObj) extTasksList.push([testObj]) @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: extInitialTasksList )) @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(extInitialTasksList) expect(@controller.tasksList).toEqual(extTasksList) describe 'controller.disable(task)', () => it 'dataService.disableTask(task) call is success and task.is_active is true', () => @stubDataService.disableTask.and.returnValue(@$q.when()) task = name: 'test' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) it 'dataService.disableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.disableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: 'test' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) describe 'controller.enable(task)', () => it 'dataService.enableTask(task) call is success and task.is_active is true', () => @stubDataService.enableTask.and.returnValue(@$q.when()) task = name: 'test' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) it 'dataService.enableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.enableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: 'test' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) describe 'controller.delete(task)', () => it 'if dataService.deleteTask(task) succesfully completed then remove item from initialTasksList and re-chunk it to tasksList', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDialogsService.confirmation.and.returnValue(@$q.when()) @stubDataService.deleteTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') it 'if dataService.deleteTask(task) but user pressed no in a confirmation dialog then the task should not be deleted.', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') describe 'controller.getStation(station)', () => it 'return list of names', () => @stubDataService.getStation.and.returnValue(@$q.when( data:[ name: 'test1' full_name: 'test1 full' code: '0' , name: 'test2' full_name: 'test2 full' code: '1' , name: 'test3' full_name: 'test3 full' code: '2' ] )) result = [] stations = @controller.getStation('test') stations.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ name: 'test1' full_name: 'test1 full' code: '0' , name: 'test2' full_name: 'test2 full' code: '1' , name: 'test3' full_name: 'test3 full' code: '2' ]) describe 'controller.getTrain(params)', () => it 'return list of trains', () => @stubDataService.getTrain.and.returnValue(@$q.when( data:[ full_name: '123B HOMIEL-MINSK' code: '123B' , full_name: '333C BREST-MINSK' code: '333C' , full_name: '232A MINSK-GRODNO' code: '232A' ] )) result = [] params = date: '10-10-2015' departure: 'HOMIEL' destination: 'MINSK' train: 'HO' trains = @controller.getTrains(params) trains.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ full_name: '123B HOMIEL-MINSK' code: '123B' , full_name: '333C BREST-MINSK' code: '333C' , full_name: '232A MINSK-GRODNO' code: '232A' ])
92329
describe 'PagesTasksCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, DataService, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @stubSession = user: resource_uri: 'not_real_user_resource_uri_just_for_test', tasks_limit: 4 @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubDialogsService = jasmine.createSpyObj('DialogsService', ['confirmation']) @stubDataService = jasmine.createSpyObj('DataService', [ 'getTasks', 'saveTask', 'disableTask', 'enableTask', 'deleteTask', 'getStation', 'getTrain' ]) @expectedInitialTasksList = [ name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_<NAME>' somefield: 'test data' resource_uri: 'fake6' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] @expectedTasksList = [ [ name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' ], [ name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake6' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: '<NAME>' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] ] @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: @expectedInitialTasksList )) @scope = $rootScope.$new() @controller = $controller('PagesTasksCtrl', $scope: @scope AlertsService: @stubAlertsService DataService: @stubDataService DialogsService: @stubDialogsService session: @stubSession ) )) describe 'controller.constructor', () => it 'tasksList and initialTasksList are empty arrays before answer from server', () => expect(@controller.initialTasksList).toEqual([]) expect(@controller.tasksList).toEqual([]) it 'after server answered the initialTasksList has the data from server and tasksList has the data chunked by 4', () => @$rootScope.$digest() expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(@expectedInitialTasksList) expect(@controller.tasksList).toEqual(@expectedTasksList) describe 'controller.createTask', () => it 'controller.newTask is a properly initialized task object', () => @controller.createTask() expect(@controller.newTask).toEqual( resource_uri: '' departure_date: '' departure_point: '' destination_point: '' train: '' car: 'ANY' seat: 'ANY' is_active: true owner: @stubSession.user.resource_uri ) it 'controller.createNewTask is setted to true', () => @controller.createTask() expect(@controller.createNewTask).toEqual(true) it 'controller.createNewTask shows and error if tasks count exceed the limit', () => @$rootScope.$digest() @controller.createTask() expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "Sorry, but the current system limitation is no more then 4 tasks per user.", @ALERTS_TYPE.ERROR, 3000 ) expect(@controller.createNewTask).toEqual(false) describe 'controller.save', () => it 'dataService.saveTask(task) was called for edit and alert showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough testObj = name: '<NAME>' resource_uri: 'fake_task_resource' @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) it 'dataService.saveTask(task) was called for creating a new item and alert was showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough, resource_uri is empty string because this is a new object testObj = name: '<NAME>' somefield: 'test data' resource_uri: '' extInitialTasksList = angular.copy(@expectedInitialTasksList) extTasksList = angular.copy(@expectedTasksList) extInitialTasksList.push(testObj) extTasksList.push([testObj]) @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: extInitialTasksList )) @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(extInitialTasksList) expect(@controller.tasksList).toEqual(extTasksList) describe 'controller.disable(task)', () => it 'dataService.disableTask(task) call is success and task.is_active is true', () => @stubDataService.disableTask.and.returnValue(@$q.when()) task = name: '<NAME>' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) it 'dataService.disableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.disableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: '<NAME>' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) describe 'controller.enable(task)', () => it 'dataService.enableTask(task) call is success and task.is_active is true', () => @stubDataService.enableTask.and.returnValue(@$q.when()) task = name: '<NAME>' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) it 'dataService.enableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.enableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: '<NAME>' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) describe 'controller.delete(task)', () => it 'if dataService.deleteTask(task) succesfully completed then remove item from initialTasksList and re-chunk it to tasksList', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDialogsService.confirmation.and.returnValue(@$q.when()) @stubDataService.deleteTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') it 'if dataService.deleteTask(task) but user pressed no in a confirmation dialog then the task should not be deleted.', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') describe 'controller.getStation(station)', () => it 'return list of names', () => @stubDataService.getStation.and.returnValue(@$q.when( data:[ name: '<NAME>' full_name: '<NAME>' code: '0' , name: '<NAME>' full_name: '<NAME>' code: '1' , name: '<NAME>' full_name: '<NAME>' code: '2' ] )) result = [] stations = @controller.getStation('test') stations.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ name: '<NAME>' full_name: '<NAME>' code: '0' , name: '<NAME>' full_name: '<NAME>' code: '1' , name: '<NAME>' full_name: '<NAME>' code: '2' ]) describe 'controller.getTrain(params)', () => it 'return list of trains', () => @stubDataService.getTrain.and.returnValue(@$q.when( data:[ full_name: '<NAME>' code: '123B' , full_name: '<NAME>' code: '333C' , full_name: '<NAME> <NAME>' code: '232A' ] )) result = [] params = date: '10-10-2015' departure: 'HOMIEL' destination: 'MINSK' train: 'HO' trains = @controller.getTrains(params) trains.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ full_name: '<NAME>' code: '123B' , full_name: '<NAME>' code: '333C' , full_name: '<NAME> <NAME>' code: '232A' ])
true
describe 'PagesTasksCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, DataService, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @stubSession = user: resource_uri: 'not_real_user_resource_uri_just_for_test', tasks_limit: 4 @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubDialogsService = jasmine.createSpyObj('DialogsService', ['confirmation']) @stubDataService = jasmine.createSpyObj('DataService', [ 'getTasks', 'saveTask', 'disableTask', 'enableTask', 'deleteTask', 'getStation', 'getTrain' ]) @expectedInitialTasksList = [ name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_PI:NAME:<NAME>END_PI' somefield: 'test data' resource_uri: 'fake6' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] @expectedTasksList = [ [ name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake1' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake2' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake3' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake4' ], [ name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake5' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake6' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake7' , name: 'PI:NAME:<NAME>END_PI' departure_point: 'from_test' destination_point: 'to_test' somefield: 'test data' resource_uri: 'fake8' ] ] @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: @expectedInitialTasksList )) @scope = $rootScope.$new() @controller = $controller('PagesTasksCtrl', $scope: @scope AlertsService: @stubAlertsService DataService: @stubDataService DialogsService: @stubDialogsService session: @stubSession ) )) describe 'controller.constructor', () => it 'tasksList and initialTasksList are empty arrays before answer from server', () => expect(@controller.initialTasksList).toEqual([]) expect(@controller.tasksList).toEqual([]) it 'after server answered the initialTasksList has the data from server and tasksList has the data chunked by 4', () => @$rootScope.$digest() expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(@expectedInitialTasksList) expect(@controller.tasksList).toEqual(@expectedTasksList) describe 'controller.createTask', () => it 'controller.newTask is a properly initialized task object', () => @controller.createTask() expect(@controller.newTask).toEqual( resource_uri: '' departure_date: '' departure_point: '' destination_point: '' train: '' car: 'ANY' seat: 'ANY' is_active: true owner: @stubSession.user.resource_uri ) it 'controller.createNewTask is setted to true', () => @controller.createTask() expect(@controller.createNewTask).toEqual(true) it 'controller.createNewTask shows and error if tasks count exceed the limit', () => @$rootScope.$digest() @controller.createTask() expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "Sorry, but the current system limitation is no more then 4 tasks per user.", @ALERTS_TYPE.ERROR, 3000 ) expect(@controller.createNewTask).toEqual(false) describe 'controller.save', () => it 'dataService.saveTask(task) was called for edit and alert showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough testObj = name: 'PI:NAME:<NAME>END_PI' resource_uri: 'fake_task_resource' @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) it 'dataService.saveTask(task) was called for creating a new item and alert was showed', () => # Tatypie by default does not return created object back, lets emulate similar behavior @stubDataService.saveTask.and.returnValue(@$q.when()) # We do not need the real structure for test, only name and resource_uri will # be enough, resource_uri is empty string because this is a new object testObj = name: 'PI:NAME:<NAME>END_PI' somefield: 'test data' resource_uri: '' extInitialTasksList = angular.copy(@expectedInitialTasksList) extTasksList = angular.copy(@expectedTasksList) extInitialTasksList.push(testObj) extTasksList.push([testObj]) @stubDataService.getTasks.and.returnValue(@$q.when( data: objects: extInitialTasksList )) @controller.save(testObj) @$rootScope.$digest() expect(@stubDataService.saveTask).toHaveBeenCalledWith(testObj) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "The task successfully saved!" @ALERTS_TYPE.SUCCESS, 3000 ) expect(@stubDataService.getTasks).toHaveBeenCalled() expect(@controller.initialTasksList).toEqual(extInitialTasksList) expect(@controller.tasksList).toEqual(extTasksList) describe 'controller.disable(task)', () => it 'dataService.disableTask(task) call is success and task.is_active is true', () => @stubDataService.disableTask.and.returnValue(@$q.when()) task = name: 'PI:NAME:<NAME>END_PI' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) it 'dataService.disableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.disableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: 'PI:NAME:<NAME>END_PI' resource_uri: 'test' is_active: true @controller.disable(task) @$rootScope.$digest() expect(@stubDataService.disableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) describe 'controller.enable(task)', () => it 'dataService.enableTask(task) call is success and task.is_active is true', () => @stubDataService.enableTask.and.returnValue(@$q.when()) task = name: 'PI:NAME:<NAME>END_PI' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(true) it 'dataService.enableTask(task) call is failed and task.is_active is not changed', () => @stubDataService.enableTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) task = name: 'PI:NAME:<NAME>END_PI' resource_uri: 'test' is_active: false @controller.enable(task) @$rootScope.$digest() expect(@stubDataService.enableTask).toHaveBeenCalledWith(task) expect(task.is_active).toEqual(false) describe 'controller.delete(task)', () => it 'if dataService.deleteTask(task) succesfully completed then remove item from initialTasksList and re-chunk it to tasksList', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDialogsService.confirmation.and.returnValue(@$q.when()) @stubDataService.deleteTask.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') it 'if dataService.deleteTask(task) but user pressed no in a confirmation dialog then the task should not be deleted.', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.returnValue(@$q.when()) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') task = @expectedInitialTasksList[0] @controller.delete(task) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalledWith( "Delete task", "Do you really want delete the task #{task.departure_point} - #{task.destination_point}" ) expect(@stubDataService.deleteTask).toHaveBeenCalledWith(deletedItem) expect(@controller.initialTasksList[0].name).toEqual('test2') expect(@controller.tasksList[0][0].name).toEqual('test2') it 'if dataService.deleteTask(task) completed with error then initialTasksList and tasksList shall not be changed', () => @stubDataService.deleteTask.and.returnValue(@$q.when()) @stubDialogsService.confirmation.and.callFake(() => p = @$q.defer() p.reject('') p.promise ) deletedItem = angular.copy(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') @controller.delete(@expectedInitialTasksList[0]) @$rootScope.$digest() expect(@stubDialogsService.confirmation).toHaveBeenCalled() expect(@controller.initialTasksList[0].name).toEqual('test1') expect(@controller.tasksList[0][0].name).toEqual('test1') describe 'controller.getStation(station)', () => it 'return list of names', () => @stubDataService.getStation.and.returnValue(@$q.when( data:[ name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '0' , name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '1' , name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '2' ] )) result = [] stations = @controller.getStation('test') stations.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '0' , name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '1' , name: 'PI:NAME:<NAME>END_PI' full_name: 'PI:NAME:<NAME>END_PI' code: '2' ]) describe 'controller.getTrain(params)', () => it 'return list of trains', () => @stubDataService.getTrain.and.returnValue(@$q.when( data:[ full_name: 'PI:NAME:<NAME>END_PI' code: '123B' , full_name: 'PI:NAME:<NAME>END_PI' code: '333C' , full_name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' code: '232A' ] )) result = [] params = date: '10-10-2015' departure: 'HOMIEL' destination: 'MINSK' train: 'HO' trains = @controller.getTrains(params) trains.then (data) -> result = data @$rootScope.$digest() expect(result).toEqual([ full_name: 'PI:NAME:<NAME>END_PI' code: '123B' , full_name: 'PI:NAME:<NAME>END_PI' code: '333C' , full_name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' code: '232A' ])
[ { "context": "lass CustomSearch extends Widget\n constructor: (@name, @parentView, @widgetOpenBool) ->\n # console.d", "end": 4414, "score": 0.589633584022522, "start": 4410, "tag": "USERNAME", "value": "name" }, { "context": "efreshView: 'conversations'\n keyName: 'kiwi_userPreferences'\n newValue: popupParcel.kiwi_userPrefe", "end": 19122, "score": 0.9995174407958984, "start": 19102, "tag": "KEY", "value": "kiwi_userPreferences" }, { "context": "efreshView: 'conversations'\n keyName: 'kiwi_userPreferences'\n newValue: popupParcel.kiwi_userPrefe", "end": 30327, "score": 0.9995759725570679, "start": 30307, "tag": "KEY", "value": "kiwi_userPreferences" }, { "context": " = \", <a target='_blank' href='https://github.com/producthunt/producthunt-api/wiki/Product-Hunt-APIs#algolia-se", "end": 39903, "score": 0.9343862533569336, "start": 39892, "tag": "USERNAME", "value": "producthunt" }, { "context": "friendly APIs!&nbsp; <a href='https://twitter.com/spencenow' target='_blank'>Tweet me</a> if you're intereste", "end": 43508, "score": 0.9995611906051636, "start": 43499, "tag": "USERNAME", "value": "spencenow" }, { "context": "shView: 'userPreferences'\n keyName: 'kiwi_servicesInfo'\n newValue: popupParcel.kiwi_service", "end": 45355, "score": 0.9993076324462891, "start": 45338, "tag": "KEY", "value": "kiwi_servicesInfo" }, { "context": "shView: 'userPreferences'\n keyName: 'kiwi_servicesInfo'\n newValue: popupParcel.kiwi_service", "end": 45892, "score": 0.9992901086807251, "start": 45875, "tag": "KEY", "value": "kiwi_servicesInfo" }, { "context": "reshView: 'userPreferences'\n keyName: 'kiwi_userPreferences'\n newValue: popupParcel.kiwi_userPrefe", "end": 47199, "score": 0.9995412826538086, "start": 47179, "tag": "KEY", "value": "kiwi_userPreferences" }, { "context": "reshView: 'userPreferences'\n keyName: 'kiwi_userPreferences'\n newValue: popupParcel.kiwi_userPrefe", "end": 47934, "score": 0.999557614326477, "start": 47914, "tag": "KEY", "value": "kiwi_userPreferences" }, { "context": "ty @ProductHunt. \"\n # kiwi_author_name: \"Ben Tossell\"\n # kiwi_author_username: \"bentossell\"\n ", "end": 62936, "score": 0.9999018311500549, "start": 62925, "tag": "NAME", "value": "Ben Tossell" }, { "context": " \"Ben Tossell\"\n # kiwi_author_username: \"bentossell\"\n # kiwi_discussion_url: \"http://www.pro", "end": 62983, "score": 0.9996249079704285, "start": 62973, "tag": "USERNAME", "value": "bentossell" }, { "context": "ne: \"Co-founder/CEO, Buffer\"\n # name: \"Joel Gascoigne\"\n # profile_url: \"http://www.producthu", "end": 63200, "score": 0.9999077916145325, "start": 63186, "tag": "NAME", "value": "Joel Gascoigne" }, { "context": " # profile_url: \"http://www.producthunt.com/@joelgascoigne\"\n # username: \"joelgascoigne\"\n ", "end": 63271, "score": 0.9699117541313171, "start": 63257, "tag": "USERNAME", "value": "@joelgascoigne" }, { "context": "hunt.com/@joelgascoigne\"\n # username: \"joelgascoigne\"\n # website_url: \"http://joel.is\"\n ", "end": 63311, "score": 0.9996906518936157, "start": 63298, "tag": "USERNAME", "value": "joelgascoigne" }, { "context": " \n if listing.kiwi_author_username == maker.username\n preppedHTMLstring += \" (also submit", "end": 66023, "score": 0.6994614005088806, "start": 66010, "tag": "USERNAME", "value": "aker.username" } ]
coffeescripts--content-scripts/KiwiPopup.coffee
sdailey/kiwi-firefox
5
viewElementId = '' renderedBool = false preferencesOnlyPage = false initialize = (popupParcel) -> # console.log 'in init' if getURLParam(window.location, 'optionsOnly') != '' preferencesOnlyPage = true switchViews.userPreferences.render(popupParcel) return 0 for viewName, view of fixedViews view.init(popupParcel) # views.userPreferences.render(popupParcel) if popupParcel.view? and switchViews[popupParcel.view]? switchViews[popupParcel.view].render(popupParcel) else switchViews.conversations.render(popupParcel) class Widget # basic building block constructor: (@name, @parentView, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = @parentView.DOMselector + " #" + @name + "_Widget" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews # console.log _viewName # bind to goToView buttons els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') # console.debug els_goTo_view @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @unbindWidget = => for el in @elsToUnbind el.unbind() @elsToUnbind = [] @render = (renderState, popupParcel) => @totalRenders++ @unbindWidget(@name) @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) @renderStates = @__renderStates__() return @ class MessageCenter extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ # console.log ' trying ' super @name, @parentView, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render('showMessages',popupParcel) __renderStates__: => showMessages: paint: (popupParcel) => # console.log 'messagesHTML = "" # console.debug popupParcel' messagesHTML = "" # console.debug popupParcel if popupParcel.kiwi_userMessages.length > 0 messagesHTML += '<div style="padding-top:4px; padding-bottom:10px;">' for messageObj in popupParcel.kiwi_userMessages messagesHTML += '<div class="bg-warning" style="margin:6px; padding:8px; text-align:justify;"> <button style="float:right; margin:8px; padding:4px; padding-right:6px; padding-left:6px;" class="btn btn-xs btn-default acknowledgeMessage" data-messageToAcknowledge="' + messageObj.name + '" > <span title="remove" data-messageToAcknowledge="' + messageObj.name + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> ' + messageObj.baseValue + ' &nbsp; </div>' messagesHTML += '<div style="width:100%; text-align:center;"> <b>message priority</b>: urgent. &nbsp;&nbsp; please acknowledge the message(s) by clicking the "x" button(s). Thanks! :) </div></div>' $(@DOMselector).html(messagesHTML) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => if popupParcel.kiwi_userMessages.length > 0 # console.log 'bind: (popupParcel) =>' ackMessageButtons = $(@DOMselector + ' .acknowledgeMessage') @elsToUnbind = @elsToUnbind.concat ackMessageButtons ackMessageButtons.bind 'click', (ev) => console.log "trying for ackMessageButtons.bind 'click', (ev) =>" messageToAcknowledge = $(ev.target).attr('data-messageToAcknowledge') console.log 'messageToAcknowledge ' + messageToAcknowledge # console.debug popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch # console.debug whitelistSubString parcel = messageToAcknowledge: messageToAcknowledge msg: 'kiwiPP_acknowledgeMessage' sendParcel(parcel) class CustomSearch extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ super @name, @parentView, @__renderStates__ init: (popupParcel) -> @Widgets = {messageCenter: new MessageCenter 'messageCenter', @, false} @unbindWidget() if @widgetOpenBool == false @render('collapsed',popupParcel) else @render('opened',popupParcel) __renderStates__: => collapsed: paint: (popupParcel) => openedCustomSearchHTML = ' <div class="topSearchBar" style="padding-bottom: 14px;"> <div class="evenlySpacedContainer"> <input class="queryInputOpen" id="customSearchQueryInput" type="text" placeholder=" combined search" /> <button class="btn btn-mini btn-default goTo_userPreferencesView">User Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> ' if popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' openedCustomSearchHTML += "<div style='padding-top: 12px;'><a id='openPreviousSearch'>see custom results for '" + popupParcel.kiwi_customSearchResults.queryString + "' </a> &nbsp;&nbsp;&nbsp;&nbsp; <a id='clearPreviousSearch'>clear</a></div>" openedCustomSearchHTML += " <div id='messageCenter_Widget'></div> </div> <div class='notFixed'></div>" $(@DOMselector).html(openedCustomSearchHTML) # console?.log 'console.log @DOMselector + " .topSearchBar"' + @DOMselector + " .topSearchBar" duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight closed' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => # console.log 'bind: (popupParcel) =>' inputSearchQueryInput = $("#customSearchQueryInput") previousSearchLink = $("#openPreviousSearch") clearPreviousSearch = $("#clearPreviousSearch") @elsToUnbind = @elsToUnbind.concat inputSearchQueryInput, previousSearchLink, clearPreviousSearch previousSearchLink.bind 'click', -> $("#customSearchQueryInput").click() clearPreviousSearch.bind 'click', -> parcel = msg: 'kiwiPP_refreshSearchQuery' sendParcel(parcel) inputSearchQueryInput.bind 'click', => # console.log '@widgetOpenBool = true' @widgetOpenBool = true @render('opened',popupParcel) opened: paint: (popupParcel) => # console.log 'popupParcel.kiwi_servicesInfo.length' # console.log popupParcel.kiwi_servicesInfo.length queryString = if popupParcel.kiwi_customSearchResults.queryString? then popupParcel.kiwi_customSearchResults.queryString else '' openedCustomSearchHTML = '<div class="topSearchBar"> <div class="evenlySpacedContainer"> <input id="customSearchQueryInput" value="' + queryString + '" type="text" placeholder=" combined search" style="width:234px; margin-right: 10px;" /> <button class="btn btn-mini btn-default" id="customSearchQuerySubmit" style="margin-right: 10px;">Submit</button> <button style="" class="goTo_userPreferencesView btn btn-mini btn-default"> Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> <br> <div class="evenlySpacedContainer" style="position: relative; top: -8px; margin-bottom: 3px;">' for serviceInfoObject in popupParcel.kiwi_servicesInfo openedCustomSearchHTML += '<div>' # console.log 'asdfasdf ' + serviceInfoObject.name # console.debug serviceInfoObject if serviceInfoObject.active == 'off' serviceDisabledAttr = ' disabled title="Service must be active, can be changed in options." ' else serviceDisabledAttr = ' ' if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? activeClass = ' active ' ariaPressedState = 'true' else if !popupParcel.kiwi_customSearchResults.servicesSearchesRequested? activeClass = if serviceInfoObject.active is 'off' then ' ' else ' active ' ariaPressedState = if serviceInfoObject.active is 'off' then 'false' else 'true' else activeClass = ' ' ariaPressedState = 'false' if serviceInfoObject.customSearchTags? and Object.keys(serviceInfoObject.customSearchTags).length > 0 openedCustomSearchHTML += '<div class="btn-group"> <button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" ' + serviceDisabledAttr + ' class="servicesToSearch btn btn-default btn-mini dropdownLabel ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button> <button ' + serviceDisabledAttr + ' data-toggle="dropdown" class="btn btn-default dropdown-toggle ' + activeClass + ' dropDownPrefs_' + serviceInfoObject.name + '" data-placeholder="false"><span class="caret"></span></button> <ul class="dropdown-menu">' for tagName, tagObject of serviceInfoObject.customSearchTags if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? if popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name].customSearchTags[tagName]? tagActiveChecked = ' checked ' else tagActiveChecked = '' else tagActiveChecked = if tagObject.include is true then ' checked ' else '' tagDisabledAttr = if serviceInfoObject.active is 'off' then ' disabled title="Service must be active, can be changed in options." ' else '' openedCustomSearchHTML += '<li><input ' + tagActiveChecked + tagDisabledAttr + ' type="checkbox" value="' + tagName + '" class="tagPref tagPref_' + serviceInfoObject.name + '" id="' + serviceInfoObject.name + tagName + '"> <label for="' + serviceInfoObject.name + tagName + '"> ' + tagObject.title + ' </label></li>' openedCustomSearchHTML += '</ul></div>' else openedCustomSearchHTML += '<button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" type="button" class="servicesToSearch btn btn-mini btn-default ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button>' openedCustomSearchHTML += '</div>' openedCustomSearchHTML += '<div> <button aria-pressed="false" autocomplete="off" type="button" class="btn btn-mini btn-default" id="close__' + @name + '" > close <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </div> </div>' openedCustomSearchHTML += ' <div id="messageCenter_Widget">asdfasd</div> </div> <div class="notFixed"></div> <div id="customSearchResults"></div> ' resultsSummaryArray = [] customSearchResultsHTML = "" if popupParcel.kiwi_customSearchResults? and popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name]? service_PreppedResults = popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name].results resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") customSearchResultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject, service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 customSearchResultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else customSearchResultsHTML += '<br>No results for ' + serviceInfoObject.title + '<br>' # customSearchResultsHTML += '</div>' else customSearchResultsHTML += '<div id="customSearchResultsDrop"><br>No results to show... make a search! :) </div><br>' customSearchResultsHTML = "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div>" + customSearchResultsHTML customSearchResultsHTML += "<br>" $(@DOMselector).html(openedCustomSearchHTML) $(@DOMselector + " #customSearchResults").html(customSearchResultsHTML) $(@DOMselector + " .hidden_listing").hide() duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight opened' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) bind: (popupParcel) => customSearchQueryInput = $(@DOMselector + " #customSearchQueryInput") customSearchQuerySubmit = $(@DOMselector + " #customSearchQuerySubmit") closeWidget = $(@DOMselector + ' #close__' + @name) customSearch_sortByPref = $(@DOMselector + " .conversations_sortByPref") modifySearch = $(@DOMselector + " .customSearchOpen") elsServicesButtons = $(@DOMselector + " button.servicesToSearch ") elsServicesActivePrefs = $(@DOMselector + " .customSearchServicePref input") showHidden = $(@DOMselector + " .showHidden") jumpToServiceCustomResults = $(@DOMselector + " #customSearchResults .jumpTo") @elsToUnbind = @elsToUnbind.concat(customSearchQueryInput, closeWidget, customSearchQuerySubmit, elsServicesButtons, customSearch_sortByPref, showHidden, jumpToServiceCustomResults, modifySearch) modifySearch.bind 'click', -> $(@DOMselector + " #customSearchQueryInput").focus() jumpToServiceCustomResults.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) pxFromTop = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).offset().top # offsetBy = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).outerHeight() + 40 $('body').scrollTop(pxFromTop - 100) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) ->" # console.debug ev serviceName = $(ev.target).data('servicename') # resultsBox__" + serviceInfoObject.name + # console.log @DOMselector + " .resultsBox__" + serviceName + " .hidden_listing" $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() elsServicesButtons.bind('click', (ev) => if $(ev.target).hasClass("dropdownLabel") serviceName = $(ev.target).attr('data-serviceName') # console.log serviceName # console.debug $(ev.target).attr('aria-pressed') ariaPressed = $(ev.target).attr('aria-pressed') if ariaPressed == 'true' $('button.dropDownPrefs_' + serviceName).removeClass('active') # console.log 'if ev.target.checked == "false" ' + serviceName $(@DOMselector + " input.tagPref_" + serviceName ).attr('disabled','disabled') else $('button.dropDownPrefs_' + serviceName).addClass('active') # console.log $(ev.target).attr('aria-pressed') + "asdfasdf" $(@DOMselector + " input.tagPref_" + serviceName ).removeAttr('disabled') $(ev.target).blur() ) customSearch_sortByPref.bind 'change', (ev) -> # console.log ' customSearch_sortByPref.val()' # console.log popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: 'kiwi_userPreferences' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) sendSearch = => queryString = customSearchQueryInput.val() elsServicesToSearch = $(@DOMselector + ' button.servicesToSearch[aria-pressed="true"]') # ariaPressed = $(ev.target).attr('aria-pressed') # if ariaPressed == 'true' servicesToSearch = {} for el in elsServicesToSearch serviceName = $(el).attr('data-serviceName') servicesToSearch[serviceName] = {} servicesToSearch[serviceName].customSearchTags = {} elTagPrefs = $(@DOMselector + " input.tagPref_" + serviceName + ":checked") for elTagPref in elTagPrefs tagName = $(elTagPref).val() servicesToSearch[serviceName].customSearchTags[tagName] = {} # console.log 'asfdasdfasdf ' + serviceName # console.debug servicesToSearch if queryString != '' parcel = msg: 'kiwiPP_post_customSearch' customSearchRequest: queryString: queryString servicesToSearch: servicesToSearch sendParcel(parcel) customSearchQueryInput.keypress (event) -> charCode = if event.keyCode then event.keyCode else event.which if charCode == 13 sendSearch() customSearchQuerySubmit.bind 'click', => sendSearch() closeWidget.bind 'click', => @widgetOpenBool = false @render('collapsed',popupParcel) customSearchQueryInput.focus() # showViewAndBindGoToViewButtons class View # basic building block constructor: (@name, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = "#" + @name + "_View" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @renderStates = @__renderStates__() return @ unbindView: => # console.log 'unbinding view' # console.debug @elsToUnbind # $(".userPreferencesSave").unbind() for el in @elsToUnbind el.unbind() @elsToUnbind = [] for widget in @Widgets widget.unbindWidget() render: (popupParcel, renderState = "__normal__") => @totalRenders++ @unbindView(@name) if !renderState? and !@renderStates.__normal__? console?.log 'ERROR: must declare renderState for view ' + @name + ' since __normal__ undefined' # console.log 'console.debug renderState ' + @name + renderState # console.log @totalRenders # console.debug @renderStates @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) class FixedView extends View constructor: (@name, @__renderStates__, uniqueSelectorPostfix) -> super @name, @__renderStates__ @DOMselector += uniqueSelectorPostfix # console.log @DOMselector class SwitchView extends View constructor: (@name, @__renderStates__) -> super @name, @__renderStates__ showView: => for _viewName, viewValue of switchViews if _viewName == @name # show # console.log 'showing ' + _viewName $('#' + _viewName + '_View').css({'display':'block'}) else # hide # console.log 'hiding ' + _viewName $('#' + _viewName + '_View').css({'display':'none'}) render: (popupParcel, renderState = "__normal__") => super popupParcel, renderState @showView() class Conversations extends SwitchView constructor: (@name) -> super @name, @__renderStates__ @Widgets = customSearch: new CustomSearch 'customSearch', @, false init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => # console.log ' in conversations view' # console.log popupParcel @Widgets['customSearch'].init(popupParcel) researchModeDisabledButtonsHTML = '' if popupParcel.urlBlocked == true or popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' or (popupParcel.oldUrl? and popupParcel.oldUrl == true) researchModeDisabledButtonsHTML += "<br> <div style='width:100%;text-align: center;'><button class='btn btn-success' style='font-size: 1.1em;display: inline-block;' id='researchUrlOverride'>Research this Url</button></div> <br>" if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' researchModeDisabledButtonsHTML += "<br> <div style='width:100%; text-align:center;'> Research Mode is off: &nbsp; <button class='goTo_userPreferencesView btn btn-xs btn-default' style='position:relative; bottom:2px;'> change settings </button> </div>" $("#researchModeDisabledButtons").html(researchModeDisabledButtonsHTML) resultsSummaryArray = [] resultsHTML = "" totalResults = 0 for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.allPreppedResults[serviceInfoObject.name]? and popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults.length > 0 service_PreppedResults = popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults totalResults += service_PreppedResults.length resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") resultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject,service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 resultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else if serviceInfoObject.submitTitle? submitUrl = serviceInfoObject.submitUrl submitTitle = serviceInfoObject.submitTitle resultsHTML += '<div class="serviceResultJumpTo">No conversation matches for ' + serviceInfoObject.title + '... <br> &nbsp;&nbsp;&nbsp;<a target="_blank" href="' + submitUrl + '">' + submitTitle + '</a></div><br>' else resultsHTML += '<div>No results for ' + serviceInfoObject.title + '</div>' preppedHTMLstring = '' if (popupParcel.urlBlocked == true and Object.keys(popupParcel.allPreppedResults).length < 2) # do nothing preppedHTMLstring += "<div style='width: 100%; text-align: justify; padding:20px; font-size:.9em; opacity:.9;'> <em> Certain super-high traffic URLs (or weird urls (like 'about:config' and chrome new tab pages)) have been excluded from auto-search out of respect for the APIs of the conversation sites. you can still manually search them by hitting the green button </em> </div><br>" else if ((totalResults > 0 and popupParcel.kiwi_userPreferences.researchModeOnOff == 'off') or popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or Object.keys(popupParcel.allPreppedResults).length > 1) preppedHTMLstring = '<br><h3 style="position:relative; top:-10px;">Results for this URL:</h3>' preppedHTMLstring += "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div><br>" preppedHTMLstring += resultsHTML $("#resultsByService").html(preppedHTMLstring) $(@DOMselector + " .hidden_listing").hide() if totalResults < 4 and @totalRenders < 4 fixedViews.kiwiSlice.render(popupParcel, "open") setTimeout( -> # to reign in a chrome rendering issue # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() , 300 ) # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() bind: (popupParcel) => showHidden = $(@DOMselector + " .showHidden") researchUrlOverrideButton = $(@DOMselector + " #researchUrlOverride") conversations_sortByPref = $(@DOMselector + " .conversations_sortByPref") customSearchOpen = $(@DOMselector + " .customSearchOpen") jumpToService = $("#resultsByService .jumpTo") @elsToUnbind = @elsToUnbind.concat(conversations_sortByPref, showHidden, researchUrlOverrideButton, customSearchOpen, jumpToService) jumpToService.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) # console.log serviceIndex pxFromTop = parseInt($($(@DOMselector + " #resultsByService .serviceResultJumpTo")[serviceIndex]).offset().top) # offsetBy = parseInt($($("#resultsByService .serviceResultsHeaderBar")[serviceIndex]).outerHeight()) + 40 $('body,html').scrollTop(pxFromTop - 100) customSearchOpen.bind 'click', -> $("#customSearchQueryInput").click() researchUrlOverrideButton.bind 'click', -> parcel = msg: 'kiwiPP_researchUrlOverrideButton' sendParcel(parcel) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) -> " # console.debug ev serviceName = $(ev.target).data('servicename') $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() conversations_sortByPref.bind 'change', (ev) -> # console.log "'conversations_sortByPref.bind 'change', (ev) ->" # console.log $(ev.target).val() popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: 'kiwi_userPreferences' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) class UserPreferences extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => $(@DOMselector + " .userErrMsg").html('') # console.log 'paint: adsfaeaewfawefawefawef(popupParcel) =># viewName = ' if preferencesOnlyPage is true $("#menuBar_preferences").hide() currentTime = Date.now() if popupParcel.kiwi_userPreferences.researchModeOnOff == "off" $("#autoOffTimer").html("Research mode is off, so auto-off timer is not set") else if popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp > currentTime $("#autoOffTimer").html("Auto-Off timer expires at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? $("#autoOffTimer").html("Auto-off timer last expired at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else $("#autoOffTimer").html("Auto-off timer is not set") researchModeHtml = '' if popupParcel.kiwi_userPreferences.researchModeOnOff is "off" researchOnString = "" researchOffString = " checked='checked' " else researchOnString = " checked='checked' " researchOffString = "" autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue `var auto20, auto60, autoAlways, autoCustom, autoCustomValue = ''; if(autoOffTimerType != null){ if(autoOffTimerType == "20"){ auto20 = " checked='checked' " } else if(autoOffTimerType == "60"){ auto60 = " checked='checked' " } else if(autoOffTimerType == "always"){ autoAlways = " checked='checked' " } else if(autoOffTimerType == "custom"){ autoCustom = " checked='checked' "; autoCustomValue = autoOffTimerValue;} }` researchModeHtml += 'Research Mode: <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;"><sup><em> ?</em></sup></div> <span style="bottom:34px; left:-114px;"> When the Research mode is "Off", Kiwi won\'t automatically search URLs as you surf; instead, you can check URLs on a case-by-case basis (and still be able to do custom searches) </span> </a> <label style="font-weight: normal;" for="researchmodeON"> on </label> <input id="researchmodeON" type="radio" name="research" value="on" ' + researchOnString + '> - <label style="font-weight: normal;" for="researchmodeOFF"> off </label> <input id="researchmodeOFF" type="radio" name="research" value="off" ' + researchOffString + '> &nbsp;&nbsp;<button class="btn btn-mini btn-default userPreferencesSave"> save preferences </button><br>' if popupParcel.kiwi_userPreferences.researchModeOnOff is 'off' researchModeHtml += '' timerDisabled = ' disabled ' timerOnlyUsefulWhenMessage = '<br> <span style="font-size:.8em;"><i> &nbsp;&nbsp;Note: the auto-off-timer only matters when Research Mode is "on". </i></span> <br>' else timerDisabled = ' ' researchModeHtml += '<br> <span style="font-size:.8em;"><i> Note: The Whitelist only makes a difference when Research mode is turned "off", which it currently isn\'t. </i></span> <br>' timerOnlyUsefulWhenMessage = '' researchModeHtml += ' <br> <table class="table table-bordered table-striped whitelistTable"> <thead> <tr> <th colspan="3"> <div class="input-group" id="addWhiteListString"> <label class="input-group-addon"> <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;">whitelist strings <sup><em> ?</em></sup></div> <span style="bottom:84px;left:-12px;"> <b>Whitelist strings:</b> <br> Kiwi will automatically research any URL (upon visiting) that contains a user-provided Whitelist string -- even when Research Mode is "off". Try it with "github.com" or "bitbucket.org", and then visit the respective site with research mode "off". </span> </a> </label> <input type="text" class="form-control ignoreSaveButtonListen"> <label class="input-group-addon btn btn-default"> add </label> </div> </th> </tr> </thead> <tbody> ' for whitelistSubString, index in popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch researchModeHtml += ' <tr> <th scope="row" style="width:35px;"> ' + (index + 1) + ' </th> <td> ' + whitelistSubString + ' </td> <td style="width:35px;"> <button title="remove" class="btn btn-xs btn-default removeWhitelistString" data-whitelistStringToRemove="' + whitelistSubString + '" > <span data-whitelistStringToRemove="' + whitelistSubString + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> </td> </tr>' researchModeHtml += ' </tbody> </table> <br>Auto-Off Timer set for: ' + timerOnlyUsefulWhenMessage + ' <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto20 + ' value="20"> 20 min</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto60 + ' value="60"> 1 hr</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoAlways + ' value="always"> Always On</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoCustom + ' value="custom"> Custom</label> &nbsp; &nbsp; <input ' + timerDisabled + ' id="autoCustomValue" type="text" value="' + autoCustomValue + '" size="4" disabled /> minutes' $("#researchModeDrop").html(researchModeHtml) servicesHtml = '' for service, index in popupParcel.kiwi_servicesInfo if service.active == "on" activeCheck = " checked='checked' " notActiveCheck = "" else activeCheck = "" notActiveCheck = " checked='checked' " servicesHtml += '<br> <div class="serviceListing listing"> <table><tbody><tr> <td class="upDownButtons">' if index != 0 servicesHtml += '<span title="Move ' + service.title + ' results above ' + popupParcel.kiwi_servicesInfo[index - 1].title + '" class="glyphicon glyphicon-chevron-up" id="' + service.name + '_moveServiceUp" aria-hidden="true"></span>' if index != 0 and index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<br><br>' if index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<span title="Move ' + service.title + ' results below ' + popupParcel.kiwi_servicesInfo[index + 1].title + '" class="glyphicon glyphicon-chevron-down" id="' + service.name + '_moveServiceDown" aria-hidden="true"></span>' brandedTitle = if (service.name is 'reddit') then "for " + service.title else service.title brandingImage = '' if service.brandingImage? brandingImage = "&nbsp;<a target='_blank' href='" + service.broughtToYouByURL + "' style='text-decoration:none;'> <img height='28' src='" + service.brandingImage + "'/></a>&nbsp;" servicesHtml += '</td> <td class="serviceInfo">' + brandedTitle + ' - using: ' + brandingImage + ' <a target="_blank" href="' + service.broughtToYouByURL + '">' + service.broughtToYouByTitle + '</a><br>' if service.name == "productHunt" specificAPIlink = ", <a target='_blank' href='https://github.com/producthunt/producthunt-api/wiki/Product-Hunt-APIs#algolia-search-api'>for PH</a>" if service.customSearchBroughtToYouByTitle? customSearchApiBrandingHTML = "<div class='bg-warning' style='margin:4px; margin-top:10px;padding:6px;'> <em><div style='padding-bottom:2px;'>&nbsp;&nbsp;&nbsp;&nbsp;custom searches are using: </div>" + ' <div style="padding-bottom:4px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a target="_blank" href="' + service.customSearchBroughtToYouByURL + '">' + service.customSearchBroughtToYouByTitle + '</a> ' + specificAPIlink + ' </em> </div> </em> </div>' else customSearchApiBrandingHTML = "" servicesHtml += '<div style="padding-left:15px;"> status: <label style="font-weight: normal;" for="' + service.name + '_serviceStatusON"> on </label> <input id="' + service.name + '_serviceStatusON" type="radio" name="' + service.name + '_serviceStatus" value="on" ' + activeCheck + '> - <label style="font-weight: normal;" for="' + service.name + '_serviceStatusOFF"> off </label> <input id="' + service.name + '_serviceStatusOFF" type="radio" name="' + service.name + '_serviceStatus" value="off" ' + notActiveCheck + '> <br><br>Results are deemed notable (capitilizes badge letter) if:' if service.name == 'gnews' servicesHtml += '<br><br> the topic has had <input id="' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit" type="text" size="4" value="' + service.notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit + '"/> or more related stories published within the last <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> hours <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> number of News Clusters <input id="' + service.name + '_numberOfRelatedItemsWithClusterURL" type="text" size="4" value="' + service.notableConditions.numberOfRelatedItemsWithClusterURL + '"/> </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' else servicesHtml += '<br> URL is an exact match, and: <br> it has been <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> or fewer hours since posting <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> a post has <input id="' + service.name + '_commentsNotable" type="text" size="4" value="' + service.notableConditions.num_comments + '"/> or more comments </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' servicesHtml += "<div class='serviceListing listing' style='padding:15px; margin-top: 30px;'> Wouldn't it be awesome if we could add some more services to opt-in to?&nbsp;&nbsp; All that's needed are friendly APIs!&nbsp; <a href='https://twitter.com/spencenow' target='_blank'>Tweet me</a> if you're interested in adding one! </div> <br>" $("#servicesInfoDrop").html(servicesHtml) bind: (popupParcel) => saveButtons = $(@DOMselector + " .userPreferencesSave") removeWhitelistStringButtons = $(@DOMselector + " .removeWhitelistString") autoTimerRadios = $(@DOMselector + " input:radio[name='researchAutoOffType']") allInputs = $(@DOMselector + ' input:not(.ignoreSaveButtonListen)') addWhitelistString_button = $(@DOMselector + " #addWhiteListString label") @elsToUnbind = @elsToUnbind.concat allInputs, saveButtons, autoTimerRadios, removeWhitelistStringButtons, addWhitelistString_button saveButtons.attr('disabled','disabled') allInputs.bind 'change', -> $(".userPreferencesSave").removeAttr('disabled') allInputs.bind 'focus', -> $(".userPreferencesSave").removeAttr('disabled') if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') autoTimerRadios.bind 'change', -> if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') else $("#autoCustomValue").attr('disabled','disabled') _bindDown = (downButton, index) => downButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index + 1) parcel = refreshView: 'userPreferences' keyName: 'kiwi_servicesInfo' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) _bindUp = (upButton, index) => upButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index - 1 ) parcel = refreshView: 'userPreferences' keyName: 'kiwi_servicesInfo' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) for service,index in popupParcel.kiwi_servicesInfo downButton = $("#" + service.name + '_moveServiceDown') if downButton.length > 0 @elsToUnbind.push downButton _bindDown(downButton, index) upButton = $("#" + service.name + '_moveServiceUp') if upButton.length > 0 @elsToUnbind.push upButton _bindUp(upButton, index) postError = (userErrMsg) => # console.log 'trying to post error ' + userErrMsg $(@DOMselector + " .userErrMsg").html("<br>" + userErrMsg) addWhitelistString_button.bind 'click', (ev) => # whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') whitelistSubString_toAdd = $(@DOMselector + " #addWhiteListString input").val() popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch.push whitelistSubString_toAdd parcel = refreshView: 'userPreferences' keyName: 'kiwi_userPreferences' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) removeWhitelistStringButtons.bind 'click', (ev) -> whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') newWhitelistAnyMatchArray = _.without(popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch, whitelistSubString); popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch = newWhitelistAnyMatchArray parcel = refreshView: 'userPreferences' keyName: 'kiwi_userPreferences' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) saveButtons.bind 'click', -> researchModeHTMLval = $("input:radio[name='research']:checked").val() # console.log 'researchModeHTMLval is ' + researchModeHTMLval if researchModeHTMLval != 'on' and researchModeHTMLval != 'off' postError('research mode must be "on" or "off"'); return 0; allowedAutoOffTypes = ["20","60","always","custom"] autoOffTimerType = $("input:radio[name='researchAutoOffType']:checked").val() autoOffTimerValue = $("#autoCustomValue").val() if autoOffTimerType in allowedAutoOffTypes if autoOffTimerType == 'custom' and (autoOffTimerValue == '' or isNaN(autoOffTimerValue)) postError('Must specify a number of minutes for auto-off timer.'); return 0; else postError('not acceptable autoOffTimerType'); return 0; # autoOffAtUTCmilliTimestamp for service, index in popupParcel.kiwi_servicesInfo if service.name == 'gnews' active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() if numberOfStoriesFoundWithinTheHoursSincePostedLimit == '' or isNaN(numberOfStoriesFoundWithinTheHoursSincePostedLimit) postError('number Of Stories Found Within The Hours Since Posted Limit must be an integer'); return 0; numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() if numberOfRelatedItemsWithClusterURL == '' or isNaN(numberOfRelatedItemsWithClusterURL) postError('number Of Related Items With Cluster URL of comments must be an integer'); return 0; else active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; hoursSincePosted = $('#' + service.name + '_hoursNotable').val() if hoursSincePosted == '' or isNaN(hoursSincePosted) postError('Hours must be an number'); return 0; num_comments = $('#' + service.name + '_commentsNotable').val() if num_comments == '' or isNaN(num_comments) postError('Number of comments must be an integer'); return 0; # console.log '1234' popupParcel.kiwi_userPreferences.researchModeOnOff = researchModeHTMLval if (autoOffTimerType != 'custom') popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType else popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType popupParcel.kiwi_userPreferences.autoOffTimerValue = parseFloat(autoOffTimerValue) for service, index in popupParcel.kiwi_servicesInfo active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() popupParcel.kiwi_servicesInfo[index].active = active # notableSound = $("input:radio[name='" + service.name + "_soundStatus']:checked").val() # popupParcel.kiwi_servicesInfo[index].notableSound = notableSound hoursSincePosted = $('#' + service.name + '_hoursNotable').val() # console.log popupParcel.kiwi_servicesInfo[index].name # console.log "hoursSincePosted = $('#' + service.name + '_hoursNotable').val() " + hoursSincePosted popupParcel.kiwi_servicesInfo[index].notableConditions.hoursSincePosted = parseFloat(hoursSincePosted) if service.name == 'gnews' numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfRelatedItemsWithClusterURL = parseInt(numberOfRelatedItemsWithClusterURL) numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit = parseInt(numberOfStoriesFoundWithinTheHoursSincePostedLimit) else num_comments = $('#' + service.name + '_commentsNotable').val() popupParcel.kiwi_servicesInfo[index].notableConditions.num_comments = parseInt(num_comments) popupParcel.view = 'userPreferences' # console.log '4567' # console.debug popupParcel parcel = refreshView: popupParcel.view newPopupParcel: popupParcel msg: 'kiwiPP_post_savePopupParcel' sendParcel(parcel) class Credits extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class Loading extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class KiwiSlice extends FixedView constructor: (@name, uniqueSelectorPostfix) -> super @name, @__renderStates__, uniqueSelectorPostfix init: (popupParcel, renderState = null) => @renderStateTransitions = @__renderStateTransitions__() # console.log 'hehehehee init: (popupParcel, renderState = null) =>' @unbindView() renderState = if renderState? then renderstate else "collapsed" # console.log ' renderState = if renderState? then renderstate else "collapsed" ' + renderState @render(popupParcel, 'collapsed') render: (popupParcel, renderState, fromState = null) => # console.log 'in render for kiwi' __renderStates__callback = (popupParcel, renderState) => super popupParcel, renderState if fromState? and @renderStateTransitions[fromState + "__to__" + renderState]? # console.log 'yep, has renderstate' @renderStateTransitions[fromState + "__to__" + renderState](popupParcel, renderState, __renderStates__callback) else super popupParcel, renderState __renderStates__: => collapsed: paint: (popupParcel) => kiwiSliceHTML = '<div id="sliceActivateTransition" style="position:fixed; bottom: -33px; right: -33px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) bind: (popupParcel) => elActivateTransition = $(@DOMselector + " #sliceActivateTransition") @elsToUnbind = @elsToUnbind.concat elActivateTransition elActivateTransition.bind 'mouseover', (ev) => elActivateTransition.addClass('rotateClockwiseFull') elActivateTransition.bind 'mouseout', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') elActivateTransition.bind 'click', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') @render(popupParcel,'open', 'collapsed') open: paint: (popupParcel) => # console.log 'painting ' + @name kiwiSliceHTML = '<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter"> <button type="button" class=" goTo_creditsView btn btn-mini btn-default">credits</button> <a class="btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class=" btn btn-mini btn-default" id="clearKiwiURLCache">clear cache</button> <button class=" btn btn-mini btn-default" id="refreshURLresults">refresh</button> </div> <div id="sliceActivateTransition" style="position:fixed; bottom: 15px; right: 15px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) # console.log kiwiSliceHTML bind: (popupParcel) => # console.log 'binding ' + @name elActivateTransition = $(@DOMselector + " #sliceActivateTransition") clearKiwiURLCacheButton = $(@DOMselector + " #clearKiwiURLCache") refreshURLresultsButton = $(@DOMselector + " #refreshURLresults") @elsToUnbind = @elsToUnbind.concat elActivateTransition, refreshURLresultsButton, clearKiwiURLCacheButton refreshURLresultsButton.bind 'click', -> parcel = msg: 'kiwiPP_refreshURLresults' sendParcel(parcel) $('body').mouseup((e) => # console.log 'test test test' container = $(@DOMselector) if (!container.is(e.target) && container.has(e.target).length == 0) $('body').unbind 'mouseup' @render(popupParcel,'collapsed', 'open') ) elActivateTransition.bind 'click', (ev) => @render(popupParcel,'collapsed', 'open') clearKiwiURLCacheButton.bind 'click', -> parcel = msg: 'kiwiPP_clearAllURLresults' sendParcel(parcel) # \/ \/ \/ THIS IS A WORK IN PROGRESS \/ \/ \/ __renderStateTransitions__: => 'open__to__collapsed': (popupParcel, renderState, __renderStates__callback) => $(@DOMselector + " #transition_open_showMe").animate({'opacity':0}, 300) $(@DOMselector + " #sliceActivateTransition").addClass('rotateClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '-33px', "right": "-33px"}, { duration: 500, complete: -> __renderStates__callback(popupParcel, renderState) }) # return transitionObj 'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) => # console.log "'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) =>" $(@DOMselector + " #sliceActivateTransition").addClass('rotateCounterClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '15px', "right": "15px"}, { duration: 500, complete: -> # console.log 'we are done with animation' __renderStates__callback(popupParcel, renderState) }) $(@DOMselector).prepend('<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter" style="opacity: 0;"> <button type="button" class="goTo_creditsView btn btn-mini btn-default ">credits</button> <a class=" btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class="btn btn-mini btn-default " id="clearKiwiURLCache">clear cache</button> <button class="btn btn-mini btn-default " id="refreshURLresults">refresh</button> </div>') # setTimeout => $(@DOMselector + " #transition_open_showMe").animate({'opacity':1}, 499) # , 200 fixedViews = kiwiSlice: new KiwiSlice 'kiwiSlice', 'FixedBottom' switchViews = conversations: new Conversations 'conversations' userPreferences: new UserPreferences 'userPreferences' credits: new Credits 'credits' loading: new Loading 'loading' tailorResults = productHunt: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() fuzzyMatchBool = false brandingDisplay = '' if serviceInfoObject.brandingImage? brandingDisplay = '<img style="margin-left:7px;" title="' + serviceInfoObject.title + '" height="28" src="' + serviceInfoObject.brandingImage + '"/> &nbsp;&nbsp; <span class="serviceResultsTitles" style="color:black; position: relative;top: 6px;"">' + serviceInfoObject.title + '</span>' else brandingDisplay = "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" + brandingDisplay + "</div>" # recency doesn't make sense for PH # if kiwi_userPreferences.sortByPref == 'attention' # selectedString_attention = 'selected' # selectedString_recency = '' # else # selectedString_attention = '' # selectedString_recency = 'selected' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_num_comments') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else if (listing.kiwi_created_at? and currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) recentTag = "<span class='recentListingTag'>Recent: </span>" else recentTag = "" if listing.kiwi_makers.length > 3 gridLayoutBool = false else gridLayoutBool = true preppedHTMLstring += '<div class="listing ' + listingClass + '">' # kiwi_created_at: 1439471020625 # kiwi_author_headline: "Community @ProductHunt. " # kiwi_author_name: "Ben Tossell" # kiwi_author_username: "bentossell" # kiwi_discussion_url: "http://www.producthunt.com/tech/buffer-for-video" # kiwi_makers: Array[9] # headline: "Co-founder/CEO, Buffer" # name: "Joel Gascoigne" # profile_url: "http://www.producthunt.com/@joelgascoigne" # username: "joelgascoigne" # website_url: "http://joel.is" # kiwi_num_comments: 30 # kiwi_score: 244 # name: "Buffer for Video" # tagline: "All-in-one video scheduling & management for social media" # redirect_url: "http://www.producthunt.com/r/4918f991fdd705/30839?app_id=1674" # screenshot_url: Object if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 60%; padding-right:8px;">' else preppedHTMLstring += '<div>' preppedHTMLstring += ' <a class="listingTitle" target="_blank" href="' + listing.kiwi_discussion_url + '"> <div style="color:black; padding:4px; padding-bottom: 8px; font-size: 1.1em;">' + recentTag + ' <b>' + listing.name + '</b> </div> <div style="color:#4D586F; padding-left:18px;"> <div style="padding-bottom:4px;">"' + listing.tagline + '"</div>' preppedHTMLstring += '<div style="padding-bottom:4px;"> ' + listing.kiwi_num_comments + ' comments, ' + listing.kiwi_score + ' upvotes </div>' if listing.kiwi_created_at? _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += '' + _time preppedHTMLstring += '</div></a></div>' if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 39%;">' else preppedHTMLstring += '<div style="padding: 8px;">' makerUsernames = [] if listing.kiwi_makers? and listing.kiwi_makers.length > 0 preppedHTMLstring += '<div><div style="padding-bottom:2px;"><b>made by</b>: </div>' for maker in listing.kiwi_makers if gridLayoutBool preppedHTMLstring += '<div style="padding-bottom: 4px;">' else preppedHTMLstring += '<div style="padding-bottom: 4px; padding-left: 10px;">' preppedHTMLstring += '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + maker.username + '" style="color:#727E98;">' + maker.name if maker.headline? and maker.headline != "" preppedHTMLstring += ', "' + maker.headline + '"' preppedHTMLstring += '</a>' if maker.website_url? preppedHTMLstring += ' <a href="' + maker.website_url + '" target="_blank"><span class="glyphicon glyphicon-log-in" style="color:blue;"></span> </a>' if listing.kiwi_author_username == maker.username preppedHTMLstring += " (also submitted post)" preppedHTMLstring += '</div>' preppedHTMLstring += '</div>' makerUsernames.push maker.username if listing.kiwi_author_username not in makerUsernames if gridLayoutBool gridLayoutAuthorDiv = '<div style="padding-bottom: 2px;">' else gridLayoutAuthorDiv = '<div style="padding-bottom: 2px; margin-left: 10px;">' preppedHTMLstring += '<div style=""> <div style="padding-bottom:2px;"><b>submitted by:</b></div> ' + gridLayoutAuthorDiv + '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.kiwi_author_username + '" style="color:#727E98;">' + listing.kiwi_author_name + ' ' if listing.kiwi_author_headline? and listing.kiwi_author_headline != "" preppedHTMLstring += ', "' + listing.kiwi_author_headline + '"' preppedHTMLstring += '</a></div></div>' preppedHTMLstring += '</div></div>' preppedHTMLstring += "</div>" return preppedHTMLstring hackerNews: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) reddit: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) _tailorHNcomment = (listing, serviceInfoObject, listingClass) -> currentTime = Date.now() commentHtml = "" # story_text # comment_text # story_id # story_title # story_url recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" commentHtml += '<div class="listing ' + listingClass + ' " style="position:relative;">' + recentTag if listing.over_18? and listing.over_18 is true commentHtml += '<span class="nsfw">NSFW</span> For story: ' + listing.story_title + '<br>' else commentHtml += "For story: <a target='_blank' href='" + serviceInfoObject.permalinkBase + listing.story_id + "'>" + listing.story_title + '</a><br>' _time = formatTime(listing.kiwi_created_at) commentHtml += 'at ' + _time + ', <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '">' + listing.author + '</a> recieved ' + listing.kiwi_score + ' upvotes, by saying: ( <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"> comment permalink </a> , <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.story_id + '"> story permalink </a> )<br><div class="commentBox"> ' + listing.comment_text + ' </div></div>' return commentHtml tailorRedditAndHNresults_returnHtml = (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() # kiwi_exact_match # fuzzy matches # linkify stuff fuzzyMatchBool = false preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" if serviceInfoObject.name == 'reddit' preppedHTMLstring += "<span class='serviceResultsTitles'>for " + serviceInfoObject.title + ':</span>' else preppedHTMLstring += "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' if kiwi_userPreferences.sortByPref == 'attention' selectedString_attention = 'selected' selectedString_recency = '' else selectedString_attention = '' selectedString_recency = 'selected' preppedHTMLstring += '<div style="float:right; padding-top: 9px;"> &nbsp;&nbsp sorted by: <select class="conversations_sortByPref"> <option ' + selectedString_attention + ' id="_attention" value="attention">attention</option> <option ' + selectedString_recency + ' id="_recency" value="recency">recency</option> </select></div> </div>' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else if !service_PreppedResults[0].comment_text? and kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'num_comments') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_score') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'recency' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_created_at') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" if listing.kiwi_exact_match # preppedHTMLstring += '<div class="listing ' + listingClass + '" style="position:relative;">' + recentTag + ' # <div style="float:right;"> # <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> # </div> # <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '">' preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes -- ' + _time + '</span></a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a> </div>' preppedHTMLstring += '<br></div>' else fuzzyMatchBool = true if fuzzyMatchBool numberOfExactMatches = _.reduce(service_PreppedResults, (memo, obj) -> if obj.kiwi_exact_match memo++ return memo else memo ) if (service_PreppedResults.length - numberOfExactMatches) > 10 and service_PreppedResults.length > 14 listingClass = ' hidden_listing ' else listingClass = '' # listingClass = if nonFuzzyItemCounter > 10 then ' hidden_listing ' else '' preppedHTMLstring += '<div class="showFuzzyMatches ' + listingClass + '" style="position:relative;"> fuzzy matches: <br></div> <span class="fuzzyMatches">' # console.log 'fuzzy matches 12312312 ' + serviceInfoObject.name for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if !listing.kiwi_exact_match recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes ' + formatTime(listing.kiwi_created_at) + '</span> <br> for Url: <span class="altURL">' + listing.url + '</span> </a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a></div>' preppedHTMLstring += '<br></div>' preppedHTMLstring += "</span>" preppedHTMLstring += "</div>" return preppedHTMLstring bindGoToViewButtons = (buttonEls, viewName, viewData) -> for el in buttonEls $(el).bind('click', (ev) -> # console.log 'clicked ' + viewName switchViews[viewName].render(viewData) ) moveArrayElement = (array, from, to) -> array.splice(to, 0, array.splice(from, 1)[0]); return array getRandom = (min, max) -> return min + Math.floor(Math.random() * (max - min + 1)) formatTime = (utcMillisecondTimestamp) -> a = new Date(utcMillisecondTimestamp) months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] year = a.getFullYear() month = months[a.getMonth()] date = a.getDate() hour = a.getHours() min = a.getMinutes() sec = a.getSeconds() amOrPm = if hour > 11 then 'pm' else 'am' if hour > 12 hour = hour - 12 else if parseInt(hour) == 0 hour = 12 if min < 10 min = '0' + min time = month + ' ' + date + ', ' + year + ' - ' + hour + ':' + min + amOrPm return time renderExtensionHeight = (elementSelector, extraPx) -> if viewElementId is elementSelector extraPx = 2 extHeight_ = $(elementSelector).outerHeight() + extraPx if extHeight_ > 590 extHeight_ = 590 # $('html').css('height',extHeight+'px') $('body').css('height', extHeight_ + 'px') `heightString = extHeight_.toString() +'px'` $('html').css('min-height', heightString) extHeight_-- $('body').css('min-height', heightString) capitalizeFirstLetter = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) # // http://css-tricks.com/snippets/javascript/htmlentities-for-javascript/ htmlEntities = (str) -> return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); getURLParam = (oTarget, sVar) -> return decodeURI(oTarget.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); algoliaPHclient = null algoliaPHindex = null initAlgoliaPHcustomSearch = -> algoliaPHclient = algoliasearch('0H4SMABBSG', '9670d2d619b9d07859448d7628eea5f3') algoliaPHindex = algoliaPHclient.initIndex('Post_production') initAlgoliaPHcustomSearch() fetchAlgoliaProductHuntResultsFirst = (parcel) -> # console.log 'yoyoyo here ' + parcel.customSearchRequest.queryString # console.log parcel # not ideal because it's blocking, and it'd be better to have persistent index object # but the restrictions in FF addons force this approach. if algoliaPHindex? algoliaPHindex.search(parcel.customSearchRequest.queryString, (err, content) -> # // err is either `null` or an `Error` object, with a `message` property # // content is either the result of the command or `undefined` if (err) console.error(err) parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) return 0 if content? and content.hits? parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = content.hits else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] # console.log 'sending this PH' # console.log parcel.customSearchRequest.servicesToSearch.productHunt.rawResults self.port.emit('kiwiPP_post_customSearch', parcel) ) else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) sendParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_acknowledgeMessage' self.port.emit('kiwiPP_acknowledgeMessage', parcel); when 'kiwiPP_refreshSearchQuery' # port.postMessage(parcel) self.port.emit('kiwiPP_refreshSearchQuery', parcel); when 'kiwiPP_post_customSearch' # not ideal because it's blocking, but the restrictions in FF addons force this approach if parcel.customSearchRequest.servicesToSearch.productHunt? fetchAlgoliaProductHuntResultsFirst(parcel) else port.postMessage(parcel) when 'kiwiPP_request_popupParcel' self.port.emit('kiwiPP_request_popupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_savePopupParcel' self.port.emit('kiwiPP_post_savePopupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_save_a_la_carte' self.port.emit('kiwiPP_post_save_a_la_carte', parcel) # port.postMessage(parcel) when 'kiwiPP_clearAllURLresults' self.port.emit('kiwiPP_clearAllURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_refreshURLresults' self.port.emit('kiwiPP_refreshURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_researchUrlOverrideButton' self.port.emit('kiwiPP_researchUrlOverrideButton', parcel) # port.postMessage(parcel) receiveParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_popupParcel_ready' initialize(parcel.popupParcel) self.port.on('kiwi_fromBackgroundToPopup', (parcel) -> receiveParcel(parcel) )
4712
viewElementId = '' renderedBool = false preferencesOnlyPage = false initialize = (popupParcel) -> # console.log 'in init' if getURLParam(window.location, 'optionsOnly') != '' preferencesOnlyPage = true switchViews.userPreferences.render(popupParcel) return 0 for viewName, view of fixedViews view.init(popupParcel) # views.userPreferences.render(popupParcel) if popupParcel.view? and switchViews[popupParcel.view]? switchViews[popupParcel.view].render(popupParcel) else switchViews.conversations.render(popupParcel) class Widget # basic building block constructor: (@name, @parentView, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = @parentView.DOMselector + " #" + @name + "_Widget" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews # console.log _viewName # bind to goToView buttons els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') # console.debug els_goTo_view @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @unbindWidget = => for el in @elsToUnbind el.unbind() @elsToUnbind = [] @render = (renderState, popupParcel) => @totalRenders++ @unbindWidget(@name) @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) @renderStates = @__renderStates__() return @ class MessageCenter extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ # console.log ' trying ' super @name, @parentView, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render('showMessages',popupParcel) __renderStates__: => showMessages: paint: (popupParcel) => # console.log 'messagesHTML = "" # console.debug popupParcel' messagesHTML = "" # console.debug popupParcel if popupParcel.kiwi_userMessages.length > 0 messagesHTML += '<div style="padding-top:4px; padding-bottom:10px;">' for messageObj in popupParcel.kiwi_userMessages messagesHTML += '<div class="bg-warning" style="margin:6px; padding:8px; text-align:justify;"> <button style="float:right; margin:8px; padding:4px; padding-right:6px; padding-left:6px;" class="btn btn-xs btn-default acknowledgeMessage" data-messageToAcknowledge="' + messageObj.name + '" > <span title="remove" data-messageToAcknowledge="' + messageObj.name + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> ' + messageObj.baseValue + ' &nbsp; </div>' messagesHTML += '<div style="width:100%; text-align:center;"> <b>message priority</b>: urgent. &nbsp;&nbsp; please acknowledge the message(s) by clicking the "x" button(s). Thanks! :) </div></div>' $(@DOMselector).html(messagesHTML) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => if popupParcel.kiwi_userMessages.length > 0 # console.log 'bind: (popupParcel) =>' ackMessageButtons = $(@DOMselector + ' .acknowledgeMessage') @elsToUnbind = @elsToUnbind.concat ackMessageButtons ackMessageButtons.bind 'click', (ev) => console.log "trying for ackMessageButtons.bind 'click', (ev) =>" messageToAcknowledge = $(ev.target).attr('data-messageToAcknowledge') console.log 'messageToAcknowledge ' + messageToAcknowledge # console.debug popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch # console.debug whitelistSubString parcel = messageToAcknowledge: messageToAcknowledge msg: 'kiwiPP_acknowledgeMessage' sendParcel(parcel) class CustomSearch extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ super @name, @parentView, @__renderStates__ init: (popupParcel) -> @Widgets = {messageCenter: new MessageCenter 'messageCenter', @, false} @unbindWidget() if @widgetOpenBool == false @render('collapsed',popupParcel) else @render('opened',popupParcel) __renderStates__: => collapsed: paint: (popupParcel) => openedCustomSearchHTML = ' <div class="topSearchBar" style="padding-bottom: 14px;"> <div class="evenlySpacedContainer"> <input class="queryInputOpen" id="customSearchQueryInput" type="text" placeholder=" combined search" /> <button class="btn btn-mini btn-default goTo_userPreferencesView">User Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> ' if popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' openedCustomSearchHTML += "<div style='padding-top: 12px;'><a id='openPreviousSearch'>see custom results for '" + popupParcel.kiwi_customSearchResults.queryString + "' </a> &nbsp;&nbsp;&nbsp;&nbsp; <a id='clearPreviousSearch'>clear</a></div>" openedCustomSearchHTML += " <div id='messageCenter_Widget'></div> </div> <div class='notFixed'></div>" $(@DOMselector).html(openedCustomSearchHTML) # console?.log 'console.log @DOMselector + " .topSearchBar"' + @DOMselector + " .topSearchBar" duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight closed' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => # console.log 'bind: (popupParcel) =>' inputSearchQueryInput = $("#customSearchQueryInput") previousSearchLink = $("#openPreviousSearch") clearPreviousSearch = $("#clearPreviousSearch") @elsToUnbind = @elsToUnbind.concat inputSearchQueryInput, previousSearchLink, clearPreviousSearch previousSearchLink.bind 'click', -> $("#customSearchQueryInput").click() clearPreviousSearch.bind 'click', -> parcel = msg: 'kiwiPP_refreshSearchQuery' sendParcel(parcel) inputSearchQueryInput.bind 'click', => # console.log '@widgetOpenBool = true' @widgetOpenBool = true @render('opened',popupParcel) opened: paint: (popupParcel) => # console.log 'popupParcel.kiwi_servicesInfo.length' # console.log popupParcel.kiwi_servicesInfo.length queryString = if popupParcel.kiwi_customSearchResults.queryString? then popupParcel.kiwi_customSearchResults.queryString else '' openedCustomSearchHTML = '<div class="topSearchBar"> <div class="evenlySpacedContainer"> <input id="customSearchQueryInput" value="' + queryString + '" type="text" placeholder=" combined search" style="width:234px; margin-right: 10px;" /> <button class="btn btn-mini btn-default" id="customSearchQuerySubmit" style="margin-right: 10px;">Submit</button> <button style="" class="goTo_userPreferencesView btn btn-mini btn-default"> Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> <br> <div class="evenlySpacedContainer" style="position: relative; top: -8px; margin-bottom: 3px;">' for serviceInfoObject in popupParcel.kiwi_servicesInfo openedCustomSearchHTML += '<div>' # console.log 'asdfasdf ' + serviceInfoObject.name # console.debug serviceInfoObject if serviceInfoObject.active == 'off' serviceDisabledAttr = ' disabled title="Service must be active, can be changed in options." ' else serviceDisabledAttr = ' ' if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? activeClass = ' active ' ariaPressedState = 'true' else if !popupParcel.kiwi_customSearchResults.servicesSearchesRequested? activeClass = if serviceInfoObject.active is 'off' then ' ' else ' active ' ariaPressedState = if serviceInfoObject.active is 'off' then 'false' else 'true' else activeClass = ' ' ariaPressedState = 'false' if serviceInfoObject.customSearchTags? and Object.keys(serviceInfoObject.customSearchTags).length > 0 openedCustomSearchHTML += '<div class="btn-group"> <button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" ' + serviceDisabledAttr + ' class="servicesToSearch btn btn-default btn-mini dropdownLabel ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button> <button ' + serviceDisabledAttr + ' data-toggle="dropdown" class="btn btn-default dropdown-toggle ' + activeClass + ' dropDownPrefs_' + serviceInfoObject.name + '" data-placeholder="false"><span class="caret"></span></button> <ul class="dropdown-menu">' for tagName, tagObject of serviceInfoObject.customSearchTags if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? if popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name].customSearchTags[tagName]? tagActiveChecked = ' checked ' else tagActiveChecked = '' else tagActiveChecked = if tagObject.include is true then ' checked ' else '' tagDisabledAttr = if serviceInfoObject.active is 'off' then ' disabled title="Service must be active, can be changed in options." ' else '' openedCustomSearchHTML += '<li><input ' + tagActiveChecked + tagDisabledAttr + ' type="checkbox" value="' + tagName + '" class="tagPref tagPref_' + serviceInfoObject.name + '" id="' + serviceInfoObject.name + tagName + '"> <label for="' + serviceInfoObject.name + tagName + '"> ' + tagObject.title + ' </label></li>' openedCustomSearchHTML += '</ul></div>' else openedCustomSearchHTML += '<button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" type="button" class="servicesToSearch btn btn-mini btn-default ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button>' openedCustomSearchHTML += '</div>' openedCustomSearchHTML += '<div> <button aria-pressed="false" autocomplete="off" type="button" class="btn btn-mini btn-default" id="close__' + @name + '" > close <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </div> </div>' openedCustomSearchHTML += ' <div id="messageCenter_Widget">asdfasd</div> </div> <div class="notFixed"></div> <div id="customSearchResults"></div> ' resultsSummaryArray = [] customSearchResultsHTML = "" if popupParcel.kiwi_customSearchResults? and popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name]? service_PreppedResults = popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name].results resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") customSearchResultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject, service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 customSearchResultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else customSearchResultsHTML += '<br>No results for ' + serviceInfoObject.title + '<br>' # customSearchResultsHTML += '</div>' else customSearchResultsHTML += '<div id="customSearchResultsDrop"><br>No results to show... make a search! :) </div><br>' customSearchResultsHTML = "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div>" + customSearchResultsHTML customSearchResultsHTML += "<br>" $(@DOMselector).html(openedCustomSearchHTML) $(@DOMselector + " #customSearchResults").html(customSearchResultsHTML) $(@DOMselector + " .hidden_listing").hide() duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight opened' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) bind: (popupParcel) => customSearchQueryInput = $(@DOMselector + " #customSearchQueryInput") customSearchQuerySubmit = $(@DOMselector + " #customSearchQuerySubmit") closeWidget = $(@DOMselector + ' #close__' + @name) customSearch_sortByPref = $(@DOMselector + " .conversations_sortByPref") modifySearch = $(@DOMselector + " .customSearchOpen") elsServicesButtons = $(@DOMselector + " button.servicesToSearch ") elsServicesActivePrefs = $(@DOMselector + " .customSearchServicePref input") showHidden = $(@DOMselector + " .showHidden") jumpToServiceCustomResults = $(@DOMselector + " #customSearchResults .jumpTo") @elsToUnbind = @elsToUnbind.concat(customSearchQueryInput, closeWidget, customSearchQuerySubmit, elsServicesButtons, customSearch_sortByPref, showHidden, jumpToServiceCustomResults, modifySearch) modifySearch.bind 'click', -> $(@DOMselector + " #customSearchQueryInput").focus() jumpToServiceCustomResults.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) pxFromTop = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).offset().top # offsetBy = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).outerHeight() + 40 $('body').scrollTop(pxFromTop - 100) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) ->" # console.debug ev serviceName = $(ev.target).data('servicename') # resultsBox__" + serviceInfoObject.name + # console.log @DOMselector + " .resultsBox__" + serviceName + " .hidden_listing" $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() elsServicesButtons.bind('click', (ev) => if $(ev.target).hasClass("dropdownLabel") serviceName = $(ev.target).attr('data-serviceName') # console.log serviceName # console.debug $(ev.target).attr('aria-pressed') ariaPressed = $(ev.target).attr('aria-pressed') if ariaPressed == 'true' $('button.dropDownPrefs_' + serviceName).removeClass('active') # console.log 'if ev.target.checked == "false" ' + serviceName $(@DOMselector + " input.tagPref_" + serviceName ).attr('disabled','disabled') else $('button.dropDownPrefs_' + serviceName).addClass('active') # console.log $(ev.target).attr('aria-pressed') + "asdfasdf" $(@DOMselector + " input.tagPref_" + serviceName ).removeAttr('disabled') $(ev.target).blur() ) customSearch_sortByPref.bind 'change', (ev) -> # console.log ' customSearch_sortByPref.val()' # console.log popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: '<KEY>' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) sendSearch = => queryString = customSearchQueryInput.val() elsServicesToSearch = $(@DOMselector + ' button.servicesToSearch[aria-pressed="true"]') # ariaPressed = $(ev.target).attr('aria-pressed') # if ariaPressed == 'true' servicesToSearch = {} for el in elsServicesToSearch serviceName = $(el).attr('data-serviceName') servicesToSearch[serviceName] = {} servicesToSearch[serviceName].customSearchTags = {} elTagPrefs = $(@DOMselector + " input.tagPref_" + serviceName + ":checked") for elTagPref in elTagPrefs tagName = $(elTagPref).val() servicesToSearch[serviceName].customSearchTags[tagName] = {} # console.log 'asfdasdfasdf ' + serviceName # console.debug servicesToSearch if queryString != '' parcel = msg: 'kiwiPP_post_customSearch' customSearchRequest: queryString: queryString servicesToSearch: servicesToSearch sendParcel(parcel) customSearchQueryInput.keypress (event) -> charCode = if event.keyCode then event.keyCode else event.which if charCode == 13 sendSearch() customSearchQuerySubmit.bind 'click', => sendSearch() closeWidget.bind 'click', => @widgetOpenBool = false @render('collapsed',popupParcel) customSearchQueryInput.focus() # showViewAndBindGoToViewButtons class View # basic building block constructor: (@name, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = "#" + @name + "_View" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @renderStates = @__renderStates__() return @ unbindView: => # console.log 'unbinding view' # console.debug @elsToUnbind # $(".userPreferencesSave").unbind() for el in @elsToUnbind el.unbind() @elsToUnbind = [] for widget in @Widgets widget.unbindWidget() render: (popupParcel, renderState = "__normal__") => @totalRenders++ @unbindView(@name) if !renderState? and !@renderStates.__normal__? console?.log 'ERROR: must declare renderState for view ' + @name + ' since __normal__ undefined' # console.log 'console.debug renderState ' + @name + renderState # console.log @totalRenders # console.debug @renderStates @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) class FixedView extends View constructor: (@name, @__renderStates__, uniqueSelectorPostfix) -> super @name, @__renderStates__ @DOMselector += uniqueSelectorPostfix # console.log @DOMselector class SwitchView extends View constructor: (@name, @__renderStates__) -> super @name, @__renderStates__ showView: => for _viewName, viewValue of switchViews if _viewName == @name # show # console.log 'showing ' + _viewName $('#' + _viewName + '_View').css({'display':'block'}) else # hide # console.log 'hiding ' + _viewName $('#' + _viewName + '_View').css({'display':'none'}) render: (popupParcel, renderState = "__normal__") => super popupParcel, renderState @showView() class Conversations extends SwitchView constructor: (@name) -> super @name, @__renderStates__ @Widgets = customSearch: new CustomSearch 'customSearch', @, false init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => # console.log ' in conversations view' # console.log popupParcel @Widgets['customSearch'].init(popupParcel) researchModeDisabledButtonsHTML = '' if popupParcel.urlBlocked == true or popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' or (popupParcel.oldUrl? and popupParcel.oldUrl == true) researchModeDisabledButtonsHTML += "<br> <div style='width:100%;text-align: center;'><button class='btn btn-success' style='font-size: 1.1em;display: inline-block;' id='researchUrlOverride'>Research this Url</button></div> <br>" if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' researchModeDisabledButtonsHTML += "<br> <div style='width:100%; text-align:center;'> Research Mode is off: &nbsp; <button class='goTo_userPreferencesView btn btn-xs btn-default' style='position:relative; bottom:2px;'> change settings </button> </div>" $("#researchModeDisabledButtons").html(researchModeDisabledButtonsHTML) resultsSummaryArray = [] resultsHTML = "" totalResults = 0 for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.allPreppedResults[serviceInfoObject.name]? and popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults.length > 0 service_PreppedResults = popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults totalResults += service_PreppedResults.length resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") resultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject,service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 resultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else if serviceInfoObject.submitTitle? submitUrl = serviceInfoObject.submitUrl submitTitle = serviceInfoObject.submitTitle resultsHTML += '<div class="serviceResultJumpTo">No conversation matches for ' + serviceInfoObject.title + '... <br> &nbsp;&nbsp;&nbsp;<a target="_blank" href="' + submitUrl + '">' + submitTitle + '</a></div><br>' else resultsHTML += '<div>No results for ' + serviceInfoObject.title + '</div>' preppedHTMLstring = '' if (popupParcel.urlBlocked == true and Object.keys(popupParcel.allPreppedResults).length < 2) # do nothing preppedHTMLstring += "<div style='width: 100%; text-align: justify; padding:20px; font-size:.9em; opacity:.9;'> <em> Certain super-high traffic URLs (or weird urls (like 'about:config' and chrome new tab pages)) have been excluded from auto-search out of respect for the APIs of the conversation sites. you can still manually search them by hitting the green button </em> </div><br>" else if ((totalResults > 0 and popupParcel.kiwi_userPreferences.researchModeOnOff == 'off') or popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or Object.keys(popupParcel.allPreppedResults).length > 1) preppedHTMLstring = '<br><h3 style="position:relative; top:-10px;">Results for this URL:</h3>' preppedHTMLstring += "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div><br>" preppedHTMLstring += resultsHTML $("#resultsByService").html(preppedHTMLstring) $(@DOMselector + " .hidden_listing").hide() if totalResults < 4 and @totalRenders < 4 fixedViews.kiwiSlice.render(popupParcel, "open") setTimeout( -> # to reign in a chrome rendering issue # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() , 300 ) # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() bind: (popupParcel) => showHidden = $(@DOMselector + " .showHidden") researchUrlOverrideButton = $(@DOMselector + " #researchUrlOverride") conversations_sortByPref = $(@DOMselector + " .conversations_sortByPref") customSearchOpen = $(@DOMselector + " .customSearchOpen") jumpToService = $("#resultsByService .jumpTo") @elsToUnbind = @elsToUnbind.concat(conversations_sortByPref, showHidden, researchUrlOverrideButton, customSearchOpen, jumpToService) jumpToService.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) # console.log serviceIndex pxFromTop = parseInt($($(@DOMselector + " #resultsByService .serviceResultJumpTo")[serviceIndex]).offset().top) # offsetBy = parseInt($($("#resultsByService .serviceResultsHeaderBar")[serviceIndex]).outerHeight()) + 40 $('body,html').scrollTop(pxFromTop - 100) customSearchOpen.bind 'click', -> $("#customSearchQueryInput").click() researchUrlOverrideButton.bind 'click', -> parcel = msg: 'kiwiPP_researchUrlOverrideButton' sendParcel(parcel) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) -> " # console.debug ev serviceName = $(ev.target).data('servicename') $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() conversations_sortByPref.bind 'change', (ev) -> # console.log "'conversations_sortByPref.bind 'change', (ev) ->" # console.log $(ev.target).val() popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: '<KEY>' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) class UserPreferences extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => $(@DOMselector + " .userErrMsg").html('') # console.log 'paint: adsfaeaewfawefawefawef(popupParcel) =># viewName = ' if preferencesOnlyPage is true $("#menuBar_preferences").hide() currentTime = Date.now() if popupParcel.kiwi_userPreferences.researchModeOnOff == "off" $("#autoOffTimer").html("Research mode is off, so auto-off timer is not set") else if popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp > currentTime $("#autoOffTimer").html("Auto-Off timer expires at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? $("#autoOffTimer").html("Auto-off timer last expired at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else $("#autoOffTimer").html("Auto-off timer is not set") researchModeHtml = '' if popupParcel.kiwi_userPreferences.researchModeOnOff is "off" researchOnString = "" researchOffString = " checked='checked' " else researchOnString = " checked='checked' " researchOffString = "" autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue `var auto20, auto60, autoAlways, autoCustom, autoCustomValue = ''; if(autoOffTimerType != null){ if(autoOffTimerType == "20"){ auto20 = " checked='checked' " } else if(autoOffTimerType == "60"){ auto60 = " checked='checked' " } else if(autoOffTimerType == "always"){ autoAlways = " checked='checked' " } else if(autoOffTimerType == "custom"){ autoCustom = " checked='checked' "; autoCustomValue = autoOffTimerValue;} }` researchModeHtml += 'Research Mode: <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;"><sup><em> ?</em></sup></div> <span style="bottom:34px; left:-114px;"> When the Research mode is "Off", Kiwi won\'t automatically search URLs as you surf; instead, you can check URLs on a case-by-case basis (and still be able to do custom searches) </span> </a> <label style="font-weight: normal;" for="researchmodeON"> on </label> <input id="researchmodeON" type="radio" name="research" value="on" ' + researchOnString + '> - <label style="font-weight: normal;" for="researchmodeOFF"> off </label> <input id="researchmodeOFF" type="radio" name="research" value="off" ' + researchOffString + '> &nbsp;&nbsp;<button class="btn btn-mini btn-default userPreferencesSave"> save preferences </button><br>' if popupParcel.kiwi_userPreferences.researchModeOnOff is 'off' researchModeHtml += '' timerDisabled = ' disabled ' timerOnlyUsefulWhenMessage = '<br> <span style="font-size:.8em;"><i> &nbsp;&nbsp;Note: the auto-off-timer only matters when Research Mode is "on". </i></span> <br>' else timerDisabled = ' ' researchModeHtml += '<br> <span style="font-size:.8em;"><i> Note: The Whitelist only makes a difference when Research mode is turned "off", which it currently isn\'t. </i></span> <br>' timerOnlyUsefulWhenMessage = '' researchModeHtml += ' <br> <table class="table table-bordered table-striped whitelistTable"> <thead> <tr> <th colspan="3"> <div class="input-group" id="addWhiteListString"> <label class="input-group-addon"> <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;">whitelist strings <sup><em> ?</em></sup></div> <span style="bottom:84px;left:-12px;"> <b>Whitelist strings:</b> <br> Kiwi will automatically research any URL (upon visiting) that contains a user-provided Whitelist string -- even when Research Mode is "off". Try it with "github.com" or "bitbucket.org", and then visit the respective site with research mode "off". </span> </a> </label> <input type="text" class="form-control ignoreSaveButtonListen"> <label class="input-group-addon btn btn-default"> add </label> </div> </th> </tr> </thead> <tbody> ' for whitelistSubString, index in popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch researchModeHtml += ' <tr> <th scope="row" style="width:35px;"> ' + (index + 1) + ' </th> <td> ' + whitelistSubString + ' </td> <td style="width:35px;"> <button title="remove" class="btn btn-xs btn-default removeWhitelistString" data-whitelistStringToRemove="' + whitelistSubString + '" > <span data-whitelistStringToRemove="' + whitelistSubString + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> </td> </tr>' researchModeHtml += ' </tbody> </table> <br>Auto-Off Timer set for: ' + timerOnlyUsefulWhenMessage + ' <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto20 + ' value="20"> 20 min</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto60 + ' value="60"> 1 hr</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoAlways + ' value="always"> Always On</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoCustom + ' value="custom"> Custom</label> &nbsp; &nbsp; <input ' + timerDisabled + ' id="autoCustomValue" type="text" value="' + autoCustomValue + '" size="4" disabled /> minutes' $("#researchModeDrop").html(researchModeHtml) servicesHtml = '' for service, index in popupParcel.kiwi_servicesInfo if service.active == "on" activeCheck = " checked='checked' " notActiveCheck = "" else activeCheck = "" notActiveCheck = " checked='checked' " servicesHtml += '<br> <div class="serviceListing listing"> <table><tbody><tr> <td class="upDownButtons">' if index != 0 servicesHtml += '<span title="Move ' + service.title + ' results above ' + popupParcel.kiwi_servicesInfo[index - 1].title + '" class="glyphicon glyphicon-chevron-up" id="' + service.name + '_moveServiceUp" aria-hidden="true"></span>' if index != 0 and index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<br><br>' if index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<span title="Move ' + service.title + ' results below ' + popupParcel.kiwi_servicesInfo[index + 1].title + '" class="glyphicon glyphicon-chevron-down" id="' + service.name + '_moveServiceDown" aria-hidden="true"></span>' brandedTitle = if (service.name is 'reddit') then "for " + service.title else service.title brandingImage = '' if service.brandingImage? brandingImage = "&nbsp;<a target='_blank' href='" + service.broughtToYouByURL + "' style='text-decoration:none;'> <img height='28' src='" + service.brandingImage + "'/></a>&nbsp;" servicesHtml += '</td> <td class="serviceInfo">' + brandedTitle + ' - using: ' + brandingImage + ' <a target="_blank" href="' + service.broughtToYouByURL + '">' + service.broughtToYouByTitle + '</a><br>' if service.name == "productHunt" specificAPIlink = ", <a target='_blank' href='https://github.com/producthunt/producthunt-api/wiki/Product-Hunt-APIs#algolia-search-api'>for PH</a>" if service.customSearchBroughtToYouByTitle? customSearchApiBrandingHTML = "<div class='bg-warning' style='margin:4px; margin-top:10px;padding:6px;'> <em><div style='padding-bottom:2px;'>&nbsp;&nbsp;&nbsp;&nbsp;custom searches are using: </div>" + ' <div style="padding-bottom:4px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a target="_blank" href="' + service.customSearchBroughtToYouByURL + '">' + service.customSearchBroughtToYouByTitle + '</a> ' + specificAPIlink + ' </em> </div> </em> </div>' else customSearchApiBrandingHTML = "" servicesHtml += '<div style="padding-left:15px;"> status: <label style="font-weight: normal;" for="' + service.name + '_serviceStatusON"> on </label> <input id="' + service.name + '_serviceStatusON" type="radio" name="' + service.name + '_serviceStatus" value="on" ' + activeCheck + '> - <label style="font-weight: normal;" for="' + service.name + '_serviceStatusOFF"> off </label> <input id="' + service.name + '_serviceStatusOFF" type="radio" name="' + service.name + '_serviceStatus" value="off" ' + notActiveCheck + '> <br><br>Results are deemed notable (capitilizes badge letter) if:' if service.name == 'gnews' servicesHtml += '<br><br> the topic has had <input id="' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit" type="text" size="4" value="' + service.notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit + '"/> or more related stories published within the last <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> hours <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> number of News Clusters <input id="' + service.name + '_numberOfRelatedItemsWithClusterURL" type="text" size="4" value="' + service.notableConditions.numberOfRelatedItemsWithClusterURL + '"/> </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' else servicesHtml += '<br> URL is an exact match, and: <br> it has been <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> or fewer hours since posting <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> a post has <input id="' + service.name + '_commentsNotable" type="text" size="4" value="' + service.notableConditions.num_comments + '"/> or more comments </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' servicesHtml += "<div class='serviceListing listing' style='padding:15px; margin-top: 30px;'> Wouldn't it be awesome if we could add some more services to opt-in to?&nbsp;&nbsp; All that's needed are friendly APIs!&nbsp; <a href='https://twitter.com/spencenow' target='_blank'>Tweet me</a> if you're interested in adding one! </div> <br>" $("#servicesInfoDrop").html(servicesHtml) bind: (popupParcel) => saveButtons = $(@DOMselector + " .userPreferencesSave") removeWhitelistStringButtons = $(@DOMselector + " .removeWhitelistString") autoTimerRadios = $(@DOMselector + " input:radio[name='researchAutoOffType']") allInputs = $(@DOMselector + ' input:not(.ignoreSaveButtonListen)') addWhitelistString_button = $(@DOMselector + " #addWhiteListString label") @elsToUnbind = @elsToUnbind.concat allInputs, saveButtons, autoTimerRadios, removeWhitelistStringButtons, addWhitelistString_button saveButtons.attr('disabled','disabled') allInputs.bind 'change', -> $(".userPreferencesSave").removeAttr('disabled') allInputs.bind 'focus', -> $(".userPreferencesSave").removeAttr('disabled') if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') autoTimerRadios.bind 'change', -> if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') else $("#autoCustomValue").attr('disabled','disabled') _bindDown = (downButton, index) => downButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index + 1) parcel = refreshView: 'userPreferences' keyName: '<KEY>' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) _bindUp = (upButton, index) => upButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index - 1 ) parcel = refreshView: 'userPreferences' keyName: '<KEY>' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) for service,index in popupParcel.kiwi_servicesInfo downButton = $("#" + service.name + '_moveServiceDown') if downButton.length > 0 @elsToUnbind.push downButton _bindDown(downButton, index) upButton = $("#" + service.name + '_moveServiceUp') if upButton.length > 0 @elsToUnbind.push upButton _bindUp(upButton, index) postError = (userErrMsg) => # console.log 'trying to post error ' + userErrMsg $(@DOMselector + " .userErrMsg").html("<br>" + userErrMsg) addWhitelistString_button.bind 'click', (ev) => # whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') whitelistSubString_toAdd = $(@DOMselector + " #addWhiteListString input").val() popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch.push whitelistSubString_toAdd parcel = refreshView: 'userPreferences' keyName: '<KEY>' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) removeWhitelistStringButtons.bind 'click', (ev) -> whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') newWhitelistAnyMatchArray = _.without(popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch, whitelistSubString); popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch = newWhitelistAnyMatchArray parcel = refreshView: 'userPreferences' keyName: '<KEY>' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) saveButtons.bind 'click', -> researchModeHTMLval = $("input:radio[name='research']:checked").val() # console.log 'researchModeHTMLval is ' + researchModeHTMLval if researchModeHTMLval != 'on' and researchModeHTMLval != 'off' postError('research mode must be "on" or "off"'); return 0; allowedAutoOffTypes = ["20","60","always","custom"] autoOffTimerType = $("input:radio[name='researchAutoOffType']:checked").val() autoOffTimerValue = $("#autoCustomValue").val() if autoOffTimerType in allowedAutoOffTypes if autoOffTimerType == 'custom' and (autoOffTimerValue == '' or isNaN(autoOffTimerValue)) postError('Must specify a number of minutes for auto-off timer.'); return 0; else postError('not acceptable autoOffTimerType'); return 0; # autoOffAtUTCmilliTimestamp for service, index in popupParcel.kiwi_servicesInfo if service.name == 'gnews' active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() if numberOfStoriesFoundWithinTheHoursSincePostedLimit == '' or isNaN(numberOfStoriesFoundWithinTheHoursSincePostedLimit) postError('number Of Stories Found Within The Hours Since Posted Limit must be an integer'); return 0; numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() if numberOfRelatedItemsWithClusterURL == '' or isNaN(numberOfRelatedItemsWithClusterURL) postError('number Of Related Items With Cluster URL of comments must be an integer'); return 0; else active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; hoursSincePosted = $('#' + service.name + '_hoursNotable').val() if hoursSincePosted == '' or isNaN(hoursSincePosted) postError('Hours must be an number'); return 0; num_comments = $('#' + service.name + '_commentsNotable').val() if num_comments == '' or isNaN(num_comments) postError('Number of comments must be an integer'); return 0; # console.log '1234' popupParcel.kiwi_userPreferences.researchModeOnOff = researchModeHTMLval if (autoOffTimerType != 'custom') popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType else popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType popupParcel.kiwi_userPreferences.autoOffTimerValue = parseFloat(autoOffTimerValue) for service, index in popupParcel.kiwi_servicesInfo active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() popupParcel.kiwi_servicesInfo[index].active = active # notableSound = $("input:radio[name='" + service.name + "_soundStatus']:checked").val() # popupParcel.kiwi_servicesInfo[index].notableSound = notableSound hoursSincePosted = $('#' + service.name + '_hoursNotable').val() # console.log popupParcel.kiwi_servicesInfo[index].name # console.log "hoursSincePosted = $('#' + service.name + '_hoursNotable').val() " + hoursSincePosted popupParcel.kiwi_servicesInfo[index].notableConditions.hoursSincePosted = parseFloat(hoursSincePosted) if service.name == 'gnews' numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfRelatedItemsWithClusterURL = parseInt(numberOfRelatedItemsWithClusterURL) numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit = parseInt(numberOfStoriesFoundWithinTheHoursSincePostedLimit) else num_comments = $('#' + service.name + '_commentsNotable').val() popupParcel.kiwi_servicesInfo[index].notableConditions.num_comments = parseInt(num_comments) popupParcel.view = 'userPreferences' # console.log '4567' # console.debug popupParcel parcel = refreshView: popupParcel.view newPopupParcel: popupParcel msg: 'kiwiPP_post_savePopupParcel' sendParcel(parcel) class Credits extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class Loading extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class KiwiSlice extends FixedView constructor: (@name, uniqueSelectorPostfix) -> super @name, @__renderStates__, uniqueSelectorPostfix init: (popupParcel, renderState = null) => @renderStateTransitions = @__renderStateTransitions__() # console.log 'hehehehee init: (popupParcel, renderState = null) =>' @unbindView() renderState = if renderState? then renderstate else "collapsed" # console.log ' renderState = if renderState? then renderstate else "collapsed" ' + renderState @render(popupParcel, 'collapsed') render: (popupParcel, renderState, fromState = null) => # console.log 'in render for kiwi' __renderStates__callback = (popupParcel, renderState) => super popupParcel, renderState if fromState? and @renderStateTransitions[fromState + "__to__" + renderState]? # console.log 'yep, has renderstate' @renderStateTransitions[fromState + "__to__" + renderState](popupParcel, renderState, __renderStates__callback) else super popupParcel, renderState __renderStates__: => collapsed: paint: (popupParcel) => kiwiSliceHTML = '<div id="sliceActivateTransition" style="position:fixed; bottom: -33px; right: -33px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) bind: (popupParcel) => elActivateTransition = $(@DOMselector + " #sliceActivateTransition") @elsToUnbind = @elsToUnbind.concat elActivateTransition elActivateTransition.bind 'mouseover', (ev) => elActivateTransition.addClass('rotateClockwiseFull') elActivateTransition.bind 'mouseout', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') elActivateTransition.bind 'click', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') @render(popupParcel,'open', 'collapsed') open: paint: (popupParcel) => # console.log 'painting ' + @name kiwiSliceHTML = '<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter"> <button type="button" class=" goTo_creditsView btn btn-mini btn-default">credits</button> <a class="btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class=" btn btn-mini btn-default" id="clearKiwiURLCache">clear cache</button> <button class=" btn btn-mini btn-default" id="refreshURLresults">refresh</button> </div> <div id="sliceActivateTransition" style="position:fixed; bottom: 15px; right: 15px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) # console.log kiwiSliceHTML bind: (popupParcel) => # console.log 'binding ' + @name elActivateTransition = $(@DOMselector + " #sliceActivateTransition") clearKiwiURLCacheButton = $(@DOMselector + " #clearKiwiURLCache") refreshURLresultsButton = $(@DOMselector + " #refreshURLresults") @elsToUnbind = @elsToUnbind.concat elActivateTransition, refreshURLresultsButton, clearKiwiURLCacheButton refreshURLresultsButton.bind 'click', -> parcel = msg: 'kiwiPP_refreshURLresults' sendParcel(parcel) $('body').mouseup((e) => # console.log 'test test test' container = $(@DOMselector) if (!container.is(e.target) && container.has(e.target).length == 0) $('body').unbind 'mouseup' @render(popupParcel,'collapsed', 'open') ) elActivateTransition.bind 'click', (ev) => @render(popupParcel,'collapsed', 'open') clearKiwiURLCacheButton.bind 'click', -> parcel = msg: 'kiwiPP_clearAllURLresults' sendParcel(parcel) # \/ \/ \/ THIS IS A WORK IN PROGRESS \/ \/ \/ __renderStateTransitions__: => 'open__to__collapsed': (popupParcel, renderState, __renderStates__callback) => $(@DOMselector + " #transition_open_showMe").animate({'opacity':0}, 300) $(@DOMselector + " #sliceActivateTransition").addClass('rotateClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '-33px', "right": "-33px"}, { duration: 500, complete: -> __renderStates__callback(popupParcel, renderState) }) # return transitionObj 'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) => # console.log "'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) =>" $(@DOMselector + " #sliceActivateTransition").addClass('rotateCounterClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '15px', "right": "15px"}, { duration: 500, complete: -> # console.log 'we are done with animation' __renderStates__callback(popupParcel, renderState) }) $(@DOMselector).prepend('<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter" style="opacity: 0;"> <button type="button" class="goTo_creditsView btn btn-mini btn-default ">credits</button> <a class=" btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class="btn btn-mini btn-default " id="clearKiwiURLCache">clear cache</button> <button class="btn btn-mini btn-default " id="refreshURLresults">refresh</button> </div>') # setTimeout => $(@DOMselector + " #transition_open_showMe").animate({'opacity':1}, 499) # , 200 fixedViews = kiwiSlice: new KiwiSlice 'kiwiSlice', 'FixedBottom' switchViews = conversations: new Conversations 'conversations' userPreferences: new UserPreferences 'userPreferences' credits: new Credits 'credits' loading: new Loading 'loading' tailorResults = productHunt: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() fuzzyMatchBool = false brandingDisplay = '' if serviceInfoObject.brandingImage? brandingDisplay = '<img style="margin-left:7px;" title="' + serviceInfoObject.title + '" height="28" src="' + serviceInfoObject.brandingImage + '"/> &nbsp;&nbsp; <span class="serviceResultsTitles" style="color:black; position: relative;top: 6px;"">' + serviceInfoObject.title + '</span>' else brandingDisplay = "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" + brandingDisplay + "</div>" # recency doesn't make sense for PH # if kiwi_userPreferences.sortByPref == 'attention' # selectedString_attention = 'selected' # selectedString_recency = '' # else # selectedString_attention = '' # selectedString_recency = 'selected' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_num_comments') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else if (listing.kiwi_created_at? and currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) recentTag = "<span class='recentListingTag'>Recent: </span>" else recentTag = "" if listing.kiwi_makers.length > 3 gridLayoutBool = false else gridLayoutBool = true preppedHTMLstring += '<div class="listing ' + listingClass + '">' # kiwi_created_at: 1439471020625 # kiwi_author_headline: "Community @ProductHunt. " # kiwi_author_name: "<NAME>" # kiwi_author_username: "bentossell" # kiwi_discussion_url: "http://www.producthunt.com/tech/buffer-for-video" # kiwi_makers: Array[9] # headline: "Co-founder/CEO, Buffer" # name: "<NAME>" # profile_url: "http://www.producthunt.com/@joelgascoigne" # username: "joelgascoigne" # website_url: "http://joel.is" # kiwi_num_comments: 30 # kiwi_score: 244 # name: "Buffer for Video" # tagline: "All-in-one video scheduling & management for social media" # redirect_url: "http://www.producthunt.com/r/4918f991fdd705/30839?app_id=1674" # screenshot_url: Object if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 60%; padding-right:8px;">' else preppedHTMLstring += '<div>' preppedHTMLstring += ' <a class="listingTitle" target="_blank" href="' + listing.kiwi_discussion_url + '"> <div style="color:black; padding:4px; padding-bottom: 8px; font-size: 1.1em;">' + recentTag + ' <b>' + listing.name + '</b> </div> <div style="color:#4D586F; padding-left:18px;"> <div style="padding-bottom:4px;">"' + listing.tagline + '"</div>' preppedHTMLstring += '<div style="padding-bottom:4px;"> ' + listing.kiwi_num_comments + ' comments, ' + listing.kiwi_score + ' upvotes </div>' if listing.kiwi_created_at? _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += '' + _time preppedHTMLstring += '</div></a></div>' if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 39%;">' else preppedHTMLstring += '<div style="padding: 8px;">' makerUsernames = [] if listing.kiwi_makers? and listing.kiwi_makers.length > 0 preppedHTMLstring += '<div><div style="padding-bottom:2px;"><b>made by</b>: </div>' for maker in listing.kiwi_makers if gridLayoutBool preppedHTMLstring += '<div style="padding-bottom: 4px;">' else preppedHTMLstring += '<div style="padding-bottom: 4px; padding-left: 10px;">' preppedHTMLstring += '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + maker.username + '" style="color:#727E98;">' + maker.name if maker.headline? and maker.headline != "" preppedHTMLstring += ', "' + maker.headline + '"' preppedHTMLstring += '</a>' if maker.website_url? preppedHTMLstring += ' <a href="' + maker.website_url + '" target="_blank"><span class="glyphicon glyphicon-log-in" style="color:blue;"></span> </a>' if listing.kiwi_author_username == maker.username preppedHTMLstring += " (also submitted post)" preppedHTMLstring += '</div>' preppedHTMLstring += '</div>' makerUsernames.push maker.username if listing.kiwi_author_username not in makerUsernames if gridLayoutBool gridLayoutAuthorDiv = '<div style="padding-bottom: 2px;">' else gridLayoutAuthorDiv = '<div style="padding-bottom: 2px; margin-left: 10px;">' preppedHTMLstring += '<div style=""> <div style="padding-bottom:2px;"><b>submitted by:</b></div> ' + gridLayoutAuthorDiv + '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.kiwi_author_username + '" style="color:#727E98;">' + listing.kiwi_author_name + ' ' if listing.kiwi_author_headline? and listing.kiwi_author_headline != "" preppedHTMLstring += ', "' + listing.kiwi_author_headline + '"' preppedHTMLstring += '</a></div></div>' preppedHTMLstring += '</div></div>' preppedHTMLstring += "</div>" return preppedHTMLstring hackerNews: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) reddit: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) _tailorHNcomment = (listing, serviceInfoObject, listingClass) -> currentTime = Date.now() commentHtml = "" # story_text # comment_text # story_id # story_title # story_url recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" commentHtml += '<div class="listing ' + listingClass + ' " style="position:relative;">' + recentTag if listing.over_18? and listing.over_18 is true commentHtml += '<span class="nsfw">NSFW</span> For story: ' + listing.story_title + '<br>' else commentHtml += "For story: <a target='_blank' href='" + serviceInfoObject.permalinkBase + listing.story_id + "'>" + listing.story_title + '</a><br>' _time = formatTime(listing.kiwi_created_at) commentHtml += 'at ' + _time + ', <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '">' + listing.author + '</a> recieved ' + listing.kiwi_score + ' upvotes, by saying: ( <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"> comment permalink </a> , <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.story_id + '"> story permalink </a> )<br><div class="commentBox"> ' + listing.comment_text + ' </div></div>' return commentHtml tailorRedditAndHNresults_returnHtml = (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() # kiwi_exact_match # fuzzy matches # linkify stuff fuzzyMatchBool = false preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" if serviceInfoObject.name == 'reddit' preppedHTMLstring += "<span class='serviceResultsTitles'>for " + serviceInfoObject.title + ':</span>' else preppedHTMLstring += "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' if kiwi_userPreferences.sortByPref == 'attention' selectedString_attention = 'selected' selectedString_recency = '' else selectedString_attention = '' selectedString_recency = 'selected' preppedHTMLstring += '<div style="float:right; padding-top: 9px;"> &nbsp;&nbsp sorted by: <select class="conversations_sortByPref"> <option ' + selectedString_attention + ' id="_attention" value="attention">attention</option> <option ' + selectedString_recency + ' id="_recency" value="recency">recency</option> </select></div> </div>' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else if !service_PreppedResults[0].comment_text? and kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'num_comments') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_score') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'recency' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_created_at') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" if listing.kiwi_exact_match # preppedHTMLstring += '<div class="listing ' + listingClass + '" style="position:relative;">' + recentTag + ' # <div style="float:right;"> # <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> # </div> # <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '">' preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes -- ' + _time + '</span></a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a> </div>' preppedHTMLstring += '<br></div>' else fuzzyMatchBool = true if fuzzyMatchBool numberOfExactMatches = _.reduce(service_PreppedResults, (memo, obj) -> if obj.kiwi_exact_match memo++ return memo else memo ) if (service_PreppedResults.length - numberOfExactMatches) > 10 and service_PreppedResults.length > 14 listingClass = ' hidden_listing ' else listingClass = '' # listingClass = if nonFuzzyItemCounter > 10 then ' hidden_listing ' else '' preppedHTMLstring += '<div class="showFuzzyMatches ' + listingClass + '" style="position:relative;"> fuzzy matches: <br></div> <span class="fuzzyMatches">' # console.log 'fuzzy matches 12312312 ' + serviceInfoObject.name for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if !listing.kiwi_exact_match recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes ' + formatTime(listing.kiwi_created_at) + '</span> <br> for Url: <span class="altURL">' + listing.url + '</span> </a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a></div>' preppedHTMLstring += '<br></div>' preppedHTMLstring += "</span>" preppedHTMLstring += "</div>" return preppedHTMLstring bindGoToViewButtons = (buttonEls, viewName, viewData) -> for el in buttonEls $(el).bind('click', (ev) -> # console.log 'clicked ' + viewName switchViews[viewName].render(viewData) ) moveArrayElement = (array, from, to) -> array.splice(to, 0, array.splice(from, 1)[0]); return array getRandom = (min, max) -> return min + Math.floor(Math.random() * (max - min + 1)) formatTime = (utcMillisecondTimestamp) -> a = new Date(utcMillisecondTimestamp) months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] year = a.getFullYear() month = months[a.getMonth()] date = a.getDate() hour = a.getHours() min = a.getMinutes() sec = a.getSeconds() amOrPm = if hour > 11 then 'pm' else 'am' if hour > 12 hour = hour - 12 else if parseInt(hour) == 0 hour = 12 if min < 10 min = '0' + min time = month + ' ' + date + ', ' + year + ' - ' + hour + ':' + min + amOrPm return time renderExtensionHeight = (elementSelector, extraPx) -> if viewElementId is elementSelector extraPx = 2 extHeight_ = $(elementSelector).outerHeight() + extraPx if extHeight_ > 590 extHeight_ = 590 # $('html').css('height',extHeight+'px') $('body').css('height', extHeight_ + 'px') `heightString = extHeight_.toString() +'px'` $('html').css('min-height', heightString) extHeight_-- $('body').css('min-height', heightString) capitalizeFirstLetter = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) # // http://css-tricks.com/snippets/javascript/htmlentities-for-javascript/ htmlEntities = (str) -> return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); getURLParam = (oTarget, sVar) -> return decodeURI(oTarget.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); algoliaPHclient = null algoliaPHindex = null initAlgoliaPHcustomSearch = -> algoliaPHclient = algoliasearch('0H4SMABBSG', '9670d2d619b9d07859448d7628eea5f3') algoliaPHindex = algoliaPHclient.initIndex('Post_production') initAlgoliaPHcustomSearch() fetchAlgoliaProductHuntResultsFirst = (parcel) -> # console.log 'yoyoyo here ' + parcel.customSearchRequest.queryString # console.log parcel # not ideal because it's blocking, and it'd be better to have persistent index object # but the restrictions in FF addons force this approach. if algoliaPHindex? algoliaPHindex.search(parcel.customSearchRequest.queryString, (err, content) -> # // err is either `null` or an `Error` object, with a `message` property # // content is either the result of the command or `undefined` if (err) console.error(err) parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) return 0 if content? and content.hits? parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = content.hits else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] # console.log 'sending this PH' # console.log parcel.customSearchRequest.servicesToSearch.productHunt.rawResults self.port.emit('kiwiPP_post_customSearch', parcel) ) else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) sendParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_acknowledgeMessage' self.port.emit('kiwiPP_acknowledgeMessage', parcel); when 'kiwiPP_refreshSearchQuery' # port.postMessage(parcel) self.port.emit('kiwiPP_refreshSearchQuery', parcel); when 'kiwiPP_post_customSearch' # not ideal because it's blocking, but the restrictions in FF addons force this approach if parcel.customSearchRequest.servicesToSearch.productHunt? fetchAlgoliaProductHuntResultsFirst(parcel) else port.postMessage(parcel) when 'kiwiPP_request_popupParcel' self.port.emit('kiwiPP_request_popupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_savePopupParcel' self.port.emit('kiwiPP_post_savePopupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_save_a_la_carte' self.port.emit('kiwiPP_post_save_a_la_carte', parcel) # port.postMessage(parcel) when 'kiwiPP_clearAllURLresults' self.port.emit('kiwiPP_clearAllURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_refreshURLresults' self.port.emit('kiwiPP_refreshURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_researchUrlOverrideButton' self.port.emit('kiwiPP_researchUrlOverrideButton', parcel) # port.postMessage(parcel) receiveParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_popupParcel_ready' initialize(parcel.popupParcel) self.port.on('kiwi_fromBackgroundToPopup', (parcel) -> receiveParcel(parcel) )
true
viewElementId = '' renderedBool = false preferencesOnlyPage = false initialize = (popupParcel) -> # console.log 'in init' if getURLParam(window.location, 'optionsOnly') != '' preferencesOnlyPage = true switchViews.userPreferences.render(popupParcel) return 0 for viewName, view of fixedViews view.init(popupParcel) # views.userPreferences.render(popupParcel) if popupParcel.view? and switchViews[popupParcel.view]? switchViews[popupParcel.view].render(popupParcel) else switchViews.conversations.render(popupParcel) class Widget # basic building block constructor: (@name, @parentView, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = @parentView.DOMselector + " #" + @name + "_Widget" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews # console.log _viewName # bind to goToView buttons els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') # console.debug els_goTo_view @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @unbindWidget = => for el in @elsToUnbind el.unbind() @elsToUnbind = [] @render = (renderState, popupParcel) => @totalRenders++ @unbindWidget(@name) @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) @renderStates = @__renderStates__() return @ class MessageCenter extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ # console.log ' trying ' super @name, @parentView, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render('showMessages',popupParcel) __renderStates__: => showMessages: paint: (popupParcel) => # console.log 'messagesHTML = "" # console.debug popupParcel' messagesHTML = "" # console.debug popupParcel if popupParcel.kiwi_userMessages.length > 0 messagesHTML += '<div style="padding-top:4px; padding-bottom:10px;">' for messageObj in popupParcel.kiwi_userMessages messagesHTML += '<div class="bg-warning" style="margin:6px; padding:8px; text-align:justify;"> <button style="float:right; margin:8px; padding:4px; padding-right:6px; padding-left:6px;" class="btn btn-xs btn-default acknowledgeMessage" data-messageToAcknowledge="' + messageObj.name + '" > <span title="remove" data-messageToAcknowledge="' + messageObj.name + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> ' + messageObj.baseValue + ' &nbsp; </div>' messagesHTML += '<div style="width:100%; text-align:center;"> <b>message priority</b>: urgent. &nbsp;&nbsp; please acknowledge the message(s) by clicking the "x" button(s). Thanks! :) </div></div>' $(@DOMselector).html(messagesHTML) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => if popupParcel.kiwi_userMessages.length > 0 # console.log 'bind: (popupParcel) =>' ackMessageButtons = $(@DOMselector + ' .acknowledgeMessage') @elsToUnbind = @elsToUnbind.concat ackMessageButtons ackMessageButtons.bind 'click', (ev) => console.log "trying for ackMessageButtons.bind 'click', (ev) =>" messageToAcknowledge = $(ev.target).attr('data-messageToAcknowledge') console.log 'messageToAcknowledge ' + messageToAcknowledge # console.debug popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch # console.debug whitelistSubString parcel = messageToAcknowledge: messageToAcknowledge msg: 'kiwiPP_acknowledgeMessage' sendParcel(parcel) class CustomSearch extends Widget constructor: (@name, @parentView, @widgetOpenBool) -> # console.debug @__renderStates__ super @name, @parentView, @__renderStates__ init: (popupParcel) -> @Widgets = {messageCenter: new MessageCenter 'messageCenter', @, false} @unbindWidget() if @widgetOpenBool == false @render('collapsed',popupParcel) else @render('opened',popupParcel) __renderStates__: => collapsed: paint: (popupParcel) => openedCustomSearchHTML = ' <div class="topSearchBar" style="padding-bottom: 14px;"> <div class="evenlySpacedContainer"> <input class="queryInputOpen" id="customSearchQueryInput" type="text" placeholder=" combined search" /> <button class="btn btn-mini btn-default goTo_userPreferencesView">User Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> ' if popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' openedCustomSearchHTML += "<div style='padding-top: 12px;'><a id='openPreviousSearch'>see custom results for '" + popupParcel.kiwi_customSearchResults.queryString + "' </a> &nbsp;&nbsp;&nbsp;&nbsp; <a id='clearPreviousSearch'>clear</a></div>" openedCustomSearchHTML += " <div id='messageCenter_Widget'></div> </div> <div class='notFixed'></div>" $(@DOMselector).html(openedCustomSearchHTML) # console?.log 'console.log @DOMselector + " .topSearchBar"' + @DOMselector + " .topSearchBar" duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight closed' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) # $(@DOMselector + " .notFixed").css({'height':fixedHeight + "px"}) bind: (popupParcel) => # console.log 'bind: (popupParcel) =>' inputSearchQueryInput = $("#customSearchQueryInput") previousSearchLink = $("#openPreviousSearch") clearPreviousSearch = $("#clearPreviousSearch") @elsToUnbind = @elsToUnbind.concat inputSearchQueryInput, previousSearchLink, clearPreviousSearch previousSearchLink.bind 'click', -> $("#customSearchQueryInput").click() clearPreviousSearch.bind 'click', -> parcel = msg: 'kiwiPP_refreshSearchQuery' sendParcel(parcel) inputSearchQueryInput.bind 'click', => # console.log '@widgetOpenBool = true' @widgetOpenBool = true @render('opened',popupParcel) opened: paint: (popupParcel) => # console.log 'popupParcel.kiwi_servicesInfo.length' # console.log popupParcel.kiwi_servicesInfo.length queryString = if popupParcel.kiwi_customSearchResults.queryString? then popupParcel.kiwi_customSearchResults.queryString else '' openedCustomSearchHTML = '<div class="topSearchBar"> <div class="evenlySpacedContainer"> <input id="customSearchQueryInput" value="' + queryString + '" type="text" placeholder=" combined search" style="width:234px; margin-right: 10px;" /> <button class="btn btn-mini btn-default" id="customSearchQuerySubmit" style="margin-right: 10px;">Submit</button> <button style="" class="goTo_userPreferencesView btn btn-mini btn-default"> Options <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button> </div> <br> <div class="evenlySpacedContainer" style="position: relative; top: -8px; margin-bottom: 3px;">' for serviceInfoObject in popupParcel.kiwi_servicesInfo openedCustomSearchHTML += '<div>' # console.log 'asdfasdf ' + serviceInfoObject.name # console.debug serviceInfoObject if serviceInfoObject.active == 'off' serviceDisabledAttr = ' disabled title="Service must be active, can be changed in options." ' else serviceDisabledAttr = ' ' if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? activeClass = ' active ' ariaPressedState = 'true' else if !popupParcel.kiwi_customSearchResults.servicesSearchesRequested? activeClass = if serviceInfoObject.active is 'off' then ' ' else ' active ' ariaPressedState = if serviceInfoObject.active is 'off' then 'false' else 'true' else activeClass = ' ' ariaPressedState = 'false' if serviceInfoObject.customSearchTags? and Object.keys(serviceInfoObject.customSearchTags).length > 0 openedCustomSearchHTML += '<div class="btn-group"> <button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" ' + serviceDisabledAttr + ' class="servicesToSearch btn btn-default btn-mini dropdownLabel ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button> <button ' + serviceDisabledAttr + ' data-toggle="dropdown" class="btn btn-default dropdown-toggle ' + activeClass + ' dropDownPrefs_' + serviceInfoObject.name + '" data-placeholder="false"><span class="caret"></span></button> <ul class="dropdown-menu">' for tagName, tagObject of serviceInfoObject.customSearchTags if popupParcel.kiwi_customSearchResults.servicesSearchesRequested? and popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name]? if popupParcel.kiwi_customSearchResults.servicesSearchesRequested[serviceInfoObject.name].customSearchTags[tagName]? tagActiveChecked = ' checked ' else tagActiveChecked = '' else tagActiveChecked = if tagObject.include is true then ' checked ' else '' tagDisabledAttr = if serviceInfoObject.active is 'off' then ' disabled title="Service must be active, can be changed in options." ' else '' openedCustomSearchHTML += '<li><input ' + tagActiveChecked + tagDisabledAttr + ' type="checkbox" value="' + tagName + '" class="tagPref tagPref_' + serviceInfoObject.name + '" id="' + serviceInfoObject.name + tagName + '"> <label for="' + serviceInfoObject.name + tagName + '"> ' + tagObject.title + ' </label></li>' openedCustomSearchHTML += '</ul></div>' else openedCustomSearchHTML += '<button data-toggle="button" aria-pressed="' + ariaPressedState + '" autocomplete="off" type="button" class="servicesToSearch btn btn-mini btn-default ' + activeClass + '" data-serviceName="' + serviceInfoObject.name + '"> ' + serviceInfoObject.title + ' </button>' openedCustomSearchHTML += '</div>' openedCustomSearchHTML += '<div> <button aria-pressed="false" autocomplete="off" type="button" class="btn btn-mini btn-default" id="close__' + @name + '" > close <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </div> </div>' openedCustomSearchHTML += ' <div id="messageCenter_Widget">asdfasd</div> </div> <div class="notFixed"></div> <div id="customSearchResults"></div> ' resultsSummaryArray = [] customSearchResultsHTML = "" if popupParcel.kiwi_customSearchResults? and popupParcel.kiwi_customSearchResults.queryString? and popupParcel.kiwi_customSearchResults.queryString != '' for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name]? service_PreppedResults = popupParcel.kiwi_customSearchResults.servicesSearched[serviceInfoObject.name].results resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") customSearchResultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject, service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 customSearchResultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else customSearchResultsHTML += '<br>No results for ' + serviceInfoObject.title + '<br>' # customSearchResultsHTML += '</div>' else customSearchResultsHTML += '<div id="customSearchResultsDrop"><br>No results to show... make a search! :) </div><br>' customSearchResultsHTML = "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div>" + customSearchResultsHTML customSearchResultsHTML += "<br>" $(@DOMselector).html(openedCustomSearchHTML) $(@DOMselector + " #customSearchResults").html(customSearchResultsHTML) $(@DOMselector + " .hidden_listing").hide() duplicateFixedHeight = => fixedElHeight = $(@DOMselector + " .topSearchBar").outerHeight() # console.log 'console.log fixedElHeight opened' # console.log fixedElHeight if popupParcel.kiwi_userMessages? and popupParcel.kiwi_userMessages.length > 0 fixedElHeight += 70 + popupParcel.kiwi_userMessages.length * 60 if fixedElHeight == 0 setTimeout -> # defer to next browser event tick duplicateFixedHeight() , 0 else $(@DOMselector + " .notFixed").css({'height':fixedElHeight + "px"}) duplicateFixedHeight() @Widgets.messageCenter.render('showMessages', popupParcel) bind: (popupParcel) => customSearchQueryInput = $(@DOMselector + " #customSearchQueryInput") customSearchQuerySubmit = $(@DOMselector + " #customSearchQuerySubmit") closeWidget = $(@DOMselector + ' #close__' + @name) customSearch_sortByPref = $(@DOMselector + " .conversations_sortByPref") modifySearch = $(@DOMselector + " .customSearchOpen") elsServicesButtons = $(@DOMselector + " button.servicesToSearch ") elsServicesActivePrefs = $(@DOMselector + " .customSearchServicePref input") showHidden = $(@DOMselector + " .showHidden") jumpToServiceCustomResults = $(@DOMselector + " #customSearchResults .jumpTo") @elsToUnbind = @elsToUnbind.concat(customSearchQueryInput, closeWidget, customSearchQuerySubmit, elsServicesButtons, customSearch_sortByPref, showHidden, jumpToServiceCustomResults, modifySearch) modifySearch.bind 'click', -> $(@DOMselector + " #customSearchQueryInput").focus() jumpToServiceCustomResults.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) pxFromTop = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).offset().top # offsetBy = $($(@DOMselector + " #customSearchResults .serviceResultJumpTo")[serviceIndex]).outerHeight() + 40 $('body').scrollTop(pxFromTop - 100) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) ->" # console.debug ev serviceName = $(ev.target).data('servicename') # resultsBox__" + serviceInfoObject.name + # console.log @DOMselector + " .resultsBox__" + serviceName + " .hidden_listing" $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() elsServicesButtons.bind('click', (ev) => if $(ev.target).hasClass("dropdownLabel") serviceName = $(ev.target).attr('data-serviceName') # console.log serviceName # console.debug $(ev.target).attr('aria-pressed') ariaPressed = $(ev.target).attr('aria-pressed') if ariaPressed == 'true' $('button.dropDownPrefs_' + serviceName).removeClass('active') # console.log 'if ev.target.checked == "false" ' + serviceName $(@DOMselector + " input.tagPref_" + serviceName ).attr('disabled','disabled') else $('button.dropDownPrefs_' + serviceName).addClass('active') # console.log $(ev.target).attr('aria-pressed') + "asdfasdf" $(@DOMselector + " input.tagPref_" + serviceName ).removeAttr('disabled') $(ev.target).blur() ) customSearch_sortByPref.bind 'change', (ev) -> # console.log ' customSearch_sortByPref.val()' # console.log popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) sendSearch = => queryString = customSearchQueryInput.val() elsServicesToSearch = $(@DOMselector + ' button.servicesToSearch[aria-pressed="true"]') # ariaPressed = $(ev.target).attr('aria-pressed') # if ariaPressed == 'true' servicesToSearch = {} for el in elsServicesToSearch serviceName = $(el).attr('data-serviceName') servicesToSearch[serviceName] = {} servicesToSearch[serviceName].customSearchTags = {} elTagPrefs = $(@DOMselector + " input.tagPref_" + serviceName + ":checked") for elTagPref in elTagPrefs tagName = $(elTagPref).val() servicesToSearch[serviceName].customSearchTags[tagName] = {} # console.log 'asfdasdfasdf ' + serviceName # console.debug servicesToSearch if queryString != '' parcel = msg: 'kiwiPP_post_customSearch' customSearchRequest: queryString: queryString servicesToSearch: servicesToSearch sendParcel(parcel) customSearchQueryInput.keypress (event) -> charCode = if event.keyCode then event.keyCode else event.which if charCode == 13 sendSearch() customSearchQuerySubmit.bind 'click', => sendSearch() closeWidget.bind 'click', => @widgetOpenBool = false @render('collapsed',popupParcel) customSearchQueryInput.focus() # showViewAndBindGoToViewButtons class View # basic building block constructor: (@name, @__renderStates__) -> @elsToUnbind = [] @totalRenders = 0 @DOMselector = "#" + @name + "_View" @Widgets = {} @bindAllGoToViewButtons = (viewData) => for _viewName, viewValue of switchViews els_goTo_view = $(@DOMselector + ' .goTo_' + _viewName + 'View') @elsToUnbind.push els_goTo_view bindGoToViewButtons(els_goTo_view, _viewName, viewData) @renderStates = @__renderStates__() return @ unbindView: => # console.log 'unbinding view' # console.debug @elsToUnbind # $(".userPreferencesSave").unbind() for el in @elsToUnbind el.unbind() @elsToUnbind = [] for widget in @Widgets widget.unbindWidget() render: (popupParcel, renderState = "__normal__") => @totalRenders++ @unbindView(@name) if !renderState? and !@renderStates.__normal__? console?.log 'ERROR: must declare renderState for view ' + @name + ' since __normal__ undefined' # console.log 'console.debug renderState ' + @name + renderState # console.log @totalRenders # console.debug @renderStates @renderStates[renderState].paint(popupParcel) @bindAllGoToViewButtons(popupParcel) @renderStates[renderState].bind(popupParcel) class FixedView extends View constructor: (@name, @__renderStates__, uniqueSelectorPostfix) -> super @name, @__renderStates__ @DOMselector += uniqueSelectorPostfix # console.log @DOMselector class SwitchView extends View constructor: (@name, @__renderStates__) -> super @name, @__renderStates__ showView: => for _viewName, viewValue of switchViews if _viewName == @name # show # console.log 'showing ' + _viewName $('#' + _viewName + '_View').css({'display':'block'}) else # hide # console.log 'hiding ' + _viewName $('#' + _viewName + '_View').css({'display':'none'}) render: (popupParcel, renderState = "__normal__") => super popupParcel, renderState @showView() class Conversations extends SwitchView constructor: (@name) -> super @name, @__renderStates__ @Widgets = customSearch: new CustomSearch 'customSearch', @, false init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => # console.log ' in conversations view' # console.log popupParcel @Widgets['customSearch'].init(popupParcel) researchModeDisabledButtonsHTML = '' if popupParcel.urlBlocked == true or popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' or (popupParcel.oldUrl? and popupParcel.oldUrl == true) researchModeDisabledButtonsHTML += "<br> <div style='width:100%;text-align: center;'><button class='btn btn-success' style='font-size: 1.1em;display: inline-block;' id='researchUrlOverride'>Research this Url</button></div> <br>" if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' researchModeDisabledButtonsHTML += "<br> <div style='width:100%; text-align:center;'> Research Mode is off: &nbsp; <button class='goTo_userPreferencesView btn btn-xs btn-default' style='position:relative; bottom:2px;'> change settings </button> </div>" $("#researchModeDisabledButtons").html(researchModeDisabledButtonsHTML) resultsSummaryArray = [] resultsHTML = "" totalResults = 0 for serviceInfoObject, index in popupParcel.kiwi_servicesInfo if popupParcel.allPreppedResults[serviceInfoObject.name]? and popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults.length > 0 service_PreppedResults = popupParcel.allPreppedResults[serviceInfoObject.name].service_PreppedResults totalResults += service_PreppedResults.length resultsSummaryArray.push("<a class='jumpTo' data-serviceindex='" + index + "'>" + serviceInfoObject.title + " (" + service_PreppedResults.length + ")</a>") resultsHTML += tailorResults[serviceInfoObject.name](serviceInfoObject,service_PreppedResults, popupParcel.kiwi_userPreferences) if service_PreppedResults.length > 14 resultsHTML += '<div class="listing showHidden" data-servicename="' + serviceInfoObject.name + '"> show remaining ' + (service_PreppedResults.length - 11) + ' results</div>' else if serviceInfoObject.submitTitle? submitUrl = serviceInfoObject.submitUrl submitTitle = serviceInfoObject.submitTitle resultsHTML += '<div class="serviceResultJumpTo">No conversation matches for ' + serviceInfoObject.title + '... <br> &nbsp;&nbsp;&nbsp;<a target="_blank" href="' + submitUrl + '">' + submitTitle + '</a></div><br>' else resultsHTML += '<div>No results for ' + serviceInfoObject.title + '</div>' preppedHTMLstring = '' if (popupParcel.urlBlocked == true and Object.keys(popupParcel.allPreppedResults).length < 2) # do nothing preppedHTMLstring += "<div style='width: 100%; text-align: justify; padding:20px; font-size:.9em; opacity:.9;'> <em> Certain super-high traffic URLs (or weird urls (like 'about:config' and chrome new tab pages)) have been excluded from auto-search out of respect for the APIs of the conversation sites. you can still manually search them by hitting the green button </em> </div><br>" else if ((totalResults > 0 and popupParcel.kiwi_userPreferences.researchModeOnOff == 'off') or popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or Object.keys(popupParcel.allPreppedResults).length > 1) preppedHTMLstring = '<br><h3 style="position:relative; top:-10px;">Results for this URL:</h3>' preppedHTMLstring += "<div style='width: 100%; text-align: center;font-size:.9em;'>" + resultsSummaryArray.join(" - ") + "</div><br>" preppedHTMLstring += resultsHTML $("#resultsByService").html(preppedHTMLstring) $(@DOMselector + " .hidden_listing").hide() if totalResults < 4 and @totalRenders < 4 fixedViews.kiwiSlice.render(popupParcel, "open") setTimeout( -> # to reign in a chrome rendering issue # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() , 300 ) # renderExtensionHeight(@DOMselector, 1) $($('input')[0]).blur() $($('a')[0]).blur() $($('button')[0]).blur() bind: (popupParcel) => showHidden = $(@DOMselector + " .showHidden") researchUrlOverrideButton = $(@DOMselector + " #researchUrlOverride") conversations_sortByPref = $(@DOMselector + " .conversations_sortByPref") customSearchOpen = $(@DOMselector + " .customSearchOpen") jumpToService = $("#resultsByService .jumpTo") @elsToUnbind = @elsToUnbind.concat(conversations_sortByPref, showHidden, researchUrlOverrideButton, customSearchOpen, jumpToService) jumpToService.bind 'click', (ev) => serviceIndex = parseInt($(ev.target).data('serviceindex')) # console.log serviceIndex pxFromTop = parseInt($($(@DOMselector + " #resultsByService .serviceResultJumpTo")[serviceIndex]).offset().top) # offsetBy = parseInt($($("#resultsByService .serviceResultsHeaderBar")[serviceIndex]).outerHeight()) + 40 $('body,html').scrollTop(pxFromTop - 100) customSearchOpen.bind 'click', -> $("#customSearchQueryInput").click() researchUrlOverrideButton.bind 'click', -> parcel = msg: 'kiwiPP_researchUrlOverrideButton' sendParcel(parcel) showHidden.bind 'click', (ev) => # console.log "showHidden.bind 'click', (ev) -> " # console.debug ev serviceName = $(ev.target).data('servicename') $(@DOMselector + " .resultsBox__" + serviceName + " .hidden_listing").show(1200) $(ev.target).remove() conversations_sortByPref.bind 'change', (ev) -> # console.log "'conversations_sortByPref.bind 'change', (ev) ->" # console.log $(ev.target).val() popupParcel.kiwi_userPreferences.sortByPref = $(ev.target).val() parcel = refreshView: 'conversations' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) class UserPreferences extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => $(@DOMselector + " .userErrMsg").html('') # console.log 'paint: adsfaeaewfawefawefawef(popupParcel) =># viewName = ' if preferencesOnlyPage is true $("#menuBar_preferences").hide() currentTime = Date.now() if popupParcel.kiwi_userPreferences.researchModeOnOff == "off" $("#autoOffTimer").html("Research mode is off, so auto-off timer is not set") else if popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp > currentTime $("#autoOffTimer").html("Auto-Off timer expires at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else if popupParcel.kiwi_userPreferences.researchModeOnOff == 'off' and popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp? $("#autoOffTimer").html("Auto-off timer last expired at: " + formatTime(popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp) + "<br>") else $("#autoOffTimer").html("Auto-off timer is not set") researchModeHtml = '' if popupParcel.kiwi_userPreferences.researchModeOnOff is "off" researchOnString = "" researchOffString = " checked='checked' " else researchOnString = " checked='checked' " researchOffString = "" autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue `var auto20, auto60, autoAlways, autoCustom, autoCustomValue = ''; if(autoOffTimerType != null){ if(autoOffTimerType == "20"){ auto20 = " checked='checked' " } else if(autoOffTimerType == "60"){ auto60 = " checked='checked' " } else if(autoOffTimerType == "always"){ autoAlways = " checked='checked' " } else if(autoOffTimerType == "custom"){ autoCustom = " checked='checked' "; autoCustomValue = autoOffTimerValue;} }` researchModeHtml += 'Research Mode: <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;"><sup><em> ?</em></sup></div> <span style="bottom:34px; left:-114px;"> When the Research mode is "Off", Kiwi won\'t automatically search URLs as you surf; instead, you can check URLs on a case-by-case basis (and still be able to do custom searches) </span> </a> <label style="font-weight: normal;" for="researchmodeON"> on </label> <input id="researchmodeON" type="radio" name="research" value="on" ' + researchOnString + '> - <label style="font-weight: normal;" for="researchmodeOFF"> off </label> <input id="researchmodeOFF" type="radio" name="research" value="off" ' + researchOffString + '> &nbsp;&nbsp;<button class="btn btn-mini btn-default userPreferencesSave"> save preferences </button><br>' if popupParcel.kiwi_userPreferences.researchModeOnOff is 'off' researchModeHtml += '' timerDisabled = ' disabled ' timerOnlyUsefulWhenMessage = '<br> <span style="font-size:.8em;"><i> &nbsp;&nbsp;Note: the auto-off-timer only matters when Research Mode is "on". </i></span> <br>' else timerDisabled = ' ' researchModeHtml += '<br> <span style="font-size:.8em;"><i> Note: The Whitelist only makes a difference when Research mode is turned "off", which it currently isn\'t. </i></span> <br>' timerOnlyUsefulWhenMessage = '' researchModeHtml += ' <br> <table class="table table-bordered table-striped whitelistTable"> <thead> <tr> <th colspan="3"> <div class="input-group" id="addWhiteListString"> <label class="input-group-addon"> <a class="tooltipCustom" style="position: relative;"> <div style="display:inline; font-size:.9em;">whitelist strings <sup><em> ?</em></sup></div> <span style="bottom:84px;left:-12px;"> <b>Whitelist strings:</b> <br> Kiwi will automatically research any URL (upon visiting) that contains a user-provided Whitelist string -- even when Research Mode is "off". Try it with "github.com" or "bitbucket.org", and then visit the respective site with research mode "off". </span> </a> </label> <input type="text" class="form-control ignoreSaveButtonListen"> <label class="input-group-addon btn btn-default"> add </label> </div> </th> </tr> </thead> <tbody> ' for whitelistSubString, index in popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch researchModeHtml += ' <tr> <th scope="row" style="width:35px;"> ' + (index + 1) + ' </th> <td> ' + whitelistSubString + ' </td> <td style="width:35px;"> <button title="remove" class="btn btn-xs btn-default removeWhitelistString" data-whitelistStringToRemove="' + whitelistSubString + '" > <span data-whitelistStringToRemove="' + whitelistSubString + '" class="glyphicon glyphicon-remove" aria-hidden="true" style="color:#E65F5F;" ></span> </button> </td> </tr>' researchModeHtml += ' </tbody> </table> <br>Auto-Off Timer set for: ' + timerOnlyUsefulWhenMessage + ' <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto20 + ' value="20"> 20 min</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + auto60 + ' value="60"> 1 hr</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoAlways + ' value="always"> Always On</label> <br>&nbsp; &nbsp;<label><input ' + timerDisabled + ' type="radio" name="researchAutoOffType" ' + autoCustom + ' value="custom"> Custom</label> &nbsp; &nbsp; <input ' + timerDisabled + ' id="autoCustomValue" type="text" value="' + autoCustomValue + '" size="4" disabled /> minutes' $("#researchModeDrop").html(researchModeHtml) servicesHtml = '' for service, index in popupParcel.kiwi_servicesInfo if service.active == "on" activeCheck = " checked='checked' " notActiveCheck = "" else activeCheck = "" notActiveCheck = " checked='checked' " servicesHtml += '<br> <div class="serviceListing listing"> <table><tbody><tr> <td class="upDownButtons">' if index != 0 servicesHtml += '<span title="Move ' + service.title + ' results above ' + popupParcel.kiwi_servicesInfo[index - 1].title + '" class="glyphicon glyphicon-chevron-up" id="' + service.name + '_moveServiceUp" aria-hidden="true"></span>' if index != 0 and index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<br><br>' if index != popupParcel.kiwi_servicesInfo.length - 1 servicesHtml += '<span title="Move ' + service.title + ' results below ' + popupParcel.kiwi_servicesInfo[index + 1].title + '" class="glyphicon glyphicon-chevron-down" id="' + service.name + '_moveServiceDown" aria-hidden="true"></span>' brandedTitle = if (service.name is 'reddit') then "for " + service.title else service.title brandingImage = '' if service.brandingImage? brandingImage = "&nbsp;<a target='_blank' href='" + service.broughtToYouByURL + "' style='text-decoration:none;'> <img height='28' src='" + service.brandingImage + "'/></a>&nbsp;" servicesHtml += '</td> <td class="serviceInfo">' + brandedTitle + ' - using: ' + brandingImage + ' <a target="_blank" href="' + service.broughtToYouByURL + '">' + service.broughtToYouByTitle + '</a><br>' if service.name == "productHunt" specificAPIlink = ", <a target='_blank' href='https://github.com/producthunt/producthunt-api/wiki/Product-Hunt-APIs#algolia-search-api'>for PH</a>" if service.customSearchBroughtToYouByTitle? customSearchApiBrandingHTML = "<div class='bg-warning' style='margin:4px; margin-top:10px;padding:6px;'> <em><div style='padding-bottom:2px;'>&nbsp;&nbsp;&nbsp;&nbsp;custom searches are using: </div>" + ' <div style="padding-bottom:4px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a target="_blank" href="' + service.customSearchBroughtToYouByURL + '">' + service.customSearchBroughtToYouByTitle + '</a> ' + specificAPIlink + ' </em> </div> </em> </div>' else customSearchApiBrandingHTML = "" servicesHtml += '<div style="padding-left:15px;"> status: <label style="font-weight: normal;" for="' + service.name + '_serviceStatusON"> on </label> <input id="' + service.name + '_serviceStatusON" type="radio" name="' + service.name + '_serviceStatus" value="on" ' + activeCheck + '> - <label style="font-weight: normal;" for="' + service.name + '_serviceStatusOFF"> off </label> <input id="' + service.name + '_serviceStatusOFF" type="radio" name="' + service.name + '_serviceStatus" value="off" ' + notActiveCheck + '> <br><br>Results are deemed notable (capitilizes badge letter) if:' if service.name == 'gnews' servicesHtml += '<br><br> the topic has had <input id="' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit" type="text" size="4" value="' + service.notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit + '"/> or more related stories published within the last <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> hours <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> number of News Clusters <input id="' + service.name + '_numberOfRelatedItemsWithClusterURL" type="text" size="4" value="' + service.notableConditions.numberOfRelatedItemsWithClusterURL + '"/> </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' else servicesHtml += '<br> URL is an exact match, and: <br> it has been <input id="' + service.name + '_hoursNotable" type="text" size="4" value="' + service.notableConditions.hoursSincePosted + '"/> or fewer hours since posting <br> <div style="width:100%; text-align:center;"><span style="padding:7px; margin-right: 280px; display: inline-block;"> - or - </span></div> a post has <input id="' + service.name + '_commentsNotable" type="text" size="4" value="' + service.notableConditions.num_comments + '"/> or more comments </div> ' + customSearchApiBrandingHTML + ' </td> </tr></tbody></table> </div>' servicesHtml += "<div class='serviceListing listing' style='padding:15px; margin-top: 30px;'> Wouldn't it be awesome if we could add some more services to opt-in to?&nbsp;&nbsp; All that's needed are friendly APIs!&nbsp; <a href='https://twitter.com/spencenow' target='_blank'>Tweet me</a> if you're interested in adding one! </div> <br>" $("#servicesInfoDrop").html(servicesHtml) bind: (popupParcel) => saveButtons = $(@DOMselector + " .userPreferencesSave") removeWhitelistStringButtons = $(@DOMselector + " .removeWhitelistString") autoTimerRadios = $(@DOMselector + " input:radio[name='researchAutoOffType']") allInputs = $(@DOMselector + ' input:not(.ignoreSaveButtonListen)') addWhitelistString_button = $(@DOMselector + " #addWhiteListString label") @elsToUnbind = @elsToUnbind.concat allInputs, saveButtons, autoTimerRadios, removeWhitelistStringButtons, addWhitelistString_button saveButtons.attr('disabled','disabled') allInputs.bind 'change', -> $(".userPreferencesSave").removeAttr('disabled') allInputs.bind 'focus', -> $(".userPreferencesSave").removeAttr('disabled') if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') autoTimerRadios.bind 'change', -> if $("input:radio[name='researchAutoOffType']:checked").val() is 'custom' $("#autoCustomValue").removeAttr('disabled') else $("#autoCustomValue").attr('disabled','disabled') _bindDown = (downButton, index) => downButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index + 1) parcel = refreshView: 'userPreferences' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) _bindUp = (upButton, index) => upButton.bind 'click', -> popupParcel.kiwi_servicesInfo = moveArrayElement(popupParcel.kiwi_servicesInfo, index, index - 1 ) parcel = refreshView: 'userPreferences' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_servicesInfo localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) for service,index in popupParcel.kiwi_servicesInfo downButton = $("#" + service.name + '_moveServiceDown') if downButton.length > 0 @elsToUnbind.push downButton _bindDown(downButton, index) upButton = $("#" + service.name + '_moveServiceUp') if upButton.length > 0 @elsToUnbind.push upButton _bindUp(upButton, index) postError = (userErrMsg) => # console.log 'trying to post error ' + userErrMsg $(@DOMselector + " .userErrMsg").html("<br>" + userErrMsg) addWhitelistString_button.bind 'click', (ev) => # whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') whitelistSubString_toAdd = $(@DOMselector + " #addWhiteListString input").val() popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch.push whitelistSubString_toAdd parcel = refreshView: 'userPreferences' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) removeWhitelistStringButtons.bind 'click', (ev) -> whitelistSubString = $(ev.target).attr('data-whitelistStringToRemove') newWhitelistAnyMatchArray = _.without(popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch, whitelistSubString); popupParcel.kiwi_userPreferences.urlSubstring_whitelists.anyMatch = newWhitelistAnyMatchArray parcel = refreshView: 'userPreferences' keyName: 'PI:KEY:<KEY>END_PI' newValue: popupParcel.kiwi_userPreferences localOrSync: 'sync' msg: 'kiwiPP_post_save_a_la_carte' sendParcel(parcel) saveButtons.bind 'click', -> researchModeHTMLval = $("input:radio[name='research']:checked").val() # console.log 'researchModeHTMLval is ' + researchModeHTMLval if researchModeHTMLval != 'on' and researchModeHTMLval != 'off' postError('research mode must be "on" or "off"'); return 0; allowedAutoOffTypes = ["20","60","always","custom"] autoOffTimerType = $("input:radio[name='researchAutoOffType']:checked").val() autoOffTimerValue = $("#autoCustomValue").val() if autoOffTimerType in allowedAutoOffTypes if autoOffTimerType == 'custom' and (autoOffTimerValue == '' or isNaN(autoOffTimerValue)) postError('Must specify a number of minutes for auto-off timer.'); return 0; else postError('not acceptable autoOffTimerType'); return 0; # autoOffAtUTCmilliTimestamp for service, index in popupParcel.kiwi_servicesInfo if service.name == 'gnews' active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() if numberOfStoriesFoundWithinTheHoursSincePostedLimit == '' or isNaN(numberOfStoriesFoundWithinTheHoursSincePostedLimit) postError('number Of Stories Found Within The Hours Since Posted Limit must be an integer'); return 0; numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() if numberOfRelatedItemsWithClusterURL == '' or isNaN(numberOfRelatedItemsWithClusterURL) postError('number Of Related Items With Cluster URL of comments must be an integer'); return 0; else active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() if active != 'on' and active != 'off' postError('active must be "on" or "off"'); return 0; hoursSincePosted = $('#' + service.name + '_hoursNotable').val() if hoursSincePosted == '' or isNaN(hoursSincePosted) postError('Hours must be an number'); return 0; num_comments = $('#' + service.name + '_commentsNotable').val() if num_comments == '' or isNaN(num_comments) postError('Number of comments must be an integer'); return 0; # console.log '1234' popupParcel.kiwi_userPreferences.researchModeOnOff = researchModeHTMLval if (autoOffTimerType != 'custom') popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType else popupParcel.kiwi_userPreferences.autoOffTimerType = autoOffTimerType popupParcel.kiwi_userPreferences.autoOffTimerValue = parseFloat(autoOffTimerValue) for service, index in popupParcel.kiwi_servicesInfo active = $("input:radio[name='" + service.name + "_serviceStatus']:checked").val() popupParcel.kiwi_servicesInfo[index].active = active # notableSound = $("input:radio[name='" + service.name + "_soundStatus']:checked").val() # popupParcel.kiwi_servicesInfo[index].notableSound = notableSound hoursSincePosted = $('#' + service.name + '_hoursNotable').val() # console.log popupParcel.kiwi_servicesInfo[index].name # console.log "hoursSincePosted = $('#' + service.name + '_hoursNotable').val() " + hoursSincePosted popupParcel.kiwi_servicesInfo[index].notableConditions.hoursSincePosted = parseFloat(hoursSincePosted) if service.name == 'gnews' numberOfRelatedItemsWithClusterURL = $('#' + service.name + '_numberOfRelatedItemsWithClusterURL').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfRelatedItemsWithClusterURL = parseInt(numberOfRelatedItemsWithClusterURL) numberOfStoriesFoundWithinTheHoursSincePostedLimit = $('#' + service.name + '_numberOfStoriesFoundWithinTheHoursSincePostedLimit').val() popupParcel.kiwi_servicesInfo[index].notableConditions.numberOfStoriesFoundWithinTheHoursSincePostedLimit = parseInt(numberOfStoriesFoundWithinTheHoursSincePostedLimit) else num_comments = $('#' + service.name + '_commentsNotable').val() popupParcel.kiwi_servicesInfo[index].notableConditions.num_comments = parseInt(num_comments) popupParcel.view = 'userPreferences' # console.log '4567' # console.debug popupParcel parcel = refreshView: popupParcel.view newPopupParcel: popupParcel msg: 'kiwiPP_post_savePopupParcel' sendParcel(parcel) class Credits extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class Loading extends SwitchView constructor: (@name) -> super @name, @__renderStates__ init: (popupParcel) -> @unbindWidget() @render(popupParcel) __renderStates__: => __normal__: paint: (popupParcel) => console?.log 'painting ' + @name bind: (popupParcel) => console?.log 'binding ' + @name class KiwiSlice extends FixedView constructor: (@name, uniqueSelectorPostfix) -> super @name, @__renderStates__, uniqueSelectorPostfix init: (popupParcel, renderState = null) => @renderStateTransitions = @__renderStateTransitions__() # console.log 'hehehehee init: (popupParcel, renderState = null) =>' @unbindView() renderState = if renderState? then renderstate else "collapsed" # console.log ' renderState = if renderState? then renderstate else "collapsed" ' + renderState @render(popupParcel, 'collapsed') render: (popupParcel, renderState, fromState = null) => # console.log 'in render for kiwi' __renderStates__callback = (popupParcel, renderState) => super popupParcel, renderState if fromState? and @renderStateTransitions[fromState + "__to__" + renderState]? # console.log 'yep, has renderstate' @renderStateTransitions[fromState + "__to__" + renderState](popupParcel, renderState, __renderStates__callback) else super popupParcel, renderState __renderStates__: => collapsed: paint: (popupParcel) => kiwiSliceHTML = '<div id="sliceActivateTransition" style="position:fixed; bottom: -33px; right: -33px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) bind: (popupParcel) => elActivateTransition = $(@DOMselector + " #sliceActivateTransition") @elsToUnbind = @elsToUnbind.concat elActivateTransition elActivateTransition.bind 'mouseover', (ev) => elActivateTransition.addClass('rotateClockwiseFull') elActivateTransition.bind 'mouseout', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') elActivateTransition.bind 'click', (ev) => elActivateTransition.removeClass('rotateClockwiseFull') @render(popupParcel,'open', 'collapsed') open: paint: (popupParcel) => # console.log 'painting ' + @name kiwiSliceHTML = '<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter"> <button type="button" class=" goTo_creditsView btn btn-mini btn-default">credits</button> <a class="btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class=" btn btn-mini btn-default" id="clearKiwiURLCache">clear cache</button> <button class=" btn btn-mini btn-default" id="refreshURLresults">refresh</button> </div> <div id="sliceActivateTransition" style="position:fixed; bottom: 15px; right: 15px; "> <img style="width: 66px; height: 66px;" src="symmetricKiwi.png" /> </div>' $(@DOMselector).html(kiwiSliceHTML) # console.log kiwiSliceHTML bind: (popupParcel) => # console.log 'binding ' + @name elActivateTransition = $(@DOMselector + " #sliceActivateTransition") clearKiwiURLCacheButton = $(@DOMselector + " #clearKiwiURLCache") refreshURLresultsButton = $(@DOMselector + " #refreshURLresults") @elsToUnbind = @elsToUnbind.concat elActivateTransition, refreshURLresultsButton, clearKiwiURLCacheButton refreshURLresultsButton.bind 'click', -> parcel = msg: 'kiwiPP_refreshURLresults' sendParcel(parcel) $('body').mouseup((e) => # console.log 'test test test' container = $(@DOMselector) if (!container.is(e.target) && container.has(e.target).length == 0) $('body').unbind 'mouseup' @render(popupParcel,'collapsed', 'open') ) elActivateTransition.bind 'click', (ev) => @render(popupParcel,'collapsed', 'open') clearKiwiURLCacheButton.bind 'click', -> parcel = msg: 'kiwiPP_clearAllURLresults' sendParcel(parcel) # \/ \/ \/ THIS IS A WORK IN PROGRESS \/ \/ \/ __renderStateTransitions__: => 'open__to__collapsed': (popupParcel, renderState, __renderStates__callback) => $(@DOMselector + " #transition_open_showMe").animate({'opacity':0}, 300) $(@DOMselector + " #sliceActivateTransition").addClass('rotateClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '-33px', "right": "-33px"}, { duration: 500, complete: -> __renderStates__callback(popupParcel, renderState) }) # return transitionObj 'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) => # console.log "'collapsed__to__open': (popupParcel, renderState, __renderStates__callback) =>" $(@DOMselector + " #sliceActivateTransition").addClass('rotateCounterClockwise') $(@DOMselector + " #sliceActivateTransition").animate({"bottom": '15px', "right": "15px"}, { duration: 500, complete: -> # console.log 'we are done with animation' __renderStates__callback(popupParcel, renderState) }) $(@DOMselector).prepend('<div id="transition_open_showMe" class="evenlySpacedContainer kiwiSliceOpenPlatter" style="opacity: 0;"> <button type="button" class="goTo_creditsView btn btn-mini btn-default ">credits</button> <a class=" btn btn-mini btn-default" style="font-size:.8em;" target="_blank" href="http://www.metafruit.com/kiwi/">MetaFruit <span class="glyphicon glyphicon-apple"></span></a> <button class="btn btn-mini btn-default " id="clearKiwiURLCache">clear cache</button> <button class="btn btn-mini btn-default " id="refreshURLresults">refresh</button> </div>') # setTimeout => $(@DOMselector + " #transition_open_showMe").animate({'opacity':1}, 499) # , 200 fixedViews = kiwiSlice: new KiwiSlice 'kiwiSlice', 'FixedBottom' switchViews = conversations: new Conversations 'conversations' userPreferences: new UserPreferences 'userPreferences' credits: new Credits 'credits' loading: new Loading 'loading' tailorResults = productHunt: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() fuzzyMatchBool = false brandingDisplay = '' if serviceInfoObject.brandingImage? brandingDisplay = '<img style="margin-left:7px;" title="' + serviceInfoObject.title + '" height="28" src="' + serviceInfoObject.brandingImage + '"/> &nbsp;&nbsp; <span class="serviceResultsTitles" style="color:black; position: relative;top: 6px;"">' + serviceInfoObject.title + '</span>' else brandingDisplay = "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" + brandingDisplay + "</div>" # recency doesn't make sense for PH # if kiwi_userPreferences.sortByPref == 'attention' # selectedString_attention = 'selected' # selectedString_recency = '' # else # selectedString_attention = '' # selectedString_recency = 'selected' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_num_comments') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else if (listing.kiwi_created_at? and currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) recentTag = "<span class='recentListingTag'>Recent: </span>" else recentTag = "" if listing.kiwi_makers.length > 3 gridLayoutBool = false else gridLayoutBool = true preppedHTMLstring += '<div class="listing ' + listingClass + '">' # kiwi_created_at: 1439471020625 # kiwi_author_headline: "Community @ProductHunt. " # kiwi_author_name: "PI:NAME:<NAME>END_PI" # kiwi_author_username: "bentossell" # kiwi_discussion_url: "http://www.producthunt.com/tech/buffer-for-video" # kiwi_makers: Array[9] # headline: "Co-founder/CEO, Buffer" # name: "PI:NAME:<NAME>END_PI" # profile_url: "http://www.producthunt.com/@joelgascoigne" # username: "joelgascoigne" # website_url: "http://joel.is" # kiwi_num_comments: 30 # kiwi_score: 244 # name: "Buffer for Video" # tagline: "All-in-one video scheduling & management for social media" # redirect_url: "http://www.producthunt.com/r/4918f991fdd705/30839?app_id=1674" # screenshot_url: Object if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 60%; padding-right:8px;">' else preppedHTMLstring += '<div>' preppedHTMLstring += ' <a class="listingTitle" target="_blank" href="' + listing.kiwi_discussion_url + '"> <div style="color:black; padding:4px; padding-bottom: 8px; font-size: 1.1em;">' + recentTag + ' <b>' + listing.name + '</b> </div> <div style="color:#4D586F; padding-left:18px;"> <div style="padding-bottom:4px;">"' + listing.tagline + '"</div>' preppedHTMLstring += '<div style="padding-bottom:4px;"> ' + listing.kiwi_num_comments + ' comments, ' + listing.kiwi_score + ' upvotes </div>' if listing.kiwi_created_at? _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += '' + _time preppedHTMLstring += '</div></a></div>' if gridLayoutBool preppedHTMLstring += '<div style="display:inline-table; width: 39%;">' else preppedHTMLstring += '<div style="padding: 8px;">' makerUsernames = [] if listing.kiwi_makers? and listing.kiwi_makers.length > 0 preppedHTMLstring += '<div><div style="padding-bottom:2px;"><b>made by</b>: </div>' for maker in listing.kiwi_makers if gridLayoutBool preppedHTMLstring += '<div style="padding-bottom: 4px;">' else preppedHTMLstring += '<div style="padding-bottom: 4px; padding-left: 10px;">' preppedHTMLstring += '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + maker.username + '" style="color:#727E98;">' + maker.name if maker.headline? and maker.headline != "" preppedHTMLstring += ', "' + maker.headline + '"' preppedHTMLstring += '</a>' if maker.website_url? preppedHTMLstring += ' <a href="' + maker.website_url + '" target="_blank"><span class="glyphicon glyphicon-log-in" style="color:blue;"></span> </a>' if listing.kiwi_author_username == maker.username preppedHTMLstring += " (also submitted post)" preppedHTMLstring += '</div>' preppedHTMLstring += '</div>' makerUsernames.push maker.username if listing.kiwi_author_username not in makerUsernames if gridLayoutBool gridLayoutAuthorDiv = '<div style="padding-bottom: 2px;">' else gridLayoutAuthorDiv = '<div style="padding-bottom: 2px; margin-left: 10px;">' preppedHTMLstring += '<div style=""> <div style="padding-bottom:2px;"><b>submitted by:</b></div> ' + gridLayoutAuthorDiv + '<a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.kiwi_author_username + '" style="color:#727E98;">' + listing.kiwi_author_name + ' ' if listing.kiwi_author_headline? and listing.kiwi_author_headline != "" preppedHTMLstring += ', "' + listing.kiwi_author_headline + '"' preppedHTMLstring += '</a></div></div>' preppedHTMLstring += '</div></div>' preppedHTMLstring += "</div>" return preppedHTMLstring hackerNews: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) reddit: (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> return tailorRedditAndHNresults_returnHtml(serviceInfoObject, service_PreppedResults, kiwi_userPreferences) _tailorHNcomment = (listing, serviceInfoObject, listingClass) -> currentTime = Date.now() commentHtml = "" # story_text # comment_text # story_id # story_title # story_url recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" commentHtml += '<div class="listing ' + listingClass + ' " style="position:relative;">' + recentTag if listing.over_18? and listing.over_18 is true commentHtml += '<span class="nsfw">NSFW</span> For story: ' + listing.story_title + '<br>' else commentHtml += "For story: <a target='_blank' href='" + serviceInfoObject.permalinkBase + listing.story_id + "'>" + listing.story_title + '</a><br>' _time = formatTime(listing.kiwi_created_at) commentHtml += 'at ' + _time + ', <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '">' + listing.author + '</a> recieved ' + listing.kiwi_score + ' upvotes, by saying: ( <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"> comment permalink </a> , <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.story_id + '"> story permalink </a> )<br><div class="commentBox"> ' + listing.comment_text + ' </div></div>' return commentHtml tailorRedditAndHNresults_returnHtml = (serviceInfoObject, service_PreppedResults, kiwi_userPreferences) -> preppedHTMLstring = '' currentTime = Date.now() # kiwi_exact_match # fuzzy matches # linkify stuff fuzzyMatchBool = false preppedHTMLstring += "<div class='serviceResultsBox serviceResultJumpTo resultsBox__" + serviceInfoObject.name + "'> <div class='serviceResultsHeaderBar'>" if serviceInfoObject.name == 'reddit' preppedHTMLstring += "<span class='serviceResultsTitles'>for " + serviceInfoObject.title + ':</span>' else preppedHTMLstring += "<span class='serviceResultsTitles'>" + serviceInfoObject.title + '</span>' if kiwi_userPreferences.sortByPref == 'attention' selectedString_attention = 'selected' selectedString_recency = '' else selectedString_attention = '' selectedString_recency = 'selected' preppedHTMLstring += '<div style="float:right; padding-top: 9px;"> &nbsp;&nbsp sorted by: <select class="conversations_sortByPref"> <option ' + selectedString_attention + ' id="_attention" value="attention">attention</option> <option ' + selectedString_recency + ' id="_recency" value="recency">recency</option> </select></div> </div>' if service_PreppedResults.length < 1 preppedHTMLstring += ' no results <br>' return preppedHTMLstring else if !service_PreppedResults[0].comment_text? and kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'num_comments') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'attention' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_score') service_PreppedResults.reverse() else if kiwi_userPreferences.sortByPref is 'recency' service_PreppedResults = _.sortBy(service_PreppedResults, 'kiwi_created_at') service_PreppedResults.reverse() for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if listing.comment_text? preppedHTMLstring += _tailorHNcomment(listing, serviceInfoObject, listingClass) else recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" if listing.kiwi_exact_match # preppedHTMLstring += '<div class="listing ' + listingClass + '" style="position:relative;">' + recentTag + ' # <div style="float:right;"> # <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> # </div> # <a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '">' preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' _time = formatTime(listing.kiwi_created_at) preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes -- ' + _time + '</span></a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a> </div>' preppedHTMLstring += '<br></div>' else fuzzyMatchBool = true if fuzzyMatchBool numberOfExactMatches = _.reduce(service_PreppedResults, (memo, obj) -> if obj.kiwi_exact_match memo++ return memo else memo ) if (service_PreppedResults.length - numberOfExactMatches) > 10 and service_PreppedResults.length > 14 listingClass = ' hidden_listing ' else listingClass = '' # listingClass = if nonFuzzyItemCounter > 10 then ' hidden_listing ' else '' preppedHTMLstring += '<div class="showFuzzyMatches ' + listingClass + '" style="position:relative;"> fuzzy matches: <br></div> <span class="fuzzyMatches">' # console.log 'fuzzy matches 12312312 ' + serviceInfoObject.name for listing, index in service_PreppedResults listingClass = if (index > 10 and service_PreppedResults.length > 14) then ' hidden_listing ' else '' if !listing.kiwi_exact_match recentTag = if (currentTime - listing.kiwi_created_at < 1000 * 60 * 60 * 4) then "<span class='recentListingTag'>Recent: </span>" else "" preppedHTMLstring += '<div class="listing ' + listingClass + '">' if serviceInfoObject.name != 'reddit' preppedHTMLstring += '<div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + '</a> </div>' preppedHTMLstring += '<a class="listingTitle" target="_blank" href="' + serviceInfoObject.permalinkBase + listing.kiwi_permaId + '"><span style="color:black;">' + recentTag if listing.over_18? and listing.over_18 is true preppedHTMLstring += '<span class="nsfw">NSFW</span> <b>' + listing.title + '</b><br>' else preppedHTMLstring += '<b>' + listing.title + '</b><br>' preppedHTMLstring += listing.num_comments + ' comments, ' + listing.kiwi_score + ' upvotes ' + formatTime(listing.kiwi_created_at) + '</span> <br> for Url: <span class="altURL">' + listing.url + '</span> </a>' if listing.subreddit? preppedHTMLstring += '<br><span> <a target="_blank" href="' + serviceInfoObject.permalinkBase + '/r/' + listing.subreddit + '"> subreddit: ' + listing.subreddit + '</a></span> <div style="float:right;"> <a target="_blank" href="' + serviceInfoObject.userPageBaselink + listing.author + '"> by ' + listing.author + ' </a></div>' preppedHTMLstring += '<br></div>' preppedHTMLstring += "</span>" preppedHTMLstring += "</div>" return preppedHTMLstring bindGoToViewButtons = (buttonEls, viewName, viewData) -> for el in buttonEls $(el).bind('click', (ev) -> # console.log 'clicked ' + viewName switchViews[viewName].render(viewData) ) moveArrayElement = (array, from, to) -> array.splice(to, 0, array.splice(from, 1)[0]); return array getRandom = (min, max) -> return min + Math.floor(Math.random() * (max - min + 1)) formatTime = (utcMillisecondTimestamp) -> a = new Date(utcMillisecondTimestamp) months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] year = a.getFullYear() month = months[a.getMonth()] date = a.getDate() hour = a.getHours() min = a.getMinutes() sec = a.getSeconds() amOrPm = if hour > 11 then 'pm' else 'am' if hour > 12 hour = hour - 12 else if parseInt(hour) == 0 hour = 12 if min < 10 min = '0' + min time = month + ' ' + date + ', ' + year + ' - ' + hour + ':' + min + amOrPm return time renderExtensionHeight = (elementSelector, extraPx) -> if viewElementId is elementSelector extraPx = 2 extHeight_ = $(elementSelector).outerHeight() + extraPx if extHeight_ > 590 extHeight_ = 590 # $('html').css('height',extHeight+'px') $('body').css('height', extHeight_ + 'px') `heightString = extHeight_.toString() +'px'` $('html').css('min-height', heightString) extHeight_-- $('body').css('min-height', heightString) capitalizeFirstLetter = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) # // http://css-tricks.com/snippets/javascript/htmlentities-for-javascript/ htmlEntities = (str) -> return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); getURLParam = (oTarget, sVar) -> return decodeURI(oTarget.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); algoliaPHclient = null algoliaPHindex = null initAlgoliaPHcustomSearch = -> algoliaPHclient = algoliasearch('0H4SMABBSG', '9670d2d619b9d07859448d7628eea5f3') algoliaPHindex = algoliaPHclient.initIndex('Post_production') initAlgoliaPHcustomSearch() fetchAlgoliaProductHuntResultsFirst = (parcel) -> # console.log 'yoyoyo here ' + parcel.customSearchRequest.queryString # console.log parcel # not ideal because it's blocking, and it'd be better to have persistent index object # but the restrictions in FF addons force this approach. if algoliaPHindex? algoliaPHindex.search(parcel.customSearchRequest.queryString, (err, content) -> # // err is either `null` or an `Error` object, with a `message` property # // content is either the result of the command or `undefined` if (err) console.error(err) parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) return 0 if content? and content.hits? parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = content.hits else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] # console.log 'sending this PH' # console.log parcel.customSearchRequest.servicesToSearch.productHunt.rawResults self.port.emit('kiwiPP_post_customSearch', parcel) ) else parcel.customSearchRequest.servicesToSearch.productHunt.rawResults = [] self.port.emit('kiwiPP_post_customSearch', parcel) sendParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_acknowledgeMessage' self.port.emit('kiwiPP_acknowledgeMessage', parcel); when 'kiwiPP_refreshSearchQuery' # port.postMessage(parcel) self.port.emit('kiwiPP_refreshSearchQuery', parcel); when 'kiwiPP_post_customSearch' # not ideal because it's blocking, but the restrictions in FF addons force this approach if parcel.customSearchRequest.servicesToSearch.productHunt? fetchAlgoliaProductHuntResultsFirst(parcel) else port.postMessage(parcel) when 'kiwiPP_request_popupParcel' self.port.emit('kiwiPP_request_popupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_savePopupParcel' self.port.emit('kiwiPP_post_savePopupParcel', parcel) # port.postMessage(parcel) when 'kiwiPP_post_save_a_la_carte' self.port.emit('kiwiPP_post_save_a_la_carte', parcel) # port.postMessage(parcel) when 'kiwiPP_clearAllURLresults' self.port.emit('kiwiPP_clearAllURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_refreshURLresults' self.port.emit('kiwiPP_refreshURLresults', parcel) # port.postMessage(parcel) when 'kiwiPP_researchUrlOverrideButton' self.port.emit('kiwiPP_researchUrlOverrideButton', parcel) # port.postMessage(parcel) receiveParcel = (parcel) -> if !parcel.msg? return false switch parcel.msg when 'kiwiPP_popupParcel_ready' initialize(parcel.popupParcel) self.port.on('kiwi_fromBackgroundToPopup', (parcel) -> receiveParcel(parcel) )
[ { "context": "# @author mrdoob / http://mrdoob.com/\n# @author aladjev.andrew@gma", "end": 16, "score": 0.9996249675750732, "start": 10, "tag": "USERNAME", "value": "mrdoob" }, { "context": "# @author mrdoob / http://mrdoob.com/\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/loaders/loader\n#= require new", "end": 72, "score": 0.9999088644981384, "start": 48, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/loaders/obj.coffee
andrew-aladev/three.js
0
# @author mrdoob / http://mrdoob.com/ # @author aladjev.andrew@gmail.com #= require new_src/loaders/loader #= require new_src/core/geometry #= require new_src/core/object_3d #= require new_src/core/vector_3 #= require new_src/core/face_3 #= require new_src/core/face_4 #= require new_src/core/uv class OBJLoader extends THREE.Loader load: (url, callback) -> xhr = new XMLHttpRequest() xhr.onreadystatechange = => if xhr.readyState is 4 if xhr.status is 200 or xhr.status is 0 callback @parse(xhr.responseText) else console.error "THREE.OBJLoader: Couldn't load ", url, " (", xhr.status, ")" xhr.open "GET", url, true xhr.send null parse: (data) -> group = new THREE.Object3D() vertices = [] normals = [] uvs = [] # v float float float pattern = /v( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? vertices.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vn float float float pattern = /vn( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? normals.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vt float float pattern = /vt( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vt 0.1 0.2", "0.1", "0.2"] while (result = pattern.exec(data))? uvs.push new THREE.UV( parseFloat(result[1]), 1.0 - parseFloat(result[2]) ) data = data.split("\no ") length = data.length for i in [0...length] object = data[i] obj_model = new OBJModel object, vertices, normals, uvs group.add new THREE.Mesh(obj_model, new THREE.MeshLambertMaterial()) group class OBJModel extends THREE.Geometry constructor: (object, vertices, normals, uvs) -> super() @vertices = vertices @normals = normals @object = object @uvs = uvs @parseModel() parseModel: -> # f vertex vertex vertex ... pattern = /f( [\d]+)( [\d]+)( [\d]+)( [\d]+)?/g while (result = pattern.exec(@object))? # ["f 1 2 3", "1", "2", "3", undefined] unless result[4] @faces.push new THREE.Face3( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 ) else @faces.push new THREE.Face4( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 parseInt(result[4]) - 1 ) # f vertex/uv vertex/uv vertex/uv ... pattern = /f( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] @uvs[parseInt(result[12]) - 1] ] # f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... pattern = /f( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] unless result[13]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 parseInt(result[14]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] @normals[parseInt(result[16]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] @uvs[parseInt(result[15]) - 1] ] # f vertex//normal vertex//normal vertex//normal ... pattern = /f( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] ] ) else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] @normals[parseInt(result[12]) - 1] ] ) @computeCentroids() namespace "THREE", (exports) -> exports.OBJLoader = OBJLoader exports.OBJModel = OBJModel
212093
# @author mrdoob / http://mrdoob.com/ # @author <EMAIL> #= require new_src/loaders/loader #= require new_src/core/geometry #= require new_src/core/object_3d #= require new_src/core/vector_3 #= require new_src/core/face_3 #= require new_src/core/face_4 #= require new_src/core/uv class OBJLoader extends THREE.Loader load: (url, callback) -> xhr = new XMLHttpRequest() xhr.onreadystatechange = => if xhr.readyState is 4 if xhr.status is 200 or xhr.status is 0 callback @parse(xhr.responseText) else console.error "THREE.OBJLoader: Couldn't load ", url, " (", xhr.status, ")" xhr.open "GET", url, true xhr.send null parse: (data) -> group = new THREE.Object3D() vertices = [] normals = [] uvs = [] # v float float float pattern = /v( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? vertices.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vn float float float pattern = /vn( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? normals.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vt float float pattern = /vt( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vt 0.1 0.2", "0.1", "0.2"] while (result = pattern.exec(data))? uvs.push new THREE.UV( parseFloat(result[1]), 1.0 - parseFloat(result[2]) ) data = data.split("\no ") length = data.length for i in [0...length] object = data[i] obj_model = new OBJModel object, vertices, normals, uvs group.add new THREE.Mesh(obj_model, new THREE.MeshLambertMaterial()) group class OBJModel extends THREE.Geometry constructor: (object, vertices, normals, uvs) -> super() @vertices = vertices @normals = normals @object = object @uvs = uvs @parseModel() parseModel: -> # f vertex vertex vertex ... pattern = /f( [\d]+)( [\d]+)( [\d]+)( [\d]+)?/g while (result = pattern.exec(@object))? # ["f 1 2 3", "1", "2", "3", undefined] unless result[4] @faces.push new THREE.Face3( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 ) else @faces.push new THREE.Face4( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 parseInt(result[4]) - 1 ) # f vertex/uv vertex/uv vertex/uv ... pattern = /f( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] @uvs[parseInt(result[12]) - 1] ] # f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... pattern = /f( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] unless result[13]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 parseInt(result[14]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] @normals[parseInt(result[16]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] @uvs[parseInt(result[15]) - 1] ] # f vertex//normal vertex//normal vertex//normal ... pattern = /f( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] ] ) else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] @normals[parseInt(result[12]) - 1] ] ) @computeCentroids() namespace "THREE", (exports) -> exports.OBJLoader = OBJLoader exports.OBJModel = OBJModel
true
# @author mrdoob / http://mrdoob.com/ # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/loaders/loader #= require new_src/core/geometry #= require new_src/core/object_3d #= require new_src/core/vector_3 #= require new_src/core/face_3 #= require new_src/core/face_4 #= require new_src/core/uv class OBJLoader extends THREE.Loader load: (url, callback) -> xhr = new XMLHttpRequest() xhr.onreadystatechange = => if xhr.readyState is 4 if xhr.status is 200 or xhr.status is 0 callback @parse(xhr.responseText) else console.error "THREE.OBJLoader: Couldn't load ", url, " (", xhr.status, ")" xhr.open "GET", url, true xhr.send null parse: (data) -> group = new THREE.Object3D() vertices = [] normals = [] uvs = [] # v float float float pattern = /v( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? vertices.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vn float float float pattern = /vn( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] while (result = pattern.exec(data))? normals.push new THREE.Vector3( parseFloat result[1] parseFloat result[2] parseFloat result[3] ) # vt float float pattern = /vt( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/g # ["vt 0.1 0.2", "0.1", "0.2"] while (result = pattern.exec(data))? uvs.push new THREE.UV( parseFloat(result[1]), 1.0 - parseFloat(result[2]) ) data = data.split("\no ") length = data.length for i in [0...length] object = data[i] obj_model = new OBJModel object, vertices, normals, uvs group.add new THREE.Mesh(obj_model, new THREE.MeshLambertMaterial()) group class OBJModel extends THREE.Geometry constructor: (object, vertices, normals, uvs) -> super() @vertices = vertices @normals = normals @object = object @uvs = uvs @parseModel() parseModel: -> # f vertex vertex vertex ... pattern = /f( [\d]+)( [\d]+)( [\d]+)( [\d]+)?/g while (result = pattern.exec(@object))? # ["f 1 2 3", "1", "2", "3", undefined] unless result[4] @faces.push new THREE.Face3( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 ) else @faces.push new THREE.Face4( parseInt(result[1]) - 1 parseInt(result[2]) - 1 parseInt(result[3]) - 1 parseInt(result[4]) - 1 ) # f vertex/uv vertex/uv vertex/uv ... pattern = /f( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[6]) - 1] @uvs[parseInt(result[9]) - 1] @uvs[parseInt(result[12]) - 1] ] # f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... pattern = /f( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] unless result[13]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] ] else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[6]) - 1 parseInt(result[10]) - 1 parseInt(result[14]) - 1 [ @normals[parseInt(result[4]) - 1] @normals[parseInt(result[8]) - 1] @normals[parseInt(result[12]) - 1] @normals[parseInt(result[16]) - 1] ] ) @faceVertexUvs[0].push [ @uvs[parseInt(result[3]) - 1] @uvs[parseInt(result[7]) - 1] @uvs[parseInt(result[11]) - 1] @uvs[parseInt(result[15]) - 1] ] # f vertex//normal vertex//normal vertex//normal ... pattern = /f( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))?/g while (result = pattern.exec(@object))? # ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] unless result[10]? @faces.push new THREE.Face3( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] ] ) else @faces.push new THREE.Face4( parseInt(result[2]) - 1 parseInt(result[5]) - 1 parseInt(result[8]) - 1 parseInt(result[11]) - 1 [ @normals[parseInt(result[3]) - 1] @normals[parseInt(result[6]) - 1] @normals[parseInt(result[9]) - 1] @normals[parseInt(result[12]) - 1] ] ) @computeCentroids() namespace "THREE", (exports) -> exports.OBJLoader = OBJLoader exports.OBJModel = OBJModel
[ { "context": "\n# Commands:\n#\n# Author:\n# Symphony Integration by Vinay Mistry\nEntities = require('html-entities').XmlEntities\ne", "end": 1407, "score": 0.9997658133506775, "start": 1395, "tag": "NAME", "value": "Vinay Mistry" }, { "context": "= process.env.HUBOT_JIRA_USERNAME\n jiraPassword = process.env.HUBOT_JIRA_PASSWORD\n\n if jiraUsername != unde", "end": 1783, "score": 0.7760342359542847, "start": 1776, "tag": "PASSWORD", "value": "process" }, { "context": "ndefined && jiraUsername.length > 0\n auth = \"#{jiraUsername}:#{jiraPassword}\"\n\n jiraIgnoreUsers = process.en", "end": 1893, "score": 0.9220390319824219, "start": 1881, "tag": "USERNAME", "value": "jiraUsername" } ]
src/scripts/jira.coffee
mcleo-d/bot-butler
3
# # # # Copyright 2016 Symphony Communication Services, LLC # # Licensed to Symphony Communication Services, LLC under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # # # # Description: # Looks up jira issues when they're mentioned in chat # # Will ignore users set in HUBOT_JIRA_ISSUES_IGNORE_USERS (by default, JIRA and GitHub). # # Dependencies: # None # # Configuration: # HUBOT_JIRA_URL (format: "https://jira-domain.com:9090") # HUBOT_JIRA_IGNORECASE (optional; default is "true") # HUBOT_JIRA_USERNAME (optional) # HUBOT_JIRA_PASSWORD (optional) # HUBOT_JIRA_ISSUES_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github") # # Commands: # # Author: # Symphony Integration by Vinay Mistry Entities = require('html-entities').XmlEntities entities = new Entities() module.exports = (robot) -> cache = [] # In case someone upgrades form the previous version, we'll default to the # previous behavior. jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}" jiraUsername = process.env.HUBOT_JIRA_USERNAME jiraPassword = process.env.HUBOT_JIRA_PASSWORD if jiraUsername != undefined && jiraUsername.length > 0 auth = "#{jiraUsername}:#{jiraPassword}" jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS if jiraIgnoreUsers == undefined jiraIgnoreUsers = "jira|github" if auth != undefined robot.http(jiraUrl + "/rest/api/2/project") .auth(auth) .get() (err, res, body) -> json = JSON.parse(body) jiraPrefixes = ( entry.key for entry in json ) reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g" ic = process.env.HUBOT_JIRA_IGNORECASE if ic == undefined || ic == "true" jiraPattern += "i" robot.hear eval(jiraPattern), (msg) -> # return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi")) for i in msg.match issue = i.toUpperCase() now = new Date().getTime() if cache.length > 0 cache.shift() until cache.length is 0 or cache[0].expires >= now msg.send item.message for item in cache when item.issue is issue if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0 robot.http(jiraUrl + "/rest/api/2/issue/" + issue) .auth(auth) .get() (err, res, body) -> try json = JSON.parse(body) key = json.key # Return Cache Results message = "[ Cache" + key + "] " + json.fields.summary message += '\n Cache Status: ' + json.fields.status.name # Return API Results msg.send "<messageML><card iconSrc=\"http://www.icone-png.com/png/52/51835.png\" accent=\"tempo-bg-color--blue\"><header><b >#{key}</b> <b>#{json.fields.summary}</b></header><body>#{json.fields.description}<br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/ ></body></card></messageML>" # <messageML><card iconSrc="https://symphony.foundation/images/SymphonyLlcSymbol.png" accent="tempo-bg-color--purple"><header><a href="https://perzoinc.atlassian.net/browse/ESS-984">ESS-984</a> Checklist: WebRTC settings for s40<i>(header)</i></header><body>d<br/><br/><i>(body)</i></body></card></messageML> # msg.send { # format: 'MESSAGEML' # text: "<messageML><b>#{key}</b> <b>#{json.fields.summary}</b><br/><i>Status: #{json.fields.status.name.toUpperCase()} Priority: #{json.fields.priority.name.toUpperCase()}</i><br/><i>Assignee: #{json.fields.assignee.displayName} Reported By: #{json.fields.reporter.displayName}</i><br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/></messageML>" # } # cache.push({issue: issue, expires: now + 120000, message: message}) catch error try msg.send "[*ERROR*] " + json.errorMessages[0] catch reallyError msg.send "[*ERROR*] " + reallyError
56603
# # # # Copyright 2016 Symphony Communication Services, LLC # # Licensed to Symphony Communication Services, LLC under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # # # # Description: # Looks up jira issues when they're mentioned in chat # # Will ignore users set in HUBOT_JIRA_ISSUES_IGNORE_USERS (by default, JIRA and GitHub). # # Dependencies: # None # # Configuration: # HUBOT_JIRA_URL (format: "https://jira-domain.com:9090") # HUBOT_JIRA_IGNORECASE (optional; default is "true") # HUBOT_JIRA_USERNAME (optional) # HUBOT_JIRA_PASSWORD (optional) # HUBOT_JIRA_ISSUES_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github") # # Commands: # # Author: # Symphony Integration by <NAME> Entities = require('html-entities').XmlEntities entities = new Entities() module.exports = (robot) -> cache = [] # In case someone upgrades form the previous version, we'll default to the # previous behavior. jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}" jiraUsername = process.env.HUBOT_JIRA_USERNAME jiraPassword = <PASSWORD>.env.HUBOT_JIRA_PASSWORD if jiraUsername != undefined && jiraUsername.length > 0 auth = "#{jiraUsername}:#{jiraPassword}" jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS if jiraIgnoreUsers == undefined jiraIgnoreUsers = "jira|github" if auth != undefined robot.http(jiraUrl + "/rest/api/2/project") .auth(auth) .get() (err, res, body) -> json = JSON.parse(body) jiraPrefixes = ( entry.key for entry in json ) reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g" ic = process.env.HUBOT_JIRA_IGNORECASE if ic == undefined || ic == "true" jiraPattern += "i" robot.hear eval(jiraPattern), (msg) -> # return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi")) for i in msg.match issue = i.toUpperCase() now = new Date().getTime() if cache.length > 0 cache.shift() until cache.length is 0 or cache[0].expires >= now msg.send item.message for item in cache when item.issue is issue if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0 robot.http(jiraUrl + "/rest/api/2/issue/" + issue) .auth(auth) .get() (err, res, body) -> try json = JSON.parse(body) key = json.key # Return Cache Results message = "[ Cache" + key + "] " + json.fields.summary message += '\n Cache Status: ' + json.fields.status.name # Return API Results msg.send "<messageML><card iconSrc=\"http://www.icone-png.com/png/52/51835.png\" accent=\"tempo-bg-color--blue\"><header><b >#{key}</b> <b>#{json.fields.summary}</b></header><body>#{json.fields.description}<br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/ ></body></card></messageML>" # <messageML><card iconSrc="https://symphony.foundation/images/SymphonyLlcSymbol.png" accent="tempo-bg-color--purple"><header><a href="https://perzoinc.atlassian.net/browse/ESS-984">ESS-984</a> Checklist: WebRTC settings for s40<i>(header)</i></header><body>d<br/><br/><i>(body)</i></body></card></messageML> # msg.send { # format: 'MESSAGEML' # text: "<messageML><b>#{key}</b> <b>#{json.fields.summary}</b><br/><i>Status: #{json.fields.status.name.toUpperCase()} Priority: #{json.fields.priority.name.toUpperCase()}</i><br/><i>Assignee: #{json.fields.assignee.displayName} Reported By: #{json.fields.reporter.displayName}</i><br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/></messageML>" # } # cache.push({issue: issue, expires: now + 120000, message: message}) catch error try msg.send "[*ERROR*] " + json.errorMessages[0] catch reallyError msg.send "[*ERROR*] " + reallyError
true
# # # # Copyright 2016 Symphony Communication Services, LLC # # Licensed to Symphony Communication Services, LLC under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # # # # Description: # Looks up jira issues when they're mentioned in chat # # Will ignore users set in HUBOT_JIRA_ISSUES_IGNORE_USERS (by default, JIRA and GitHub). # # Dependencies: # None # # Configuration: # HUBOT_JIRA_URL (format: "https://jira-domain.com:9090") # HUBOT_JIRA_IGNORECASE (optional; default is "true") # HUBOT_JIRA_USERNAME (optional) # HUBOT_JIRA_PASSWORD (optional) # HUBOT_JIRA_ISSUES_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github") # # Commands: # # Author: # Symphony Integration by PI:NAME:<NAME>END_PI Entities = require('html-entities').XmlEntities entities = new Entities() module.exports = (robot) -> cache = [] # In case someone upgrades form the previous version, we'll default to the # previous behavior. jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}" jiraUsername = process.env.HUBOT_JIRA_USERNAME jiraPassword = PI:PASSWORD:<PASSWORD>END_PI.env.HUBOT_JIRA_PASSWORD if jiraUsername != undefined && jiraUsername.length > 0 auth = "#{jiraUsername}:#{jiraPassword}" jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS if jiraIgnoreUsers == undefined jiraIgnoreUsers = "jira|github" if auth != undefined robot.http(jiraUrl + "/rest/api/2/project") .auth(auth) .get() (err, res, body) -> json = JSON.parse(body) jiraPrefixes = ( entry.key for entry in json ) reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g" ic = process.env.HUBOT_JIRA_IGNORECASE if ic == undefined || ic == "true" jiraPattern += "i" robot.hear eval(jiraPattern), (msg) -> # return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi")) for i in msg.match issue = i.toUpperCase() now = new Date().getTime() if cache.length > 0 cache.shift() until cache.length is 0 or cache[0].expires >= now msg.send item.message for item in cache when item.issue is issue if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0 robot.http(jiraUrl + "/rest/api/2/issue/" + issue) .auth(auth) .get() (err, res, body) -> try json = JSON.parse(body) key = json.key # Return Cache Results message = "[ Cache" + key + "] " + json.fields.summary message += '\n Cache Status: ' + json.fields.status.name # Return API Results msg.send "<messageML><card iconSrc=\"http://www.icone-png.com/png/52/51835.png\" accent=\"tempo-bg-color--blue\"><header><b >#{key}</b> <b>#{json.fields.summary}</b></header><body>#{json.fields.description}<br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/ ></body></card></messageML>" # <messageML><card iconSrc="https://symphony.foundation/images/SymphonyLlcSymbol.png" accent="tempo-bg-color--purple"><header><a href="https://perzoinc.atlassian.net/browse/ESS-984">ESS-984</a> Checklist: WebRTC settings for s40<i>(header)</i></header><body>d<br/><br/><i>(body)</i></body></card></messageML> # msg.send { # format: 'MESSAGEML' # text: "<messageML><b>#{key}</b> <b>#{json.fields.summary}</b><br/><i>Status: #{json.fields.status.name.toUpperCase()} Priority: #{json.fields.priority.name.toUpperCase()}</i><br/><i>Assignee: #{json.fields.assignee.displayName} Reported By: #{json.fields.reporter.displayName}</i><br/><a href=\"#{entities.encode(jiraUrl)}/browse/#{key}\"/></messageML>" # } # cache.push({issue: issue, expires: now + 120000, message: message}) catch error try msg.send "[*ERROR*] " + json.errorMessages[0] catch reallyError msg.send "[*ERROR*] " + reallyError
[ { "context": " \"mailto:#{@get('email')}?subject=#{subject}&cc=inquiries@artsy.net\"\n\n getSimpleWebsite: ->\n return \"\" unless @ha", "end": 1542, "score": 0.9971751570701599, "start": 1523, "tag": "EMAIL", "value": "inquiries@artsy.net" } ]
src/desktop/models/partner.coffee
mikehrom/force
1
_ = require 'underscore' sd = require('sharify').data Backbone = require 'backbone' Icon = require './icon.coffee' Relations = require './mixins/relations/partner.coffee' module.exports = class Partner extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{sd.API_URL}/api/v1/partner" @types: 'Auction': 'Auction House' 'Demo': 'Demo' 'Gallery': 'Gallery' 'Private Collector': 'Private Collector' 'Private Dealer': 'Gallery' displayType: -> @constructor.types[@get 'type'] or 'Gallery' icon: -> new Icon @get('icon'), profileId: @get('id') isLinkable: -> @get('default_profile_id') and @get('default_profile_public') alphaSortKey: -> @get('sortable_id') href: -> "/partner/#{@get('id')}" displayName: -> @get('name') defaultIconInitials: -> iconInitials = '' reduceFunction = (result, name) -> return result unless name[0] and /\w/.test name[0] result + name[0] iconInitials = _.reduce(@displayName()?.split(' '), reduceFunction, '')[0..1] iconInitials displayNameAndLocation: -> _.compact([ @displayName() @displayLocations() ]).join(', ') # @param {String} preferredCity (optional) displayLocations: (preferredCity) -> @related().locations.displayLocations(preferredCity) getMailTo: -> return "" unless @has('email') && @get('email').length > 0 subject = encodeURIComponent "Connecting with #{@get('name')} via Artsy" "mailto:#{@get('email')}?subject=#{subject}&cc=inquiries@artsy.net" getSimpleWebsite: -> return "" unless @has('website') && @get('website').length > 0 @get('website').replace('http://', '').replace(/\/$/g, '') typeName: -> if @get('type') is 'Gallery' then 'Gallery' else 'Institution' claimed: -> @get('claimed')
112213
_ = require 'underscore' sd = require('sharify').data Backbone = require 'backbone' Icon = require './icon.coffee' Relations = require './mixins/relations/partner.coffee' module.exports = class Partner extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{sd.API_URL}/api/v1/partner" @types: 'Auction': 'Auction House' 'Demo': 'Demo' 'Gallery': 'Gallery' 'Private Collector': 'Private Collector' 'Private Dealer': 'Gallery' displayType: -> @constructor.types[@get 'type'] or 'Gallery' icon: -> new Icon @get('icon'), profileId: @get('id') isLinkable: -> @get('default_profile_id') and @get('default_profile_public') alphaSortKey: -> @get('sortable_id') href: -> "/partner/#{@get('id')}" displayName: -> @get('name') defaultIconInitials: -> iconInitials = '' reduceFunction = (result, name) -> return result unless name[0] and /\w/.test name[0] result + name[0] iconInitials = _.reduce(@displayName()?.split(' '), reduceFunction, '')[0..1] iconInitials displayNameAndLocation: -> _.compact([ @displayName() @displayLocations() ]).join(', ') # @param {String} preferredCity (optional) displayLocations: (preferredCity) -> @related().locations.displayLocations(preferredCity) getMailTo: -> return "" unless @has('email') && @get('email').length > 0 subject = encodeURIComponent "Connecting with #{@get('name')} via Artsy" "mailto:#{@get('email')}?subject=#{subject}&cc=<EMAIL>" getSimpleWebsite: -> return "" unless @has('website') && @get('website').length > 0 @get('website').replace('http://', '').replace(/\/$/g, '') typeName: -> if @get('type') is 'Gallery' then 'Gallery' else 'Institution' claimed: -> @get('claimed')
true
_ = require 'underscore' sd = require('sharify').data Backbone = require 'backbone' Icon = require './icon.coffee' Relations = require './mixins/relations/partner.coffee' module.exports = class Partner extends Backbone.Model _.extend @prototype, Relations urlRoot: "#{sd.API_URL}/api/v1/partner" @types: 'Auction': 'Auction House' 'Demo': 'Demo' 'Gallery': 'Gallery' 'Private Collector': 'Private Collector' 'Private Dealer': 'Gallery' displayType: -> @constructor.types[@get 'type'] or 'Gallery' icon: -> new Icon @get('icon'), profileId: @get('id') isLinkable: -> @get('default_profile_id') and @get('default_profile_public') alphaSortKey: -> @get('sortable_id') href: -> "/partner/#{@get('id')}" displayName: -> @get('name') defaultIconInitials: -> iconInitials = '' reduceFunction = (result, name) -> return result unless name[0] and /\w/.test name[0] result + name[0] iconInitials = _.reduce(@displayName()?.split(' '), reduceFunction, '')[0..1] iconInitials displayNameAndLocation: -> _.compact([ @displayName() @displayLocations() ]).join(', ') # @param {String} preferredCity (optional) displayLocations: (preferredCity) -> @related().locations.displayLocations(preferredCity) getMailTo: -> return "" unless @has('email') && @get('email').length > 0 subject = encodeURIComponent "Connecting with #{@get('name')} via Artsy" "mailto:#{@get('email')}?subject=#{subject}&cc=PI:EMAIL:<EMAIL>END_PI" getSimpleWebsite: -> return "" unless @has('website') && @get('website').length > 0 @get('website').replace('http://', '').replace(/\/$/g, '') typeName: -> if @get('type') is 'Gallery' then 'Gallery' else 'Institution' claimed: -> @get('claimed')
[ { "context": "tion for Backbone.Marionette\n#\n# Copyright (C)2012 Derick Bailey, Muted Solutions, LLC\n# Distributed Under MIT Lic", "end": 108, "score": 0.9998266696929932, "start": 95, "tag": "NAME", "value": "Derick Bailey" }, { "context": "nd Full License Available at:\n# http://github.com/derickbailey/backbone.bbclonemail\n# http://github.com/derickba", "end": 244, "score": 0.9994946122169495, "start": 232, "tag": "USERNAME", "value": "derickbailey" }, { "context": "ckbailey/backbone.bbclonemail\n# http://github.com/derickbailey/backbone.marionette\n#\n# BBCloneMail Models And Co", "end": 298, "score": 0.9996500611305237, "start": 286, "tag": "USERNAME", "value": "derickbailey" } ]
client/01-main/collection.coffee
zhangcheng/bbclonemail-meteor
1
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 Derick Bailey, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # # BBCloneMail Models And Collections # ---------------------------------- # Provide a guaranteed execution of a "reset" event for # collections so I can find an item in the collection after # the collection has been loaded. BBCloneMail.Collection = Backbone.Collection.extend constructor: -> args = Array::slice.call(arguments) Backbone.Collection::constructor.apply @, args @onResetCallbacks = new Backbone.Marionette.Callbacks() @on "reset", @runOnResetCallbacks, @ onReset: (callback) -> @onResetCallbacks.add callback runOnResetCallbacks: -> @onResetCallbacks.run @, @
194089
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 <NAME>, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # # BBCloneMail Models And Collections # ---------------------------------- # Provide a guaranteed execution of a "reset" event for # collections so I can find an item in the collection after # the collection has been loaded. BBCloneMail.Collection = Backbone.Collection.extend constructor: -> args = Array::slice.call(arguments) Backbone.Collection::constructor.apply @, args @onResetCallbacks = new Backbone.Marionette.Callbacks() @on "reset", @runOnResetCallbacks, @ onReset: (callback) -> @onResetCallbacks.add callback runOnResetCallbacks: -> @onResetCallbacks.run @, @
true
# Backbone.BBCloneMail # A reference application for Backbone.Marionette # # Copyright (C)2012 PI:NAME:<NAME>END_PI, Muted Solutions, LLC # Distributed Under MIT License # # Documentation and Full License Available at: # http://github.com/derickbailey/backbone.bbclonemail # http://github.com/derickbailey/backbone.marionette # # BBCloneMail Models And Collections # ---------------------------------- # Provide a guaranteed execution of a "reset" event for # collections so I can find an item in the collection after # the collection has been loaded. BBCloneMail.Collection = Backbone.Collection.extend constructor: -> args = Array::slice.call(arguments) Backbone.Collection::constructor.apply @, args @onResetCallbacks = new Backbone.Marionette.Callbacks() @on "reset", @runOnResetCallbacks, @ onReset: (callback) -> @onResetCallbacks.add callback runOnResetCallbacks: -> @onResetCallbacks.run @, @
[ { "context": " at the start', ->\n expect(_.regexIndexOf('Mr. Smith', /Mr./, 0)).toBe 0\n\n it 'should allow startpo", "end": 1468, "score": 0.9383359551429749, "start": 1459, "tag": "NAME", "value": "Mr. Smith" }, { "context": "o be optional', ->\n expect(_.regexIndexOf('Mr. Smith', /Mr./)).toBe 0\n\n it 'should return the locat", "end": 1580, "score": 0.8201470971107483, "start": 1571, "tag": "NAME", "value": "Mr. Smith" }, { "context": "ch at the end', ->\n expect(_.regexIndexOf('Mr. Smith Jr.', /Jr./)).toBe 10\n\n it 'should return the ", "end": 1701, "score": 0.6706042289733887, "start": 1692, "tag": "NAME", "value": "Mr. Smith" } ]
cyclotron-site/test/unit/mixins-spec.coffee
baumandm/cyclotron
1,657
### # Copyright (c) 2013-2018 the original author or authors. # # Licensed under the MIT License (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.opensource.org/licenses/mit-license.php # # 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. ### # jasmine specs for Mixins go here */ describe 'Unit: _.false', -> it 'should return false', -> expect(_.false()).toBeFalse() describe 'Unit: _.isNullOrUndefined', -> it 'should return true for undefined', -> expect(_.isNullOrUndefined(undefined)).toBeTrue() it 'should return true for null', -> expect(_.isNullOrUndefined(null)).toBeTrue() it 'should return false for an object', -> expect(_.isNullOrUndefined(new Object())).toBeFalse() it 'should return false for a number', -> expect(_.isNullOrUndefined(99)).toBeFalse() describe 'Unit: _.regexIndexOf', -> it 'should return -1 if the regex cannot be found', -> expect(_.regexIndexOf('a string', /regex/, 0)).toBe -1 it 'should return the location of a match at the start', -> expect(_.regexIndexOf('Mr. Smith', /Mr./, 0)).toBe 0 it 'should allow startpos to be optional', -> expect(_.regexIndexOf('Mr. Smith', /Mr./)).toBe 0 it 'should return the location of a match at the end', -> expect(_.regexIndexOf('Mr. Smith Jr.', /Jr./)).toBe 10 it 'should return the location of a match in the middle', -> expect(_.regexIndexOf('405 Parc Ave Apt 445, Seattle', /Apt \d+/)).toBe 13 it 'should return the location of the first match of multiple', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/)).toBe 4 it 'should return the location of the first match of multiple afte the startpos', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/, 6)).toBe 11 describe 'Unit: _.titleCase', -> it 'should return null if given null', -> expect(_.titleCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.titleCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.titleCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.titleCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.titleCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should ignore the case of the rest of the word', -> expect(_.titleCase('GYRO SANDWICH')).toBe 'GYRO SANDWICH' expect(_.titleCase('Expedia EU')).toBe 'Expedia EU' describe 'Unit: _.fromCamelCase', -> it 'should return null if given null', -> expect(_.fromCamelCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.fromCamelCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.fromCamelCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.fromCamelCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.fromCamelCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should split multiple words camel-cased together', -> expect(_.fromCamelCase('gyroSandwich')).toBe 'Gyro Sandwich' expect(_.fromCamelCase('tastyGyroSandwich')).toBe 'Tasty Gyro Sandwich' expect(_.fromCamelCase('5tastyGyroSandwiches')).toBe '5 Tasty Gyro Sandwiches' it 'should operate on multiple camel-case words', -> expect(_.fromCamelCase('mochaLatte & gyroSandwich')).toBe 'Mocha Latte & Gyro Sandwich' describe 'Unit: _.replaceInside', -> it 'should do nothing if given null', -> expect(_.replaceInside(null, null)).toEqual null original = {x: 1} expect(_.replaceInside(original, null)).toEqual null expect(original).toEqual original it 'should return empty object if given that', -> original = {} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should replace an object with an empty object', -> original = {x: 1} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should return the replacement object if original is null', -> original = null expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual null it 'should replace all keys of the original', -> original = {c: 5, d: 6, e: 8} expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual {a: 1, b: 2} it 'should replace with nested objects', -> original = {widget: [{id: 1}]} expect(_.replaceInside(original, {pages: [{duration: 40}]})).toEqual {pages: [{duration: 40}]} expect(original).toEqual {pages: [{duration: 40}]} describe 'Unit: _.numeralformat', -> it 'should return null if given null', -> expect(_.numeralformat('0.0', null)).toBeNull() it 'should return null if given undefined', -> expect(_.numeralformat('0.0', undefined)).toBeNull() it 'should return the number if format is null', -> expect(_.numeralformat(null, 20.20512)).toBe 20.20512 it 'should return the number if format is empty', -> expect(_.numeralformat('', 20.20512)).toBe 20.20512 it 'should return NaN if number is NaN', -> expect(_.numeralformat('0.0', 0/0)).toBe 'NaN' it 'should apply format correctly', -> expect(_.numeralformat('0.0', 20.20512)).toBe '20.2' it 'should apply format correctly to strings', -> expect(_.numeralformat('0,0.0', '2002.041')).toBe '2,002.0' it 'should return the string if a non-numeric string is provided', -> expect(_.numeralformat('0,0.0', 'null')).toBe 'null' describe 'Unit: _.ngApply', -> actual = null mockScope = { $apply: (f) -> actual = f() return 1 } mockFunction = -> 2 it 'should call $apply on the scope and pass the function', -> x = _.ngApply(mockScope, mockFunction)() expect(x).toBe 1 expect(actual).toBe 2 describe 'Unit: _.ngNonPropagatingHandler', -> oracle = { a: 0, b: 0, c: 0 } mockScope = { $apply: (f) -> actual = f() return 1 } mockFunctionA = -> oracle.a = 1 mockFunctionB = -> oracle.b = 2 return true mockFunctionC = -> oracle.c = 3 return 'OK' it 'should return a function', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA) expect(a).toBeFunction() it 'should call the function A and return false', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA)() expect(a).toBeFalse() expect(oracle.a).toBe 1 it 'should call the function B and return false', -> b = _.ngNonPropagatingHandler(mockScope, mockFunctionB)() expect(b).toBeFalse() expect(oracle.b).toBe 2 it 'should call the function C and return false', -> c = _.ngNonPropagatingHandler(mockScope, mockFunctionC)() expect(c).toBeFalse() expect(oracle.c).toBe 3
62126
### # Copyright (c) 2013-2018 the original author or authors. # # Licensed under the MIT License (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.opensource.org/licenses/mit-license.php # # 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. ### # jasmine specs for Mixins go here */ describe 'Unit: _.false', -> it 'should return false', -> expect(_.false()).toBeFalse() describe 'Unit: _.isNullOrUndefined', -> it 'should return true for undefined', -> expect(_.isNullOrUndefined(undefined)).toBeTrue() it 'should return true for null', -> expect(_.isNullOrUndefined(null)).toBeTrue() it 'should return false for an object', -> expect(_.isNullOrUndefined(new Object())).toBeFalse() it 'should return false for a number', -> expect(_.isNullOrUndefined(99)).toBeFalse() describe 'Unit: _.regexIndexOf', -> it 'should return -1 if the regex cannot be found', -> expect(_.regexIndexOf('a string', /regex/, 0)).toBe -1 it 'should return the location of a match at the start', -> expect(_.regexIndexOf('<NAME>', /Mr./, 0)).toBe 0 it 'should allow startpos to be optional', -> expect(_.regexIndexOf('<NAME>', /Mr./)).toBe 0 it 'should return the location of a match at the end', -> expect(_.regexIndexOf('<NAME> Jr.', /Jr./)).toBe 10 it 'should return the location of a match in the middle', -> expect(_.regexIndexOf('405 Parc Ave Apt 445, Seattle', /Apt \d+/)).toBe 13 it 'should return the location of the first match of multiple', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/)).toBe 4 it 'should return the location of the first match of multiple afte the startpos', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/, 6)).toBe 11 describe 'Unit: _.titleCase', -> it 'should return null if given null', -> expect(_.titleCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.titleCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.titleCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.titleCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.titleCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should ignore the case of the rest of the word', -> expect(_.titleCase('GYRO SANDWICH')).toBe 'GYRO SANDWICH' expect(_.titleCase('Expedia EU')).toBe 'Expedia EU' describe 'Unit: _.fromCamelCase', -> it 'should return null if given null', -> expect(_.fromCamelCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.fromCamelCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.fromCamelCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.fromCamelCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.fromCamelCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should split multiple words camel-cased together', -> expect(_.fromCamelCase('gyroSandwich')).toBe 'Gyro Sandwich' expect(_.fromCamelCase('tastyGyroSandwich')).toBe 'Tasty Gyro Sandwich' expect(_.fromCamelCase('5tastyGyroSandwiches')).toBe '5 Tasty Gyro Sandwiches' it 'should operate on multiple camel-case words', -> expect(_.fromCamelCase('mochaLatte & gyroSandwich')).toBe 'Mocha Latte & Gyro Sandwich' describe 'Unit: _.replaceInside', -> it 'should do nothing if given null', -> expect(_.replaceInside(null, null)).toEqual null original = {x: 1} expect(_.replaceInside(original, null)).toEqual null expect(original).toEqual original it 'should return empty object if given that', -> original = {} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should replace an object with an empty object', -> original = {x: 1} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should return the replacement object if original is null', -> original = null expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual null it 'should replace all keys of the original', -> original = {c: 5, d: 6, e: 8} expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual {a: 1, b: 2} it 'should replace with nested objects', -> original = {widget: [{id: 1}]} expect(_.replaceInside(original, {pages: [{duration: 40}]})).toEqual {pages: [{duration: 40}]} expect(original).toEqual {pages: [{duration: 40}]} describe 'Unit: _.numeralformat', -> it 'should return null if given null', -> expect(_.numeralformat('0.0', null)).toBeNull() it 'should return null if given undefined', -> expect(_.numeralformat('0.0', undefined)).toBeNull() it 'should return the number if format is null', -> expect(_.numeralformat(null, 20.20512)).toBe 20.20512 it 'should return the number if format is empty', -> expect(_.numeralformat('', 20.20512)).toBe 20.20512 it 'should return NaN if number is NaN', -> expect(_.numeralformat('0.0', 0/0)).toBe 'NaN' it 'should apply format correctly', -> expect(_.numeralformat('0.0', 20.20512)).toBe '20.2' it 'should apply format correctly to strings', -> expect(_.numeralformat('0,0.0', '2002.041')).toBe '2,002.0' it 'should return the string if a non-numeric string is provided', -> expect(_.numeralformat('0,0.0', 'null')).toBe 'null' describe 'Unit: _.ngApply', -> actual = null mockScope = { $apply: (f) -> actual = f() return 1 } mockFunction = -> 2 it 'should call $apply on the scope and pass the function', -> x = _.ngApply(mockScope, mockFunction)() expect(x).toBe 1 expect(actual).toBe 2 describe 'Unit: _.ngNonPropagatingHandler', -> oracle = { a: 0, b: 0, c: 0 } mockScope = { $apply: (f) -> actual = f() return 1 } mockFunctionA = -> oracle.a = 1 mockFunctionB = -> oracle.b = 2 return true mockFunctionC = -> oracle.c = 3 return 'OK' it 'should return a function', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA) expect(a).toBeFunction() it 'should call the function A and return false', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA)() expect(a).toBeFalse() expect(oracle.a).toBe 1 it 'should call the function B and return false', -> b = _.ngNonPropagatingHandler(mockScope, mockFunctionB)() expect(b).toBeFalse() expect(oracle.b).toBe 2 it 'should call the function C and return false', -> c = _.ngNonPropagatingHandler(mockScope, mockFunctionC)() expect(c).toBeFalse() expect(oracle.c).toBe 3
true
### # Copyright (c) 2013-2018 the original author or authors. # # Licensed under the MIT License (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.opensource.org/licenses/mit-license.php # # 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. ### # jasmine specs for Mixins go here */ describe 'Unit: _.false', -> it 'should return false', -> expect(_.false()).toBeFalse() describe 'Unit: _.isNullOrUndefined', -> it 'should return true for undefined', -> expect(_.isNullOrUndefined(undefined)).toBeTrue() it 'should return true for null', -> expect(_.isNullOrUndefined(null)).toBeTrue() it 'should return false for an object', -> expect(_.isNullOrUndefined(new Object())).toBeFalse() it 'should return false for a number', -> expect(_.isNullOrUndefined(99)).toBeFalse() describe 'Unit: _.regexIndexOf', -> it 'should return -1 if the regex cannot be found', -> expect(_.regexIndexOf('a string', /regex/, 0)).toBe -1 it 'should return the location of a match at the start', -> expect(_.regexIndexOf('PI:NAME:<NAME>END_PI', /Mr./, 0)).toBe 0 it 'should allow startpos to be optional', -> expect(_.regexIndexOf('PI:NAME:<NAME>END_PI', /Mr./)).toBe 0 it 'should return the location of a match at the end', -> expect(_.regexIndexOf('PI:NAME:<NAME>END_PI Jr.', /Jr./)).toBe 10 it 'should return the location of a match in the middle', -> expect(_.regexIndexOf('405 Parc Ave Apt 445, Seattle', /Apt \d+/)).toBe 13 it 'should return the location of the first match of multiple', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/)).toBe 4 it 'should return the location of the first match of multiple afte the startpos', -> expect(_.regexIndexOf('450 NE 445 SE 304.3 SW 33 NW', /[A-Z]{2}/, 6)).toBe 11 describe 'Unit: _.titleCase', -> it 'should return null if given null', -> expect(_.titleCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.titleCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.titleCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.titleCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.titleCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should ignore the case of the rest of the word', -> expect(_.titleCase('GYRO SANDWICH')).toBe 'GYRO SANDWICH' expect(_.titleCase('Expedia EU')).toBe 'Expedia EU' describe 'Unit: _.fromCamelCase', -> it 'should return null if given null', -> expect(_.fromCamelCase(null)).toBeNull() it 'should return undefined if given undefined', -> expect(_.fromCamelCase(undefined)).toBeUndefined() it 'should return empty string if given an empty string', -> expect(_.fromCamelCase('')).toBeEmptyString() it 'should capitalize the first letter of a single word', -> expect(_.fromCamelCase('gyro')).toBe 'Gyro' it 'should capitalize the first letter of each word', -> expect(_.fromCamelCase('gyro sandwich')).toBe 'Gyro Sandwich' it 'should split multiple words camel-cased together', -> expect(_.fromCamelCase('gyroSandwich')).toBe 'Gyro Sandwich' expect(_.fromCamelCase('tastyGyroSandwich')).toBe 'Tasty Gyro Sandwich' expect(_.fromCamelCase('5tastyGyroSandwiches')).toBe '5 Tasty Gyro Sandwiches' it 'should operate on multiple camel-case words', -> expect(_.fromCamelCase('mochaLatte & gyroSandwich')).toBe 'Mocha Latte & Gyro Sandwich' describe 'Unit: _.replaceInside', -> it 'should do nothing if given null', -> expect(_.replaceInside(null, null)).toEqual null original = {x: 1} expect(_.replaceInside(original, null)).toEqual null expect(original).toEqual original it 'should return empty object if given that', -> original = {} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should replace an object with an empty object', -> original = {x: 1} expect(_.replaceInside(original, {})).toEqual {} expect(original).toEqual {} it 'should return the replacement object if original is null', -> original = null expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual null it 'should replace all keys of the original', -> original = {c: 5, d: 6, e: 8} expect(_.replaceInside(original, {a: 1, b: 2})).toEqual {a: 1, b: 2} expect(original).toEqual {a: 1, b: 2} it 'should replace with nested objects', -> original = {widget: [{id: 1}]} expect(_.replaceInside(original, {pages: [{duration: 40}]})).toEqual {pages: [{duration: 40}]} expect(original).toEqual {pages: [{duration: 40}]} describe 'Unit: _.numeralformat', -> it 'should return null if given null', -> expect(_.numeralformat('0.0', null)).toBeNull() it 'should return null if given undefined', -> expect(_.numeralformat('0.0', undefined)).toBeNull() it 'should return the number if format is null', -> expect(_.numeralformat(null, 20.20512)).toBe 20.20512 it 'should return the number if format is empty', -> expect(_.numeralformat('', 20.20512)).toBe 20.20512 it 'should return NaN if number is NaN', -> expect(_.numeralformat('0.0', 0/0)).toBe 'NaN' it 'should apply format correctly', -> expect(_.numeralformat('0.0', 20.20512)).toBe '20.2' it 'should apply format correctly to strings', -> expect(_.numeralformat('0,0.0', '2002.041')).toBe '2,002.0' it 'should return the string if a non-numeric string is provided', -> expect(_.numeralformat('0,0.0', 'null')).toBe 'null' describe 'Unit: _.ngApply', -> actual = null mockScope = { $apply: (f) -> actual = f() return 1 } mockFunction = -> 2 it 'should call $apply on the scope and pass the function', -> x = _.ngApply(mockScope, mockFunction)() expect(x).toBe 1 expect(actual).toBe 2 describe 'Unit: _.ngNonPropagatingHandler', -> oracle = { a: 0, b: 0, c: 0 } mockScope = { $apply: (f) -> actual = f() return 1 } mockFunctionA = -> oracle.a = 1 mockFunctionB = -> oracle.b = 2 return true mockFunctionC = -> oracle.c = 3 return 'OK' it 'should return a function', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA) expect(a).toBeFunction() it 'should call the function A and return false', -> a = _.ngNonPropagatingHandler(mockScope, mockFunctionA)() expect(a).toBeFalse() expect(oracle.a).toBe 1 it 'should call the function B and return false', -> b = _.ngNonPropagatingHandler(mockScope, mockFunctionB)() expect(b).toBeFalse() expect(oracle.b).toBe 2 it 'should call the function C and return false', -> c = _.ngNonPropagatingHandler(mockScope, mockFunctionC)() expect(c).toBeFalse() expect(oracle.c).toBe 3
[ { "context": "@fileoverview Tests for complexity rule.\n# @author Gyandeep Singh\n###\n\n'use strict'\n\n#-----------------------------", "end": 72, "score": 0.9998620748519897, "start": 58, "tag": "NAME", "value": "Gyandeep Singh" }, { "context": "WithoutGet: no\n # ]\n # https://github.com/eslint/eslint/issues/3262\n 'o = set: ->'\n 'Object.", "end": 1340, "score": 0.9371088147163391, "start": 1334, "tag": "USERNAME", "value": "eslint" } ]
src/tests/rules/accessor-pairs.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for complexity rule. # @author Gyandeep Singh ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/accessor-pairs' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingGetterInPropertyDescriptorError = messageId: 'missingGetterInPropertyDescriptor' # setterError = messageId: 'setter' ruleTester.run 'accessor-pairs', rule, valid: [ 'o = { a: 1 }' # 'o = {\n get a() {\n return val \n} \n}' # 'o = {\n set a(value) {\n val = value \n},\n get a() {\n return val \n} \n}' ''' o = {a: 1} Object.defineProperty(o, 'b', { set: (value) -> val = value get: -> val }) ''' # , # code: "expr = 'foo' o = { set [expr](value) { val = value }, get [expr]() { return val } }" # , # code: 'o = {\n set a(value) {\n val = value \n} \n}' # options: [ # setWithoutGet: no # ] # https://github.com/eslint/eslint/issues/3262 'o = set: ->' 'Object.defineProperties obj, set: value: ->' 'Object.create null, set: value: ->' , code: 'o = get: ->', options: [getWithoutSet: yes] , code: 'o = {[set]: ->}' , code: ''' set = 'value' Object.defineProperty(obj, 'foo', {[set]: (value) ->}) ''' ] invalid: [ # code: 'o = {\n set a(value) {\n val = value \n} \n}' # errors: [getterError] # , # code: 'o = {\n get a() {\n return val \n} \n}' # options: [ # getWithoutSet: yes # ] # errors: [setterError] # , code: ''' o = {d: 1} Object.defineProperty o, 'c', set: (value) -> val = value ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Reflect.defineProperty obj, 'foo', set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.defineProperties obj, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.create null, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] # , # code: "expr = 'foo' o = { set [expr](value) { val = value } }" # parserOptions: ecmaVersion: 6 # errors: [getterError] ]
147344
###* # @fileoverview Tests for complexity rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/accessor-pairs' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingGetterInPropertyDescriptorError = messageId: 'missingGetterInPropertyDescriptor' # setterError = messageId: 'setter' ruleTester.run 'accessor-pairs', rule, valid: [ 'o = { a: 1 }' # 'o = {\n get a() {\n return val \n} \n}' # 'o = {\n set a(value) {\n val = value \n},\n get a() {\n return val \n} \n}' ''' o = {a: 1} Object.defineProperty(o, 'b', { set: (value) -> val = value get: -> val }) ''' # , # code: "expr = 'foo' o = { set [expr](value) { val = value }, get [expr]() { return val } }" # , # code: 'o = {\n set a(value) {\n val = value \n} \n}' # options: [ # setWithoutGet: no # ] # https://github.com/eslint/eslint/issues/3262 'o = set: ->' 'Object.defineProperties obj, set: value: ->' 'Object.create null, set: value: ->' , code: 'o = get: ->', options: [getWithoutSet: yes] , code: 'o = {[set]: ->}' , code: ''' set = 'value' Object.defineProperty(obj, 'foo', {[set]: (value) ->}) ''' ] invalid: [ # code: 'o = {\n set a(value) {\n val = value \n} \n}' # errors: [getterError] # , # code: 'o = {\n get a() {\n return val \n} \n}' # options: [ # getWithoutSet: yes # ] # errors: [setterError] # , code: ''' o = {d: 1} Object.defineProperty o, 'c', set: (value) -> val = value ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Reflect.defineProperty obj, 'foo', set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.defineProperties obj, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.create null, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] # , # code: "expr = 'foo' o = { set [expr](value) { val = value } }" # parserOptions: ecmaVersion: 6 # errors: [getterError] ]
true
###* # @fileoverview Tests for complexity rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/accessor-pairs' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingGetterInPropertyDescriptorError = messageId: 'missingGetterInPropertyDescriptor' # setterError = messageId: 'setter' ruleTester.run 'accessor-pairs', rule, valid: [ 'o = { a: 1 }' # 'o = {\n get a() {\n return val \n} \n}' # 'o = {\n set a(value) {\n val = value \n},\n get a() {\n return val \n} \n}' ''' o = {a: 1} Object.defineProperty(o, 'b', { set: (value) -> val = value get: -> val }) ''' # , # code: "expr = 'foo' o = { set [expr](value) { val = value }, get [expr]() { return val } }" # , # code: 'o = {\n set a(value) {\n val = value \n} \n}' # options: [ # setWithoutGet: no # ] # https://github.com/eslint/eslint/issues/3262 'o = set: ->' 'Object.defineProperties obj, set: value: ->' 'Object.create null, set: value: ->' , code: 'o = get: ->', options: [getWithoutSet: yes] , code: 'o = {[set]: ->}' , code: ''' set = 'value' Object.defineProperty(obj, 'foo', {[set]: (value) ->}) ''' ] invalid: [ # code: 'o = {\n set a(value) {\n val = value \n} \n}' # errors: [getterError] # , # code: 'o = {\n get a() {\n return val \n} \n}' # options: [ # getWithoutSet: yes # ] # errors: [setterError] # , code: ''' o = {d: 1} Object.defineProperty o, 'c', set: (value) -> val = value ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Reflect.defineProperty obj, 'foo', set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.defineProperties obj, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] , code: ''' Object.create null, foo: set: (value) -> ''' errors: [missingGetterInPropertyDescriptorError] # , # code: "expr = 'foo' o = { set [expr](value) { val = value } }" # parserOptions: ecmaVersion: 6 # errors: [getterError] ]
[ { "context": "# Copyright (c) 2015 Riceball LEE, MIT License\nltgt = require('ltg", "end": 33, "score": 0.9998031854629517, "start": 21, "tag": "NAME", "value": "Riceball LEE" } ]
src/subkey-iterator.coffee
marwahaha/node-nosql-subkey
0
# Copyright (c) 2015 Riceball LEE, MIT License ltgt = require('ltgt') EncodingIterator = require("encoding-iterator") inherits = require("abstract-object/lib/util/inherits") isArray = require("abstract-object/lib/util/isArray") extend = require("abstract-object/lib/util/_extend") Codec = require('buffer-codec') codec = require("./codec") consts = require("./consts") lowerBound = codec.lowerBound upperBound = codec.upperBound encodeKey = codec.encodeKey decodeKey = codec.decodeKey toLtgt = ltgt.toLtgt GET_OP = consts.GET_OP module.exports = class SubkeyIterator inherits SubkeyIterator, EncodingIterator encodeOptions: (options)-> vOptions = extend {}, options vPath = options.path || [] options.valueEncoding = Codec(options.valueEncoding) options.keyEncoding = keyEncoding = Codec(options.keyEncoding) #the key is lowerBound or upperBound. #if opts.start is exists then lowBound key is opt.start encodeKeyPath = (key) -> encoding = if key is lowerBound or key is upperBound then null else keyEncoding vOptions.path = options.path encodeKey(vPath, key, encoding, vOptions) #convert the lower/upper bounds to real lower/upper bounds. #codec.lowerBound, codec.upperBound are default bounds in case of the options have no bounds. toLtgt(options, options, encodeKeyPath, lowerBound, upperBound) if options.bounded isnt false options.keyAsBuffer = options.valueAsBuffer = false if isArray options.range result = [] for k in options.range vOptions.path = options.path k = encodeKey vPath, k, keyEncoding, vOptions, GET_OP result.push k if k isnt false options.range = result #console.log("it:opts:", options) options decodeResult: (result)-> keyEncoding = @options.keyEncoding valueEncoding = @options.valueEncoding result[0] = decodeKey result[0], keyEncoding, @options if result[0]? result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding result
7844
# Copyright (c) 2015 <NAME>, MIT License ltgt = require('ltgt') EncodingIterator = require("encoding-iterator") inherits = require("abstract-object/lib/util/inherits") isArray = require("abstract-object/lib/util/isArray") extend = require("abstract-object/lib/util/_extend") Codec = require('buffer-codec') codec = require("./codec") consts = require("./consts") lowerBound = codec.lowerBound upperBound = codec.upperBound encodeKey = codec.encodeKey decodeKey = codec.decodeKey toLtgt = ltgt.toLtgt GET_OP = consts.GET_OP module.exports = class SubkeyIterator inherits SubkeyIterator, EncodingIterator encodeOptions: (options)-> vOptions = extend {}, options vPath = options.path || [] options.valueEncoding = Codec(options.valueEncoding) options.keyEncoding = keyEncoding = Codec(options.keyEncoding) #the key is lowerBound or upperBound. #if opts.start is exists then lowBound key is opt.start encodeKeyPath = (key) -> encoding = if key is lowerBound or key is upperBound then null else keyEncoding vOptions.path = options.path encodeKey(vPath, key, encoding, vOptions) #convert the lower/upper bounds to real lower/upper bounds. #codec.lowerBound, codec.upperBound are default bounds in case of the options have no bounds. toLtgt(options, options, encodeKeyPath, lowerBound, upperBound) if options.bounded isnt false options.keyAsBuffer = options.valueAsBuffer = false if isArray options.range result = [] for k in options.range vOptions.path = options.path k = encodeKey vPath, k, keyEncoding, vOptions, GET_OP result.push k if k isnt false options.range = result #console.log("it:opts:", options) options decodeResult: (result)-> keyEncoding = @options.keyEncoding valueEncoding = @options.valueEncoding result[0] = decodeKey result[0], keyEncoding, @options if result[0]? result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding result
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI, MIT License ltgt = require('ltgt') EncodingIterator = require("encoding-iterator") inherits = require("abstract-object/lib/util/inherits") isArray = require("abstract-object/lib/util/isArray") extend = require("abstract-object/lib/util/_extend") Codec = require('buffer-codec') codec = require("./codec") consts = require("./consts") lowerBound = codec.lowerBound upperBound = codec.upperBound encodeKey = codec.encodeKey decodeKey = codec.decodeKey toLtgt = ltgt.toLtgt GET_OP = consts.GET_OP module.exports = class SubkeyIterator inherits SubkeyIterator, EncodingIterator encodeOptions: (options)-> vOptions = extend {}, options vPath = options.path || [] options.valueEncoding = Codec(options.valueEncoding) options.keyEncoding = keyEncoding = Codec(options.keyEncoding) #the key is lowerBound or upperBound. #if opts.start is exists then lowBound key is opt.start encodeKeyPath = (key) -> encoding = if key is lowerBound or key is upperBound then null else keyEncoding vOptions.path = options.path encodeKey(vPath, key, encoding, vOptions) #convert the lower/upper bounds to real lower/upper bounds. #codec.lowerBound, codec.upperBound are default bounds in case of the options have no bounds. toLtgt(options, options, encodeKeyPath, lowerBound, upperBound) if options.bounded isnt false options.keyAsBuffer = options.valueAsBuffer = false if isArray options.range result = [] for k in options.range vOptions.path = options.path k = encodeKey vPath, k, keyEncoding, vOptions, GET_OP result.push k if k isnt false options.range = result #console.log("it:opts:", options) options decodeResult: (result)-> keyEncoding = @options.keyEncoding valueEncoding = @options.valueEncoding result[0] = decodeKey result[0], keyEncoding, @options if result[0]? result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding result
[ { "context": "time('import')\n\t\t\t\t# 辽河区域中心/中国石油抚顺石化公司/石油三厂/分子筛车间,aicfscfzs@petrochina.com.cn,艾长飞,3\n\t\t\t\troot_org = db.organizations.findOne({sp", "end": 1406, "score": 0.9999324083328247, "start": 1379, "tag": "EMAIL", "value": "aicfscfzs@petrochina.com.cn" }, { "context": "3] == 0 then false else true\n\n\t\t\t\t\t\t# 新建user, 默认密码123456\n\t\t\t\t\t\tuser_id = null\n\t\t\t\t\t\tuq = db.users.find({\"e", "end": 1918, "score": 0.9979269504547119, "start": 1912, "tag": "PASSWORD", "value": "123456" }, { "context": "\n\t\t\t\t\t\t\tudoc.steedos_id = email\n\t\t\t\t\t\t\tudoc.name = name\n\t\t\t\t\t\t\tudoc.locale = \"zh-cn\"\n\t\t\t\t\t\t\tudoc.is_delet", "end": 2173, "score": 0.5212746858596802, "start": 2169, "tag": "NAME", "value": "name" }, { "context": " true}]\n\t\t\t\t\t\t\tudoc.services = {password: {bcrypt: \"$2a$10$o2qrOKUtfICH/c3ATkxrwu11h5u5I.Mc4ANU6pMbBjUaNs6C3f2sG\"}}\n\t\t\t\t\t\t\tudoc.created = now\n\t\t\t\t\t\t\tudoc.modified", "end": 2394, "score": 0.9986768960952759, "start": 2333, "tag": "PASSWORD", "value": "\"$2a$10$o2qrOKUtfICH/c3ATkxrwu11h5u5I.Mc4ANU6pMbBjUaNs6C3f2sG" }, { "context": "u_doc.user_accepted = accept\n\t\t\t\t\t\t\t\tsu_doc.name = name\n\t\t\t\t\t\t\t\tsu_doc.email = email\n\t\t\t\t\t\t\t\tsu_doc.creat", "end": 4491, "score": 0.9870633482933044, "start": 4487, "tag": "NAME", "value": "name" }, { "context": " = Package.email.Email\n\t\t\t\t\tEmail.send\n\t\t\t\t\t\tto: 'support@steedos.com'\n\t\t\t\t\t\tfrom: Accounts.emailTemplates.from\n\t\t\t\t\t\ts", "end": 6081, "score": 0.9999226331710815, "start": 6062, "tag": "EMAIL", "value": "support@steedos.com" } ]
packages/steedos-api/routes/import.coffee
steedos/creator
42
# FSSH数据导入规则 # 需要将csv文件 用notepad++ 转为utf-8无bom编码格式 # 在列名行(第一行)前增加符号 井号 用于注释掉列名行 # 需要参数space_id csv = require('csv') Cookies = require("cookies") JsonRoutes.add "post", "/api/import/space_org_users", (req, res, next) -> console.log '====api/import' console.log req.query query = req.query # TODO 用户登录验证 cookies = new Cookies( req, res ); # first check request body if req.body userId = req.body["X-User-Id"] authToken = req.body["X-Auth-Token"] # then check cookie if !userId or !authToken userId = cookies.get("X-User-Id") authToken = cookies.get("X-Auth-Token") if !(userId and authToken) JsonRoutes.sendResult res, code: 401, data: "error": "Validate Request -- Missing X-Auth-Token", "success": false return; if !query || !query.space_id JsonRoutes.sendResult res, data: msg: '缺少参数space_id' return; space_id = query.space_id space = db.spaces.findOne(space_id) if !space || !space?.admins.includes(userId) JsonRoutes.sendResult res, data: msg: '参数space_id非法' return; owner_id = space.owner JsonRoutes.parseFiles req, res, ()-> if req.files and req.files[0] console.log req.files[0] f = req.files[0] dataStr = f.data.toString() csv.parse dataStr, {comment: '#'}, Meteor.bindEnvironment(((err, data) -> console.log data.length console.time('import') # 辽河区域中心/中国石油抚顺石化公司/石油三厂/分子筛车间,aicfscfzs@petrochina.com.cn,艾长飞,3 root_org = db.organizations.findOne({space: space_id, is_company: true, parent: null}) root_org_name = root_org.name root_org_id = root_org._id now = new Date() result = [] data.forEach (row, index)-> try dept_fullname = row[0] depts = dept_fullname.split('/') depts_length = depts.length email = row[1] name = if row[2] then row[2] else "未命名" # 0表示禁用 ,非0表示启用 accept = if row[3] == 0 then false else true # 新建user, 默认密码123456 user_id = null uq = db.users.find({"emails.address": email}) if uq.count() > 0 user_id = uq.fetch()[0]._id else udoc = {} udoc._id = db.users._makeNewID() udoc.steedos_id = email udoc.name = name udoc.locale = "zh-cn" udoc.is_deleted = false udoc.emails = [{address: email, verified: true}] udoc.services = {password: {bcrypt: "$2a$10$o2qrOKUtfICH/c3ATkxrwu11h5u5I.Mc4ANU6pMbBjUaNs6C3f2sG"}} udoc.created = now udoc.modified = now udoc.utcOffset = 8 if row.length >= 7 udoc.username = row[6] user_id = db.users.direct.insert(udoc) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) # 新建organization # if depts[0] == '所有用户组' # i = 1 # else i = 2 fullname = root_org_name parent_org_id = root_org_id while i < depts_length dept_name = depts[i] fullname = fullname + '/' + dept_name co = db.organizations.find({space: space_id, fullname: fullname}) if co.count() > 0 org = co.fetch()[0] parent_org_id = org._id else org_doc = {} org_doc._id = db.organizations._makeNewID() org_doc.space = space_id org_doc.name = dept_name org_doc.parent = parent_org_id org_doc.created = now org_doc.created_by = owner_id org_doc.modified = now org_doc.modified_by = owner_id org_id = db.organizations.direct.insert(org_doc) if org_id org = db.organizations.findOne(org_id) updateFields = {} updateFields.parents = org.calculateParents() updateFields.fullname = org.calculateFullname() if !_.isEmpty(updateFields) db.organizations.direct.update(org._id, {$set: updateFields}) if org.parent parent = db.organizations.findOne(org.parent) db.organizations.direct.update(parent._id, {$set: {children: parent.calculateChildren()}}) parent_org_id = org_id i++ # 新建space_user ,并将space_user放入所属组织 suq = db.space_users.findOne({space: space_id, user: user_id}) space_user_org = db.organizations.findOne({space: space_id, fullname: fullname}) if !suq if space_user_org space_user_org_id = space_user_org._id su_doc = {} su_doc._id = db.space_users._makeNewID() su_doc.user = user_id su_doc.space = space_id su_doc.user_accepted = accept su_doc.name = name su_doc.email = email su_doc.created = now su_doc.created_by = owner_id su_doc.organization = space_user_org_id su_doc.organizations = [su_doc.organization] if row.length >= 5 su_doc.sort_no = row[4] space_user_id = db.space_users.direct.insert(su_doc) if space_user_id # update org users space_user_org.updateUsers() # users_changelogs ucl_doc = {} ucl_doc.change_date = moment().format('YYYYMMDD') ucl_doc.operator = owner_id ucl_doc.space = space_id ucl_doc.operation = "add" ucl_doc.user = user_id ucl_doc.created = now ucl_doc.created_by = owner_id count = db.space_users.direct.find({space: space_id}).count() ucl_doc.user_count = count db.users_changelogs.direct.insert(ucl_doc) else if space_user_org if !suq.organizations suq.organizations = [] suq.organizations.push(space_user_org._id) db.space_users.direct.update({space: space_id, user: user_id}, {$set: {organizations: _.uniq(suq.organizations)}}) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) space_user_org.updateUsers() catch e # ... console.error email console.error e r = {} r.email = email r.error = e.message result.push(r) console.timeEnd('import') if result.length > 0 console.error result Email = Package.email.Email Email.send to: 'support@steedos.com' from: Accounts.emailTemplates.from subject: 'steedos import result' text: JSON.stringify({'result': result}) ), (err)-> console.error 'Failed to bind environment' console.error err ) res.end(); else res.statusCode = 500; res.end();
90137
# FSSH数据导入规则 # 需要将csv文件 用notepad++ 转为utf-8无bom编码格式 # 在列名行(第一行)前增加符号 井号 用于注释掉列名行 # 需要参数space_id csv = require('csv') Cookies = require("cookies") JsonRoutes.add "post", "/api/import/space_org_users", (req, res, next) -> console.log '====api/import' console.log req.query query = req.query # TODO 用户登录验证 cookies = new Cookies( req, res ); # first check request body if req.body userId = req.body["X-User-Id"] authToken = req.body["X-Auth-Token"] # then check cookie if !userId or !authToken userId = cookies.get("X-User-Id") authToken = cookies.get("X-Auth-Token") if !(userId and authToken) JsonRoutes.sendResult res, code: 401, data: "error": "Validate Request -- Missing X-Auth-Token", "success": false return; if !query || !query.space_id JsonRoutes.sendResult res, data: msg: '缺少参数space_id' return; space_id = query.space_id space = db.spaces.findOne(space_id) if !space || !space?.admins.includes(userId) JsonRoutes.sendResult res, data: msg: '参数space_id非法' return; owner_id = space.owner JsonRoutes.parseFiles req, res, ()-> if req.files and req.files[0] console.log req.files[0] f = req.files[0] dataStr = f.data.toString() csv.parse dataStr, {comment: '#'}, Meteor.bindEnvironment(((err, data) -> console.log data.length console.time('import') # 辽河区域中心/中国石油抚顺石化公司/石油三厂/分子筛车间,<EMAIL>,艾长飞,3 root_org = db.organizations.findOne({space: space_id, is_company: true, parent: null}) root_org_name = root_org.name root_org_id = root_org._id now = new Date() result = [] data.forEach (row, index)-> try dept_fullname = row[0] depts = dept_fullname.split('/') depts_length = depts.length email = row[1] name = if row[2] then row[2] else "未命名" # 0表示禁用 ,非0表示启用 accept = if row[3] == 0 then false else true # 新建user, 默认密码<PASSWORD> user_id = null uq = db.users.find({"emails.address": email}) if uq.count() > 0 user_id = uq.fetch()[0]._id else udoc = {} udoc._id = db.users._makeNewID() udoc.steedos_id = email udoc.name = <NAME> udoc.locale = "zh-cn" udoc.is_deleted = false udoc.emails = [{address: email, verified: true}] udoc.services = {password: {bcrypt: <PASSWORD>"}} udoc.created = now udoc.modified = now udoc.utcOffset = 8 if row.length >= 7 udoc.username = row[6] user_id = db.users.direct.insert(udoc) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) # 新建organization # if depts[0] == '所有用户组' # i = 1 # else i = 2 fullname = root_org_name parent_org_id = root_org_id while i < depts_length dept_name = depts[i] fullname = fullname + '/' + dept_name co = db.organizations.find({space: space_id, fullname: fullname}) if co.count() > 0 org = co.fetch()[0] parent_org_id = org._id else org_doc = {} org_doc._id = db.organizations._makeNewID() org_doc.space = space_id org_doc.name = dept_name org_doc.parent = parent_org_id org_doc.created = now org_doc.created_by = owner_id org_doc.modified = now org_doc.modified_by = owner_id org_id = db.organizations.direct.insert(org_doc) if org_id org = db.organizations.findOne(org_id) updateFields = {} updateFields.parents = org.calculateParents() updateFields.fullname = org.calculateFullname() if !_.isEmpty(updateFields) db.organizations.direct.update(org._id, {$set: updateFields}) if org.parent parent = db.organizations.findOne(org.parent) db.organizations.direct.update(parent._id, {$set: {children: parent.calculateChildren()}}) parent_org_id = org_id i++ # 新建space_user ,并将space_user放入所属组织 suq = db.space_users.findOne({space: space_id, user: user_id}) space_user_org = db.organizations.findOne({space: space_id, fullname: fullname}) if !suq if space_user_org space_user_org_id = space_user_org._id su_doc = {} su_doc._id = db.space_users._makeNewID() su_doc.user = user_id su_doc.space = space_id su_doc.user_accepted = accept su_doc.name = <NAME> su_doc.email = email su_doc.created = now su_doc.created_by = owner_id su_doc.organization = space_user_org_id su_doc.organizations = [su_doc.organization] if row.length >= 5 su_doc.sort_no = row[4] space_user_id = db.space_users.direct.insert(su_doc) if space_user_id # update org users space_user_org.updateUsers() # users_changelogs ucl_doc = {} ucl_doc.change_date = moment().format('YYYYMMDD') ucl_doc.operator = owner_id ucl_doc.space = space_id ucl_doc.operation = "add" ucl_doc.user = user_id ucl_doc.created = now ucl_doc.created_by = owner_id count = db.space_users.direct.find({space: space_id}).count() ucl_doc.user_count = count db.users_changelogs.direct.insert(ucl_doc) else if space_user_org if !suq.organizations suq.organizations = [] suq.organizations.push(space_user_org._id) db.space_users.direct.update({space: space_id, user: user_id}, {$set: {organizations: _.uniq(suq.organizations)}}) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) space_user_org.updateUsers() catch e # ... console.error email console.error e r = {} r.email = email r.error = e.message result.push(r) console.timeEnd('import') if result.length > 0 console.error result Email = Package.email.Email Email.send to: '<EMAIL>' from: Accounts.emailTemplates.from subject: 'steedos import result' text: JSON.stringify({'result': result}) ), (err)-> console.error 'Failed to bind environment' console.error err ) res.end(); else res.statusCode = 500; res.end();
true
# FSSH数据导入规则 # 需要将csv文件 用notepad++ 转为utf-8无bom编码格式 # 在列名行(第一行)前增加符号 井号 用于注释掉列名行 # 需要参数space_id csv = require('csv') Cookies = require("cookies") JsonRoutes.add "post", "/api/import/space_org_users", (req, res, next) -> console.log '====api/import' console.log req.query query = req.query # TODO 用户登录验证 cookies = new Cookies( req, res ); # first check request body if req.body userId = req.body["X-User-Id"] authToken = req.body["X-Auth-Token"] # then check cookie if !userId or !authToken userId = cookies.get("X-User-Id") authToken = cookies.get("X-Auth-Token") if !(userId and authToken) JsonRoutes.sendResult res, code: 401, data: "error": "Validate Request -- Missing X-Auth-Token", "success": false return; if !query || !query.space_id JsonRoutes.sendResult res, data: msg: '缺少参数space_id' return; space_id = query.space_id space = db.spaces.findOne(space_id) if !space || !space?.admins.includes(userId) JsonRoutes.sendResult res, data: msg: '参数space_id非法' return; owner_id = space.owner JsonRoutes.parseFiles req, res, ()-> if req.files and req.files[0] console.log req.files[0] f = req.files[0] dataStr = f.data.toString() csv.parse dataStr, {comment: '#'}, Meteor.bindEnvironment(((err, data) -> console.log data.length console.time('import') # 辽河区域中心/中国石油抚顺石化公司/石油三厂/分子筛车间,PI:EMAIL:<EMAIL>END_PI,艾长飞,3 root_org = db.organizations.findOne({space: space_id, is_company: true, parent: null}) root_org_name = root_org.name root_org_id = root_org._id now = new Date() result = [] data.forEach (row, index)-> try dept_fullname = row[0] depts = dept_fullname.split('/') depts_length = depts.length email = row[1] name = if row[2] then row[2] else "未命名" # 0表示禁用 ,非0表示启用 accept = if row[3] == 0 then false else true # 新建user, 默认密码PI:PASSWORD:<PASSWORD>END_PI user_id = null uq = db.users.find({"emails.address": email}) if uq.count() > 0 user_id = uq.fetch()[0]._id else udoc = {} udoc._id = db.users._makeNewID() udoc.steedos_id = email udoc.name = PI:NAME:<NAME>END_PI udoc.locale = "zh-cn" udoc.is_deleted = false udoc.emails = [{address: email, verified: true}] udoc.services = {password: {bcrypt: PI:PASSWORD:<PASSWORD>END_PI"}} udoc.created = now udoc.modified = now udoc.utcOffset = 8 if row.length >= 7 udoc.username = row[6] user_id = db.users.direct.insert(udoc) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) # 新建organization # if depts[0] == '所有用户组' # i = 1 # else i = 2 fullname = root_org_name parent_org_id = root_org_id while i < depts_length dept_name = depts[i] fullname = fullname + '/' + dept_name co = db.organizations.find({space: space_id, fullname: fullname}) if co.count() > 0 org = co.fetch()[0] parent_org_id = org._id else org_doc = {} org_doc._id = db.organizations._makeNewID() org_doc.space = space_id org_doc.name = dept_name org_doc.parent = parent_org_id org_doc.created = now org_doc.created_by = owner_id org_doc.modified = now org_doc.modified_by = owner_id org_id = db.organizations.direct.insert(org_doc) if org_id org = db.organizations.findOne(org_id) updateFields = {} updateFields.parents = org.calculateParents() updateFields.fullname = org.calculateFullname() if !_.isEmpty(updateFields) db.organizations.direct.update(org._id, {$set: updateFields}) if org.parent parent = db.organizations.findOne(org.parent) db.organizations.direct.update(parent._id, {$set: {children: parent.calculateChildren()}}) parent_org_id = org_id i++ # 新建space_user ,并将space_user放入所属组织 suq = db.space_users.findOne({space: space_id, user: user_id}) space_user_org = db.organizations.findOne({space: space_id, fullname: fullname}) if !suq if space_user_org space_user_org_id = space_user_org._id su_doc = {} su_doc._id = db.space_users._makeNewID() su_doc.user = user_id su_doc.space = space_id su_doc.user_accepted = accept su_doc.name = PI:NAME:<NAME>END_PI su_doc.email = email su_doc.created = now su_doc.created_by = owner_id su_doc.organization = space_user_org_id su_doc.organizations = [su_doc.organization] if row.length >= 5 su_doc.sort_no = row[4] space_user_id = db.space_users.direct.insert(su_doc) if space_user_id # update org users space_user_org.updateUsers() # users_changelogs ucl_doc = {} ucl_doc.change_date = moment().format('YYYYMMDD') ucl_doc.operator = owner_id ucl_doc.space = space_id ucl_doc.operation = "add" ucl_doc.user = user_id ucl_doc.created = now ucl_doc.created_by = owner_id count = db.space_users.direct.find({space: space_id}).count() ucl_doc.user_count = count db.users_changelogs.direct.insert(ucl_doc) else if space_user_org if !suq.organizations suq.organizations = [] suq.organizations.push(space_user_org._id) db.space_users.direct.update({space: space_id, user: user_id}, {$set: {organizations: _.uniq(suq.organizations)}}) if row.length >= 6 Accounts.setPassword(user_id, row[5], {logout: false}) space_user_org.updateUsers() catch e # ... console.error email console.error e r = {} r.email = email r.error = e.message result.push(r) console.timeEnd('import') if result.length > 0 console.error result Email = Package.email.Email Email.send to: 'PI:EMAIL:<EMAIL>END_PI' from: Accounts.emailTemplates.from subject: 'steedos import result' text: JSON.stringify({'result': result}) ), (err)-> console.error 'Failed to bind environment' console.error err ) res.end(); else res.statusCode = 500; res.end();
[ { "context": "_pages = \"/\":\n key: \"/\"\n name: \"Hello World\"\n link: \"http://facebook.github.io/react\"\n logo", "end": 45, "score": 0.9989219903945923, "start": 34, "tag": "NAME", "value": "Hello World" } ]
app/stores/PageStore.coffee
arthurpark/brunch-react-skeleton
0
_pages = "/": key: "/" name: "Hello World" link: "http://facebook.github.io/react" logo: "images/react.png" PageStore = getPageFromKey: (key) -> return null unless _pages.hasOwnProperty(key) _pages[key] getAll: -> _pages module.exports = PageStore
43220
_pages = "/": key: "/" name: "<NAME>" link: "http://facebook.github.io/react" logo: "images/react.png" PageStore = getPageFromKey: (key) -> return null unless _pages.hasOwnProperty(key) _pages[key] getAll: -> _pages module.exports = PageStore
true
_pages = "/": key: "/" name: "PI:NAME:<NAME>END_PI" link: "http://facebook.github.io/react" logo: "images/react.png" PageStore = getPageFromKey: (key) -> return null unless _pages.hasOwnProperty(key) _pages[key] getAll: -> _pages module.exports = PageStore
[ { "context": "ror} = require '../errors'\n\nJSONBlobStorageKey = 'task-queue'\n\nif not NylasEnv.isWorkWindow() and not NylasEnv", "end": 422, "score": 0.9878225922584534, "start": 412, "tag": "KEY", "value": "task-queue" } ]
app/src/flux/stores/task-queue.coffee
immershy/nodemail
0
_ = require 'underscore' fs = require 'fs-plus' path = require 'path' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' Task = require "../tasks/task" Utils = require "../models/utils" Reflux = require 'reflux' Actions = require '../actions' DatabaseStore = require './database-store' {APIError, TimeoutError} = require '../errors' JSONBlobStorageKey = 'task-queue' if not NylasEnv.isWorkWindow() and not NylasEnv.inSpecMode() module.exports = {JSONBlobStorageKey} return ### Public: The TaskQueue is a Flux-compatible Store that manages a queue of {Task} objects. Each {Task} represents an individual API action, like sending a draft or marking a thread as "read". Tasks optimistically make changes to the app's local cache and encapsulate logic for performing changes on the server, rolling back in case of failure, and waiting on dependent tasks. The TaskQueue is essential to offline mode in N1. It automatically pauses when the user's internet connection is unavailable and resumes when online. The task queue is persisted to disk, ensuring that tasks are executed later, even if the user quits N1. The TaskQueue is only available in the app's main window. Rather than directly queuing tasks, you should use the {Actions} to interact with the {TaskQueue}. Tasks queued from secondary windows are serialized and sent to the application's main window via IPC. ## Queueing a Task ```coffee if @_thread && @_thread.unread Actions.queueTask(new ChangeStarredTask(thread: @_thread, starred: true)) ``` ## Dequeueing a Task ```coffee Actions.dequeueMatchingTask({ type: 'DestroyCategoryTask', matching: { categoryId: 'bla' } }) ``` ## Creating Tasks Support for creating custom {Task} subclasses in third-party packages is coming soon. This is currently blocked by the ActionBridge, which is responsible for sending actions between windows, since it's JSON serializer is not extensible. Section: Stores ### class TaskQueue @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @_queue = [] @_completed = [] @_updatePeriodicallyTimeout = null @_currentSequentialId = Date.now() @_restoreQueue() @listenTo Actions.queueTask, @enqueue @listenTo Actions.queueTasks, (tasks) => return unless tasks and tasks.length > 0 @enqueue(t) for t in tasks @listenTo Actions.undoTaskId, @enqueueUndoOfTaskId @listenTo Actions.dequeueTask, @dequeue @listenTo Actions.dequeueAllTasks, @dequeueAll @listenTo Actions.dequeueMatchingTask, @dequeueMatching @listenTo Actions.clearDeveloperConsole, @clearCompleted queue: => @_queue ### Public: Returns an existing task in the queue that matches the type you provide, and any other match properties. Useful for checking to see if something, like a "SendDraft" task is in-flight. - `type`: The string name of the task class, or the Task class itself. (ie: {SaveDraftTask} or 'SaveDraftTask') - `matching`: Optional An {Object} with criteria to pass to _.isMatch. For a SaveDraftTask, this could be {draftClientId: "123123"} Returns a matching {Task}, or null. ### findTask: (type, matching = {}) -> type = type.name unless _.isString(type) match = _.find @_queue, (task) -> task.constructor.name is type and _.isMatch(task, matching) match ? null enqueue: (task) => if not (task instanceof Task) throw new Error("You must queue a `Task` instance") if not task.id throw new Error("Tasks must have an ID prior to being queued. Check that your Task constructor is calling `super`") if not task.queueState throw new Error("Tasks must have a queueState prior to being queued. Check that your Task constructor is calling `super`") task.sequentialId = ++@_currentSequentialId @_dequeueObsoleteTasks(task) task.runLocal().then => @_queue.push(task) @_updateSoon() enqueueUndoOfTaskId: (taskId) => task = _.findWhere(@_queue, {id: taskId}) task ?= _.findWhere(@_completed, {id: taskId}) if task @enqueue(task.createUndoTask()) dequeue: (taskOrId) => task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") if task.queueState.isProcessing # We cannot remove a task from the queue while it's running and pretend # things have stopped. Ask the task to cancel. It's promise will resolve # or reject, and then we'll end up back here. task.cancel() else @_queue.splice(@_queue.indexOf(task), 1) @_completed.push(task) @_completed.shift() if @_completed.length > 1000 @_updateSoon() dequeueTaskAndDependents: (taskOrId) -> task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") dequeueAll: => for task in @_queue by -1 @dequeue(task) dequeueMatching: ({type, matching}) => task = @findTask(type, matching) if not task console.warn("Could not find matching task: #{type}", matching) return @dequeue(task) clearCompleted: => @_completed = [] @trigger() # Helper Methods _processQueue: => started = 0 if @_processQueueTimeout clearTimeout(@_processQueueTimeout) @_processQueueTimeout = null now = Date.now() reprocessIn = Number.MAX_VALUE for task in @_queue by -1 if @_taskIsBlocked(task) task.queueState.debugStatus = Task.DebugStatus.WaitingOnDependency continue if task.queueState.retryAfter and task.queueState.retryAfter > now reprocessIn = Math.min(task.queueState.retryAfter - now, reprocessIn) task.queueState.debugStatus = Task.DebugStatus.WaitingToRetry continue @_processTask(task) started += 1 if started > 0 @trigger() if reprocessIn isnt Number.MAX_VALUE @_processQueueTimeout = setTimeout(@_processQueue, reprocessIn + 500) _processTask: (task) => return if task.queueState.isProcessing task.queueState.isProcessing = true task.runRemote() .finally => task.queueState.isProcessing = false @trigger() .then (status) => if status is Task.Status.Retry task.queueState.retryDelay = Math.round(Math.min((task.queueState.retryDelay ? 1000) * 1.2, 30000)) task.queueState.retryAfter = Date.now() + task.queueState.retryDelay else @dequeue(task) @_updateSoon() .catch (err) => @_seenDownstream = {} @_notifyOfDependentError(task, err) .then (responses) => @_dequeueDownstreamTasks(responses) @dequeue(task) # When we `_notifyOfDependentError`s, we collect a nested array of # responses of the tasks we notified. We need to responses to determine # whether or not we should dequeue that task. _dequeueDownstreamTasks: (responses=[]) -> # Responses are nested arrays due to the recursion responses = _.flatten(responses) # A response may be `null` if it hit our infinite recursion check. responses = _.filter responses, (r) -> r? responses.forEach (resp) => resp.downstreamTask.queueState.status = Task.Status.Continue resp.downstreamTask.queueState.debugStatus = Task.DebugStatus.DequeuedDependency @dequeue(resp.downstreamTask) # Recursively notifies tasks of dependent errors _notifyOfDependentError: (failedTask, err) -> downstream = @_tasksDependingOn(failedTask) ? [] Promise.map downstream, (downstreamTask) => return Promise.resolve(null) unless downstreamTask # Infinte recursion check! # These will get removed later return Promise.resolve(null) if @_seenDownstream[downstreamTask.id] @_seenDownstream[downstreamTask.id] = true responseHash = Promise.props returnValue: downstreamTask.onDependentTaskError(failedTask, err) downstreamTask: downstreamTask return Promise.all([ responseHash @_notifyOfDependentError(downstreamTask, err) ]) _dequeueObsoleteTasks: (task) => obsolete = _.filter @_queue, (otherTask) => # Do not interrupt tasks which are currently processing return false if otherTask.queueState.isProcessing # Do not remove ourselves from the queue return false if otherTask is task # Dequeue tasks which our new task indicates it makes obsolete return task.shouldDequeueOtherTask(otherTask) for otherTask in obsolete otherTask.queueState.status = Task.Status.Continue otherTask.queueState.debugStatus = Task.DebugStatus.DequeuedObsolete @dequeue(otherTask) _tasksDependingOn: (task) -> _.filter @_queue, (otherTask) -> otherTask.isDependentOnTask(task) and task isnt otherTask _taskIsBlocked: (task) => _.any @_queue, (otherTask) -> task.isDependentOnTask(otherTask) and task isnt otherTask _resolveTaskArgument: (taskOrId) => if not taskOrId return null else if taskOrId instanceof Task return _.find @_queue, (task) -> task is taskOrId else return _.findWhere(@_queue, id: taskOrId) _restoreQueue: => DatabaseStore.findJSONBlob(JSONBlobStorageKey).then (queue = []) => # We need to set the processing bit back to false so it gets # re-retried upon inflation for task in queue task.queueState ?= {} task.queueState.isProcessing = false delete task.queueState['retryAfter'] delete task.queueState['retryDelay'] @_queue = queue @_updateSoon() _updateSoon: => @_updateSoonThrottled ?= _.throttle => DatabaseStore.inTransaction (t) => t.persistJSONBlob(JSONBlobStorageKey, @_queue ? []) _.defer => @_processQueue() @_ensurePeriodicUpdates() , 10 @_updateSoonThrottled() _ensurePeriodicUpdates: => anyIsProcessing = _.any @_queue, (task) -> task.queueState.isProcessing # The task queue triggers periodically as tasks are processed, even if no # major events have occurred. This allows tasks which have state, like # SendDraftTask.progress to be propogated through the app and inspected. if anyIsProcessing and not @_updatePeriodicallyTimeout @_updatePeriodicallyTimeout = setInterval => @_updateSoon() , 1000 else if not anyIsProcessing and @_updatePeriodicallyTimeout clearTimeout(@_updatePeriodicallyTimeout) @_updatePeriodicallyTimeout = null module.exports = new TaskQueue() module.exports.JSONBlobStorageKey = JSONBlobStorageKey
98164
_ = require 'underscore' fs = require 'fs-plus' path = require 'path' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' Task = require "../tasks/task" Utils = require "../models/utils" Reflux = require 'reflux' Actions = require '../actions' DatabaseStore = require './database-store' {APIError, TimeoutError} = require '../errors' JSONBlobStorageKey = '<KEY>' if not NylasEnv.isWorkWindow() and not NylasEnv.inSpecMode() module.exports = {JSONBlobStorageKey} return ### Public: The TaskQueue is a Flux-compatible Store that manages a queue of {Task} objects. Each {Task} represents an individual API action, like sending a draft or marking a thread as "read". Tasks optimistically make changes to the app's local cache and encapsulate logic for performing changes on the server, rolling back in case of failure, and waiting on dependent tasks. The TaskQueue is essential to offline mode in N1. It automatically pauses when the user's internet connection is unavailable and resumes when online. The task queue is persisted to disk, ensuring that tasks are executed later, even if the user quits N1. The TaskQueue is only available in the app's main window. Rather than directly queuing tasks, you should use the {Actions} to interact with the {TaskQueue}. Tasks queued from secondary windows are serialized and sent to the application's main window via IPC. ## Queueing a Task ```coffee if @_thread && @_thread.unread Actions.queueTask(new ChangeStarredTask(thread: @_thread, starred: true)) ``` ## Dequeueing a Task ```coffee Actions.dequeueMatchingTask({ type: 'DestroyCategoryTask', matching: { categoryId: 'bla' } }) ``` ## Creating Tasks Support for creating custom {Task} subclasses in third-party packages is coming soon. This is currently blocked by the ActionBridge, which is responsible for sending actions between windows, since it's JSON serializer is not extensible. Section: Stores ### class TaskQueue @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @_queue = [] @_completed = [] @_updatePeriodicallyTimeout = null @_currentSequentialId = Date.now() @_restoreQueue() @listenTo Actions.queueTask, @enqueue @listenTo Actions.queueTasks, (tasks) => return unless tasks and tasks.length > 0 @enqueue(t) for t in tasks @listenTo Actions.undoTaskId, @enqueueUndoOfTaskId @listenTo Actions.dequeueTask, @dequeue @listenTo Actions.dequeueAllTasks, @dequeueAll @listenTo Actions.dequeueMatchingTask, @dequeueMatching @listenTo Actions.clearDeveloperConsole, @clearCompleted queue: => @_queue ### Public: Returns an existing task in the queue that matches the type you provide, and any other match properties. Useful for checking to see if something, like a "SendDraft" task is in-flight. - `type`: The string name of the task class, or the Task class itself. (ie: {SaveDraftTask} or 'SaveDraftTask') - `matching`: Optional An {Object} with criteria to pass to _.isMatch. For a SaveDraftTask, this could be {draftClientId: "123123"} Returns a matching {Task}, or null. ### findTask: (type, matching = {}) -> type = type.name unless _.isString(type) match = _.find @_queue, (task) -> task.constructor.name is type and _.isMatch(task, matching) match ? null enqueue: (task) => if not (task instanceof Task) throw new Error("You must queue a `Task` instance") if not task.id throw new Error("Tasks must have an ID prior to being queued. Check that your Task constructor is calling `super`") if not task.queueState throw new Error("Tasks must have a queueState prior to being queued. Check that your Task constructor is calling `super`") task.sequentialId = ++@_currentSequentialId @_dequeueObsoleteTasks(task) task.runLocal().then => @_queue.push(task) @_updateSoon() enqueueUndoOfTaskId: (taskId) => task = _.findWhere(@_queue, {id: taskId}) task ?= _.findWhere(@_completed, {id: taskId}) if task @enqueue(task.createUndoTask()) dequeue: (taskOrId) => task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") if task.queueState.isProcessing # We cannot remove a task from the queue while it's running and pretend # things have stopped. Ask the task to cancel. It's promise will resolve # or reject, and then we'll end up back here. task.cancel() else @_queue.splice(@_queue.indexOf(task), 1) @_completed.push(task) @_completed.shift() if @_completed.length > 1000 @_updateSoon() dequeueTaskAndDependents: (taskOrId) -> task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") dequeueAll: => for task in @_queue by -1 @dequeue(task) dequeueMatching: ({type, matching}) => task = @findTask(type, matching) if not task console.warn("Could not find matching task: #{type}", matching) return @dequeue(task) clearCompleted: => @_completed = [] @trigger() # Helper Methods _processQueue: => started = 0 if @_processQueueTimeout clearTimeout(@_processQueueTimeout) @_processQueueTimeout = null now = Date.now() reprocessIn = Number.MAX_VALUE for task in @_queue by -1 if @_taskIsBlocked(task) task.queueState.debugStatus = Task.DebugStatus.WaitingOnDependency continue if task.queueState.retryAfter and task.queueState.retryAfter > now reprocessIn = Math.min(task.queueState.retryAfter - now, reprocessIn) task.queueState.debugStatus = Task.DebugStatus.WaitingToRetry continue @_processTask(task) started += 1 if started > 0 @trigger() if reprocessIn isnt Number.MAX_VALUE @_processQueueTimeout = setTimeout(@_processQueue, reprocessIn + 500) _processTask: (task) => return if task.queueState.isProcessing task.queueState.isProcessing = true task.runRemote() .finally => task.queueState.isProcessing = false @trigger() .then (status) => if status is Task.Status.Retry task.queueState.retryDelay = Math.round(Math.min((task.queueState.retryDelay ? 1000) * 1.2, 30000)) task.queueState.retryAfter = Date.now() + task.queueState.retryDelay else @dequeue(task) @_updateSoon() .catch (err) => @_seenDownstream = {} @_notifyOfDependentError(task, err) .then (responses) => @_dequeueDownstreamTasks(responses) @dequeue(task) # When we `_notifyOfDependentError`s, we collect a nested array of # responses of the tasks we notified. We need to responses to determine # whether or not we should dequeue that task. _dequeueDownstreamTasks: (responses=[]) -> # Responses are nested arrays due to the recursion responses = _.flatten(responses) # A response may be `null` if it hit our infinite recursion check. responses = _.filter responses, (r) -> r? responses.forEach (resp) => resp.downstreamTask.queueState.status = Task.Status.Continue resp.downstreamTask.queueState.debugStatus = Task.DebugStatus.DequeuedDependency @dequeue(resp.downstreamTask) # Recursively notifies tasks of dependent errors _notifyOfDependentError: (failedTask, err) -> downstream = @_tasksDependingOn(failedTask) ? [] Promise.map downstream, (downstreamTask) => return Promise.resolve(null) unless downstreamTask # Infinte recursion check! # These will get removed later return Promise.resolve(null) if @_seenDownstream[downstreamTask.id] @_seenDownstream[downstreamTask.id] = true responseHash = Promise.props returnValue: downstreamTask.onDependentTaskError(failedTask, err) downstreamTask: downstreamTask return Promise.all([ responseHash @_notifyOfDependentError(downstreamTask, err) ]) _dequeueObsoleteTasks: (task) => obsolete = _.filter @_queue, (otherTask) => # Do not interrupt tasks which are currently processing return false if otherTask.queueState.isProcessing # Do not remove ourselves from the queue return false if otherTask is task # Dequeue tasks which our new task indicates it makes obsolete return task.shouldDequeueOtherTask(otherTask) for otherTask in obsolete otherTask.queueState.status = Task.Status.Continue otherTask.queueState.debugStatus = Task.DebugStatus.DequeuedObsolete @dequeue(otherTask) _tasksDependingOn: (task) -> _.filter @_queue, (otherTask) -> otherTask.isDependentOnTask(task) and task isnt otherTask _taskIsBlocked: (task) => _.any @_queue, (otherTask) -> task.isDependentOnTask(otherTask) and task isnt otherTask _resolveTaskArgument: (taskOrId) => if not taskOrId return null else if taskOrId instanceof Task return _.find @_queue, (task) -> task is taskOrId else return _.findWhere(@_queue, id: taskOrId) _restoreQueue: => DatabaseStore.findJSONBlob(JSONBlobStorageKey).then (queue = []) => # We need to set the processing bit back to false so it gets # re-retried upon inflation for task in queue task.queueState ?= {} task.queueState.isProcessing = false delete task.queueState['retryAfter'] delete task.queueState['retryDelay'] @_queue = queue @_updateSoon() _updateSoon: => @_updateSoonThrottled ?= _.throttle => DatabaseStore.inTransaction (t) => t.persistJSONBlob(JSONBlobStorageKey, @_queue ? []) _.defer => @_processQueue() @_ensurePeriodicUpdates() , 10 @_updateSoonThrottled() _ensurePeriodicUpdates: => anyIsProcessing = _.any @_queue, (task) -> task.queueState.isProcessing # The task queue triggers periodically as tasks are processed, even if no # major events have occurred. This allows tasks which have state, like # SendDraftTask.progress to be propogated through the app and inspected. if anyIsProcessing and not @_updatePeriodicallyTimeout @_updatePeriodicallyTimeout = setInterval => @_updateSoon() , 1000 else if not anyIsProcessing and @_updatePeriodicallyTimeout clearTimeout(@_updatePeriodicallyTimeout) @_updatePeriodicallyTimeout = null module.exports = new TaskQueue() module.exports.JSONBlobStorageKey = JSONBlobStorageKey
true
_ = require 'underscore' fs = require 'fs-plus' path = require 'path' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' Task = require "../tasks/task" Utils = require "../models/utils" Reflux = require 'reflux' Actions = require '../actions' DatabaseStore = require './database-store' {APIError, TimeoutError} = require '../errors' JSONBlobStorageKey = 'PI:KEY:<KEY>END_PI' if not NylasEnv.isWorkWindow() and not NylasEnv.inSpecMode() module.exports = {JSONBlobStorageKey} return ### Public: The TaskQueue is a Flux-compatible Store that manages a queue of {Task} objects. Each {Task} represents an individual API action, like sending a draft or marking a thread as "read". Tasks optimistically make changes to the app's local cache and encapsulate logic for performing changes on the server, rolling back in case of failure, and waiting on dependent tasks. The TaskQueue is essential to offline mode in N1. It automatically pauses when the user's internet connection is unavailable and resumes when online. The task queue is persisted to disk, ensuring that tasks are executed later, even if the user quits N1. The TaskQueue is only available in the app's main window. Rather than directly queuing tasks, you should use the {Actions} to interact with the {TaskQueue}. Tasks queued from secondary windows are serialized and sent to the application's main window via IPC. ## Queueing a Task ```coffee if @_thread && @_thread.unread Actions.queueTask(new ChangeStarredTask(thread: @_thread, starred: true)) ``` ## Dequeueing a Task ```coffee Actions.dequeueMatchingTask({ type: 'DestroyCategoryTask', matching: { categoryId: 'bla' } }) ``` ## Creating Tasks Support for creating custom {Task} subclasses in third-party packages is coming soon. This is currently blocked by the ActionBridge, which is responsible for sending actions between windows, since it's JSON serializer is not extensible. Section: Stores ### class TaskQueue @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @_queue = [] @_completed = [] @_updatePeriodicallyTimeout = null @_currentSequentialId = Date.now() @_restoreQueue() @listenTo Actions.queueTask, @enqueue @listenTo Actions.queueTasks, (tasks) => return unless tasks and tasks.length > 0 @enqueue(t) for t in tasks @listenTo Actions.undoTaskId, @enqueueUndoOfTaskId @listenTo Actions.dequeueTask, @dequeue @listenTo Actions.dequeueAllTasks, @dequeueAll @listenTo Actions.dequeueMatchingTask, @dequeueMatching @listenTo Actions.clearDeveloperConsole, @clearCompleted queue: => @_queue ### Public: Returns an existing task in the queue that matches the type you provide, and any other match properties. Useful for checking to see if something, like a "SendDraft" task is in-flight. - `type`: The string name of the task class, or the Task class itself. (ie: {SaveDraftTask} or 'SaveDraftTask') - `matching`: Optional An {Object} with criteria to pass to _.isMatch. For a SaveDraftTask, this could be {draftClientId: "123123"} Returns a matching {Task}, or null. ### findTask: (type, matching = {}) -> type = type.name unless _.isString(type) match = _.find @_queue, (task) -> task.constructor.name is type and _.isMatch(task, matching) match ? null enqueue: (task) => if not (task instanceof Task) throw new Error("You must queue a `Task` instance") if not task.id throw new Error("Tasks must have an ID prior to being queued. Check that your Task constructor is calling `super`") if not task.queueState throw new Error("Tasks must have a queueState prior to being queued. Check that your Task constructor is calling `super`") task.sequentialId = ++@_currentSequentialId @_dequeueObsoleteTasks(task) task.runLocal().then => @_queue.push(task) @_updateSoon() enqueueUndoOfTaskId: (taskId) => task = _.findWhere(@_queue, {id: taskId}) task ?= _.findWhere(@_completed, {id: taskId}) if task @enqueue(task.createUndoTask()) dequeue: (taskOrId) => task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") if task.queueState.isProcessing # We cannot remove a task from the queue while it's running and pretend # things have stopped. Ask the task to cancel. It's promise will resolve # or reject, and then we'll end up back here. task.cancel() else @_queue.splice(@_queue.indexOf(task), 1) @_completed.push(task) @_completed.shift() if @_completed.length > 1000 @_updateSoon() dequeueTaskAndDependents: (taskOrId) -> task = @_resolveTaskArgument(taskOrId) if not task throw new Error("Couldn't find task in queue to dequeue") dequeueAll: => for task in @_queue by -1 @dequeue(task) dequeueMatching: ({type, matching}) => task = @findTask(type, matching) if not task console.warn("Could not find matching task: #{type}", matching) return @dequeue(task) clearCompleted: => @_completed = [] @trigger() # Helper Methods _processQueue: => started = 0 if @_processQueueTimeout clearTimeout(@_processQueueTimeout) @_processQueueTimeout = null now = Date.now() reprocessIn = Number.MAX_VALUE for task in @_queue by -1 if @_taskIsBlocked(task) task.queueState.debugStatus = Task.DebugStatus.WaitingOnDependency continue if task.queueState.retryAfter and task.queueState.retryAfter > now reprocessIn = Math.min(task.queueState.retryAfter - now, reprocessIn) task.queueState.debugStatus = Task.DebugStatus.WaitingToRetry continue @_processTask(task) started += 1 if started > 0 @trigger() if reprocessIn isnt Number.MAX_VALUE @_processQueueTimeout = setTimeout(@_processQueue, reprocessIn + 500) _processTask: (task) => return if task.queueState.isProcessing task.queueState.isProcessing = true task.runRemote() .finally => task.queueState.isProcessing = false @trigger() .then (status) => if status is Task.Status.Retry task.queueState.retryDelay = Math.round(Math.min((task.queueState.retryDelay ? 1000) * 1.2, 30000)) task.queueState.retryAfter = Date.now() + task.queueState.retryDelay else @dequeue(task) @_updateSoon() .catch (err) => @_seenDownstream = {} @_notifyOfDependentError(task, err) .then (responses) => @_dequeueDownstreamTasks(responses) @dequeue(task) # When we `_notifyOfDependentError`s, we collect a nested array of # responses of the tasks we notified. We need to responses to determine # whether or not we should dequeue that task. _dequeueDownstreamTasks: (responses=[]) -> # Responses are nested arrays due to the recursion responses = _.flatten(responses) # A response may be `null` if it hit our infinite recursion check. responses = _.filter responses, (r) -> r? responses.forEach (resp) => resp.downstreamTask.queueState.status = Task.Status.Continue resp.downstreamTask.queueState.debugStatus = Task.DebugStatus.DequeuedDependency @dequeue(resp.downstreamTask) # Recursively notifies tasks of dependent errors _notifyOfDependentError: (failedTask, err) -> downstream = @_tasksDependingOn(failedTask) ? [] Promise.map downstream, (downstreamTask) => return Promise.resolve(null) unless downstreamTask # Infinte recursion check! # These will get removed later return Promise.resolve(null) if @_seenDownstream[downstreamTask.id] @_seenDownstream[downstreamTask.id] = true responseHash = Promise.props returnValue: downstreamTask.onDependentTaskError(failedTask, err) downstreamTask: downstreamTask return Promise.all([ responseHash @_notifyOfDependentError(downstreamTask, err) ]) _dequeueObsoleteTasks: (task) => obsolete = _.filter @_queue, (otherTask) => # Do not interrupt tasks which are currently processing return false if otherTask.queueState.isProcessing # Do not remove ourselves from the queue return false if otherTask is task # Dequeue tasks which our new task indicates it makes obsolete return task.shouldDequeueOtherTask(otherTask) for otherTask in obsolete otherTask.queueState.status = Task.Status.Continue otherTask.queueState.debugStatus = Task.DebugStatus.DequeuedObsolete @dequeue(otherTask) _tasksDependingOn: (task) -> _.filter @_queue, (otherTask) -> otherTask.isDependentOnTask(task) and task isnt otherTask _taskIsBlocked: (task) => _.any @_queue, (otherTask) -> task.isDependentOnTask(otherTask) and task isnt otherTask _resolveTaskArgument: (taskOrId) => if not taskOrId return null else if taskOrId instanceof Task return _.find @_queue, (task) -> task is taskOrId else return _.findWhere(@_queue, id: taskOrId) _restoreQueue: => DatabaseStore.findJSONBlob(JSONBlobStorageKey).then (queue = []) => # We need to set the processing bit back to false so it gets # re-retried upon inflation for task in queue task.queueState ?= {} task.queueState.isProcessing = false delete task.queueState['retryAfter'] delete task.queueState['retryDelay'] @_queue = queue @_updateSoon() _updateSoon: => @_updateSoonThrottled ?= _.throttle => DatabaseStore.inTransaction (t) => t.persistJSONBlob(JSONBlobStorageKey, @_queue ? []) _.defer => @_processQueue() @_ensurePeriodicUpdates() , 10 @_updateSoonThrottled() _ensurePeriodicUpdates: => anyIsProcessing = _.any @_queue, (task) -> task.queueState.isProcessing # The task queue triggers periodically as tasks are processed, even if no # major events have occurred. This allows tasks which have state, like # SendDraftTask.progress to be propogated through the app and inspected. if anyIsProcessing and not @_updatePeriodicallyTimeout @_updatePeriodicallyTimeout = setInterval => @_updateSoon() , 1000 else if not anyIsProcessing and @_updatePeriodicallyTimeout clearTimeout(@_updatePeriodicallyTimeout) @_updatePeriodicallyTimeout = null module.exports = new TaskQueue() module.exports.JSONBlobStorageKey = JSONBlobStorageKey
[ { "context": "text onto HTML canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under ", "end": 106, "score": 0.9998903274536133, "start": 95, "tag": "NAME", "value": "Karl Naylor" }, { "context": " canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under law, the author(s)", "end": 124, "score": 0.9999279379844666, "start": 108, "tag": "EMAIL", "value": "kpn103@yahoo.com" } ]
src/content/coffee/handywriteOnCanvas/boxes.coffee
karlorg/phonetify
1
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by Karl Naylor <kpn103@yahoo.com> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> 'use strict' boxes = {} boxes.BoundingBox = class BoundingBox constructor: (@_left, @_top, @_right, @_bottom, @_transformed=false) -> # @transformed should be false if this bounding box is in the default # grapheme co-ordinate system, true otherwise left: -> @_left top: -> @_top right: -> @_right bottom: -> @_bottom scale: (sx, sy) -> new BoundingBox( @_left * sx, @_top * sy, @_right * sx, @_bottom * sy, true) translate: (dx, dy) -> new BoundingBox( @_left + dx, @_top + dy, @_right + dx, @_bottom + dy, true) boxes.boxFromPoints = (pointList) -> unless pointList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((point.x for point in pointList)...) top = Math.min((point.y for point in pointList)...) right = Math.max((point.x for point in pointList)...) bottom = Math.max((point.y for point in pointList)...) return new BoundingBox(left, top, right, bottom) boxes.combineBoundingBoxes = (boxList) -> unless boxList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((box.left() for box in boxList)...) top = Math.min((box.top() for box in boxList)...) right = Math.max((box.right() for box in boxList)...) bottom = Math.max((box.bottom() for box in boxList)...) return new BoundingBox(left, top, right, bottom, boxList[0]._transformed) return boxes
175141
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by <NAME> <<EMAIL>> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> 'use strict' boxes = {} boxes.BoundingBox = class BoundingBox constructor: (@_left, @_top, @_right, @_bottom, @_transformed=false) -> # @transformed should be false if this bounding box is in the default # grapheme co-ordinate system, true otherwise left: -> @_left top: -> @_top right: -> @_right bottom: -> @_bottom scale: (sx, sy) -> new BoundingBox( @_left * sx, @_top * sy, @_right * sx, @_bottom * sy, true) translate: (dx, dy) -> new BoundingBox( @_left + dx, @_top + dy, @_right + dx, @_bottom + dy, true) boxes.boxFromPoints = (pointList) -> unless pointList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((point.x for point in pointList)...) top = Math.min((point.y for point in pointList)...) right = Math.max((point.x for point in pointList)...) bottom = Math.max((point.y for point in pointList)...) return new BoundingBox(left, top, right, bottom) boxes.combineBoundingBoxes = (boxList) -> unless boxList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((box.left() for box in boxList)...) top = Math.min((box.top() for box in boxList)...) right = Math.max((box.right() for box in boxList)...) bottom = Math.max((box.bottom() for box in boxList)...) return new BoundingBox(left, top, right, bottom, boxList[0]._transformed) return boxes
true
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define -> 'use strict' boxes = {} boxes.BoundingBox = class BoundingBox constructor: (@_left, @_top, @_right, @_bottom, @_transformed=false) -> # @transformed should be false if this bounding box is in the default # grapheme co-ordinate system, true otherwise left: -> @_left top: -> @_top right: -> @_right bottom: -> @_bottom scale: (sx, sy) -> new BoundingBox( @_left * sx, @_top * sy, @_right * sx, @_bottom * sy, true) translate: (dx, dy) -> new BoundingBox( @_left + dx, @_top + dy, @_right + dx, @_bottom + dy, true) boxes.boxFromPoints = (pointList) -> unless pointList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((point.x for point in pointList)...) top = Math.min((point.y for point in pointList)...) right = Math.max((point.x for point in pointList)...) bottom = Math.max((point.y for point in pointList)...) return new BoundingBox(left, top, right, bottom) boxes.combineBoundingBoxes = (boxList) -> unless boxList.length then return new BoundingBox(0, 0, 0, 0) left = Math.min((box.left() for box in boxList)...) top = Math.min((box.top() for box in boxList)...) right = Math.max((box.right() for box in boxList)...) bottom = Math.max((box.bottom() for box in boxList)...) return new BoundingBox(left, top, right, bottom, boxList[0]._transformed) return boxes
[ { "context": "images/yokohama/neg-z.jpg'\n # ]);\n # runPrefix('storforsen');\n # runPrefix('Lycksele2');\n # runPrefix('Fja", "end": 9792, "score": 0.9937788844108582, "start": 9782, "tag": "USERNAME", "value": "storforsen" }, { "context": "# ]);\n # runPrefix('storforsen');\n # runPrefix('Lycksele2');\n # runPrefix('Fjaderholmarna');\n # runPrefix", "end": 9820, "score": 0.9706819653511047, "start": 9811, "tag": "USERNAME", "value": "Lycksele2" }, { "context": "sen');\n # runPrefix('Lycksele2');\n # runPrefix('Fjaderholmarna');\n # runPrefix(\"GoldenGateBridge\");", "end": 9841, "score": 0.5807069540023804, "start": 9839, "tag": "USERNAME", "value": "Fj" }, { "context": "n');\n # runPrefix('Lycksele2');\n # runPrefix('Fjaderholmarna');\n # runPrefix(\"GoldenGateBridge\");\n\n ts = new", "end": 9853, "score": 0.9081048965454102, "start": 9841, "tag": "NAME", "value": "aderholmarna" } ]
oldsrc/threesixty.coffee
TeamTrumpet/trumpet-auditorium
0
class ThreeSixty # The interval of movement for keyboard movements interval: Math.PI / 200 # When the drift speed is smaller than this number, drifting stops driftSpeedCutoff: 0.01 # The amount that is multipled by the speed every frame that there isn't any # movement from the mouse driftSlowdownRate: 0.90 # Vertial angle that is cut off from exceeding verticalAngleCutOff: Math.PI / 4 # Constant twoPI: (2 * Math.PI) # The direction keys that are mapped arrowDirections: [ 'left' 'right' 'up' 'down' 'w' 'a' 's' 'd' ] keyboardAliases: 'left': 37 'up': 38 'right': 39 'down': 40 constructor: (images)-> # This source is the javascript needed to build a sky box in **three.js** # It is the source about this [blog post](/blog/2011/08/15/lets-do-a-sky/). # Now lets start # declare a bunch of variable we will need later @camera = undefined @scene = undefined @renderer = undefined @keyboard = undefined @alpha = 0 @beta = 0 @gamma = 0 @keys = pressed: {} active: false @events = 'mouse': active: false panning: false position: x: 0 y: 0 @run images initEventHandlers: -> # Create the keyboard monitor document.addEventListener 'keydown', @onKeyDown, false # Setup handlers for all the arrow direction id's if they exist @arrowDirections.forEach (direction) => directionElement = document.getElementById(direction) @events[direction] = false if directionElement directionElement.addEventListener 'mousedown', => @events[direction] = true return directionElement.addEventListener 'click', (e) -> e.preventDefault() return directionElement.addEventListener 'mouseup', => @events[direction] = false return return document.addEventListener 'mouseup', => @arrowDirections.forEach (direction) => @events[direction] = false return @events['mouse'].active = false document.body.style.cursor = 'auto' return document.addEventListener 'mousemove', (event) => if @events['mouse'].active @events['mouse'].position.x = event.movementX @events['mouse'].position.y = event.movementY return @renderer.domElement.addEventListener 'mousedown', => @events['mouse'].active = true @events['mouse'].panning = true document.body.style.cursor = 'move' return # when the window is resized, we need to change our camera and renderer window.addEventListener 'resize', @onWindowResize, false degToRad = (degrees) -> degrees * Math.PI / 180 deviceOrientationChanged = (event) -> # Or rotation about Z @alpha = degToRad(event.alpha) # Or rotation about X @beta = degToRad(event.beta) - (Math.PI / 2) # Or rotation about Y @gamma = degToRad(event.gamma) # Set the data to json document.getElementById('debug').innerHTML = JSON.stringify({ alpha: @alpha beta: @beta gamma: @gamma }, null, 2) return # window.ondeviceorientation = _.throttle(deviceOrientationChanged, 300); return # Initialize everything init: (images) -> # Create the scene @scene = new (THREE.Scene) # Create the camera @camera = new (THREE.PerspectiveCamera)(70, window.innerWidth / window.innerHeight, 1, 1000) # Because we don't rotate in the Z direction, this will be a natural rotation order @camera.rotation.order = 'YXZ' # Load them THREE.ImageUtils.loadTextureCube(images, null, @onTextureLoad) onTextureLoad: (textureCube) => # init the cube shadder shader = THREE.ShaderLib['cube'] # Setup the uniform uniforms = THREE.UniformsUtils.clone(shader.uniforms) uniforms['tCube'].value = textureCube # camerate the material material = new (THREE.ShaderMaterial)( fragmentShader: shader.fragmentShader vertexShader: shader.vertexShader uniforms: uniforms side: THREE.BackSide) # Generate a sphere geometry meshGeometry = new (THREE.SphereGeometry)(1000, 32, 32) # build the skybox Mesh using the texture cube skyBox = new (THREE.Mesh)(meshGeometry, material) # and add it to the scene @scene.add skyBox # create the container element @renderer = new (THREE.WebGLRenderer)(antialias: true) # Set it to match the window @renderer.setSize window.innerWidth, window.innerHeight # Add it to the document body document.body.appendChild @renderer.domElement # Add event handlers @initEventHandlers() # make it move! @render() return onKeyDown: (event) => # Get the key pressed key = event.keyCode console.log "onKeyDown: #{key}" @keyPressed key return keyPressed: (key) => # Check if a keyboard key was pressed if @camera.keys(ThreeSixty::keyboardAliases).indexOf(key) != -1 @keys.pressed[key] = true @keys.active = true @move ThreeSixty::keyboardAliases[key] else # Check to see if a keyboard direction was pressed ThreeSixty::arrowDirections.some (direction) => # If it was pressed if direction.toUpperCase().charCodeAt(0) == key @keys.pressed[key] = true @keys.active = true # Move @move direction # And return true to kill the loop return true return onWindowResize: -> @camera.aspect = window.innerWidth / window.innerHeight @camera.updateProjectionMatrix() @renderer.setSize window.innerWidth, window.innerHeight return # Execute the move in the direction indicated move: (action) -> console.log "Moving #{action}" @move@camera action, @camera @render() return move@camera: (action, @camera) -> @move@cameraAt action, @camera, ThreeSixty::interval if action == 'up' or action == 'down' or action == 'w' or action == 's' @correctMovement @camera return clearDebug: -> document.getElementById('debug').innerHTML = null return addDebug: (obj) -> document.getElementById('debug').appendChild(document.createTextNode(JSON.stringify(obj, null, 2))) return # Move the @camera in the direction indicated at the rate indicated as well move@cameraAt: (action, @camera, rate) -> switch action when 'left', 'a' @camera.rotation.y = (@camera.rotation.y + rate) % ThreeSixty::twoPI when 'right', 'd' @camera.rotation.y = (@camera.rotation.y - rate) % ThreeSixty::twoPI when 'up', 'w' @camera.rotation.x = (@camera.rotation.x + rate) % ThreeSixty::twoPI when 'down', 's' @camera.rotation.x = (@camera.rotation.x - rate) % ThreeSixty::twoPI else break return # Correct the over and under rotation to prevent us from going upside down correctMovement: (@camera) -> # If we are going up or down if @camera.rotation.x < -ThreeSixty::verticalAngleCutOff @camera.rotation.x = -ThreeSixty::verticalAngleCutOff else if @camera.rotation.x > ThreeSixty::verticalAngleCutOff @camera.rotation.x = ThreeSixty::verticalAngleCutOff return # Animate all the camera actions for the mouse animateCameraFromMouse: -> xMovement = @events['mouse'].position.y / 400 yMovement = @events['mouse'].position.x / 400 console.log "Mouse moving x: #{}" @camera.rotation.x += xMovement @camera.rotation.y += yMovement @correctMovement @camera # Stop drift @events['mouse'].position.x *= @driftSlowdownRate @events['mouse'].position.y *= @driftSlowdownRate if !@events['mouse'].active and Math.abs(@events['mouse'].position.x) < @driftSpeedCutoff and Math.abs(@events['mouse'].position.y) < @driftSpeedCutoff # Stop the movement @events['mouse'].position.x = 0 @events['mouse'].position.y = 0 # Stop the panning @events['mouse'].panning = false return # Render the scene (called every frame) render: -> # Request this to be re-run if @events['mouse'].panning requestAnimationFrame ThreeSixty::render.bind(this) # If we are still panning @animateCameraFromMouse() # # If the mouse is not in use # if !@events['mouse'].active # # Then check buttons + keyboard # @arrowDirections.forEach (direction) => # if @keyboard.pressed(direction) or @events[direction] # @move direction # return # # Set the gyro # camera.rotation.x = beta; # camera.rotation.y = alpha; # # Set the data to json # document.getElementById('debug').innerHTML = JSON.stringify(@camera.rotation, null, 2) # Actually render the scene @renderer.render @scene, @camera return run: (images) -> # bootstrap functions # initialiaze everything @init images return document.addEventListener 'DOMContentLoaded', -> prefixData = (prefix) -> [ 'images/' + prefix + '/posx.jpg' 'images/' + prefix + '/negx.jpg' 'images/' + prefix + '/posy.jpg' 'images/' + prefix + '/negy.jpg' 'images/' + prefix + '/posz.jpg' 'images/' + prefix + '/negz.jpg' ] # run([ # 'images/canary/pos-x.png', # 'images/canary/neg-x.png', # 'images/canary/pos-y.png', # 'images/canary/neg-y.png', # 'images/canary/pos-z.png', # 'images/canary/neg-z.png' # ]); # run([ # 'images/yokohama/pos-x.jpg', # 'images/yokohama/neg-x.jpg', # 'images/yokohama/pos-y.jpg', # 'images/yokohama/neg-y.jpg', # 'images/yokohama/pos-z.jpg', # 'images/yokohama/neg-z.jpg' # ]); # runPrefix('storforsen'); # runPrefix('Lycksele2'); # runPrefix('Fjaderholmarna'); # runPrefix("GoldenGateBridge"); ts = new ThreeSixty prefixData('storforsen') return
58273
class ThreeSixty # The interval of movement for keyboard movements interval: Math.PI / 200 # When the drift speed is smaller than this number, drifting stops driftSpeedCutoff: 0.01 # The amount that is multipled by the speed every frame that there isn't any # movement from the mouse driftSlowdownRate: 0.90 # Vertial angle that is cut off from exceeding verticalAngleCutOff: Math.PI / 4 # Constant twoPI: (2 * Math.PI) # The direction keys that are mapped arrowDirections: [ 'left' 'right' 'up' 'down' 'w' 'a' 's' 'd' ] keyboardAliases: 'left': 37 'up': 38 'right': 39 'down': 40 constructor: (images)-> # This source is the javascript needed to build a sky box in **three.js** # It is the source about this [blog post](/blog/2011/08/15/lets-do-a-sky/). # Now lets start # declare a bunch of variable we will need later @camera = undefined @scene = undefined @renderer = undefined @keyboard = undefined @alpha = 0 @beta = 0 @gamma = 0 @keys = pressed: {} active: false @events = 'mouse': active: false panning: false position: x: 0 y: 0 @run images initEventHandlers: -> # Create the keyboard monitor document.addEventListener 'keydown', @onKeyDown, false # Setup handlers for all the arrow direction id's if they exist @arrowDirections.forEach (direction) => directionElement = document.getElementById(direction) @events[direction] = false if directionElement directionElement.addEventListener 'mousedown', => @events[direction] = true return directionElement.addEventListener 'click', (e) -> e.preventDefault() return directionElement.addEventListener 'mouseup', => @events[direction] = false return return document.addEventListener 'mouseup', => @arrowDirections.forEach (direction) => @events[direction] = false return @events['mouse'].active = false document.body.style.cursor = 'auto' return document.addEventListener 'mousemove', (event) => if @events['mouse'].active @events['mouse'].position.x = event.movementX @events['mouse'].position.y = event.movementY return @renderer.domElement.addEventListener 'mousedown', => @events['mouse'].active = true @events['mouse'].panning = true document.body.style.cursor = 'move' return # when the window is resized, we need to change our camera and renderer window.addEventListener 'resize', @onWindowResize, false degToRad = (degrees) -> degrees * Math.PI / 180 deviceOrientationChanged = (event) -> # Or rotation about Z @alpha = degToRad(event.alpha) # Or rotation about X @beta = degToRad(event.beta) - (Math.PI / 2) # Or rotation about Y @gamma = degToRad(event.gamma) # Set the data to json document.getElementById('debug').innerHTML = JSON.stringify({ alpha: @alpha beta: @beta gamma: @gamma }, null, 2) return # window.ondeviceorientation = _.throttle(deviceOrientationChanged, 300); return # Initialize everything init: (images) -> # Create the scene @scene = new (THREE.Scene) # Create the camera @camera = new (THREE.PerspectiveCamera)(70, window.innerWidth / window.innerHeight, 1, 1000) # Because we don't rotate in the Z direction, this will be a natural rotation order @camera.rotation.order = 'YXZ' # Load them THREE.ImageUtils.loadTextureCube(images, null, @onTextureLoad) onTextureLoad: (textureCube) => # init the cube shadder shader = THREE.ShaderLib['cube'] # Setup the uniform uniforms = THREE.UniformsUtils.clone(shader.uniforms) uniforms['tCube'].value = textureCube # camerate the material material = new (THREE.ShaderMaterial)( fragmentShader: shader.fragmentShader vertexShader: shader.vertexShader uniforms: uniforms side: THREE.BackSide) # Generate a sphere geometry meshGeometry = new (THREE.SphereGeometry)(1000, 32, 32) # build the skybox Mesh using the texture cube skyBox = new (THREE.Mesh)(meshGeometry, material) # and add it to the scene @scene.add skyBox # create the container element @renderer = new (THREE.WebGLRenderer)(antialias: true) # Set it to match the window @renderer.setSize window.innerWidth, window.innerHeight # Add it to the document body document.body.appendChild @renderer.domElement # Add event handlers @initEventHandlers() # make it move! @render() return onKeyDown: (event) => # Get the key pressed key = event.keyCode console.log "onKeyDown: #{key}" @keyPressed key return keyPressed: (key) => # Check if a keyboard key was pressed if @camera.keys(ThreeSixty::keyboardAliases).indexOf(key) != -1 @keys.pressed[key] = true @keys.active = true @move ThreeSixty::keyboardAliases[key] else # Check to see if a keyboard direction was pressed ThreeSixty::arrowDirections.some (direction) => # If it was pressed if direction.toUpperCase().charCodeAt(0) == key @keys.pressed[key] = true @keys.active = true # Move @move direction # And return true to kill the loop return true return onWindowResize: -> @camera.aspect = window.innerWidth / window.innerHeight @camera.updateProjectionMatrix() @renderer.setSize window.innerWidth, window.innerHeight return # Execute the move in the direction indicated move: (action) -> console.log "Moving #{action}" @move@camera action, @camera @render() return move@camera: (action, @camera) -> @move@cameraAt action, @camera, ThreeSixty::interval if action == 'up' or action == 'down' or action == 'w' or action == 's' @correctMovement @camera return clearDebug: -> document.getElementById('debug').innerHTML = null return addDebug: (obj) -> document.getElementById('debug').appendChild(document.createTextNode(JSON.stringify(obj, null, 2))) return # Move the @camera in the direction indicated at the rate indicated as well move@cameraAt: (action, @camera, rate) -> switch action when 'left', 'a' @camera.rotation.y = (@camera.rotation.y + rate) % ThreeSixty::twoPI when 'right', 'd' @camera.rotation.y = (@camera.rotation.y - rate) % ThreeSixty::twoPI when 'up', 'w' @camera.rotation.x = (@camera.rotation.x + rate) % ThreeSixty::twoPI when 'down', 's' @camera.rotation.x = (@camera.rotation.x - rate) % ThreeSixty::twoPI else break return # Correct the over and under rotation to prevent us from going upside down correctMovement: (@camera) -> # If we are going up or down if @camera.rotation.x < -ThreeSixty::verticalAngleCutOff @camera.rotation.x = -ThreeSixty::verticalAngleCutOff else if @camera.rotation.x > ThreeSixty::verticalAngleCutOff @camera.rotation.x = ThreeSixty::verticalAngleCutOff return # Animate all the camera actions for the mouse animateCameraFromMouse: -> xMovement = @events['mouse'].position.y / 400 yMovement = @events['mouse'].position.x / 400 console.log "Mouse moving x: #{}" @camera.rotation.x += xMovement @camera.rotation.y += yMovement @correctMovement @camera # Stop drift @events['mouse'].position.x *= @driftSlowdownRate @events['mouse'].position.y *= @driftSlowdownRate if !@events['mouse'].active and Math.abs(@events['mouse'].position.x) < @driftSpeedCutoff and Math.abs(@events['mouse'].position.y) < @driftSpeedCutoff # Stop the movement @events['mouse'].position.x = 0 @events['mouse'].position.y = 0 # Stop the panning @events['mouse'].panning = false return # Render the scene (called every frame) render: -> # Request this to be re-run if @events['mouse'].panning requestAnimationFrame ThreeSixty::render.bind(this) # If we are still panning @animateCameraFromMouse() # # If the mouse is not in use # if !@events['mouse'].active # # Then check buttons + keyboard # @arrowDirections.forEach (direction) => # if @keyboard.pressed(direction) or @events[direction] # @move direction # return # # Set the gyro # camera.rotation.x = beta; # camera.rotation.y = alpha; # # Set the data to json # document.getElementById('debug').innerHTML = JSON.stringify(@camera.rotation, null, 2) # Actually render the scene @renderer.render @scene, @camera return run: (images) -> # bootstrap functions # initialiaze everything @init images return document.addEventListener 'DOMContentLoaded', -> prefixData = (prefix) -> [ 'images/' + prefix + '/posx.jpg' 'images/' + prefix + '/negx.jpg' 'images/' + prefix + '/posy.jpg' 'images/' + prefix + '/negy.jpg' 'images/' + prefix + '/posz.jpg' 'images/' + prefix + '/negz.jpg' ] # run([ # 'images/canary/pos-x.png', # 'images/canary/neg-x.png', # 'images/canary/pos-y.png', # 'images/canary/neg-y.png', # 'images/canary/pos-z.png', # 'images/canary/neg-z.png' # ]); # run([ # 'images/yokohama/pos-x.jpg', # 'images/yokohama/neg-x.jpg', # 'images/yokohama/pos-y.jpg', # 'images/yokohama/neg-y.jpg', # 'images/yokohama/pos-z.jpg', # 'images/yokohama/neg-z.jpg' # ]); # runPrefix('storforsen'); # runPrefix('Lycksele2'); # runPrefix('Fj<NAME>'); # runPrefix("GoldenGateBridge"); ts = new ThreeSixty prefixData('storforsen') return
true
class ThreeSixty # The interval of movement for keyboard movements interval: Math.PI / 200 # When the drift speed is smaller than this number, drifting stops driftSpeedCutoff: 0.01 # The amount that is multipled by the speed every frame that there isn't any # movement from the mouse driftSlowdownRate: 0.90 # Vertial angle that is cut off from exceeding verticalAngleCutOff: Math.PI / 4 # Constant twoPI: (2 * Math.PI) # The direction keys that are mapped arrowDirections: [ 'left' 'right' 'up' 'down' 'w' 'a' 's' 'd' ] keyboardAliases: 'left': 37 'up': 38 'right': 39 'down': 40 constructor: (images)-> # This source is the javascript needed to build a sky box in **three.js** # It is the source about this [blog post](/blog/2011/08/15/lets-do-a-sky/). # Now lets start # declare a bunch of variable we will need later @camera = undefined @scene = undefined @renderer = undefined @keyboard = undefined @alpha = 0 @beta = 0 @gamma = 0 @keys = pressed: {} active: false @events = 'mouse': active: false panning: false position: x: 0 y: 0 @run images initEventHandlers: -> # Create the keyboard monitor document.addEventListener 'keydown', @onKeyDown, false # Setup handlers for all the arrow direction id's if they exist @arrowDirections.forEach (direction) => directionElement = document.getElementById(direction) @events[direction] = false if directionElement directionElement.addEventListener 'mousedown', => @events[direction] = true return directionElement.addEventListener 'click', (e) -> e.preventDefault() return directionElement.addEventListener 'mouseup', => @events[direction] = false return return document.addEventListener 'mouseup', => @arrowDirections.forEach (direction) => @events[direction] = false return @events['mouse'].active = false document.body.style.cursor = 'auto' return document.addEventListener 'mousemove', (event) => if @events['mouse'].active @events['mouse'].position.x = event.movementX @events['mouse'].position.y = event.movementY return @renderer.domElement.addEventListener 'mousedown', => @events['mouse'].active = true @events['mouse'].panning = true document.body.style.cursor = 'move' return # when the window is resized, we need to change our camera and renderer window.addEventListener 'resize', @onWindowResize, false degToRad = (degrees) -> degrees * Math.PI / 180 deviceOrientationChanged = (event) -> # Or rotation about Z @alpha = degToRad(event.alpha) # Or rotation about X @beta = degToRad(event.beta) - (Math.PI / 2) # Or rotation about Y @gamma = degToRad(event.gamma) # Set the data to json document.getElementById('debug').innerHTML = JSON.stringify({ alpha: @alpha beta: @beta gamma: @gamma }, null, 2) return # window.ondeviceorientation = _.throttle(deviceOrientationChanged, 300); return # Initialize everything init: (images) -> # Create the scene @scene = new (THREE.Scene) # Create the camera @camera = new (THREE.PerspectiveCamera)(70, window.innerWidth / window.innerHeight, 1, 1000) # Because we don't rotate in the Z direction, this will be a natural rotation order @camera.rotation.order = 'YXZ' # Load them THREE.ImageUtils.loadTextureCube(images, null, @onTextureLoad) onTextureLoad: (textureCube) => # init the cube shadder shader = THREE.ShaderLib['cube'] # Setup the uniform uniforms = THREE.UniformsUtils.clone(shader.uniforms) uniforms['tCube'].value = textureCube # camerate the material material = new (THREE.ShaderMaterial)( fragmentShader: shader.fragmentShader vertexShader: shader.vertexShader uniforms: uniforms side: THREE.BackSide) # Generate a sphere geometry meshGeometry = new (THREE.SphereGeometry)(1000, 32, 32) # build the skybox Mesh using the texture cube skyBox = new (THREE.Mesh)(meshGeometry, material) # and add it to the scene @scene.add skyBox # create the container element @renderer = new (THREE.WebGLRenderer)(antialias: true) # Set it to match the window @renderer.setSize window.innerWidth, window.innerHeight # Add it to the document body document.body.appendChild @renderer.domElement # Add event handlers @initEventHandlers() # make it move! @render() return onKeyDown: (event) => # Get the key pressed key = event.keyCode console.log "onKeyDown: #{key}" @keyPressed key return keyPressed: (key) => # Check if a keyboard key was pressed if @camera.keys(ThreeSixty::keyboardAliases).indexOf(key) != -1 @keys.pressed[key] = true @keys.active = true @move ThreeSixty::keyboardAliases[key] else # Check to see if a keyboard direction was pressed ThreeSixty::arrowDirections.some (direction) => # If it was pressed if direction.toUpperCase().charCodeAt(0) == key @keys.pressed[key] = true @keys.active = true # Move @move direction # And return true to kill the loop return true return onWindowResize: -> @camera.aspect = window.innerWidth / window.innerHeight @camera.updateProjectionMatrix() @renderer.setSize window.innerWidth, window.innerHeight return # Execute the move in the direction indicated move: (action) -> console.log "Moving #{action}" @move@camera action, @camera @render() return move@camera: (action, @camera) -> @move@cameraAt action, @camera, ThreeSixty::interval if action == 'up' or action == 'down' or action == 'w' or action == 's' @correctMovement @camera return clearDebug: -> document.getElementById('debug').innerHTML = null return addDebug: (obj) -> document.getElementById('debug').appendChild(document.createTextNode(JSON.stringify(obj, null, 2))) return # Move the @camera in the direction indicated at the rate indicated as well move@cameraAt: (action, @camera, rate) -> switch action when 'left', 'a' @camera.rotation.y = (@camera.rotation.y + rate) % ThreeSixty::twoPI when 'right', 'd' @camera.rotation.y = (@camera.rotation.y - rate) % ThreeSixty::twoPI when 'up', 'w' @camera.rotation.x = (@camera.rotation.x + rate) % ThreeSixty::twoPI when 'down', 's' @camera.rotation.x = (@camera.rotation.x - rate) % ThreeSixty::twoPI else break return # Correct the over and under rotation to prevent us from going upside down correctMovement: (@camera) -> # If we are going up or down if @camera.rotation.x < -ThreeSixty::verticalAngleCutOff @camera.rotation.x = -ThreeSixty::verticalAngleCutOff else if @camera.rotation.x > ThreeSixty::verticalAngleCutOff @camera.rotation.x = ThreeSixty::verticalAngleCutOff return # Animate all the camera actions for the mouse animateCameraFromMouse: -> xMovement = @events['mouse'].position.y / 400 yMovement = @events['mouse'].position.x / 400 console.log "Mouse moving x: #{}" @camera.rotation.x += xMovement @camera.rotation.y += yMovement @correctMovement @camera # Stop drift @events['mouse'].position.x *= @driftSlowdownRate @events['mouse'].position.y *= @driftSlowdownRate if !@events['mouse'].active and Math.abs(@events['mouse'].position.x) < @driftSpeedCutoff and Math.abs(@events['mouse'].position.y) < @driftSpeedCutoff # Stop the movement @events['mouse'].position.x = 0 @events['mouse'].position.y = 0 # Stop the panning @events['mouse'].panning = false return # Render the scene (called every frame) render: -> # Request this to be re-run if @events['mouse'].panning requestAnimationFrame ThreeSixty::render.bind(this) # If we are still panning @animateCameraFromMouse() # # If the mouse is not in use # if !@events['mouse'].active # # Then check buttons + keyboard # @arrowDirections.forEach (direction) => # if @keyboard.pressed(direction) or @events[direction] # @move direction # return # # Set the gyro # camera.rotation.x = beta; # camera.rotation.y = alpha; # # Set the data to json # document.getElementById('debug').innerHTML = JSON.stringify(@camera.rotation, null, 2) # Actually render the scene @renderer.render @scene, @camera return run: (images) -> # bootstrap functions # initialiaze everything @init images return document.addEventListener 'DOMContentLoaded', -> prefixData = (prefix) -> [ 'images/' + prefix + '/posx.jpg' 'images/' + prefix + '/negx.jpg' 'images/' + prefix + '/posy.jpg' 'images/' + prefix + '/negy.jpg' 'images/' + prefix + '/posz.jpg' 'images/' + prefix + '/negz.jpg' ] # run([ # 'images/canary/pos-x.png', # 'images/canary/neg-x.png', # 'images/canary/pos-y.png', # 'images/canary/neg-y.png', # 'images/canary/pos-z.png', # 'images/canary/neg-z.png' # ]); # run([ # 'images/yokohama/pos-x.jpg', # 'images/yokohama/neg-x.jpg', # 'images/yokohama/pos-y.jpg', # 'images/yokohama/neg-y.jpg', # 'images/yokohama/pos-z.jpg', # 'images/yokohama/neg-z.jpg' # ]); # runPrefix('storforsen'); # runPrefix('Lycksele2'); # runPrefix('FjPI:NAME:<NAME>END_PI'); # runPrefix("GoldenGateBridge"); ts = new ThreeSixty prefixData('storforsen') return
[ { "context": "TF-8 <=> UTF-16 convertion\n# \n# Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n# Version: 1.0\n# LastModified: ", "end": 142, "score": 0.9998875260353088, "start": 129, "tag": "NAME", "value": "Masanao Izumo" }, { "context": "convertion\n# \n# Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n# Version: 1.0\n# LastModified: Dec 25 1999\n# Thi", "end": 159, "score": 0.9999332427978516, "start": 144, "tag": "EMAIL", "value": "iz@onicos.co.jp" } ]
runtime/u8a_to_string.coffee
cheery/better_web_language
0
# http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt # utf.js - UTF-8 <=> UTF-16 convertion # # Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> # Version: 1.0 # LastModified: Dec 25 1999 # This library is free. You can redistribute it and/or modify it. # # Translated to coffeescript. # Added choice to pick range to translate from. # If this was C, it would have potential overflow bug. btw. betterweb.utf8ToString = (array, start=0, stop=array.length) -> out = "" i = start while i < stop c = array[i++] d = c >> 4 if c < 128 # 0xxxxxxx out += String.fromCharCode(c) else if d == 12 or d == 13 # 110x xxxx 10xx xxxx char2 = array[i++] out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)) else if d == 14 # 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++] char3 = array[i++] out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)) else throw "XXX: utf-8 decoding error?" return out
163505
# http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt # utf.js - UTF-8 <=> UTF-16 convertion # # Copyright (C) 1999 <NAME> <<EMAIL>> # Version: 1.0 # LastModified: Dec 25 1999 # This library is free. You can redistribute it and/or modify it. # # Translated to coffeescript. # Added choice to pick range to translate from. # If this was C, it would have potential overflow bug. btw. betterweb.utf8ToString = (array, start=0, stop=array.length) -> out = "" i = start while i < stop c = array[i++] d = c >> 4 if c < 128 # 0xxxxxxx out += String.fromCharCode(c) else if d == 12 or d == 13 # 110x xxxx 10xx xxxx char2 = array[i++] out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)) else if d == 14 # 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++] char3 = array[i++] out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)) else throw "XXX: utf-8 decoding error?" return out
true
# http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt # utf.js - UTF-8 <=> UTF-16 convertion # # Copyright (C) 1999 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Version: 1.0 # LastModified: Dec 25 1999 # This library is free. You can redistribute it and/or modify it. # # Translated to coffeescript. # Added choice to pick range to translate from. # If this was C, it would have potential overflow bug. btw. betterweb.utf8ToString = (array, start=0, stop=array.length) -> out = "" i = start while i < stop c = array[i++] d = c >> 4 if c < 128 # 0xxxxxxx out += String.fromCharCode(c) else if d == 12 or d == 13 # 110x xxxx 10xx xxxx char2 = array[i++] out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)) else if d == 14 # 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++] char3 = array[i++] out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)) else throw "XXX: utf-8 decoding error?" return out
[ { "context": "(@els[0], {})\n if Type.isString key\n key = camelCase key\n if arguments.length < 2\n return ", "end": 480, "score": 0.745714545249939, "start": 471, "tag": "KEY", "value": "camelCase" } ]
src/coffee/kernel/cache/cache.coffee
oatw/luda
183
import luda from '../base/luda.coffee' import camelCase from '../base/camel-case.coffee' import Type from '../base/type.coffee' import {access, _access} from './helpers/access.coffee' import './remove-cache.coffee' luda.extend cache: (isPrivate) -> if isPrivate then _access() else access() luda.include cache: (key, value) -> unless key return unless @els[0] return access(@els[0]) or access(@els[0], {}) if Type.isString key key = camelCase key if arguments.length < 2 return unless @els[0] access(@els[0], {}) unless access(@els[0]) return access @els[0], key return this if value is undefined return @removeCache key if value is null @els.forEach (el) -> access(el, {}) unless access(el) access el, key, value return this @cache k, v for k, v of key this
91787
import luda from '../base/luda.coffee' import camelCase from '../base/camel-case.coffee' import Type from '../base/type.coffee' import {access, _access} from './helpers/access.coffee' import './remove-cache.coffee' luda.extend cache: (isPrivate) -> if isPrivate then _access() else access() luda.include cache: (key, value) -> unless key return unless @els[0] return access(@els[0]) or access(@els[0], {}) if Type.isString key key = <KEY> key if arguments.length < 2 return unless @els[0] access(@els[0], {}) unless access(@els[0]) return access @els[0], key return this if value is undefined return @removeCache key if value is null @els.forEach (el) -> access(el, {}) unless access(el) access el, key, value return this @cache k, v for k, v of key this
true
import luda from '../base/luda.coffee' import camelCase from '../base/camel-case.coffee' import Type from '../base/type.coffee' import {access, _access} from './helpers/access.coffee' import './remove-cache.coffee' luda.extend cache: (isPrivate) -> if isPrivate then _access() else access() luda.include cache: (key, value) -> unless key return unless @els[0] return access(@els[0]) or access(@els[0], {}) if Type.isString key key = PI:KEY:<KEY>END_PI key if arguments.length < 2 return unless @els[0] access(@els[0], {}) unless access(@els[0]) return access @els[0], key return this if value is undefined return @removeCache key if value is null @els.forEach (el) -> access(el, {}) unless access(el) access el, key, value return this @cache k, v for k, v of key this
[ { "context": "e- Generates default rule template\n#\n# Author:\n# Scott J Roberts - @sroberts\n\nmodule.exports = (robot) ->\n robot.", "end": 209, "score": 0.9998759031295776, "start": 194, "tag": "NAME", "value": "Scott J Roberts" }, { "context": "lt rule template\n#\n# Author:\n# Scott J Roberts - @sroberts\n\nmodule.exports = (robot) ->\n robot.respond /yar", "end": 221, "score": 0.9992750883102417, "start": 212, "tag": "USERNAME", "value": "@sroberts" } ]
src/scripts/yara.coffee
3ch01c/hubot-vtr-scripts
47
# Description: # Generate Yara Rule with strings # # Dependencies: # None # # Configuration: # None… # # Commands: # hubot yara template- Generates default rule template # # Author: # Scott J Roberts - @sroberts module.exports = (robot) -> robot.respond /yara template/i, (msg) -> # Default Values yara_rule_name = "rule_name" yara_rule_category = "category" yara_meta_author = "Hubot" yara_meta_date = "2013-01-01" yara_meta_description = "Default Rule Template" yara_strings_list = ['foo', 'bar', 'baz'] # If there's strings generate rule with strings # Generate Strings Section # yara_conditions = 0 # yara_strings_parsed = "" # # for yara_string in yara_strings_list # yara_strings_parsed += " string#{yara_conditions} '#{yara_string}'\n" # yara_conditions++ new_rule = """ rule #{yara_rule_name} : #{yara_rule_category} { meta: author = '#{yara_meta_author}' date = '#{yara_meta_date}' description = '#{yara_meta_description}' strings: $string0 = "foo" $string1 = "bar" $string2 = "baz" wide condition: 3 of them } """ msg.send new_rule
24327
# Description: # Generate Yara Rule with strings # # Dependencies: # None # # Configuration: # None… # # Commands: # hubot yara template- Generates default rule template # # Author: # <NAME> - @sroberts module.exports = (robot) -> robot.respond /yara template/i, (msg) -> # Default Values yara_rule_name = "rule_name" yara_rule_category = "category" yara_meta_author = "Hubot" yara_meta_date = "2013-01-01" yara_meta_description = "Default Rule Template" yara_strings_list = ['foo', 'bar', 'baz'] # If there's strings generate rule with strings # Generate Strings Section # yara_conditions = 0 # yara_strings_parsed = "" # # for yara_string in yara_strings_list # yara_strings_parsed += " string#{yara_conditions} '#{yara_string}'\n" # yara_conditions++ new_rule = """ rule #{yara_rule_name} : #{yara_rule_category} { meta: author = '#{yara_meta_author}' date = '#{yara_meta_date}' description = '#{yara_meta_description}' strings: $string0 = "foo" $string1 = "bar" $string2 = "baz" wide condition: 3 of them } """ msg.send new_rule
true
# Description: # Generate Yara Rule with strings # # Dependencies: # None # # Configuration: # None… # # Commands: # hubot yara template- Generates default rule template # # Author: # PI:NAME:<NAME>END_PI - @sroberts module.exports = (robot) -> robot.respond /yara template/i, (msg) -> # Default Values yara_rule_name = "rule_name" yara_rule_category = "category" yara_meta_author = "Hubot" yara_meta_date = "2013-01-01" yara_meta_description = "Default Rule Template" yara_strings_list = ['foo', 'bar', 'baz'] # If there's strings generate rule with strings # Generate Strings Section # yara_conditions = 0 # yara_strings_parsed = "" # # for yara_string in yara_strings_list # yara_strings_parsed += " string#{yara_conditions} '#{yara_string}'\n" # yara_conditions++ new_rule = """ rule #{yara_rule_name} : #{yara_rule_category} { meta: author = '#{yara_meta_author}' date = '#{yara_meta_date}' description = '#{yara_meta_description}' strings: $string0 = "foo" $string1 = "bar" $string2 = "baz" wide condition: 3 of them } """ msg.send new_rule
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9986030459403992, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "eq.resume()\n return\n\nserver.listen common.PORT, \"127.0.0.1\", ->\n i = 0\n\n while i < 10\n connections++\n ", "end": 1810, "score": 0.9932437539100647, "start": 1801, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/pummel/test-http-upload-timeout.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This tests setTimeout() by having multiple clients connecting and sending # data in random intervals. Clients are also randomly disconnecting until there # are no more clients left. If no false timeout occurs, this test has passed. common = require("../common") assert = require("assert") http = require("http") server = http.createServer() connections = 0 server.on "request", (req, res) -> req.socket.setTimeout 1000 req.socket.on "timeout", -> throw new Error("Unexpected timeout")return req.on "end", -> connections-- res.writeHead 200 res.end "done\n" server.close() if connections is 0 return req.resume() return server.listen common.PORT, "127.0.0.1", -> i = 0 while i < 10 connections++ setTimeout (-> ping = -> nextPing = (Math.random() * 900).toFixed() if nextPing > 600 request.end() return request.write "ping" setTimeout ping, nextPing return request = http.request( port: common.PORT method: "POST" path: "/" ) ping() return ), i * 50 i++ return
54054
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This tests setTimeout() by having multiple clients connecting and sending # data in random intervals. Clients are also randomly disconnecting until there # are no more clients left. If no false timeout occurs, this test has passed. common = require("../common") assert = require("assert") http = require("http") server = http.createServer() connections = 0 server.on "request", (req, res) -> req.socket.setTimeout 1000 req.socket.on "timeout", -> throw new Error("Unexpected timeout")return req.on "end", -> connections-- res.writeHead 200 res.end "done\n" server.close() if connections is 0 return req.resume() return server.listen common.PORT, "127.0.0.1", -> i = 0 while i < 10 connections++ setTimeout (-> ping = -> nextPing = (Math.random() * 900).toFixed() if nextPing > 600 request.end() return request.write "ping" setTimeout ping, nextPing return request = http.request( port: common.PORT method: "POST" path: "/" ) ping() return ), i * 50 i++ return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # This tests setTimeout() by having multiple clients connecting and sending # data in random intervals. Clients are also randomly disconnecting until there # are no more clients left. If no false timeout occurs, this test has passed. common = require("../common") assert = require("assert") http = require("http") server = http.createServer() connections = 0 server.on "request", (req, res) -> req.socket.setTimeout 1000 req.socket.on "timeout", -> throw new Error("Unexpected timeout")return req.on "end", -> connections-- res.writeHead 200 res.end "done\n" server.close() if connections is 0 return req.resume() return server.listen common.PORT, "127.0.0.1", -> i = 0 while i < 10 connections++ setTimeout (-> ping = -> nextPing = (Math.random() * 900).toFixed() if nextPing > 600 request.end() return request.write "ping" setTimeout ping, nextPing return request = http.request( port: common.PORT method: "POST" path: "/" ) ping() return ), i * 50 i++ return
[ { "context": "module.exports =\n\n\tuser:\n\t\tpassword:\t\t\"bacerocks\"\n\t\ttimeoutMins:\t\"30\"\n\n\t\ttheme: \t\t\t'dawn'\n\n\t\ttypeC", "end": 48, "score": 0.9990426898002625, "start": 39, "tag": "PASSWORD", "value": "bacerocks" } ]
src/server/default-settings.coffee
mark-hahn/bace
1
module.exports = user: password: "bacerocks" timeoutMins: "30" theme: 'dawn' typeColors: text: ['white', 'black']
217244
module.exports = user: password: "<PASSWORD>" timeoutMins: "30" theme: 'dawn' typeColors: text: ['white', 'black']
true
module.exports = user: password: "PI:PASSWORD:<PASSWORD>END_PI" timeoutMins: "30" theme: 'dawn' typeColors: text: ['white', 'black']