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": "_cards.ships\n\n pilot_translations =\n \"Wedge Antilles\":\n text: \"\"\"Во время атаки, уменьшите ",
"end": 5847,
"score": 0.8435624837875366,
"start": 5833,
"tag": "NAME",
"value": "Wedge Antilles"
},
{
"context": "(значение не может быть меньше нуля).\"\"\"\n \"Garven Dreis\":\n text: \"\"\"После использования жетона",
"end": 5999,
"score": 0.9887954592704773,
"start": 5987,
"tag": "NAME",
"value": "Garven Dreis"
},
{
"context": "медленно получить жетон Захвата Цели.\"\"\"\n \"Horton Salm\":\n text: \"\"\"Во время атаки на Дистанци",
"end": 6682,
"score": 0.9526726603507996,
"start": 6671,
"tag": "NAME",
"value": "Horton Salm"
},
{
"context": " не имеющих какого-либо результата.\"\"\"\n '\"Winged Gundark\"':\n text: \"\"\"Во время атаки на Дистанц",
"end": 6854,
"score": 0.6395400166511536,
"start": 6841,
"tag": "NAME",
"value": "inged Gundark"
},
{
"context": "ации или перебрасывать кубики атаки.\"\"\"\n '\"Mauler Mithel\"':\n text: \"\"\"Когда атакуете на Дистанц",
"end": 7472,
"score": 0.9998760223388672,
"start": 7459,
"tag": "NAME",
"value": "Mauler Mithel"
},
{
"context": "бросайте на один кубик атаки больше.\"\"\"\n '\"Howlrunner\"':\n text: \"\"\"Когда другой дружественны",
"end": 7587,
"score": 0.9975263476371765,
"start": 7577,
"tag": "NAME",
"value": "Howlrunner"
},
{
"context": "н может перебросить один кубик атаки.\"\"\"\n \"Maarek Stele\":\n text: \"\"\"Когда ваша атака наносит К",
"end": 7751,
"score": 0.9996367692947388,
"start": 7739,
"tag": "NAME",
"value": "Maarek Stele"
},
{
"context": "ерете 1 из них, а остальные сбросьте.\"\"\"\n \"Darth Vader\":\n text: \"\"\"Во время шага «Выполните Д",
"end": 7947,
"score": 0.9984283447265625,
"start": 7936,
"tag": "NAME",
"value": "Darth Vader"
},
{
"context": "ии, вы можете выполнить 2 действия.\"\"\"\n \"\\\"Fel's Wrath\\\"\":\n text: \"\"\"Когда количество карт По",
"end": 8081,
"score": 0.9892123937606812,
"start": 8070,
"tag": "NAME",
"value": "Fel's Wrath"
},
{
"context": "азрушается до конца этой боевой фазы.\"\"\"\n \"Turr Phennir\":\n text: \"\"\"После выполнения атаки вы ",
"end": 8274,
"score": 0.9987329244613647,
"start": 8262,
"tag": "NAME",
"value": "Turr Phennir"
},
{
"context": "ободное действие Бочка или Ускорение.\"\"\"\n \"Soontir Fel\":\n text: \"\"\"Когда вы получаете жетон С",
"end": 8404,
"score": 0.9976633787155151,
"start": 8393,
"tag": "NAME",
"value": "Soontir Fel"
},
{
"context": "жетон Концентрация для этого корабля.\"\"\"\n \"Tycho Celchu\":\n text: \"\"\"Вы можете выполнять действ",
"end": 8547,
"score": 0.9950320720672607,
"start": 8535,
"tag": "NAME",
"value": "Tycho Celchu"
},
{
"context": "аже при наличии у вас жетона Стресса.\"\"\"\n \"Arvel Crynyd\":\n text: \"\"\"Вы можете выбрать целью дл",
"end": 8663,
"score": 0.9974587559700012,
"start": 8651,
"tag": "NAME",
"value": "Arvel Crynyd"
},
{
"context": "ельбы, даже если вы его касаетесь.\"\"\"\n \"Chewbacca\":\n text: \"\"\"Если вы получили карту Пов",
"end": 8827,
"score": 0.9499061703681946,
"start": 8821,
"tag": "NAME",
"value": "wbacca"
},
{
"context": "цом вниз (без применения ее свойств).\"\"\"\n \"Lando Calrissian\":\n text: \"\"\"После выполнения зелёного ",
"end": 9000,
"score": 0.9898614883422852,
"start": 8984,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "указанных в его карте, как свободное.\"\"\"\n \"Han Solo\":\n text: \"\"\"Во время атаки вы можете п",
"end": 9214,
"score": 0.9312007427215576,
"start": 9206,
"tag": "NAME",
"value": "Han Solo"
},
{
"context": "их максимальное возможное количество.\"\"\"\n \"Kath Scarlet\":\n text: \"\"\"Во время атаки, обороняющи",
"end": 9402,
"score": 0.9967111349105835,
"start": 9390,
"tag": "NAME",
"value": "Kath Scarlet"
},
{
"context": "ин из результатов %CRIT% был отменён.\"\"\"\n \"Boba Fett\":\n text: \"\"\"Когда вы вскрываете манёвр",
"end": 9559,
"score": 0.9972732067108154,
"start": 9550,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": "его на другой манёвр той же скорости.\"\"\"\n \"Krassis Trelix\":\n text: \"\"\"Во время атаки Дополнитель",
"end": 9721,
"score": 0.9913957715034485,
"start": 9707,
"tag": "NAME",
"value": "Krassis Trelix"
},
{
"context": "жете перебросить один кубик атаки.\"\"\"\n \"Ten Numb\":\n text: \"\"\"Во время атаки, один из",
"end": 9841,
"score": 0.5839695930480957,
"start": 9840,
"tag": "NAME",
"value": "N"
},
{
"context": "RIT% нельзя отменить кубиком защиты.\"\"\"\n \"Ibtisam\":\n text: \"\"\"Во время атаки или обороны",
"end": 9968,
"score": 0.7226576209068298,
"start": 9962,
"tag": "NAME",
"value": "btisam"
},
{
"context": " вас есть хотя бы один жетон Стресса.\"\"\"\n \"Roark Garnet\":\n text: '''После начала фазы боя, выб",
"end": 10132,
"score": 0.9997488856315613,
"start": 10120,
"tag": "NAME",
"value": "Roark Garnet"
},
{
"context": "бранного корабля считается равным 12.'''\n \"Kyle Katarn\":\n text: \"\"\"В начале фазы боя вы может",
"end": 10337,
"score": 0.9997972249984741,
"start": 10326,
"tag": "NAME",
"value": "Kyle Katarn"
},
{
"context": "жественному кораблю на Дистанции 1-3.\"\"\"\n \"Jan Ors\":\n text: \"\"\"Когда другой дружественный",
"end": 10501,
"score": 0.999562680721283,
"start": 10494,
"tag": "NAME",
"value": "Jan Ors"
},
{
"context": "сить один дополнительный кубик атаки.\"\"\"\n \"Captain Jonus\":\n text: \"\"\"Когда другой дружественный",
"end": 10748,
"score": 0.9984236359596252,
"start": 10735,
"tag": "NAME",
"value": "Captain Jonus"
},
{
"context": "ет перебросить до двух кубиков атаки.\"\"\"\n \"Major Rhymer\":\n text: \"\"\"Во время атаки дополнитель",
"end": 10932,
"score": 0.9987607598304749,
"start": 10920,
"tag": "NAME",
"value": "Major Rhymer"
},
{
"context": "ия на один, в пределах Дистанции 1-3.\"\"\"\n \"Captain Kagi\":\n text: \"\"\"Когда вражеский корабль по",
"end": 11119,
"score": 0.9977449178695679,
"start": 11107,
"tag": "NAME",
"value": "Captain Kagi"
},
{
"context": " корабль в качестве цели, если может.\"\"\"\n \"Colonel Jendon\":\n text: \"\"\"В начале фазы боя, вы може",
"end": 11286,
"score": 0.9996705055236816,
"start": 11272,
"tag": "NAME",
"value": "Colonel Jendon"
},
{
"context": "ии 1, если у него таковых не имеется.\"\"\"\n \"Captain Yorr\":\n text: \"\"\"Вы можете получить жетон С",
"end": 11486,
"score": 0.9988792538642883,
"start": 11474,
"tag": "NAME",
"value": "Captain Yorr"
},
{
"context": "ли у вас таких жетонов два или менее.\"\"\"\n \"Lieutenant Lorrir\":\n text: \"\"\"При выполнении действия Бо",
"end": 11675,
"score": 0.9996083378791809,
"start": 11658,
"tag": "NAME",
"value": "Lieutenant Lorrir"
},
{
"context": "%BANKRIGHT% 1) вместо (%STRAIGHT% 1).\"\"\"\n \"Tetran Cowall\":\n text: \"\"\"Когда вы вскрываете маневр",
"end": 11870,
"score": 0.9997966885566711,
"start": 11857,
"tag": "NAME",
"value": "Tetran Cowall"
},
{
"context": " этого маневра как \"1,\" \"3,\" или \"5\".\"\"\"\n \"Kir Kanos\":\n text: \"\"\"Во время атаки на Дистанци",
"end": 12015,
"score": 0.9998048543930054,
"start": 12006,
"tag": "NAME",
"value": "Kir Kanos"
},
{
"context": "бавить к броску один %HIT% результат.\"\"\"\n \"Carnor Jax\":\n text: \"\"\"Вражеские корабли на Диста",
"end": 12180,
"score": 0.9997227787971497,
"start": 12170,
"tag": "NAME",
"value": "Carnor Jax"
},
{
"context": "ут сбрасывать соответствующие жетоны.\"\"\"\n \"Lieutenant Blount\":\n text: \"\"\"Ваша атака считается успеш",
"end": 12368,
"score": 0.9989047646522522,
"start": 12351,
"tag": "NAME",
"value": "Lieutenant Blount"
},
{
"context": "ийся успешно отменил все повреждения.\"\"\"\n \"Airen Cracken\":\n text: \"\"\"После выполнения атаки вы ",
"end": 12504,
"score": 0.999633252620697,
"start": 12491,
"tag": "NAME",
"value": "Airen Cracken"
},
{
"context": "ции 1. Этот корабль может выполнить .\"\"\"\n \"Colonel Vessery\":\n text: \"\"\"Во время атаки, после брос",
"end": 12672,
"score": 0.9995573163032532,
"start": 12657,
"tag": "NAME",
"value": "Colonel Vessery"
},
{
"context": "уже имеет красный жетон захвата цели.\"\"\"\n \"Rexler Brath\":\n text: \"\"\"После выполнения атаки, пр",
"end": 12868,
"score": 0.999419093132019,
"start": 12856,
"tag": "NAME",
"value": "Rexler Brath"
},
{
"context": "есенных карт Повреждений лицом вверх.\"\"\"\n \"Etahn A'baht\":\n text: \"\"\"Когда корабль противника н",
"end": 13096,
"score": 0.9990949630737305,
"start": 13084,
"tag": "NAME",
"value": "Etahn A'baht"
},
{
"context": "HIT% результатов на %CRIT% результат.\"\"\"\n \"Corran Horn\":\n text: \"\"\"В начале фазы Завершения в",
"end": 13316,
"score": 0.9971685409545898,
"start": 13305,
"tag": "NAME",
"value": "Corran Horn"
},
{
"context": "аковать в течении следующего раунда.\"\"\"\n '\"Echo\"':\n text: \"\"\"Когда вы сбрасываете режи",
"end": 13466,
"score": 0.6709255576133728,
"start": 13462,
"tag": "NAME",
"value": "Echo"
},
{
"context": "ANKLEFT% 2) вместо (%STRAIGHT% 2).\"\"\"\n '\"Whisper\"':\n text: \"\"\"После выполнения успешной",
"end": 13639,
"score": 0.5530193448066711,
"start": 13634,
"tag": "NAME",
"value": "isper"
},
{
"context": "ин жетон КОнцентрации на ваш корабль.\"\"\"\n \"Wes Janson\":\n text: \"\"\"После выполнения атаки вы ",
"end": 13777,
"score": 0.9975217580795288,
"start": 13767,
"tag": "NAME",
"value": "Wes Janson"
},
{
"context": " захвата цели с защищающегося корабя.\"\"\"\n \"Jek Porkins\":\n text: \"\"\"Когда вы получаете жетон с",
"end": 13955,
"score": 0.9998701214790344,
"start": 13944,
"tag": "NAME",
"value": "Jek Porkins"
},
{
"context": "орабль карту Повреждения лицом вниз.\"\"\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Когда вы получает",
"end": 14157,
"score": 0.9996725916862488,
"start": 14151,
"tag": "NAME",
"value": "Hobbie"
},
{
"context": "карту Повреждения лицом вниз.\"\"\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Когда вы получаете или тра",
"end": 14166,
"score": 0.9995874762535095,
"start": 14159,
"tag": "NAME",
"value": "Klivian"
},
{
"context": " один жетон стресса с вашего корабля.\"\"\"\n \"Tarn Mison\":\n text: \"\"\"Когда корабль противника о",
"end": 14311,
"score": 0.9998835325241089,
"start": 14301,
"tag": "NAME",
"value": "Tarn Mison"
},
{
"context": "получить Захват цели на этот корабль.\"\"\"\n \"Jake Farrell\":\n text: \"\"\"После выполнения действия ",
"end": 14467,
"score": 0.9998878240585327,
"start": 14455,
"tag": "NAME",
"value": "Jake Farrell"
},
{
"context": "ободное действие Ускорение или Бочка.\"\"\"\n \"Gemmer Sojan\":\n text: \"\"\"Пока вы находитесь на Дист",
"end": 14649,
"score": 0.9998868107795715,
"start": 14637,
"tag": "NAME",
"value": "Gemmer Sojan"
},
{
"context": "казатель вашей маневренности на один.\"\"\"\n \"Keyan Farlander\":\n text: \"\"\"Когда атакуете, вы можете ",
"end": 14832,
"score": 0.9998878240585327,
"start": 14817,
"tag": "NAME",
"value": "Keyan Farlander"
},
{
"context": "CUS% результатов на %HIT% результаты.\"\"\"\n \"Nera Dantels\":\n text: \"\"\"Вы можете выполнять атаки ",
"end": 14996,
"score": 0.9998656511306763,
"start": 14984,
"tag": "NAME",
"value": "Nera Dantels"
},
{
"context": "ящимися вне вашего сектора стрельбы.\"\"\"\n \"Dash Rendar\":\n text: \"\"\"Вы можете игнорировать жет",
"end": 15156,
"score": 0.9961602091789246,
"start": 15145,
"tag": "NAME",
"value": "Dash Rendar"
},
{
"context": "тивации и когда совершаете Действия.\"\"\"\n '\"Leebo\"':\n text: \"\"\"Когда вы получаете карту ",
"end": 15282,
"score": 0.9797520637512207,
"start": 15277,
"tag": "NAME",
"value": "Leebo"
},
{
"context": "одну для применения, вторую сбросьте.\"\"\"\n \"Eaden Vrill\":\n text: \"\"\"Когда вы атакуете основным",
"end": 15475,
"score": 0.9980757832527161,
"start": 15464,
"tag": "NAME",
"value": "Eaden Vrill"
},
{
"context": "айте один дополнительный кубик атаки.\"\"\"\n \"Rear Admiral Chiraneau\":\n text: \"\"\"При атаке на Дистанции 1-2",
"end": 15636,
"score": 0.9976419806480408,
"start": 15614,
"tag": "NAME",
"value": "Rear Admiral Chiraneau"
},
{
"context": "ультатов %FOCUS% на %CRIT% результат.\"\"\"\n \"Commander Kenkirk\":\n text: \"\"\"Если у вас нет щитов и ест",
"end": 15791,
"score": 0.9993184804916382,
"start": 15774,
"tag": "NAME",
"value": "Commander Kenkirk"
},
{
"context": "увеличьте вашу маневренность на один.\"\"\"\n \"Captain Oicunn\":\n text: \"\"\"После выполнения маневра к",
"end": 15939,
"score": 0.999362051486969,
"start": 15925,
"tag": "NAME",
"value": "Captain Oicunn"
},
{
"context": "касаетесь, получает одно повреждение.\"\"\"\n \"Prince Xizor\":\n text: \"\"\"При защите, дружественный ",
"end": 16094,
"score": 0.9992277026176453,
"start": 16082,
"tag": "NAME",
"value": "Prince Xizor"
},
{
"context": "езультат %HIT% или %CRIT% вместо вас.\"\"\"\n \"Guri\":\n text: \"\"\"В начале фазы Боя, если вы",
"end": 16255,
"score": 0.9929649829864502,
"start": 16251,
"tag": "NAME",
"value": "Guri"
},
{
"context": " \"Guri\":\n text: \"\"\"В начале фазы Боя, если вы на Дистанции 1 от вражеского корабля, вы",
"end": 16296,
"score": 0.5300608277320862,
"start": 16294,
"tag": "NAME",
"value": "оя"
},
{
"context": "ин жетон концентрации вашему кораблю.\"\"\"\n \"Serissu\":\n text: \"\"\"Когда другой дружественный",
"end": 16423,
"score": 0.994644820690155,
"start": 16416,
"tag": "NAME",
"value": "Serissu"
},
{
"context": " может перебросить один кубик защиты.\"\"\"\n \"Laetin A'shera\":\n text: \"\"\"После того как вы выполнил",
"end": 16575,
"score": 0.9998626112937927,
"start": 16561,
"tag": "NAME",
"value": "Laetin A'shera"
},
{
"context": " (%TURNLEFT% 3) или (%TURNRIGHT% 3) .\"\"\"\n \"Boba Fett (Scum)\":\n text: \"\"\"При атаке или защит",
"end": 17376,
"score": 0.9998410940170288,
"start": 17367,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": "дый вражеский корабль на Дистанции 1.\"\"\"\n \"Kath Scarlet (Scum)\":\n text: \"\"\"При атаке корабля в",
"end": 17534,
"score": 0.999792754650116,
"start": 17522,
"tag": "NAME",
"value": "Kath Scarlet"
},
{
"context": "айте один дополнительный кубик атаки.\"\"\"\n \"Emon Azzameen\":\n text: \"\"\"При сбросе бомбы, вы может",
"end": 17692,
"score": 0.9998579621315002,
"start": 17679,
"tag": "NAME",
"value": "Emon Azzameen"
},
{
"context": "HT% 3] вместо шаблона [%STRAIGHT% 1].\"\"\"\n \"Kavil\":\n text: \"\"\"При атаке корабля вне ваше",
"end": 17865,
"score": 0.9943215250968933,
"start": 17860,
"tag": "NAME",
"value": "Kavil"
},
{
"context": "айте один дополнительный кубик атаки.\"\"\"\n \"Drea Renthal\":\n text: \"\"\"После того как вы использо",
"end": 18001,
"score": 0.9983395338058472,
"start": 17989,
"tag": "NAME",
"value": "Drea Renthal"
},
{
"context": " Стресса для выполнения Захвата цели.\"\"\"\n \"Dace Bonearm\":\n text: \"\"\"Когда вражеский корабль на",
"end": 18159,
"score": 0.9981201887130737,
"start": 18147,
"tag": "NAME",
"value": "Dace Bonearm"
},
{
"context": "нести этому кораблю одно повреждение.\"\"\"\n \"Palob Godalhi\":\n text: \"\"\"В начале фазы Боя, вы може",
"end": 18396,
"score": 0.9983089566230774,
"start": 18383,
"tag": "NAME",
"value": "Palob Godalhi"
},
{
"context": "Palob Godalhi\":\n text: \"\"\"В начале фазы Боя, вы можете удалить один жетон %FOCUS% или %EVADE%",
"end": 18437,
"score": 0.6887943744659424,
"start": 18434,
"tag": "NAME",
"value": "Боя"
},
{
"context": "и 1-2 и назначить его своему кораблю.\"\"\"\n \"Torkil Mux\":\n text: \"\"\"В начале фазы Активации вы",
"end": 18580,
"score": 0.9973117709159851,
"start": 18570,
"tag": "NAME",
"value": "Torkil Mux"
},
{
"context": "терство пилота этого корабля как \"0\".\"\"\"\n \"N'Dru Suhlak\":\n text: \"\"\"При атаке, если на Дистанц",
"end": 18770,
"score": 0.9924919009208679,
"start": 18758,
"tag": "NAME",
"value": "N'Dru Suhlak"
},
{
"context": "айте один дополнительный кубик атаки.\"\"\"\n \"Kaa'To Leeachos\":\n text: \"\"\"В начале фазы Боя вы может",
"end": 18932,
"score": 0.9593991041183472,
"start": 18917,
"tag": "NAME",
"value": "Kaa'To Leeachos"
},
{
"context": " Дистанции 1-2, и назначить его себе.\"\"\"\n \"Commander Alozen\":\n text: \"\"\"В начале фазы Боя вы может",
"end": 19124,
"score": 0.9997590780258179,
"start": 19108,
"tag": "NAME",
"value": "Commander Alozen"
},
{
"context": "2 e??? perform another primary wea???\"\"\"\n \"Juno Eclipse\":\n text: \"\"\"Когда вы открываете свой м",
"end": 19424,
"score": 0.7277004718780518,
"start": 19412,
"tag": "NAME",
"value": "Juno Eclipse"
},
{
"context": "корость на единицу (до минимума в 1).\"\"\"\n \"Zertik Strom\":\n text: \"\"\"Вражеский корабль на Диста",
"end": 19582,
"score": 0.9998674392700195,
"start": 19570,
"tag": "NAME",
"value": "Zertik Strom"
},
{
"context": "бонус дистанции при выполнении атаки.\"\"\"\n \"Lieutenant Colzet\":\n text: \"\"\"В начале фазы Завершения в",
"end": 19728,
"score": 0.9998783469200134,
"start": 19711,
"tag": "NAME",
"value": "Lieutenant Colzet"
},
{
"context": "из имеющихся у него карт Повреждений.\"\"\"\n \"Latts Razzi\":\n text: \"\"\"Когда дружественный корабл",
"end": 19959,
"score": 0.9998197555541992,
"start": 19948,
"tag": "NAME",
"value": "Latts Razzi"
},
{
"context": "ности на единицу на время этой атаки.\"\"\"\n \"Graz the Hunter\":\n text: \"\"\"При защите, если атакующий",
"end": 20189,
"score": 0.9462572932243347,
"start": 20174,
"tag": "NAME",
"value": "Graz the Hunter"
},
{
"context": "йте один дополнительный кубик защиты.\"\"\"\n \"Esege Tuketu\":\n text: \"\"\"Когда другой дружественный",
"end": 20333,
"score": 0.9988632202148438,
"start": 20321,
"tag": "NAME",
"value": "Esege Tuketu"
},
{
"context": "атем отмените все результаты кубиков.\"\"\"\n \"Proton Torpedoes\":\n text: \"\"\"<strong>Атака (Захват цели",
"end": 22086,
"score": 0.9698088765144348,
"start": 22070,
"tag": "NAME",
"value": "Proton Torpedoes"
},
{
"context": "RIT% результат, вместо этого корабля.\"\"\"\n \"Luke Skywalker\":\n text: \"\"\"%REBELONLY%%LINEBREAK%Если",
"end": 28448,
"score": 0.9912670254707336,
"start": 28434,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": " выполнять других атак в этом раунде.\"\"\"\n \"Nien Nunb\":\n text: \"\"\"%REBELONLY%%LINEBREAK%Вы м",
"end": 28718,
"score": 0.9994223713874817,
"start": 28709,
"tag": "NAME",
"value": "Nien Nunb"
},
{
"context": "бые %STRAIGHT% манёвры зелёными.\"\"\"\n \"Chewbacca\":\n name: \"Chewbacca (Crew)\"\n ",
"end": 28836,
"score": 0.5072588920593262,
"start": 28834,
"tag": "NAME",
"value": "ac"
},
{
"context": "ми.\"\"\"\n \"Chewbacca\":\n name: \"Chewbacca (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREA",
"end": 28869,
"score": 0.671812117099762,
"start": 28863,
"tag": "NAME",
"value": "wbacca"
},
{
"context": "вы можете перебросить 2 кубика атаки.\"\"\"\n \"Flechette Torpedoes\":\n name: \"Flechet-Torpedos\"\n ",
"end": 34376,
"score": 0.855026364326477,
"start": 34357,
"tag": "NAME",
"value": "Flechette Torpedoes"
},
{
"context": " \"Flechette Torpedoes\":\n name: \"Flechet-Torpedos\"\n text: \"\"\"<strong>Атака (Захват цели)",
"end": 34414,
"score": 0.8845950961112976,
"start": 34398,
"tag": "NAME",
"value": "Flechet-Torpedos"
},
{
"context": "ю вашей Маневренности, но не более 3.\"\"\"\n \"Kyle Katarn\":\n name: \"Kyle Katarn (Crew)\"\n ",
"end": 38171,
"score": 0.9995498657226562,
"start": 38160,
"tag": "NAME",
"value": "Kyle Katarn"
},
{
"context": "е 3.\"\"\"\n \"Kyle Katarn\":\n name: \"Kyle Katarn (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREA",
"end": 38204,
"score": 0.9998431205749512,
"start": 38193,
"tag": "NAME",
"value": "Kyle Katarn"
},
{
"context": "ете назначить ему жетон концентрации.\"\"\"\n \"Jan Ors\":\n name: \"Jan Ors (Crew)\"\n ",
"end": 38367,
"score": 0.9991081357002258,
"start": 38360,
"tag": "NAME",
"value": "Jan Ors"
},
{
"context": "нтрации.\"\"\"\n \"Jan Ors\":\n name: \"Jan Ors (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREA",
"end": 38396,
"score": 0.9998803734779358,
"start": 38389,
"tag": "NAME",
"value": "Jan Ors"
},
{
"context": "ия этим кораблем жетона концентрации.\"\"\"\n \"Toryn Farr\":\n text: \"\"\"%HUGESHIPONLY% %REBELONLY%",
"end": 38669,
"score": 0.9997372627258301,
"start": 38659,
"tag": "NAME",
"value": "Toryn Farr"
},
{
"context": "iscard 1 of your faceup Damage cards.\"\"\"\n \"Carlist Rieekan\":\n text: \"\"\"%HUGESHIPONLY% %REBELONLY%",
"end": 39605,
"score": 0.9998979568481445,
"start": 39590,
"tag": "NAME",
"value": "Carlist Rieekan"
},
{
"context": "e as \"12\" until the end of the phase.\"\"\"\n \"Jan Dodonna\":\n text: \"\"\"%HUGESHIPONLY% %REBELONLY%",
"end": 39837,
"score": 0.9998873472213745,
"start": 39826,
"tag": "NAME",
"value": "Jan Dodonna"
},
{
"context": "osen ship receives 1 stress token.\"\"\"\n \"Han Solo\":\n name: \"Han Solo (Crew)\"\n ",
"end": 40814,
"score": 0.5800707936286926,
"start": 40810,
"tag": "NAME",
"value": "Solo"
},
{
"context": " token.\"\"\"\n \"Han Solo\":\n name: \"Han Solo (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREA",
"end": 40844,
"score": 0.7966912388801575,
"start": 40836,
"tag": "NAME",
"value": "Han Solo"
},
{
"context": "%FOCUS% results to %HIT% results.\"\"\"\n \"Leia Organa\":\n text: \"\"\"%REBELONLY%%LINEBREAK%В",
"end": 41062,
"score": 0.5221216678619385,
"start": 41059,
"tag": "NAME",
"value": "Org"
},
{
"context": "target lock token to the chosen ship.\"\"\"\n \"Raymus Antilles\":\n text: \"\"\"%HUGESHIPONLY% %REBELONLY%",
"end": 41546,
"score": 0.9646354913711548,
"start": 41531,
"tag": "NAME",
"value": "Raymus Antilles"
},
{
"context": "energy during the \"Gain Energy\" step.\"\"\"\n \"Lando Calrissian\":\n name: \"Lando Calrissian (Crew)\"\n ",
"end": 42307,
"score": 0.997596800327301,
"start": 42291,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "\"\"\n \"Lando Calrissian\":\n name: \"Lando Calrissian (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREA",
"end": 42345,
"score": 0.9998719096183777,
"start": 42329,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "Calrissian\":\n name: \"Lando Calrissian (Crew)\"\n text: \"\"\"%REBELONLY%%LINEBREAK%<str",
"end": 42351,
"score": 0.9083598256111145,
"start": 42347,
"tag": "NAME",
"value": "Crew"
},
{
"context": "ьте 1 жетон Уклонения вашему кораблю.\"\"\"\n \"Mara Jade\":\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%В",
"end": 42631,
"score": 0.988328218460083,
"start": 42622,
"tag": "NAME",
"value": "Mara Jade"
},
{
"context": "шите его значение Маневренности на 1.\"\"\"\n \"Ysanne Isard\":\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%В",
"end": 44158,
"score": 0.9994922876358032,
"start": 44146,
"tag": "NAME",
"value": "Ysanne Isard"
},
{
"context": "выполнить свободное действие %EVADE%.\"\"\"\n \"Moff Jerjerrod\":\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%К",
"end": 44360,
"score": 0.999846339225769,
"start": 44346,
"tag": "NAME",
"value": "Moff Jerjerrod"
},
{
"context": "cel <strong>all<strong> dice results.\"\"\"\n \"Emperor Palpatine\":\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%O",
"end": 49303,
"score": 0.9014298319816589,
"start": 49286,
"tag": "NAME",
"value": "Emperor Palpatine"
},
{
"context": "trong>all</strong> dice results.\"\"\"\n 'Agent Kallus':\n text: '''%IMPERIALONLY%%LINEBREAK%A",
"end": 52529,
"score": 0.865162193775177,
"start": 52523,
"tag": "NAME",
"value": "Kallus"
},
{
"context": " если Мастерство пилота \"4\" и меньше.\"\"\"\n \"Dodonna's Pride\":\n name: \"Dodonnas Stolz\"\n ",
"end": 57861,
"score": 0.9307410717010498,
"start": 57846,
"tag": "NAME",
"value": "Dodonna's Pride"
},
{
"context": "\"\"\"\n \"Dodonna's Pride\":\n name: \"Dodonnas Stolz\"\n ship: \"CR90-Korvette (Bug)\"\n ",
"end": 57897,
"score": 0.9998571872711182,
"start": 57883,
"tag": "NAME",
"value": "Dodonnas Stolz"
},
{
"context": ").\"\"\"\n \"Jaina's Light\":\n name: \"Jainas Licht\"\n ship: \"CR90-Korvette (Bug)\"\n ",
"end": 59518,
"score": 0.9998854398727417,
"start": 59506,
"tag": "NAME",
"value": "Jainas Licht"
}
] | cards-ru.coffee | michigun/xwing | 0 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Russian'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Russian =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Recover"
"Reinforce": "Reinforce"
"Jam": "Jam"
"Coordinate": "Coordinate"
"Cloak": "Маскировка"
slot:
"Astromech": "Астромех"
"Bomb": "Бомба"
"Cannon": "Дополнительное Орудие"
"Crew": "Экипаж"
"Elite": "Талант"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Cargo"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "Нелегальный"
"Salvaged Astromech": "захваченный Астромех"
sources: # needed?
"Core": "База"
"A-Wing Expansion Pack": "Дополнение A-Wing"
"B-Wing Expansion Pack": "Дополнение B-Wing"
"X-Wing Expansion Pack": "Дополнение X-Wing"
"Y-Wing Expansion Pack": "Дополнение Y-Wing"
"Millennium Falcon Expansion Pack": "Дополнение Сокол Тысячелетия"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-Fighter"
"TIE Interceptor Expansion Pack": "Дополнение TIE-Interceptor"
"TIE Bomber Expansion Pack": "Дополнение TIE-Bomber"
"TIE Advanced Expansion Pack": "Дополнение TIE-Advanced"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Lambda-class Shuttle"
"Slave I Expansion Pack": "Дополнение Sklave I"
"Imperial Aces Expansion Pack": "Дополнение Imperial Aces"
"Rebel Transport Expansion Pack": "Дополнение Rebel Transport"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95-Headhunter"
"TIE Defender Expansion Pack": "Дополнение TIE-Defender"
"E-Wing Expansion Pack": "Дополнение E-Wing"
"TIE Phantom Expansion Pack": "Дополнение TIE-Phantom"
"Tantive IV Expansion Pack": "Дополнение Tantive IV"
"Rebel Aces Expansion Pack": "Дополнение Rebel Aces"
"YT-2400 Freighter Expansion Pack": "Дополнение YT-2400 Freighter"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Decimator"
"StarViper Expansion Pack": "Дополнение StarViper"
"M3-A Interceptor Expansion Pack": "Дополнение M3-A Interceptor"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Most Wanted"
"Imperial Raider Expansion Pack": "Дополнение Imperial Raider"
ui:
shipSelectorPlaceholder: "Выберите корабль"
pilotSelectorPlaceholder: "Выберите пилота"
upgradePlaceholder: (translator, language, slot) ->
"Нет #{translator language, 'слота', slot} улучшения"
modificationPlaceholder: "Нет модификации"
titlePlaceholder: "Нет названия"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'Слот', slot} улучшения"
unreleased: "не выпущено"
epic: "Эпик"
limited: "ограничено"
byCSSSelector:
'.translate.sort-cards-by': 'Сортировать карты по'
'.xwing-card-browser option[value="name"]': 'Имени'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (Очки)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (Имени)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Мастерство'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новый отряд'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить отряд'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Печать\Просмотр как </span>Text'
'.randomize' : 'Случайно'
'.randomize-options' : 'Опции генератора случайности'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте в пост на форуме.<textarea></textarea>'
'.vertical-space-checkbox' : """Добавить пространство для карт повреждений\улучшений на распечатке. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Печать в цвете. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Печать'
# Randomizer options
'.do-randomize' : 'Случайно!'
# Top tab bar
'#empireTab' : 'Галактическая империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Негодяи'
'#browserTab' : 'Список карт'
'#aboutTab' : 'О сервисе'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Modifikation'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Russian = () ->
exportObj.cardLanguage = 'Russian'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
pilot_translations =
"Wedge Antilles":
text: """Во время атаки, уменьшите значение Мобильности защищающегося на 1 (значение не может быть меньше нуля)."""
"Garven Dreis":
text: """После использования жетона Концентрации вы можете передать его любому другому дружественному кораблю, находящемуся на Дистанции 1-2 (вместо сброса)."""
"Biggs Darklighter":
text: """Другие дружественные корабли на Дистанции 1 не могут быть атакованы, если целью можете быть выбраны вы."""
"Luke Skywalker":
text: """Во время защиты вы можете заменить один из результатов %FOCUS% на результат %EVADE%"""
'"Dutch" Vander':
text: """После захвата цели, выберите любой другой дружественный корабль на Дистанции 1-2. Выбранный корабль может немедленно получить жетон Захвата Цели."""
"Horton Salm":
text: """Во время атаки на Дистанции 2-3 вы можете перебросить любое количество ваших кубиков, не имеющих какого-либо результата."""
'"Winged Gundark"':
text: """Во время атаки на Дистанции 1 вы можете заменить один из ваших %HIT% результатов на %CRIT% результат."""
'"Night Beast"':
text: """После выполнения зеленого манёвра вы можете выполнить свободное действие Концентрация."""
'"Backstabber"':
text: """Если во время атаки вы находитесь вне сектора стрельбы обороняющегося корабля, бросайте на один кубик атаки больше."""
'"Dark Curse"':
text: """Во время обороны, атакующие вас корабли, не могут использовать маркеры Концентрации или перебрасывать кубики атаки."""
'"Mauler Mithel"':
text: """Когда атакуете на Дистанции 1 бросайте на один кубик атаки больше."""
'"Howlrunner"':
text: """Когда другой дружественный корабль атакует на Дистанции 1 основным оружием, он может перебросить один кубик атаки."""
"Maarek Stele":
text: """Когда ваша атака наносит Критическое повреждение атакуемому кораблю, вместо 1 возьмите 3 карты Повреждений. Выберете 1 из них, а остальные сбросьте."""
"Darth Vader":
text: """Во время шага «Выполните Действие» в фазе Активации, вы можете выполнить 2 действия."""
"\"Fel's Wrath\"":
text: """Когда количество карт Повреждений будет равно или превышать значение корпуса вашего корабля, корабль не разрушается до конца этой боевой фазы."""
"Turr Phennir":
text: """После выполнения атаки вы можете выполнить свободное действие Бочка или Ускорение."""
"Soontir Fel":
text: """Когда вы получаете жетон Стресса, можете так же получить жетон Концентрация для этого корабля."""
"Tycho Celchu":
text: """Вы можете выполнять действия даже при наличии у вас жетона Стресса."""
"Arvel Crynyd":
text: """Вы можете выбрать целью для атаки вражеский корабль, находящийся в вашем секторе стрельбы, даже если вы его касаетесь."""
"Chewbacca":
text: """Если вы получили карту Повреждений лицом вверх, немедленно переверните эту карту лицом вниз (без применения ее свойств)."""
"Lando Calrissian":
text: """После выполнения зелёного манёвра, выберите 1 дружественный корабль на Дистанции 1. Этот корабль может выполнить любое из действий, указанных в его карте, как свободное."""
"Han Solo":
text: """Во время атаки вы можете перебросить все ваши кубики. Если вы выбрали это, то должно быть переброшено их максимальное возможное количество."""
"Kath Scarlet":
text: """Во время атаки, обороняющийся получает один жетон Стресса, если хотя бы один из результатов %CRIT% был отменён."""
"Boba Fett":
text: """Когда вы вскрываете манёвр %BANKLEFT% или %BANKRIGHT%, вы можете заменить его на другой манёвр той же скорости."""
"Krassis Trelix":
text: """Во время атаки Дополнительным оружием, вы можете перебросить один кубик атаки."""
"Ten Numb":
text: """Во время атаки, один из ваших результатов %CRIT% нельзя отменить кубиком защиты."""
"Ibtisam":
text: """Во время атаки или обороны вы можете перебросить один из ваших кубиков, если у вас есть хотя бы один жетон Стресса."""
"Roark Garnet":
text: '''После начала фазы боя, выберете любой другой дружественный корабль на Дистанции 1-3. До конца фазы, Мастерство пилота выбранного корабля считается равным 12.'''
"Kyle Katarn":
text: """В начале фазы боя вы можете передать один из ваших жетонов Концентрации другому дружественному кораблю на Дистанции 1-3."""
"Jan Ors":
text: """Когда другой дружественный корабль атакует на Дистанции 1-3 и у вас нет жетона Стресса, вы можете получить один жетон Стресса, чтобы позволить этому кораблю бросить один дополнительный кубик атаки."""
"Captain Jonus":
text: """Когда другой дружественный корабль атакует на Дистанции 1, используя дополнительное оружие, он может перебросить до двух кубиков атаки."""
"Major Rhymer":
text: """Во время атаки дополнительным оружием, вы можете увеличить или уменьшить дистанцию использования оружия на один, в пределах Дистанции 1-3."""
"Captain Kagi":
text: """Когда вражеский корабль получает жетон Захвата цели, он должен использовать ваш корабль в качестве цели, если может."""
"Colonel Jendon":
text: """В начале фазы боя, вы можете передать один из ваших голубых жетонов Захвата цели дружественному кораблю на Дистанции 1, если у него таковых не имеется."""
"Captain Yorr":
text: """Вы можете получить жетон Стресса вместо любого другого дружественного корабля на Дистанции 1-2, если у вас таких жетонов два или менее."""
"Lieutenant Lorrir":
text: """При выполнении действия Бочка вы можете получить 1 жетон Стресса и использовать шаблоны (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"Tetran Cowall":
text: """Когда вы вскрываете маневр %UTURN%, вы можете считать скорость этого маневра как "1," "3," или "5"."""
"Kir Kanos":
text: """Во время атаки на Дистанции 2-3 вы можете сбросить один жетон уклонения, чтобы добавить к броску один %HIT% результат."""
"Carnor Jax":
text: """Вражеские корабли на Дистанции 1 не могут выполнять действия Уклонения или Концентрации, и не могут сбрасывать соответствующие жетоны."""
"Lieutenant Blount":
text: """Ваша атака считается успешной, даже если защищающийся успешно отменил все повреждения."""
"Airen Cracken":
text: """После выполнения атаки вы можете выбрать другой дружественный корабль на Дистанции 1. Этот корабль может выполнить ."""
"Colonel Vessery":
text: """Во время атаки, после броска ваших кубиков атаки, сразу можете получить Захват цели на защищающегося, если он уже имеет красный жетон захвата цели."""
"Rexler Brath":
text: """После выполнения атаки, принесшей противнику как минимум одну карту Повреждения, вы можете сбросить один жетон Концентрации для переворота нанесенных карт Повреждений лицом вверх."""
"Etahn A'baht":
text: """Когда корабль противника находится внутри вашего сектора стрельбы на Дистанции 1-3, и защищается, то атакующий может изменить один из %HIT% результатов на %CRIT% результат."""
"Corran Horn":
text: """В начале фазы Завершения вы можете выполнить одну атаку. Вы не можете атаковать в течении следующего раунда."""
'"Echo"':
text: """Когда вы сбрасываете режим Маскировки, вы должны использовать шаблоны (%BANKRIGHT% 2) или (%BANKLEFT% 2) вместо (%STRAIGHT% 2)."""
'"Whisper"':
text: """После выполнения успешной атаки вы можете получить один жетон КОнцентрации на ваш корабль."""
"Wes Janson":
text: """После выполнения атаки вы можете удалить один жетон Концентрации, Уклонения или голубой жетон захвата цели с защищающегося корабя."""
"Jek Porkins":
text: """Когда вы получаете жетон стресса, вы можете удалить его и бросить один кубик атаки. На результате %HIT% получите на этот корабль карту Повреждения лицом вниз."""
'"Hobbie" Klivian':
text: """Когда вы получаете или тратите Захват цели, вы можете удалить один жетон стресса с вашего корабля."""
"Tarn Mison":
text: """Когда корабль противника объявил вас целью для своей атаки, вы можете получить Захват цели на этот корабль."""
"Jake Farrell":
text: """После выполнения действия Концентрации или получения жетона Концентрации, вы можете совершить свободное действие Ускорение или Бочка."""
"Gemmer Sojan":
text: """Пока вы находитесь на Дистанции 1 от, по крайней мере одного, корабля противника, увеличьте показатель вашей маневренности на один."""
"Keyan Farlander":
text: """Когда атакуете, вы можете удалить один жетон Стресса для замены всех ваших %FOCUS% результатов на %HIT% результаты."""
"Nera Dantels":
text: """Вы можете выполнять атаки торпедами %TORPEDO% по кораблям противника, находящимися вне вашего сектора стрельбы."""
"Dash Rendar":
text: """Вы можете игнорировать жетоны преград в фазе Активации и когда совершаете Действия."""
'"Leebo"':
text: """Когда вы получаете карту Повреждения лицом вверх, вытяните одну дополнительную карту Повреждения, выберите одну для применения, вторую сбросьте."""
"Eaden Vrill":
text: """Когда вы атакуете основным орудием корабль с жетоном Стресса, кидайте один дополнительный кубик атаки."""
"Rear Admiral Chiraneau":
text: """При атаке на Дистанции 1-2, вы можете поменять один из ваших результатов %FOCUS% на %CRIT% результат."""
"Commander Kenkirk":
text: """Если у вас нет щитов и есть хотя бы одна карта Повреждения, увеличьте вашу маневренность на один."""
"Captain Oicunn":
text: """После выполнения маневра каждый вражеский корабль, с которым вы соприкасаетесь, получает одно повреждение."""
"Prince Xizor":
text: """При защите, дружественный корабль на Дистанции 1 может получить один неотмененный результат %HIT% или %CRIT% вместо вас."""
"Guri":
text: """В начале фазы Боя, если вы на Дистанции 1 от вражеского корабля, вы можете назначить один жетон концентрации вашему кораблю."""
"Serissu":
text: """Когда другой дружественный корабль на Дистанции 1 защищается, он может перебросить один кубик защиты."""
"Laetin A'shera":
text: """После того как вы выполнили защиту от вражеской атаки, если атака не попала, вы можете назначить один жетон уклонения вашему кораблю."""
"IG-88A":
text: """После выполнения вами атаки, которая уничтожила цель, вы можете восстановить один щит."""
"IG-88B":
text: """Единожды в раунд, после выполнения атаки, которая не попала, вы можете осуществить атаку из имеющегося дополнительного орудия %CANNON%."""
"IG-88C":
text: """После выполнения вами действия Ускорения, вы можете совершить свободное действие Уклонения."""
"IG-88D":
text: """Вы можете осуществлять маневры (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующие шаблоны (%TURNLEFT% 3) или (%TURNRIGHT% 3) ."""
"Boba Fett (Scum)":
text: """При атаке или защите, вы можете перебросить один ваш кубик за каждый вражеский корабль на Дистанции 1."""
"Kath Scarlet (Scum)":
text: """При атаке корабля в вашем вспомогательном секторе стрельбы, бросайте один дополнительный кубик атаки."""
"Emon Azzameen":
text: """При сбросе бомбы, вы можете использовать шаблоны [%TURNLEFT% 3], [%STRAIGHT% 3], или [%TURNRIGHT% 3] вместо шаблона [%STRAIGHT% 1]."""
"Kavil":
text: """При атаке корабля вне вашего сектора обстрела бросайте один дополнительный кубик атаки."""
"Drea Renthal":
text: """После того как вы использовали Захват цели вы можете получить один жетон Стресса для выполнения Захвата цели."""
"Dace Bonearm":
text: """Когда вражеский корабль на Дистанции 1-3 получает как минимум один жетон Иона, и у вас нет жетонов Стресса, вы можете получить один жетон Стресса и нанести этому кораблю одно повреждение."""
"Palob Godalhi":
text: """В начале фазы Боя, вы можете удалить один жетон %FOCUS% или %EVADE% с вражеского корабля на Дистанции 1-2 и назначить его своему кораблю."""
"Torkil Mux":
text: """В начале фазы Активации выберите один вражеский корабль на Дистанции 1-2. До конца фазы Боя считайте Мастерство пилота этого корабля как "0"."""
"N'Dru Suhlak":
text: """При атаке, если на Дистанции 1-2 нет других дружественных кораблей, бростайте один дополнительный кубик атаки."""
"Kaa'To Leeachos":
text: """В начале фазы Боя вы можете удалить один жетон %FOCUS% или %EVADE% с другого дружественного корабля на Дистанции 1-2, и назначить его себе."""
"Commander Alozen":
text: """В начале фазы Боя вы можете получить Захват цели на вражеский корабль на Дистанции 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"Juno Eclipse":
text: """Когда вы открываете свой маневр, вы можете увеличить или уменьшить его скорость на единицу (до минимума в 1)."""
"Zertik Strom":
text: """Вражеский корабль на Дистанции 1 не может использовать бонус дистанции при выполнении атаки."""
"Lieutenant Colzet":
text: """В начале фазы Завершения вы можете использовать имеющийся Захват цели на вражеский корабль, для того чтобы перевернуть лицом вверх одну случайную из имеющихся у него карт Повреждений."""
"Latts Razzi":
text: """Когда дружественный корабль объявляет атаку, вы можете использовать имеющийся Захват цели на защищающемся корабле для уменьшения его маневренности на единицу на время этой атаки."""
"Graz the Hunter":
text: """При защите, если атакующий в вашем секторе обстрела, бросайте один дополнительный кубик защиты."""
"Esege Tuketu":
text: """Когда другой дружественный корабль на Дистанции 1-2 атакует, вы можете считать ваш жетон %FOCUS% как принадлежащий ему."""
'"Redline"':
text: """Вы можете осуществлять два захвата цели на один корабль. Когда вы осуществляете Захват цели, вы можете получить второй Захват цели на этот корабль."""
'"Deathrain"':
text: """При сбросе бомбы, вы можете использовать передние направляющие вашего корабля. После сброса бомбы вы можете осуществить свободное действие Бочка."""
"Moralo Eval":
text: """Вы можете осуществлять атаки дополнительным орудием %CANNON% против кораблей в вашем дополнительном секторе обстрела."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"Scourge"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The Inquisitor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"Zuckuss":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"Dengar":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне сектора обстрела).%LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и 1 жетон Иона. Затем отмените все результаты кубиков."""
"Proton Torpedoes":
text: """<strong>Атака (Захват цели):</strong>Потратьте жетон Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете заменить 1 из ваших %FOCUS% результатов на результат %CRIT%."""
"R2 Astromech":
text: """Манёвры со скоростью 1 и 2 вы можете считать как зелёные манёвры."""
"R2-D2":
text: """После выполнения зелёного манёвра вы можете восстановить 1 Щит (до максимума доступного вам)."""
"R2-F2":
text: """<strong>Действие:</strong> Вы можете увеличить значение Маневренности на 1 до конца текущего раунда."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты. %LINEBREAK%В случае выпадения %EVADE% или %FOCUS% результата вы можете сбросить 1 карту из ваших не-критических Повреждений."""
"R5-K6":
text: """После сброса жетона Захвата цели, бросьте1 кубик защиты.%LINEBREAK%В случае выпадения результата %EVADE% немедленно получите жетон Захвата цели на тот же самый корабль. Вы не можете
потратить его во время этой атаки."""
"R5 Astromech":
text: """Во время фазы Завершения вы можете выбрать 1 из ваших карт Критических Повреждений с заголовком <strong>Корабль</strong> и перевернуть её лицом вниз."""
"Determination":
text: """Когда вы получаете карту Критического повреждения
с заголовком <strong>Пилот</strong>, немедленно сбросьте её без выполнения её эффекта."""
"Swarm Tactics":
text: """В начале фазы Боя выберите дружественный корабль на Дистанции 1. %LINEBREAK%До конца этой фазы пилот выбранного корабля имеет значение Мастерства пилота такое же как, и у вас."""
"Squad Leader":
text: """<strong>Действие:</strong> Выберите один корабль на Дистанции 1-2, пилот которого имеет Мастерство ниже вашего.<br/>Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
text: """<strong>Действие:</strong> Выполните свободное действие Бочка. Если у вас нет пиктограммы действия %BARRELROLL%, получите 1 жетон Стресса.%LINEBREAK%Затем вы можете удалить с вашего корабля 1 жетон Захвата цели противника."""
"Marksmanship":
text: """<strong>Действие:</strong> Во время атаки в
текущем раунде вы можете поменять 1 ваш выпавший
результат %FOCUS% на %CRIT%, и все остальные ваши результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку. %LINEBREAK%Вы можете заменить 1 выпавший пустой результат на %HIT% результат."""
"Cluster Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку
дважды."""
"Daredevil":
text: """<strong>Действие: </strong>Выполните белый
(%TURNLEFT% 1) или (%TURNRIGHT% 1) манёвр. Затем бросьте два кубика атаки, если вы не имеете действия %BOOST%. Получите
попадания %HIT% и %CRIT%, если таковые выпали."""
"Elusiveness":
text: """Во время защиты, вы можете получить 1 жетон Стресса
и выбрать 1 кубик атаки. Нападающий должен перебросить этот кубик.
Если у вас есть хотя бы 1 жетон Стресса, вы не можете использовать эту
способность."""
"Homing Missiles":
text: """<strong>Атака (Захват цели): </strong>Сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Обороняющийся корабль не
может использовать жетон Уклонения во время этой атаки."""
"Push the Limit":
text: """Единожды во время раунда, после выполнения
действия вы можете выполнить 1 из имеющихся у вас на Панели действий,
как свободное.%LINEBREAK%Затем получите 1 жетон Стресса."""
"Deadeye":
text: """Вы можете считать «Атака [Захват Цели]», как «Атака [Концентрация]:»<br/> Когда правило Атаки гласит, что жетон Захвата Цели должен быть потрачен, вы можете потратить жетон Концентрации вместо этого."""
"Expose":
text: """<strong>Действие: </strong>До конца этого раунда увеличьте величину вашего основного оружия на 1, и уменьшите на 1 показатель вашей Маневренности."""
"Gunner":
text: """Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы не можете выполнять других атак в этом раунде."""
"Ion Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и
1 жетон Иона. Затем отмените все результаты кубиков."""
"Heavy Laser Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Сразу после броска кубиков атаки вы должны заменить все ваши %CRIT% результаты, на %HIT% результаты ."""
"Seismic Charges":
text: """После вскрытия своего маневра вы можете сбросить эту карту и <strong>выставить</strong> 1 жетон Сейсмического заряда.%LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы активации."""
"Mercenary Copilot":
text: """Во время атаки на Дистанции 3, вы можете заменить один из ваших %HIT% результатов на %CRIT%."""
"Assault Missiles":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадёт, другие корабли на Дистанции 1 от обороняющегося получат 1 Повреждение."""
"Veteran Instincts":
text: """Увеличьте Мастерство вашего пилота на 2."""
"Proximity Mines":
text: """<strong>Действие:</strong> Сбросьте эту карту и <strong>выставите</strong> 1 жетон Мины.%LINEBREAK%При совершении кораблем манёвра, если его база и шаблон маневра накрывают этот жетон, мина <strong>детонирует</strong>."""
"Weapons Engineer":
text: """Вы можете иметь 2 Захвата цели (по 1 на каждом
из кораблей).<br /><br />Во время получения Захвата цели вы можете отметить 2 разных корабля."""
"Draw Their Fire":
text: """
Когда любой дружественный корабль на Дистанции 1 получает попадание от атаки, вы можете принять на себя 1 не отменённый %CRIT% результат, вместо этого корабля."""
"Luke Skywalker":
text: """%REBELONLY%%LINEBREAK%Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы можете заменить 1 %FOCUS% результат на %HIT%. Вы не можете выполнять других атак в этом раунде."""
"Nien Nunb":
text: """%REBELONLY%%LINEBREAK%Вы можете считать
любые %STRAIGHT% манёвры зелёными."""
"Chewbacca":
name: "Chewbacca (Crew)"
text: """%REBELONLY%%LINEBREAK%Когда вы получаете карту Повреждения, вы можете немедленно сбросить эту карту и восстановить 1 щит.%LINEBREAK%Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Вы можете заменить до 3 пустых результатов на %FOCUS% результаты."""
"Autoblaster":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Ваши %HIT% результаты не могут быть отменены кубиками защиты.%LINEBREAK%Обороняющий может отменять %CRIT% результаты до %HIT% результатов."""
"Fire-Control System":
text: """После выполнение атаки вы можете получить жетон Захвата Цели на оборонявшийся корабль"""
"Blaster Turret":
text: """<strong>Атака (Концентрация): </strong>Потратьте 1 жетон Концентрации для выполнения этой атаки против 1 корабля противника (даже если противник находится вне вашего сектора обстрела)."""
"Recon Specialist":
text: """При выполнении действия Концентрация добавьте ещё 1 жетон Концентрация вашему кораблю."""
"Saboteur":
text: """<strong>Действие: </strong>Выберите один вражеский корабль на Дистанции 1 и бросьте кубик атаки. При выпадении %HIT% или %CTRIT% результата, выберите одну перевернутую карту повреждений этого корабля, положите её лицом вверх и исполните указанные в ней инструкции."""
"Intelligence Agent":
text: """В начале фазы Активации выберите один корабль на Дистанции 1-2. Вы можете посмотреть на выбранный этим кораблём манёвр."""
"Proton Bombs":
text: """После вскрытия своего маневра вы можете сбросить эту карту чтобы <strong>выставить</strong> 1 жетон Протонной бомбы. %LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы Активации."""
"Adrenaline Rush":
text: """При вскрытии красного манёвра вы можете сбросить эту карту и считать данный манёвр белым до конца фазы Активации."""
"Advanced Sensors":
text: """Непосредственно перед вскрытием вашего манёвра вы можете выполнить 1 свободное действие.%LINEBREAK%Если вы используете эту возможность, вы должны пропустить шаг «Выполнение Действия» в текущем раунде."""
"Sensor Jammer":
text: """Во время обороны вы можете заменить 1 из %HIT% результатов атакующего на %FOCUS% результат.%LINEBREAK%Атаковавший не может перебросить этот кубик."""
"Darth Vader":
name: "Darth Vader (Crew)"
text: """%IMPERIALONLY%%LINEBREAK%После выполнения вами атаки вражеского корабля вы можете получить 2 повреждения, чтобы вражеский корабль получил 1 критическое повреждение."""
"Rebel Captive":
text: """%IMPERIALONLY%%LINEBREAK%Единожды за раунд, первый корабль, объявивший вас целью для атаки, немедленно получает 1 жетон Стресса."""
"Flight Instructor":
text: """Во время обороны вы можете перебросить 1 из ваших %FOCUS% результатов. Если величина Мастерства нападающего пилота «2» или менее, вы можете перебросить 1 из ваших пустых результатов, вместо %FOCUS%."""
"Navigator":
text: """Во время вскрытия манёвра вы можете выбрать другой манёвр такого же направления.%LINEBREAK%Красный манёвр не может быть выбран, если у вас уже есть хотя бы 1 жетон Стресса.""
"Opportunist":
text: """Во время атаки, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон Стресса и бросить 1 дополнительный кубик атаки. %LINEBREAK%Вы не можете использовать эту способность при наличии у вас жетона Стресса."""
"Comms Booster":
text: """"""<strong>Энергия:</strong> Потратьте 1 энергию и удалите все жетоны стресса на дружественном корабле на Дистанции 1-3. Затем положите 1 жетон концентрации на этот корабль."""
"Slicer Tools":
text: """<strong>Действие:</strong> Выберите 1 или более вражеских кораблей, имеющих жетоны стресса на Дистанции 1-3. Для каждого выбранного корабля вы можете потратить 1 энергию, чтобы нанести 1 Повреждение."""
"Shield Projector":
text: """Когда корабль противника объявляет своей целью маленький или большой корабль, вы можете потратить 3 энергии, чтобы принудить этот корабль выбрать целью ва, если это возможно."""
"Ion Pulse Missiles":
text: """<strong>Атака (Захват цели): </strong><br/>Сбросьте эту карту для выполнения этой атаки.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и 2 жетона иона. Затем все результаты кубиков отменяются."""
"Wingman":
text: """Вначале фазы Боя удалите 1 жетон стресса с другого дружественного корабля на Дистанции 1."""
"Decoy":
text: """В начале фазы Боя вы можете выбрать 1 дружественный корабль на Дистанции 1-2. Обменяйтесь показателями Мастерства пилота вашего и пилота выбранного корабля до конца фазы."""
"Outmaneuver":
text: """При атаке корабля, находящегося в вашем секторе обстрела, уменьшите значение Маневренности этого корабля на 1 (до минимума 0), если вы находитесь вне его сектора обстрела."""
"Predator":
text: """Во время атаки вы можете перебросить 1 кубик атаки. Если значение Мастерства защищающегося пилота равно ‘’2’’ или меньше, вы можете перебросить 2 кубика атаки."""
"Flechette Torpedoes":
name: "Flechet-Torpedos"
text: """<strong>Атака (Захват цели): </strong><br/>Потратьте жетон захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%После выполнения этой атаки защищающийся получает 1 жетон стресса, если значение корпуса его корабля равно 4 или меньше."""
"R7 Astromech":
text: """Один раз за раунд во время
защиты, если вы имеете захват цели на нападающем, вы можете сбросить захват цели и выбрать любые или все брошенные кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
text: """<strong>Действие: </strong> Выберите корабль противника на Дистанции 1-2. Если вы находитесь в секторе обстрела этого корабля, вы можете получить Захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорение."""
"Tactician":
text: """После выполнения атаки по кораблю, находящемуся в вашем секторе обстрела и на Дистанции 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%REBELONLY%%LINEBREAK% В конце фазы Завершения, если у вашего корабля нет щитов, вы можете восстановить один щит и кинуть кубик атаки. В случае результата %HIT% случайно выберите одну из карт повреждений, лежащих лицом вниз, и переверните. Затем выполните её инструкции."""
"C-3PO":
text: """%REBELONLY%%LINEBREAK%Один раз за раунд, до броска 1 или более кубиков защиты, назовите количестве будущих результатов %EVADE%. Если выпало ровно столько %EVADE% результатов (до изменения результатов броска), добавьте 1 результат %EVADE%."""
"Single Turbolasers":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 2 энергии этой карты, чтобы выполнить атаку. Защищающийся удваивает значение Маневренности корабля против этой атаки. Вы можете поменять 1 из ваших %FOCUS% результатов на %HIT% результат."""
"Quad Laser Cannons":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 1 энергию этой карты, чтобы выполнить атаку. Если атака не принесла успеха, вы можете немедленно потратить 1 энергию этой карты, чтобы выполнить атаку снова."""
"Tibanna Gas Supplies":
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 жетона энергии."""
"Ionization Reactor":
text: """<strong>Энергия:</strong> Потратье 5 жетонов энергии с этой карты и сбросьте эту карту, чтобы каждый другой корабль на Дистанции 1 получил по 1 повреждению и по 1 жетону Иона."""
"Engine Booster":
text: """До вскрытия своего диска маневров вы можете потратить 1 энергию для выполнения белого маневра (%STRAIGHT% 1). Вы не можете воспользоваться этим умением, если есть угроза наложения на другой корабль."""
"R3-A2":
text: """При объявлении цели вашей атаки, если она находится в вашем секторе обстрела, вы можете получить 1 жетон Стресса чтобы защищающийся тоже получил 1 жетон Стресса."""
"R2-D6":
text: """Вам доступно %ELITE% Улучшение.%LINEBREAK%Вы не можете использовать экипировать этого дроида если %ELITE% уже есть на панели Улучшений, или мастерство вашего пилота 2 или меньше."""
"Enhanced Scopes":
text: """Во время фазы Активации, рассматривайте Мастерство вашего пилота как "0"."""
"Chardaan Refit":
text: """A-WING only. %LINEBREAK%Эта карта имеет отрицательную стоимость."""
"Proton Rockets":
text: """<strong>Атака (Концентрация): </strong>%LINEBREAK%Сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете бросить дополнительные кубики атаки в количестве, равном показателю вашей Маневренности, но не более 3."""
"Kyle Katarn":
name: "Kyle Katarn (Crew)"
text: """%REBELONLY%%LINEBREAK%После удаления жетона стресса с вашего корабля, вы можете назначить ему жетон концентрации."""
"Jan Ors":
name: "Jan Ors (Crew)"
text: """%REBELONLY%%LINEBREAK%Один раз в раунд вы можете назначить дружественному кораблю на Дистанции 1-3 жетон уклонения, вместо выполнения данным кораблем действия концентрации или получения этим кораблем жетона концентрации."""
"Toryn Farr":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships."""
# TODO Check card formatting
"R4-D6":
text: """Когда вас атаковали и есть как минимум 3 неотмененных %HIT% результата, вы можете выбрать отменить эти результаты, пока не останется 2. За каждый отмененный таким образом %HIT% получите 1 жетон стресса."""
"R5-P9":
text: """В конце фазы Боя вы можете потратить 1 из ваших жетонов концентрации для восстановления одного щита (до максимума, доступного вам)."""
"WED-15 Repair Droid":
text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards."""
"Carlist Rieekan":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase."""
"Jan Dodonna":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%."""
"Expanded Cargo Hold":
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value)."""
"EM Emitter":
text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1)."""
"Frequency Jammer":
text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token."""
"Han Solo":
name: "Han Solo (Crew)"
text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results."""
"Leia Organa":
text: """%REBELONLY%%LINEBREAK%В начале фазы Активации вы можете сбросить эту карту, чтобы позволить всем дружественным кораблям, раскрывающим красный маневр, рассматривать этот маневр белым до конца этой фазы."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"Raymus Antilles":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token."""
"Gunnery Team":
text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result."""
"Sensor Team":
text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3."""
"Engineering Team":
text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step."""
"Lando Calrissian":
name: "Lando Calrissian (Crew)"
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Киньте два зеленых кубика. За каждый %FOCUS% результат назначьте 1 жетон Концентрации вашему кораблю. За каждый %EVADE% результат назначьте 1 жетон Уклонения вашему кораблю."""
"Mara Jade":
text: """%IMPERIALONLY%%LINEBREAK%В конце фазы Боя каждый вражеский корабль на Дистанции 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
text: """<strong>Действие: </strong>%LINEBREAK% Выберите до 2 дружественных кораблей на Дистанции 1-2, и назначьте 1 жетон Концентрации каждому из этих кораблей. Затем получите жетон Стресса."""
"Lone Wolf":
text: """При атаке или защите, если не Дистанции 1-2 не других дружественных кораблей, вы можете перебросить один пустой результат."""
"Stay On Target":
text: """Когда вы вскрываете маневр, вы можете изменить его на другой доступный вам маневр той же скорости.%LINEBREAK% Считайте этот маневр как красный маневр."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%REBELONLY%%LINEBREAK%Вы можете атаковать находясь на препятствии."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Осуществите свободное действие Ускорение. Затем получите 1 жетон Иона."""
"Ruthlessness":
text: """%IMPERIALONLY%%LINEBREAK%После совершения атаки, которая попала в цель, вы <strong>должны</strong> выбрать один другой корабль на Дистанции 1 от цели (кроме своего). Этот корабль получает 1 Повреждение."""
"Intimidation":
text: """Пока вы касаетесь вражеского корабля, уменьшите его значение Маневренности на 1."""
"Ysanne Isard":
text: """%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, если у вас нет щитов и есть хотя бы одна карта Повреждения, вы можете выполнить свободное действие %EVADE%."""
"Moff Jerjerrod":
text: """%IMPERIALONLY%%LINEBREAK%Когда вы получаете карту Повреждения лицом вверх, вы можете сбросить эту карту, или другую карту %CREW% для того, чтобы перевернуть эту карту Повреждения рубашкой вверх (без применения её свойств)."""
"Ion Torpedoes":
text: """<strong>Атака (Захват цели): </strong>%LINEBREAK%Потратье захват цели и сбросьте эту карту чтобы выполнить эту атаку. %LINEBREAK%Если атака попала, то защищающийся и все корабли на Дистанции 1 от него получают по 1 жетону Иона."""
"Bodyguard":
text: """%SCUMONLY%%LINEBREAK%В начале фазы боя вы можете потратить жетон концентрации для выбора дружественного корабля на Дистанции 1, с мастерством пилота выше чем у вас. Увеличьте его значение Маневренности на 1 до конца раунда."""
"Calculation":
text: """При атаке вы можете потратить жетон Концентрации для изменения 1 значения %FOCUS% на значение %CRIT%."""
"Accuracy Corrector":
text: """При атаке, на шаге "Изменения кубиков атаки" вы можете отменить все значения ваших кубиков. Затем, вы можете добавить два результата %HIT% к броску.%LINEBREAK%Ваши кубики не могут быть модифицированы снова в течении этой атаки."""
"Inertial Dampeners":
text: """Когда вы вскрываете свой маневр, вы можете скинуть эту карту для выполнения белого маневра [0%STOP%] вместо выбранного. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и, если у него нет Стресса, он также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"Mangler" Cannon':
text: """<strong>Атака: </strong>Атакуйте один корабль%LINEBREAK%При атаке вы можете поменять один результат %HIT% на %CRIT%."""
"Dead Man's Switch":
text: """Когда ваш корабль уничтожен, каждый корабль на Дистанции 1 получает 1 Повреждение."""
"Feedback Array":
text: """В течении фазы Боя, вместо осуществления атаки вы можете получить 1 жетон Иона и 1 Повреждение для того, чтобы выбрать один вражеский корабль на Дистанции 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
text: """<strong>Атака: </strong>%LINEBREAK%Сбросьте эту карту для атаки одного корабля (даже если он вне вашего сектора обстрела)."""
"Greedo":
text: """%SCUMONLY%%LINEBREAK%Первый раз когда вы атакуете в каждом раунде, и первый раз когда вы защищаетесь в каждом раунде, первая карта Повреждения применяется рубашкой вниз."""
"Salvaged Astromech":
text: """Когда вы получаете карту Повреждения с заголовком <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (до применения её эффекта).%LINEBREAK%Затем сбросьте эту карту."""
"Bomb Loadout":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %BOMB%"""
'"Genius"':
text: """Если вы снаряжены бомбой, которая сбрасывается при вскрытии маневра, то вы можете сбросить её <strong>после</strong> выполнения маневра."""
"Unhinged Astromech":
text: """Вы можете считать все маневры со скоростью 3 как зеленые маневры."""
"R4-B11":
text: """При атаке, если у вас есть захват цели на защищающегося, вы можете сбросить этот захват цели для выбора некоторых или всех кубиков защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":<strong>Атака: </strong>Атакуйте один корабль (даже если он вне вашего сектора обстрела)%LINEBREAK%Ваши результаты %HIT% не могут быть отменены кубиками защиты. Защищающийся может отменить результаты %CRIT% перед результатами %HIT%."""
"R4 Agromech":
text: """При атаке, после того как вы использовали жетон Концентрации, вы можете получить Захват цели на обороняющемся."""
"K4 Security Droid":
text: """%SCUMONLY%%LINEBREAK%После выполнения зеленого маневра вы можете осуществить Захват цели."""
"Outlaw Tech":
text: """%SCUMONLY%%LINEBREAK%После выполнения красного маневра вы можете получить 1 жетон Концентрации."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%При атаке из основного оружия, если у вас есть захват цели на обороняющемся, вы можете добавить 1 результат %CRIT% к вашим результатам. Если вы делаете это, то вы не можете потратить Захват цели в течении этой атаки."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"Emperor Palpatine":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent Kallus':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
text: """Ваша Маневренности увеличена на 1. Сбросьте эту карту, если вы получили попадание при атаке."""
"Shield Upgrade":
text: """Щиты вашего корабля увеличиваются на 1."""
"Engine Upgrade":
text: """На Панель Действий добавляется действие %BOOST%"""
"Anti-Pursuit Lasers":
text: """%DE_LARGESHIPONLY%%LINEBREAK%После того как вражеский корабль совершит манёвр, который приводит его к столкновению с вашим, бросьте 1 кубик атаки. В случае выпадения %HIT% или %CRIT% результата вражеский корабль получает 1 повреждение."""
"Targeting Computer":
text: """На Панель действий добавляется действие %TARGETLOCK%."""
"Hull Upgrade":
text: """Значение корпуса вашего корабля увеличивается на 1."""
"Munitions Failsafe":
text: """При атаке второстепенным оружием, по инструкции которого вам требуется сбросить карту для выполнения этой атаки, не сбрасывайте карту, если атака не принесла успеха."""
"Stygium Particle Accelerator":
text: """Когда вы выполняете любое из действий Сброса Маскировки или Маскировки, вы можете получить свободное действие Уклонения."""
"Advanced Cloaking Device":
text: """После выполнения атаки, вы можете выполнить свободное действие маскировки."""
"Combat Retrofit":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1."""
"B-Wing/E2":
text: """На вашу панель Улучшений добавляется улучшение %CREW%."""
"Countermeasures":
text: """%DE_LARGESHIPONLY%%LINEBREAK%В начале фазы Боя вы можете сбросить эту карту для увеличения Маневрености вашего корабля на 1 до конца раунда. Затем вы можете скинуть 1 вражеский захват цели со своего корабля."""
"Experimental Interface":
text: """Единожды за раунд, после выполнения действия вы можете выполнить свободное действие c экипированной карты Улучшения с заголовком <strong>Действие</strong>. Затем получите 1 жетон Стресса."""
"Tactical Jammer":
text: """%DE_LARGESHIPONLY%%LINEBREAK%Ваш корабль может быть влияет на вражеские атаки как препятствие."""
"Autothrusters":
text: """При защите, если вы за пределами Дистанции 2 или вне сектора обстрела атакующего корабля, вы можете поменять один пустой результат на результат %EVADE%. Вы можете экипировать это улучшение только если корабль имеет действие %BOOST%."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %TORPEDO%."""
"Millennium Falcon":
text: """<span class="card-restriction">YT-1300 only</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %EVADE%"""
"Moldy Crow":
text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%В течении фазы Завершения не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%Вы можете осуществлять Захват цели на любой корабль на игровом поле."""
"Royal Guard TIE":
text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%Вы можете экипировать до двух разных Улучшений-модификации (вместо одного).%LINEBREAK%Вы не можете экипировать это улучшение если Мастерство пилота "4" и меньше."""
"Dodonna's Pride":
name: "Dodonnas Stolz"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action."""
"A-Wing Test Pilot":
text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Ваша панель Улучшений получает 1 пиктограмму %ELITE%.%LINEBREAK%Вы не можете экипировать 2 одинаковых Улучшения %ELITE%. Вы не можете экипировать это улучшение, если мастерство пилота "1" и меньше."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2)."""
"Jaina's Light":
name: "Jainas Licht"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card."""
"Outrider":
text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%Пока вы снаряжены Дополнительным Орудием %CANNON% вы <strong>не можете</strong> атаковать основным орудием, и вы можете атаковать Дополнительным Орудием %CANNON% корабли вне вашего сектора обстрела."""
"Dauntless":
text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%После выполнения маневра, который привел к перекрытию другого корабля вы можете осуществить 1 свободное действие. Затем получите 1 жетон Стресса."""
"Virago":
text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограммы %SYSTEM% и %ILLICIT%.%LINEBREAK%Вы не можете экипировать это улучшение, если Мастерство пилота "3" или ниже."""
'"Heavy Scyk" Interceptor (Cannon)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%Вы обладаете способностью пилота каждого другого дружественного корабля с улучшением <em>IG-2000</em> (в дополнение к вашей способности пилота)."""
"BTL-A4 Y-Wing":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Вы не можете атаковать корабли вне вашего сектора обстрела. После атаки основным оружием вы можете немедленно атаковать дополнительным орудием %TURRET%."""
"Andrasta":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель Улучшений содержит две дополнительные пиктограммы %BOMB%."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Ваша панель улучшения содержит пиктограмму %SYSTEM%.%LINEBREAK%Если вы экипируете Улучшение %SYSTEM%, его стоимость уменьшается на 4 (до минимальной стоимости "0")."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"Mist Hunter":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
| 154186 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Russian'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Russian =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Recover"
"Reinforce": "Reinforce"
"Jam": "Jam"
"Coordinate": "Coordinate"
"Cloak": "Маскировка"
slot:
"Astromech": "Астромех"
"Bomb": "Бомба"
"Cannon": "Дополнительное Орудие"
"Crew": "Экипаж"
"Elite": "Талант"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Cargo"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "Нелегальный"
"Salvaged Astromech": "захваченный Астромех"
sources: # needed?
"Core": "База"
"A-Wing Expansion Pack": "Дополнение A-Wing"
"B-Wing Expansion Pack": "Дополнение B-Wing"
"X-Wing Expansion Pack": "Дополнение X-Wing"
"Y-Wing Expansion Pack": "Дополнение Y-Wing"
"Millennium Falcon Expansion Pack": "Дополнение Сокол Тысячелетия"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-Fighter"
"TIE Interceptor Expansion Pack": "Дополнение TIE-Interceptor"
"TIE Bomber Expansion Pack": "Дополнение TIE-Bomber"
"TIE Advanced Expansion Pack": "Дополнение TIE-Advanced"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Lambda-class Shuttle"
"Slave I Expansion Pack": "Дополнение Sklave I"
"Imperial Aces Expansion Pack": "Дополнение Imperial Aces"
"Rebel Transport Expansion Pack": "Дополнение Rebel Transport"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95-Headhunter"
"TIE Defender Expansion Pack": "Дополнение TIE-Defender"
"E-Wing Expansion Pack": "Дополнение E-Wing"
"TIE Phantom Expansion Pack": "Дополнение TIE-Phantom"
"Tantive IV Expansion Pack": "Дополнение Tantive IV"
"Rebel Aces Expansion Pack": "Дополнение Rebel Aces"
"YT-2400 Freighter Expansion Pack": "Дополнение YT-2400 Freighter"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Decimator"
"StarViper Expansion Pack": "Дополнение StarViper"
"M3-A Interceptor Expansion Pack": "Дополнение M3-A Interceptor"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Most Wanted"
"Imperial Raider Expansion Pack": "Дополнение Imperial Raider"
ui:
shipSelectorPlaceholder: "Выберите корабль"
pilotSelectorPlaceholder: "Выберите пилота"
upgradePlaceholder: (translator, language, slot) ->
"Нет #{translator language, 'слота', slot} улучшения"
modificationPlaceholder: "Нет модификации"
titlePlaceholder: "Нет названия"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'Слот', slot} улучшения"
unreleased: "не выпущено"
epic: "Эпик"
limited: "ограничено"
byCSSSelector:
'.translate.sort-cards-by': 'Сортировать карты по'
'.xwing-card-browser option[value="name"]': 'Имени'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (Очки)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (Имени)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Мастерство'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новый отряд'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить отряд'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Печать\Просмотр как </span>Text'
'.randomize' : 'Случайно'
'.randomize-options' : 'Опции генератора случайности'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте в пост на форуме.<textarea></textarea>'
'.vertical-space-checkbox' : """Добавить пространство для карт повреждений\улучшений на распечатке. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Печать в цвете. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Печать'
# Randomizer options
'.do-randomize' : 'Случайно!'
# Top tab bar
'#empireTab' : 'Галактическая империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Негодяи'
'#browserTab' : 'Список карт'
'#aboutTab' : 'О сервисе'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Modifikation'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Russian = () ->
exportObj.cardLanguage = 'Russian'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
pilot_translations =
"<NAME>":
text: """Во время атаки, уменьшите значение Мобильности защищающегося на 1 (значение не может быть меньше нуля)."""
"<NAME>":
text: """После использования жетона Концентрации вы можете передать его любому другому дружественному кораблю, находящемуся на Дистанции 1-2 (вместо сброса)."""
"Biggs Darklighter":
text: """Другие дружественные корабли на Дистанции 1 не могут быть атакованы, если целью можете быть выбраны вы."""
"Luke Skywalker":
text: """Во время защиты вы можете заменить один из результатов %FOCUS% на результат %EVADE%"""
'"Dutch" Vander':
text: """После захвата цели, выберите любой другой дружественный корабль на Дистанции 1-2. Выбранный корабль может немедленно получить жетон Захвата Цели."""
"<NAME>":
text: """Во время атаки на Дистанции 2-3 вы можете перебросить любое количество ваших кубиков, не имеющих какого-либо результата."""
'"W<NAME>"':
text: """Во время атаки на Дистанции 1 вы можете заменить один из ваших %HIT% результатов на %CRIT% результат."""
'"Night Beast"':
text: """После выполнения зеленого манёвра вы можете выполнить свободное действие Концентрация."""
'"Backstabber"':
text: """Если во время атаки вы находитесь вне сектора стрельбы обороняющегося корабля, бросайте на один кубик атаки больше."""
'"Dark Curse"':
text: """Во время обороны, атакующие вас корабли, не могут использовать маркеры Концентрации или перебрасывать кубики атаки."""
'"<NAME>"':
text: """Когда атакуете на Дистанции 1 бросайте на один кубик атаки больше."""
'"<NAME>"':
text: """Когда другой дружественный корабль атакует на Дистанции 1 основным оружием, он может перебросить один кубик атаки."""
"<NAME>":
text: """Когда ваша атака наносит Критическое повреждение атакуемому кораблю, вместо 1 возьмите 3 карты Повреждений. Выберете 1 из них, а остальные сбросьте."""
"<NAME>":
text: """Во время шага «Выполните Действие» в фазе Активации, вы можете выполнить 2 действия."""
"\"<NAME>\"":
text: """Когда количество карт Повреждений будет равно или превышать значение корпуса вашего корабля, корабль не разрушается до конца этой боевой фазы."""
"<NAME>":
text: """После выполнения атаки вы можете выполнить свободное действие Бочка или Ускорение."""
"<NAME>":
text: """Когда вы получаете жетон Стресса, можете так же получить жетон Концентрация для этого корабля."""
"<NAME>":
text: """Вы можете выполнять действия даже при наличии у вас жетона Стресса."""
"<NAME>":
text: """Вы можете выбрать целью для атаки вражеский корабль, находящийся в вашем секторе стрельбы, даже если вы его касаетесь."""
"Che<NAME>":
text: """Если вы получили карту Повреждений лицом вверх, немедленно переверните эту карту лицом вниз (без применения ее свойств)."""
"<NAME>":
text: """После выполнения зелёного манёвра, выберите 1 дружественный корабль на Дистанции 1. Этот корабль может выполнить любое из действий, указанных в его карте, как свободное."""
"<NAME>":
text: """Во время атаки вы можете перебросить все ваши кубики. Если вы выбрали это, то должно быть переброшено их максимальное возможное количество."""
"<NAME>":
text: """Во время атаки, обороняющийся получает один жетон Стресса, если хотя бы один из результатов %CRIT% был отменён."""
"<NAME>":
text: """Когда вы вскрываете манёвр %BANKLEFT% или %BANKRIGHT%, вы можете заменить его на другой манёвр той же скорости."""
"<NAME>":
text: """Во время атаки Дополнительным оружием, вы можете перебросить один кубик атаки."""
"Ten <NAME>umb":
text: """Во время атаки, один из ваших результатов %CRIT% нельзя отменить кубиком защиты."""
"I<NAME>":
text: """Во время атаки или обороны вы можете перебросить один из ваших кубиков, если у вас есть хотя бы один жетон Стресса."""
"<NAME>":
text: '''После начала фазы боя, выберете любой другой дружественный корабль на Дистанции 1-3. До конца фазы, Мастерство пилота выбранного корабля считается равным 12.'''
"<NAME>":
text: """В начале фазы боя вы можете передать один из ваших жетонов Концентрации другому дружественному кораблю на Дистанции 1-3."""
"<NAME>":
text: """Когда другой дружественный корабль атакует на Дистанции 1-3 и у вас нет жетона Стресса, вы можете получить один жетон Стресса, чтобы позволить этому кораблю бросить один дополнительный кубик атаки."""
"<NAME>":
text: """Когда другой дружественный корабль атакует на Дистанции 1, используя дополнительное оружие, он может перебросить до двух кубиков атаки."""
"<NAME>":
text: """Во время атаки дополнительным оружием, вы можете увеличить или уменьшить дистанцию использования оружия на один, в пределах Дистанции 1-3."""
"<NAME>":
text: """Когда вражеский корабль получает жетон Захвата цели, он должен использовать ваш корабль в качестве цели, если может."""
"<NAME>":
text: """В начале фазы боя, вы можете передать один из ваших голубых жетонов Захвата цели дружественному кораблю на Дистанции 1, если у него таковых не имеется."""
"<NAME>":
text: """Вы можете получить жетон Стресса вместо любого другого дружественного корабля на Дистанции 1-2, если у вас таких жетонов два или менее."""
"<NAME>":
text: """При выполнении действия Бочка вы можете получить 1 жетон Стресса и использовать шаблоны (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"<NAME>":
text: """Когда вы вскрываете маневр %UTURN%, вы можете считать скорость этого маневра как "1," "3," или "5"."""
"<NAME>":
text: """Во время атаки на Дистанции 2-3 вы можете сбросить один жетон уклонения, чтобы добавить к броску один %HIT% результат."""
"<NAME>":
text: """Вражеские корабли на Дистанции 1 не могут выполнять действия Уклонения или Концентрации, и не могут сбрасывать соответствующие жетоны."""
"<NAME>":
text: """Ваша атака считается успешной, даже если защищающийся успешно отменил все повреждения."""
"<NAME>":
text: """После выполнения атаки вы можете выбрать другой дружественный корабль на Дистанции 1. Этот корабль может выполнить ."""
"<NAME>":
text: """Во время атаки, после броска ваших кубиков атаки, сразу можете получить Захват цели на защищающегося, если он уже имеет красный жетон захвата цели."""
"<NAME>":
text: """После выполнения атаки, принесшей противнику как минимум одну карту Повреждения, вы можете сбросить один жетон Концентрации для переворота нанесенных карт Повреждений лицом вверх."""
"<NAME>":
text: """Когда корабль противника находится внутри вашего сектора стрельбы на Дистанции 1-3, и защищается, то атакующий может изменить один из %HIT% результатов на %CRIT% результат."""
"<NAME>":
text: """В начале фазы Завершения вы можете выполнить одну атаку. Вы не можете атаковать в течении следующего раунда."""
'"<NAME>"':
text: """Когда вы сбрасываете режим Маскировки, вы должны использовать шаблоны (%BANKRIGHT% 2) или (%BANKLEFT% 2) вместо (%STRAIGHT% 2)."""
'"Wh<NAME>"':
text: """После выполнения успешной атаки вы можете получить один жетон КОнцентрации на ваш корабль."""
"<NAME>":
text: """После выполнения атаки вы можете удалить один жетон Концентрации, Уклонения или голубой жетон захвата цели с защищающегося корабя."""
"<NAME>":
text: """Когда вы получаете жетон стресса, вы можете удалить его и бросить один кубик атаки. На результате %HIT% получите на этот корабль карту Повреждения лицом вниз."""
'"<NAME>" <NAME>':
text: """Когда вы получаете или тратите Захват цели, вы можете удалить один жетон стресса с вашего корабля."""
"<NAME>":
text: """Когда корабль противника объявил вас целью для своей атаки, вы можете получить Захват цели на этот корабль."""
"<NAME>":
text: """После выполнения действия Концентрации или получения жетона Концентрации, вы можете совершить свободное действие Ускорение или Бочка."""
"<NAME>":
text: """Пока вы находитесь на Дистанции 1 от, по крайней мере одного, корабля противника, увеличьте показатель вашей маневренности на один."""
"<NAME>":
text: """Когда атакуете, вы можете удалить один жетон Стресса для замены всех ваших %FOCUS% результатов на %HIT% результаты."""
"<NAME>":
text: """Вы можете выполнять атаки торпедами %TORPEDO% по кораблям противника, находящимися вне вашего сектора стрельбы."""
"<NAME>":
text: """Вы можете игнорировать жетоны преград в фазе Активации и когда совершаете Действия."""
'"<NAME>"':
text: """Когда вы получаете карту Повреждения лицом вверх, вытяните одну дополнительную карту Повреждения, выберите одну для применения, вторую сбросьте."""
"<NAME>":
text: """Когда вы атакуете основным орудием корабль с жетоном Стресса, кидайте один дополнительный кубик атаки."""
"<NAME>":
text: """При атаке на Дистанции 1-2, вы можете поменять один из ваших результатов %FOCUS% на %CRIT% результат."""
"<NAME>":
text: """Если у вас нет щитов и есть хотя бы одна карта Повреждения, увеличьте вашу маневренность на один."""
"<NAME>":
text: """После выполнения маневра каждый вражеский корабль, с которым вы соприкасаетесь, получает одно повреждение."""
"<NAME>":
text: """При защите, дружественный корабль на Дистанции 1 может получить один неотмененный результат %HIT% или %CRIT% вместо вас."""
"<NAME>":
text: """В начале фазы Б<NAME>, если вы на Дистанции 1 от вражеского корабля, вы можете назначить один жетон концентрации вашему кораблю."""
"<NAME>":
text: """Когда другой дружественный корабль на Дистанции 1 защищается, он может перебросить один кубик защиты."""
"<NAME>":
text: """После того как вы выполнили защиту от вражеской атаки, если атака не попала, вы можете назначить один жетон уклонения вашему кораблю."""
"IG-88A":
text: """После выполнения вами атаки, которая уничтожила цель, вы можете восстановить один щит."""
"IG-88B":
text: """Единожды в раунд, после выполнения атаки, которая не попала, вы можете осуществить атаку из имеющегося дополнительного орудия %CANNON%."""
"IG-88C":
text: """После выполнения вами действия Ускорения, вы можете совершить свободное действие Уклонения."""
"IG-88D":
text: """Вы можете осуществлять маневры (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующие шаблоны (%TURNLEFT% 3) или (%TURNRIGHT% 3) ."""
"<NAME> (Scum)":
text: """При атаке или защите, вы можете перебросить один ваш кубик за каждый вражеский корабль на Дистанции 1."""
"<NAME> (Scum)":
text: """При атаке корабля в вашем вспомогательном секторе стрельбы, бросайте один дополнительный кубик атаки."""
"<NAME>":
text: """При сбросе бомбы, вы можете использовать шаблоны [%TURNLEFT% 3], [%STRAIGHT% 3], или [%TURNRIGHT% 3] вместо шаблона [%STRAIGHT% 1]."""
"<NAME>":
text: """При атаке корабля вне вашего сектора обстрела бросайте один дополнительный кубик атаки."""
"<NAME>":
text: """После того как вы использовали Захват цели вы можете получить один жетон Стресса для выполнения Захвата цели."""
"<NAME>":
text: """Когда вражеский корабль на Дистанции 1-3 получает как минимум один жетон Иона, и у вас нет жетонов Стресса, вы можете получить один жетон Стресса и нанести этому кораблю одно повреждение."""
"<NAME>":
text: """В начале фазы <NAME>, вы можете удалить один жетон %FOCUS% или %EVADE% с вражеского корабля на Дистанции 1-2 и назначить его своему кораблю."""
"<NAME>":
text: """В начале фазы Активации выберите один вражеский корабль на Дистанции 1-2. До конца фазы Боя считайте Мастерство пилота этого корабля как "0"."""
"<NAME>":
text: """При атаке, если на Дистанции 1-2 нет других дружественных кораблей, бростайте один дополнительный кубик атаки."""
"<NAME>":
text: """В начале фазы Боя вы можете удалить один жетон %FOCUS% или %EVADE% с другого дружественного корабля на Дистанции 1-2, и назначить его себе."""
"<NAME>":
text: """В начале фазы Боя вы можете получить Захват цели на вражеский корабль на Дистанции 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"<NAME>":
text: """Когда вы открываете свой маневр, вы можете увеличить или уменьшить его скорость на единицу (до минимума в 1)."""
"<NAME>":
text: """Вражеский корабль на Дистанции 1 не может использовать бонус дистанции при выполнении атаки."""
"<NAME>":
text: """В начале фазы Завершения вы можете использовать имеющийся Захват цели на вражеский корабль, для того чтобы перевернуть лицом вверх одну случайную из имеющихся у него карт Повреждений."""
"<NAME>":
text: """Когда дружественный корабль объявляет атаку, вы можете использовать имеющийся Захват цели на защищающемся корабле для уменьшения его маневренности на единицу на время этой атаки."""
"<NAME>":
text: """При защите, если атакующий в вашем секторе обстрела, бросайте один дополнительный кубик защиты."""
"<NAME>":
text: """Когда другой дружественный корабль на Дистанции 1-2 атакует, вы можете считать ваш жетон %FOCUS% как принадлежащий ему."""
'"Redline"':
text: """Вы можете осуществлять два захвата цели на один корабль. Когда вы осуществляете Захват цели, вы можете получить второй Захват цели на этот корабль."""
'"Deathrain"':
text: """При сбросе бомбы, вы можете использовать передние направляющие вашего корабля. После сброса бомбы вы можете осуществить свободное действие Бочка."""
"Moralo Eval":
text: """Вы можете осуществлять атаки дополнительным орудием %CANNON% против кораблей в вашем дополнительном секторе обстрела."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"Scourge"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The Inquisitor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"Zuckuss":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"Dengar":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне сектора обстрела).%LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и 1 жетон Иона. Затем отмените все результаты кубиков."""
"<NAME>":
text: """<strong>Атака (Захват цели):</strong>Потратьте жетон Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете заменить 1 из ваших %FOCUS% результатов на результат %CRIT%."""
"R2 Astromech":
text: """Манёвры со скоростью 1 и 2 вы можете считать как зелёные манёвры."""
"R2-D2":
text: """После выполнения зелёного манёвра вы можете восстановить 1 Щит (до максимума доступного вам)."""
"R2-F2":
text: """<strong>Действие:</strong> Вы можете увеличить значение Маневренности на 1 до конца текущего раунда."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты. %LINEBREAK%В случае выпадения %EVADE% или %FOCUS% результата вы можете сбросить 1 карту из ваших не-критических Повреждений."""
"R5-K6":
text: """После сброса жетона Захвата цели, бросьте1 кубик защиты.%LINEBREAK%В случае выпадения результата %EVADE% немедленно получите жетон Захвата цели на тот же самый корабль. Вы не можете
потратить его во время этой атаки."""
"R5 Astromech":
text: """Во время фазы Завершения вы можете выбрать 1 из ваших карт Критических Повреждений с заголовком <strong>Корабль</strong> и перевернуть её лицом вниз."""
"Determination":
text: """Когда вы получаете карту Критического повреждения
с заголовком <strong>Пилот</strong>, немедленно сбросьте её без выполнения её эффекта."""
"Swarm Tactics":
text: """В начале фазы Боя выберите дружественный корабль на Дистанции 1. %LINEBREAK%До конца этой фазы пилот выбранного корабля имеет значение Мастерства пилота такое же как, и у вас."""
"Squad Leader":
text: """<strong>Действие:</strong> Выберите один корабль на Дистанции 1-2, пилот которого имеет Мастерство ниже вашего.<br/>Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
text: """<strong>Действие:</strong> Выполните свободное действие Бочка. Если у вас нет пиктограммы действия %BARRELROLL%, получите 1 жетон Стресса.%LINEBREAK%Затем вы можете удалить с вашего корабля 1 жетон Захвата цели противника."""
"Marksmanship":
text: """<strong>Действие:</strong> Во время атаки в
текущем раунде вы можете поменять 1 ваш выпавший
результат %FOCUS% на %CRIT%, и все остальные ваши результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку. %LINEBREAK%Вы можете заменить 1 выпавший пустой результат на %HIT% результат."""
"Cluster Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку
дважды."""
"Daredevil":
text: """<strong>Действие: </strong>Выполните белый
(%TURNLEFT% 1) или (%TURNRIGHT% 1) манёвр. Затем бросьте два кубика атаки, если вы не имеете действия %BOOST%. Получите
попадания %HIT% и %CRIT%, если таковые выпали."""
"Elusiveness":
text: """Во время защиты, вы можете получить 1 жетон Стресса
и выбрать 1 кубик атаки. Нападающий должен перебросить этот кубик.
Если у вас есть хотя бы 1 жетон Стресса, вы не можете использовать эту
способность."""
"Homing Missiles":
text: """<strong>Атака (Захват цели): </strong>Сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Обороняющийся корабль не
может использовать жетон Уклонения во время этой атаки."""
"Push the Limit":
text: """Единожды во время раунда, после выполнения
действия вы можете выполнить 1 из имеющихся у вас на Панели действий,
как свободное.%LINEBREAK%Затем получите 1 жетон Стресса."""
"Deadeye":
text: """Вы можете считать «Атака [Захват Цели]», как «Атака [Концентрация]:»<br/> Когда правило Атаки гласит, что жетон Захвата Цели должен быть потрачен, вы можете потратить жетон Концентрации вместо этого."""
"Expose":
text: """<strong>Действие: </strong>До конца этого раунда увеличьте величину вашего основного оружия на 1, и уменьшите на 1 показатель вашей Маневренности."""
"Gunner":
text: """Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы не можете выполнять других атак в этом раунде."""
"Ion Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и
1 жетон Иона. Затем отмените все результаты кубиков."""
"Heavy Laser Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Сразу после броска кубиков атаки вы должны заменить все ваши %CRIT% результаты, на %HIT% результаты ."""
"Seismic Charges":
text: """После вскрытия своего маневра вы можете сбросить эту карту и <strong>выставить</strong> 1 жетон Сейсмического заряда.%LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы активации."""
"Mercenary Copilot":
text: """Во время атаки на Дистанции 3, вы можете заменить один из ваших %HIT% результатов на %CRIT%."""
"Assault Missiles":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадёт, другие корабли на Дистанции 1 от обороняющегося получат 1 Повреждение."""
"Veteran Instincts":
text: """Увеличьте Мастерство вашего пилота на 2."""
"Proximity Mines":
text: """<strong>Действие:</strong> Сбросьте эту карту и <strong>выставите</strong> 1 жетон Мины.%LINEBREAK%При совершении кораблем манёвра, если его база и шаблон маневра накрывают этот жетон, мина <strong>детонирует</strong>."""
"Weapons Engineer":
text: """Вы можете иметь 2 Захвата цели (по 1 на каждом
из кораблей).<br /><br />Во время получения Захвата цели вы можете отметить 2 разных корабля."""
"Draw Their Fire":
text: """
Когда любой дружественный корабль на Дистанции 1 получает попадание от атаки, вы можете принять на себя 1 не отменённый %CRIT% результат, вместо этого корабля."""
"<NAME>":
text: """%REBELONLY%%LINEBREAK%Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы можете заменить 1 %FOCUS% результат на %HIT%. Вы не можете выполнять других атак в этом раунде."""
"<NAME>":
text: """%REBELONLY%%LINEBREAK%Вы можете считать
любые %STRAIGHT% манёвры зелёными."""
"Chewb<NAME>ca":
name: "Che<NAME> (Crew)"
text: """%REBELONLY%%LINEBREAK%Когда вы получаете карту Повреждения, вы можете немедленно сбросить эту карту и восстановить 1 щит.%LINEBREAK%Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Вы можете заменить до 3 пустых результатов на %FOCUS% результаты."""
"Autoblaster":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Ваши %HIT% результаты не могут быть отменены кубиками защиты.%LINEBREAK%Обороняющий может отменять %CRIT% результаты до %HIT% результатов."""
"Fire-Control System":
text: """После выполнение атаки вы можете получить жетон Захвата Цели на оборонявшийся корабль"""
"Blaster Turret":
text: """<strong>Атака (Концентрация): </strong>Потратьте 1 жетон Концентрации для выполнения этой атаки против 1 корабля противника (даже если противник находится вне вашего сектора обстрела)."""
"Recon Specialist":
text: """При выполнении действия Концентрация добавьте ещё 1 жетон Концентрация вашему кораблю."""
"Saboteur":
text: """<strong>Действие: </strong>Выберите один вражеский корабль на Дистанции 1 и бросьте кубик атаки. При выпадении %HIT% или %CTRIT% результата, выберите одну перевернутую карту повреждений этого корабля, положите её лицом вверх и исполните указанные в ней инструкции."""
"Intelligence Agent":
text: """В начале фазы Активации выберите один корабль на Дистанции 1-2. Вы можете посмотреть на выбранный этим кораблём манёвр."""
"Proton Bombs":
text: """После вскрытия своего маневра вы можете сбросить эту карту чтобы <strong>выставить</strong> 1 жетон Протонной бомбы. %LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы Активации."""
"Adrenaline Rush":
text: """При вскрытии красного манёвра вы можете сбросить эту карту и считать данный манёвр белым до конца фазы Активации."""
"Advanced Sensors":
text: """Непосредственно перед вскрытием вашего манёвра вы можете выполнить 1 свободное действие.%LINEBREAK%Если вы используете эту возможность, вы должны пропустить шаг «Выполнение Действия» в текущем раунде."""
"Sensor Jammer":
text: """Во время обороны вы можете заменить 1 из %HIT% результатов атакующего на %FOCUS% результат.%LINEBREAK%Атаковавший не может перебросить этот кубик."""
"Darth Vader":
name: "Darth Vader (Crew)"
text: """%IMPERIALONLY%%LINEBREAK%После выполнения вами атаки вражеского корабля вы можете получить 2 повреждения, чтобы вражеский корабль получил 1 критическое повреждение."""
"Rebel Captive":
text: """%IMPERIALONLY%%LINEBREAK%Единожды за раунд, первый корабль, объявивший вас целью для атаки, немедленно получает 1 жетон Стресса."""
"Flight Instructor":
text: """Во время обороны вы можете перебросить 1 из ваших %FOCUS% результатов. Если величина Мастерства нападающего пилота «2» или менее, вы можете перебросить 1 из ваших пустых результатов, вместо %FOCUS%."""
"Navigator":
text: """Во время вскрытия манёвра вы можете выбрать другой манёвр такого же направления.%LINEBREAK%Красный манёвр не может быть выбран, если у вас уже есть хотя бы 1 жетон Стресса.""
"Opportunist":
text: """Во время атаки, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон Стресса и бросить 1 дополнительный кубик атаки. %LINEBREAK%Вы не можете использовать эту способность при наличии у вас жетона Стресса."""
"Comms Booster":
text: """"""<strong>Энергия:</strong> Потратьте 1 энергию и удалите все жетоны стресса на дружественном корабле на Дистанции 1-3. Затем положите 1 жетон концентрации на этот корабль."""
"Slicer Tools":
text: """<strong>Действие:</strong> Выберите 1 или более вражеских кораблей, имеющих жетоны стресса на Дистанции 1-3. Для каждого выбранного корабля вы можете потратить 1 энергию, чтобы нанести 1 Повреждение."""
"Shield Projector":
text: """Когда корабль противника объявляет своей целью маленький или большой корабль, вы можете потратить 3 энергии, чтобы принудить этот корабль выбрать целью ва, если это возможно."""
"Ion Pulse Missiles":
text: """<strong>Атака (Захват цели): </strong><br/>Сбросьте эту карту для выполнения этой атаки.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и 2 жетона иона. Затем все результаты кубиков отменяются."""
"Wingman":
text: """Вначале фазы Боя удалите 1 жетон стресса с другого дружественного корабля на Дистанции 1."""
"Decoy":
text: """В начале фазы Боя вы можете выбрать 1 дружественный корабль на Дистанции 1-2. Обменяйтесь показателями Мастерства пилота вашего и пилота выбранного корабля до конца фазы."""
"Outmaneuver":
text: """При атаке корабля, находящегося в вашем секторе обстрела, уменьшите значение Маневренности этого корабля на 1 (до минимума 0), если вы находитесь вне его сектора обстрела."""
"Predator":
text: """Во время атаки вы можете перебросить 1 кубик атаки. Если значение Мастерства защищающегося пилота равно ‘’2’’ или меньше, вы можете перебросить 2 кубика атаки."""
"<NAME>":
name: "<NAME>"
text: """<strong>Атака (Захват цели): </strong><br/>Потратьте жетон захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%После выполнения этой атаки защищающийся получает 1 жетон стресса, если значение корпуса его корабля равно 4 или меньше."""
"R7 Astromech":
text: """Один раз за раунд во время
защиты, если вы имеете захват цели на нападающем, вы можете сбросить захват цели и выбрать любые или все брошенные кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
text: """<strong>Действие: </strong> Выберите корабль противника на Дистанции 1-2. Если вы находитесь в секторе обстрела этого корабля, вы можете получить Захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорение."""
"Tactician":
text: """После выполнения атаки по кораблю, находящемуся в вашем секторе обстрела и на Дистанции 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%REBELONLY%%LINEBREAK% В конце фазы Завершения, если у вашего корабля нет щитов, вы можете восстановить один щит и кинуть кубик атаки. В случае результата %HIT% случайно выберите одну из карт повреждений, лежащих лицом вниз, и переверните. Затем выполните её инструкции."""
"C-3PO":
text: """%REBELONLY%%LINEBREAK%Один раз за раунд, до броска 1 или более кубиков защиты, назовите количестве будущих результатов %EVADE%. Если выпало ровно столько %EVADE% результатов (до изменения результатов броска), добавьте 1 результат %EVADE%."""
"Single Turbolasers":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 2 энергии этой карты, чтобы выполнить атаку. Защищающийся удваивает значение Маневренности корабля против этой атаки. Вы можете поменять 1 из ваших %FOCUS% результатов на %HIT% результат."""
"Quad Laser Cannons":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 1 энергию этой карты, чтобы выполнить атаку. Если атака не принесла успеха, вы можете немедленно потратить 1 энергию этой карты, чтобы выполнить атаку снова."""
"Tibanna Gas Supplies":
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 жетона энергии."""
"Ionization Reactor":
text: """<strong>Энергия:</strong> Потратье 5 жетонов энергии с этой карты и сбросьте эту карту, чтобы каждый другой корабль на Дистанции 1 получил по 1 повреждению и по 1 жетону Иона."""
"Engine Booster":
text: """До вскрытия своего диска маневров вы можете потратить 1 энергию для выполнения белого маневра (%STRAIGHT% 1). Вы не можете воспользоваться этим умением, если есть угроза наложения на другой корабль."""
"R3-A2":
text: """При объявлении цели вашей атаки, если она находится в вашем секторе обстрела, вы можете получить 1 жетон Стресса чтобы защищающийся тоже получил 1 жетон Стресса."""
"R2-D6":
text: """Вам доступно %ELITE% Улучшение.%LINEBREAK%Вы не можете использовать экипировать этого дроида если %ELITE% уже есть на панели Улучшений, или мастерство вашего пилота 2 или меньше."""
"Enhanced Scopes":
text: """Во время фазы Активации, рассматривайте Мастерство вашего пилота как "0"."""
"Chardaan Refit":
text: """A-WING only. %LINEBREAK%Эта карта имеет отрицательную стоимость."""
"Proton Rockets":
text: """<strong>Атака (Концентрация): </strong>%LINEBREAK%Сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете бросить дополнительные кубики атаки в количестве, равном показателю вашей Маневренности, но не более 3."""
"<NAME>":
name: "<NAME> (Crew)"
text: """%REBELONLY%%LINEBREAK%После удаления жетона стресса с вашего корабля, вы можете назначить ему жетон концентрации."""
"<NAME>":
name: "<NAME> (Crew)"
text: """%REBELONLY%%LINEBREAK%Один раз в раунд вы можете назначить дружественному кораблю на Дистанции 1-3 жетон уклонения, вместо выполнения данным кораблем действия концентрации или получения этим кораблем жетона концентрации."""
"<NAME>":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships."""
# TODO Check card formatting
"R4-D6":
text: """Когда вас атаковали и есть как минимум 3 неотмененных %HIT% результата, вы можете выбрать отменить эти результаты, пока не останется 2. За каждый отмененный таким образом %HIT% получите 1 жетон стресса."""
"R5-P9":
text: """В конце фазы Боя вы можете потратить 1 из ваших жетонов концентрации для восстановления одного щита (до максимума, доступного вам)."""
"WED-15 Repair Droid":
text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards."""
"<NAME>":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase."""
"<NAME>":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%."""
"Expanded Cargo Hold":
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value)."""
"EM Emitter":
text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1)."""
"Frequency Jammer":
text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token."""
"Han <NAME>":
name: "<NAME> (Crew)"
text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results."""
"Leia <NAME>ana":
text: """%REBELONLY%%LINEBREAK%В начале фазы Активации вы можете сбросить эту карту, чтобы позволить всем дружественным кораблям, раскрывающим красный маневр, рассматривать этот маневр белым до конца этой фазы."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"<NAME>":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token."""
"Gunnery Team":
text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result."""
"Sensor Team":
text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3."""
"Engineering Team":
text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step."""
"<NAME>":
name: "<NAME> (<NAME>)"
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Киньте два зеленых кубика. За каждый %FOCUS% результат назначьте 1 жетон Концентрации вашему кораблю. За каждый %EVADE% результат назначьте 1 жетон Уклонения вашему кораблю."""
"<NAME>":
text: """%IMPERIALONLY%%LINEBREAK%В конце фазы Боя каждый вражеский корабль на Дистанции 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
text: """<strong>Действие: </strong>%LINEBREAK% Выберите до 2 дружественных кораблей на Дистанции 1-2, и назначьте 1 жетон Концентрации каждому из этих кораблей. Затем получите жетон Стресса."""
"Lone Wolf":
text: """При атаке или защите, если не Дистанции 1-2 не других дружественных кораблей, вы можете перебросить один пустой результат."""
"Stay On Target":
text: """Когда вы вскрываете маневр, вы можете изменить его на другой доступный вам маневр той же скорости.%LINEBREAK% Считайте этот маневр как красный маневр."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%REBELONLY%%LINEBREAK%Вы можете атаковать находясь на препятствии."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Осуществите свободное действие Ускорение. Затем получите 1 жетон Иона."""
"Ruthlessness":
text: """%IMPERIALONLY%%LINEBREAK%После совершения атаки, которая попала в цель, вы <strong>должны</strong> выбрать один другой корабль на Дистанции 1 от цели (кроме своего). Этот корабль получает 1 Повреждение."""
"Intimidation":
text: """Пока вы касаетесь вражеского корабля, уменьшите его значение Маневренности на 1."""
"<NAME>":
text: """%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, если у вас нет щитов и есть хотя бы одна карта Повреждения, вы можете выполнить свободное действие %EVADE%."""
"<NAME>":
text: """%IMPERIALONLY%%LINEBREAK%Когда вы получаете карту Повреждения лицом вверх, вы можете сбросить эту карту, или другую карту %CREW% для того, чтобы перевернуть эту карту Повреждения рубашкой вверх (без применения её свойств)."""
"Ion Torpedoes":
text: """<strong>Атака (Захват цели): </strong>%LINEBREAK%Потратье захват цели и сбросьте эту карту чтобы выполнить эту атаку. %LINEBREAK%Если атака попала, то защищающийся и все корабли на Дистанции 1 от него получают по 1 жетону Иона."""
"Bodyguard":
text: """%SCUMONLY%%LINEBREAK%В начале фазы боя вы можете потратить жетон концентрации для выбора дружественного корабля на Дистанции 1, с мастерством пилота выше чем у вас. Увеличьте его значение Маневренности на 1 до конца раунда."""
"Calculation":
text: """При атаке вы можете потратить жетон Концентрации для изменения 1 значения %FOCUS% на значение %CRIT%."""
"Accuracy Corrector":
text: """При атаке, на шаге "Изменения кубиков атаки" вы можете отменить все значения ваших кубиков. Затем, вы можете добавить два результата %HIT% к броску.%LINEBREAK%Ваши кубики не могут быть модифицированы снова в течении этой атаки."""
"Inertial Dampeners":
text: """Когда вы вскрываете свой маневр, вы можете скинуть эту карту для выполнения белого маневра [0%STOP%] вместо выбранного. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и, если у него нет Стресса, он также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"Mangler" Cannon':
text: """<strong>Атака: </strong>Атакуйте один корабль%LINEBREAK%При атаке вы можете поменять один результат %HIT% на %CRIT%."""
"Dead Man's Switch":
text: """Когда ваш корабль уничтожен, каждый корабль на Дистанции 1 получает 1 Повреждение."""
"Feedback Array":
text: """В течении фазы Боя, вместо осуществления атаки вы можете получить 1 жетон Иона и 1 Повреждение для того, чтобы выбрать один вражеский корабль на Дистанции 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
text: """<strong>Атака: </strong>%LINEBREAK%Сбросьте эту карту для атаки одного корабля (даже если он вне вашего сектора обстрела)."""
"Greedo":
text: """%SCUMONLY%%LINEBREAK%Первый раз когда вы атакуете в каждом раунде, и первый раз когда вы защищаетесь в каждом раунде, первая карта Повреждения применяется рубашкой вниз."""
"Salvaged Astromech":
text: """Когда вы получаете карту Повреждения с заголовком <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (до применения её эффекта).%LINEBREAK%Затем сбросьте эту карту."""
"Bomb Loadout":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %BOMB%"""
'"Genius"':
text: """Если вы снаряжены бомбой, которая сбрасывается при вскрытии маневра, то вы можете сбросить её <strong>после</strong> выполнения маневра."""
"Unhinged Astromech":
text: """Вы можете считать все маневры со скоростью 3 как зеленые маневры."""
"R4-B11":
text: """При атаке, если у вас есть захват цели на защищающегося, вы можете сбросить этот захват цели для выбора некоторых или всех кубиков защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":<strong>Атака: </strong>Атакуйте один корабль (даже если он вне вашего сектора обстрела)%LINEBREAK%Ваши результаты %HIT% не могут быть отменены кубиками защиты. Защищающийся может отменить результаты %CRIT% перед результатами %HIT%."""
"R4 Agromech":
text: """При атаке, после того как вы использовали жетон Концентрации, вы можете получить Захват цели на обороняющемся."""
"K4 Security Droid":
text: """%SCUMONLY%%LINEBREAK%После выполнения зеленого маневра вы можете осуществить Захват цели."""
"Outlaw Tech":
text: """%SCUMONLY%%LINEBREAK%После выполнения красного маневра вы можете получить 1 жетон Концентрации."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%При атаке из основного оружия, если у вас есть захват цели на обороняющемся, вы можете добавить 1 результат %CRIT% к вашим результатам. Если вы делаете это, то вы не можете потратить Захват цели в течении этой атаки."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"<NAME>":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent <NAME>':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
text: """Ваша Маневренности увеличена на 1. Сбросьте эту карту, если вы получили попадание при атаке."""
"Shield Upgrade":
text: """Щиты вашего корабля увеличиваются на 1."""
"Engine Upgrade":
text: """На Панель Действий добавляется действие %BOOST%"""
"Anti-Pursuit Lasers":
text: """%DE_LARGESHIPONLY%%LINEBREAK%После того как вражеский корабль совершит манёвр, который приводит его к столкновению с вашим, бросьте 1 кубик атаки. В случае выпадения %HIT% или %CRIT% результата вражеский корабль получает 1 повреждение."""
"Targeting Computer":
text: """На Панель действий добавляется действие %TARGETLOCK%."""
"Hull Upgrade":
text: """Значение корпуса вашего корабля увеличивается на 1."""
"Munitions Failsafe":
text: """При атаке второстепенным оружием, по инструкции которого вам требуется сбросить карту для выполнения этой атаки, не сбрасывайте карту, если атака не принесла успеха."""
"Stygium Particle Accelerator":
text: """Когда вы выполняете любое из действий Сброса Маскировки или Маскировки, вы можете получить свободное действие Уклонения."""
"Advanced Cloaking Device":
text: """После выполнения атаки, вы можете выполнить свободное действие маскировки."""
"Combat Retrofit":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1."""
"B-Wing/E2":
text: """На вашу панель Улучшений добавляется улучшение %CREW%."""
"Countermeasures":
text: """%DE_LARGESHIPONLY%%LINEBREAK%В начале фазы Боя вы можете сбросить эту карту для увеличения Маневрености вашего корабля на 1 до конца раунда. Затем вы можете скинуть 1 вражеский захват цели со своего корабля."""
"Experimental Interface":
text: """Единожды за раунд, после выполнения действия вы можете выполнить свободное действие c экипированной карты Улучшения с заголовком <strong>Действие</strong>. Затем получите 1 жетон Стресса."""
"Tactical Jammer":
text: """%DE_LARGESHIPONLY%%LINEBREAK%Ваш корабль может быть влияет на вражеские атаки как препятствие."""
"Autothrusters":
text: """При защите, если вы за пределами Дистанции 2 или вне сектора обстрела атакующего корабля, вы можете поменять один пустой результат на результат %EVADE%. Вы можете экипировать это улучшение только если корабль имеет действие %BOOST%."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %TORPEDO%."""
"Millennium Falcon":
text: """<span class="card-restriction">YT-1300 only</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %EVADE%"""
"Moldy Crow":
text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%В течении фазы Завершения не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%Вы можете осуществлять Захват цели на любой корабль на игровом поле."""
"Royal Guard TIE":
text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%Вы можете экипировать до двух разных Улучшений-модификации (вместо одного).%LINEBREAK%Вы не можете экипировать это улучшение если Мастерство пилота "4" и меньше."""
"<NAME>":
name: "<NAME>"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action."""
"A-Wing Test Pilot":
text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Ваша панель Улучшений получает 1 пиктограмму %ELITE%.%LINEBREAK%Вы не можете экипировать 2 одинаковых Улучшения %ELITE%. Вы не можете экипировать это улучшение, если мастерство пилота "1" и меньше."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2)."""
"Jaina's Light":
name: "<NAME>"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card."""
"Outrider":
text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%Пока вы снаряжены Дополнительным Орудием %CANNON% вы <strong>не можете</strong> атаковать основным орудием, и вы можете атаковать Дополнительным Орудием %CANNON% корабли вне вашего сектора обстрела."""
"Dauntless":
text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%После выполнения маневра, который привел к перекрытию другого корабля вы можете осуществить 1 свободное действие. Затем получите 1 жетон Стресса."""
"Virago":
text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограммы %SYSTEM% и %ILLICIT%.%LINEBREAK%Вы не можете экипировать это улучшение, если Мастерство пилота "3" или ниже."""
'"Heavy Scyk" Interceptor (Cannon)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%Вы обладаете способностью пилота каждого другого дружественного корабля с улучшением <em>IG-2000</em> (в дополнение к вашей способности пилота)."""
"BTL-A4 Y-Wing":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Вы не можете атаковать корабли вне вашего сектора обстрела. После атаки основным оружием вы можете немедленно атаковать дополнительным орудием %TURRET%."""
"Andrasta":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель Улучшений содержит две дополнительные пиктограммы %BOMB%."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Ваша панель улучшения содержит пиктограмму %SYSTEM%.%LINEBREAK%Если вы экипируете Улучшение %SYSTEM%, его стоимость уменьшается на 4 (до минимальной стоимости "0")."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"Mist Hunter":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
| true | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Russian'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Russian =
action:
"Barrel Roll": "Бочка"
"Boost": "Ускорение"
"Evade": "Уклонение"
"Focus": "Концентрация"
"Target Lock": "Захват цели"
"Recover": "Recover"
"Reinforce": "Reinforce"
"Jam": "Jam"
"Coordinate": "Coordinate"
"Cloak": "Маскировка"
slot:
"Astromech": "Астромех"
"Bomb": "Бомба"
"Cannon": "Дополнительное Орудие"
"Crew": "Экипаж"
"Elite": "Талант"
"Missile": "Ракета"
"System": "Система"
"Torpedo": "Торпеда"
"Turret": "Турель"
"Cargo": "Cargo"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "Нелегальный"
"Salvaged Astromech": "захваченный Астромех"
sources: # needed?
"Core": "База"
"A-Wing Expansion Pack": "Дополнение A-Wing"
"B-Wing Expansion Pack": "Дополнение B-Wing"
"X-Wing Expansion Pack": "Дополнение X-Wing"
"Y-Wing Expansion Pack": "Дополнение Y-Wing"
"Millennium Falcon Expansion Pack": "Дополнение Сокол Тысячелетия"
"HWK-290 Expansion Pack": "Дополнение HWK-290"
"TIE Fighter Expansion Pack": "Дополнение TIE-Fighter"
"TIE Interceptor Expansion Pack": "Дополнение TIE-Interceptor"
"TIE Bomber Expansion Pack": "Дополнение TIE-Bomber"
"TIE Advanced Expansion Pack": "Дополнение TIE-Advanced"
"Lambda-Class Shuttle Expansion Pack": "Дополнение Lambda-class Shuttle"
"Slave I Expansion Pack": "Дополнение Sklave I"
"Imperial Aces Expansion Pack": "Дополнение Imperial Aces"
"Rebel Transport Expansion Pack": "Дополнение Rebel Transport"
"Z-95 Headhunter Expansion Pack": "Дополнение Z-95-Headhunter"
"TIE Defender Expansion Pack": "Дополнение TIE-Defender"
"E-Wing Expansion Pack": "Дополнение E-Wing"
"TIE Phantom Expansion Pack": "Дополнение TIE-Phantom"
"Tantive IV Expansion Pack": "Дополнение Tantive IV"
"Rebel Aces Expansion Pack": "Дополнение Rebel Aces"
"YT-2400 Freighter Expansion Pack": "Дополнение YT-2400 Freighter"
"VT-49 Decimator Expansion Pack": "Дополнение VT-49 Decimator"
"StarViper Expansion Pack": "Дополнение StarViper"
"M3-A Interceptor Expansion Pack": "Дополнение M3-A Interceptor"
"IG-2000 Expansion Pack": "Дополнение IG-2000"
"Most Wanted Expansion Pack": "Дополнение Most Wanted"
"Imperial Raider Expansion Pack": "Дополнение Imperial Raider"
ui:
shipSelectorPlaceholder: "Выберите корабль"
pilotSelectorPlaceholder: "Выберите пилота"
upgradePlaceholder: (translator, language, slot) ->
"Нет #{translator language, 'слота', slot} улучшения"
modificationPlaceholder: "Нет модификации"
titlePlaceholder: "Нет названия"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'Слот', slot} улучшения"
unreleased: "не выпущено"
epic: "Эпик"
limited: "ограничено"
byCSSSelector:
'.translate.sort-cards-by': 'Сортировать карты по'
'.xwing-card-browser option[value="name"]': 'Имени'
'.xwing-card-browser option[value="source"]': 'Источнику'
'.xwing-card-browser option[value="type-by-points"]': 'Типу (Очки)'
'.xwing-card-browser option[value="type-by-name"]': 'Типу (Имени)'
'.xwing-card-browser .translate.select-a-card': 'Выберите карту из списка слева'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Корабль'
'.info-well .info-skill td.info-header': 'Мастерство'
'.info-well .info-actions td.info-header': 'Действия'
'.info-well .info-upgrades td.info-header': 'Улучшения'
'.info-well .info-range td.info-header': 'Дистанция'
# Squadron edit buttons
'.clear-squad' : 'Новый отряд'
'.save-list' : 'Сохранить'
'.save-list-as' : 'Сохранить как'
'.delete-list' : 'Удалить'
'.backend-list-my-squads' : 'Загрузить отряд'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Печать\Просмотр как </span>Text'
'.randomize' : 'Случайно'
'.randomize-options' : 'Опции генератора случайности'
# Print/View modal
'.bbcode-list' : 'Скопируйте BBCode ниже и вставьте в пост на форуме.<textarea></textarea>'
'.vertical-space-checkbox' : """Добавить пространство для карт повреждений\улучшений на распечатке. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Печать в цвете. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Печать'
# Randomizer options
'.do-randomize' : 'Случайно!'
# Top tab bar
'#empireTab' : 'Галактическая империя'
'#rebelTab' : 'Альянс повстанцев'
'#scumTab' : 'Негодяи'
'#browserTab' : 'Список карт'
'#aboutTab' : 'О сервисе'
singular:
'pilots': 'Пилоты'
'modifications': 'Модификации'
'titles': 'Названия'
types:
'Pilot': 'Пилот'
'Modification': 'Modifikation'
'Title': 'Название'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Russian = () ->
exportObj.cardLanguage = 'Russian'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
pilot_translations =
"PI:NAME:<NAME>END_PI":
text: """Во время атаки, уменьшите значение Мобильности защищающегося на 1 (значение не может быть меньше нуля)."""
"PI:NAME:<NAME>END_PI":
text: """После использования жетона Концентрации вы можете передать его любому другому дружественному кораблю, находящемуся на Дистанции 1-2 (вместо сброса)."""
"Biggs Darklighter":
text: """Другие дружественные корабли на Дистанции 1 не могут быть атакованы, если целью можете быть выбраны вы."""
"Luke Skywalker":
text: """Во время защиты вы можете заменить один из результатов %FOCUS% на результат %EVADE%"""
'"Dutch" Vander':
text: """После захвата цели, выберите любой другой дружественный корабль на Дистанции 1-2. Выбранный корабль может немедленно получить жетон Захвата Цели."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки на Дистанции 2-3 вы можете перебросить любое количество ваших кубиков, не имеющих какого-либо результата."""
'"WPI:NAME:<NAME>END_PI"':
text: """Во время атаки на Дистанции 1 вы можете заменить один из ваших %HIT% результатов на %CRIT% результат."""
'"Night Beast"':
text: """После выполнения зеленого манёвра вы можете выполнить свободное действие Концентрация."""
'"Backstabber"':
text: """Если во время атаки вы находитесь вне сектора стрельбы обороняющегося корабля, бросайте на один кубик атаки больше."""
'"Dark Curse"':
text: """Во время обороны, атакующие вас корабли, не могут использовать маркеры Концентрации или перебрасывать кубики атаки."""
'"PI:NAME:<NAME>END_PI"':
text: """Когда атакуете на Дистанции 1 бросайте на один кубик атаки больше."""
'"PI:NAME:<NAME>END_PI"':
text: """Когда другой дружественный корабль атакует на Дистанции 1 основным оружием, он может перебросить один кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """Когда ваша атака наносит Критическое повреждение атакуемому кораблю, вместо 1 возьмите 3 карты Повреждений. Выберете 1 из них, а остальные сбросьте."""
"PI:NAME:<NAME>END_PI":
text: """Во время шага «Выполните Действие» в фазе Активации, вы можете выполнить 2 действия."""
"\"PI:NAME:<NAME>END_PI\"":
text: """Когда количество карт Повреждений будет равно или превышать значение корпуса вашего корабля, корабль не разрушается до конца этой боевой фазы."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения атаки вы можете выполнить свободное действие Бочка или Ускорение."""
"PI:NAME:<NAME>END_PI":
text: """Когда вы получаете жетон Стресса, можете так же получить жетон Концентрация для этого корабля."""
"PI:NAME:<NAME>END_PI":
text: """Вы можете выполнять действия даже при наличии у вас жетона Стресса."""
"PI:NAME:<NAME>END_PI":
text: """Вы можете выбрать целью для атаки вражеский корабль, находящийся в вашем секторе стрельбы, даже если вы его касаетесь."""
"ChePI:NAME:<NAME>END_PI":
text: """Если вы получили карту Повреждений лицом вверх, немедленно переверните эту карту лицом вниз (без применения ее свойств)."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения зелёного манёвра, выберите 1 дружественный корабль на Дистанции 1. Этот корабль может выполнить любое из действий, указанных в его карте, как свободное."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки вы можете перебросить все ваши кубики. Если вы выбрали это, то должно быть переброшено их максимальное возможное количество."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки, обороняющийся получает один жетон Стресса, если хотя бы один из результатов %CRIT% был отменён."""
"PI:NAME:<NAME>END_PI":
text: """Когда вы вскрываете манёвр %BANKLEFT% или %BANKRIGHT%, вы можете заменить его на другой манёвр той же скорости."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки Дополнительным оружием, вы можете перебросить один кубик атаки."""
"Ten PI:NAME:<NAME>END_PIumb":
text: """Во время атаки, один из ваших результатов %CRIT% нельзя отменить кубиком защиты."""
"IPI:NAME:<NAME>END_PI":
text: """Во время атаки или обороны вы можете перебросить один из ваших кубиков, если у вас есть хотя бы один жетон Стресса."""
"PI:NAME:<NAME>END_PI":
text: '''После начала фазы боя, выберете любой другой дружественный корабль на Дистанции 1-3. До конца фазы, Мастерство пилота выбранного корабля считается равным 12.'''
"PI:NAME:<NAME>END_PI":
text: """В начале фазы боя вы можете передать один из ваших жетонов Концентрации другому дружественному кораблю на Дистанции 1-3."""
"PI:NAME:<NAME>END_PI":
text: """Когда другой дружественный корабль атакует на Дистанции 1-3 и у вас нет жетона Стресса, вы можете получить один жетон Стресса, чтобы позволить этому кораблю бросить один дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """Когда другой дружественный корабль атакует на Дистанции 1, используя дополнительное оружие, он может перебросить до двух кубиков атаки."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки дополнительным оружием, вы можете увеличить или уменьшить дистанцию использования оружия на один, в пределах Дистанции 1-3."""
"PI:NAME:<NAME>END_PI":
text: """Когда вражеский корабль получает жетон Захвата цели, он должен использовать ваш корабль в качестве цели, если может."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы боя, вы можете передать один из ваших голубых жетонов Захвата цели дружественному кораблю на Дистанции 1, если у него таковых не имеется."""
"PI:NAME:<NAME>END_PI":
text: """Вы можете получить жетон Стресса вместо любого другого дружественного корабля на Дистанции 1-2, если у вас таких жетонов два или менее."""
"PI:NAME:<NAME>END_PI":
text: """При выполнении действия Бочка вы можете получить 1 жетон Стресса и использовать шаблоны (%BANKLEFT% 1) или (%BANKRIGHT% 1) вместо (%STRAIGHT% 1)."""
"PI:NAME:<NAME>END_PI":
text: """Когда вы вскрываете маневр %UTURN%, вы можете считать скорость этого маневра как "1," "3," или "5"."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки на Дистанции 2-3 вы можете сбросить один жетон уклонения, чтобы добавить к броску один %HIT% результат."""
"PI:NAME:<NAME>END_PI":
text: """Вражеские корабли на Дистанции 1 не могут выполнять действия Уклонения или Концентрации, и не могут сбрасывать соответствующие жетоны."""
"PI:NAME:<NAME>END_PI":
text: """Ваша атака считается успешной, даже если защищающийся успешно отменил все повреждения."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения атаки вы можете выбрать другой дружественный корабль на Дистанции 1. Этот корабль может выполнить ."""
"PI:NAME:<NAME>END_PI":
text: """Во время атаки, после броска ваших кубиков атаки, сразу можете получить Захват цели на защищающегося, если он уже имеет красный жетон захвата цели."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения атаки, принесшей противнику как минимум одну карту Повреждения, вы можете сбросить один жетон Концентрации для переворота нанесенных карт Повреждений лицом вверх."""
"PI:NAME:<NAME>END_PI":
text: """Когда корабль противника находится внутри вашего сектора стрельбы на Дистанции 1-3, и защищается, то атакующий может изменить один из %HIT% результатов на %CRIT% результат."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы Завершения вы можете выполнить одну атаку. Вы не можете атаковать в течении следующего раунда."""
'"PI:NAME:<NAME>END_PI"':
text: """Когда вы сбрасываете режим Маскировки, вы должны использовать шаблоны (%BANKRIGHT% 2) или (%BANKLEFT% 2) вместо (%STRAIGHT% 2)."""
'"WhPI:NAME:<NAME>END_PI"':
text: """После выполнения успешной атаки вы можете получить один жетон КОнцентрации на ваш корабль."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения атаки вы можете удалить один жетон Концентрации, Уклонения или голубой жетон захвата цели с защищающегося корабя."""
"PI:NAME:<NAME>END_PI":
text: """Когда вы получаете жетон стресса, вы можете удалить его и бросить один кубик атаки. На результате %HIT% получите на этот корабль карту Повреждения лицом вниз."""
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
text: """Когда вы получаете или тратите Захват цели, вы можете удалить один жетон стресса с вашего корабля."""
"PI:NAME:<NAME>END_PI":
text: """Когда корабль противника объявил вас целью для своей атаки, вы можете получить Захват цели на этот корабль."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения действия Концентрации или получения жетона Концентрации, вы можете совершить свободное действие Ускорение или Бочка."""
"PI:NAME:<NAME>END_PI":
text: """Пока вы находитесь на Дистанции 1 от, по крайней мере одного, корабля противника, увеличьте показатель вашей маневренности на один."""
"PI:NAME:<NAME>END_PI":
text: """Когда атакуете, вы можете удалить один жетон Стресса для замены всех ваших %FOCUS% результатов на %HIT% результаты."""
"PI:NAME:<NAME>END_PI":
text: """Вы можете выполнять атаки торпедами %TORPEDO% по кораблям противника, находящимися вне вашего сектора стрельбы."""
"PI:NAME:<NAME>END_PI":
text: """Вы можете игнорировать жетоны преград в фазе Активации и когда совершаете Действия."""
'"PI:NAME:<NAME>END_PI"':
text: """Когда вы получаете карту Повреждения лицом вверх, вытяните одну дополнительную карту Повреждения, выберите одну для применения, вторую сбросьте."""
"PI:NAME:<NAME>END_PI":
text: """Когда вы атакуете основным орудием корабль с жетоном Стресса, кидайте один дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """При атаке на Дистанции 1-2, вы можете поменять один из ваших результатов %FOCUS% на %CRIT% результат."""
"PI:NAME:<NAME>END_PI":
text: """Если у вас нет щитов и есть хотя бы одна карта Повреждения, увеличьте вашу маневренность на один."""
"PI:NAME:<NAME>END_PI":
text: """После выполнения маневра каждый вражеский корабль, с которым вы соприкасаетесь, получает одно повреждение."""
"PI:NAME:<NAME>END_PI":
text: """При защите, дружественный корабль на Дистанции 1 может получить один неотмененный результат %HIT% или %CRIT% вместо вас."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы БPI:NAME:<NAME>END_PI, если вы на Дистанции 1 от вражеского корабля, вы можете назначить один жетон концентрации вашему кораблю."""
"PI:NAME:<NAME>END_PI":
text: """Когда другой дружественный корабль на Дистанции 1 защищается, он может перебросить один кубик защиты."""
"PI:NAME:<NAME>END_PI":
text: """После того как вы выполнили защиту от вражеской атаки, если атака не попала, вы можете назначить один жетон уклонения вашему кораблю."""
"IG-88A":
text: """После выполнения вами атаки, которая уничтожила цель, вы можете восстановить один щит."""
"IG-88B":
text: """Единожды в раунд, после выполнения атаки, которая не попала, вы можете осуществить атаку из имеющегося дополнительного орудия %CANNON%."""
"IG-88C":
text: """После выполнения вами действия Ускорения, вы можете совершить свободное действие Уклонения."""
"IG-88D":
text: """Вы можете осуществлять маневры (%SLOOPLEFT% 3) или (%SLOOPRIGHT% 3) используя соответствующие шаблоны (%TURNLEFT% 3) или (%TURNRIGHT% 3) ."""
"PI:NAME:<NAME>END_PI (Scum)":
text: """При атаке или защите, вы можете перебросить один ваш кубик за каждый вражеский корабль на Дистанции 1."""
"PI:NAME:<NAME>END_PI (Scum)":
text: """При атаке корабля в вашем вспомогательном секторе стрельбы, бросайте один дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """При сбросе бомбы, вы можете использовать шаблоны [%TURNLEFT% 3], [%STRAIGHT% 3], или [%TURNRIGHT% 3] вместо шаблона [%STRAIGHT% 1]."""
"PI:NAME:<NAME>END_PI":
text: """При атаке корабля вне вашего сектора обстрела бросайте один дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """После того как вы использовали Захват цели вы можете получить один жетон Стресса для выполнения Захвата цели."""
"PI:NAME:<NAME>END_PI":
text: """Когда вражеский корабль на Дистанции 1-3 получает как минимум один жетон Иона, и у вас нет жетонов Стресса, вы можете получить один жетон Стресса и нанести этому кораблю одно повреждение."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы PI:NAME:<NAME>END_PI, вы можете удалить один жетон %FOCUS% или %EVADE% с вражеского корабля на Дистанции 1-2 и назначить его своему кораблю."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы Активации выберите один вражеский корабль на Дистанции 1-2. До конца фазы Боя считайте Мастерство пилота этого корабля как "0"."""
"PI:NAME:<NAME>END_PI":
text: """При атаке, если на Дистанции 1-2 нет других дружественных кораблей, бростайте один дополнительный кубик атаки."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы Боя вы можете удалить один жетон %FOCUS% или %EVADE% с другого дружественного корабля на Дистанции 1-2, и назначить его себе."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы Боя вы можете получить Захват цели на вражеский корабль на Дистанции 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"PI:NAME:<NAME>END_PI":
text: """Когда вы открываете свой маневр, вы можете увеличить или уменьшить его скорость на единицу (до минимума в 1)."""
"PI:NAME:<NAME>END_PI":
text: """Вражеский корабль на Дистанции 1 не может использовать бонус дистанции при выполнении атаки."""
"PI:NAME:<NAME>END_PI":
text: """В начале фазы Завершения вы можете использовать имеющийся Захват цели на вражеский корабль, для того чтобы перевернуть лицом вверх одну случайную из имеющихся у него карт Повреждений."""
"PI:NAME:<NAME>END_PI":
text: """Когда дружественный корабль объявляет атаку, вы можете использовать имеющийся Захват цели на защищающемся корабле для уменьшения его маневренности на единицу на время этой атаки."""
"PI:NAME:<NAME>END_PI":
text: """При защите, если атакующий в вашем секторе обстрела, бросайте один дополнительный кубик защиты."""
"PI:NAME:<NAME>END_PI":
text: """Когда другой дружественный корабль на Дистанции 1-2 атакует, вы можете считать ваш жетон %FOCUS% как принадлежащий ему."""
'"Redline"':
text: """Вы можете осуществлять два захвата цели на один корабль. Когда вы осуществляете Захват цели, вы можете получить второй Захват цели на этот корабль."""
'"Deathrain"':
text: """При сбросе бомбы, вы можете использовать передние направляющие вашего корабля. После сброса бомбы вы можете осуществить свободное действие Бочка."""
"Moralo Eval":
text: """Вы можете осуществлять атаки дополнительным орудием %CANNON% против кораблей в вашем дополнительном секторе обстрела."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"Scourge"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The Inquisitor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"Zuckuss":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"Dengar":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
text: """<strong>Атака:</strong> Атакуйте 1 корабль (даже если он находится вне сектора обстрела).%LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и 1 жетон Иона. Затем отмените все результаты кубиков."""
"PI:NAME:<NAME>END_PI":
text: """<strong>Атака (Захват цели):</strong>Потратьте жетон Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете заменить 1 из ваших %FOCUS% результатов на результат %CRIT%."""
"R2 Astromech":
text: """Манёвры со скоростью 1 и 2 вы можете считать как зелёные манёвры."""
"R2-D2":
text: """После выполнения зелёного манёвра вы можете восстановить 1 Щит (до максимума доступного вам)."""
"R2-F2":
text: """<strong>Действие:</strong> Вы можете увеличить значение Маневренности на 1 до конца текущего раунда."""
"R5-D8":
text: """<strong>Действие:</strong> Бросьте 1 кубик защиты. %LINEBREAK%В случае выпадения %EVADE% или %FOCUS% результата вы можете сбросить 1 карту из ваших не-критических Повреждений."""
"R5-K6":
text: """После сброса жетона Захвата цели, бросьте1 кубик защиты.%LINEBREAK%В случае выпадения результата %EVADE% немедленно получите жетон Захвата цели на тот же самый корабль. Вы не можете
потратить его во время этой атаки."""
"R5 Astromech":
text: """Во время фазы Завершения вы можете выбрать 1 из ваших карт Критических Повреждений с заголовком <strong>Корабль</strong> и перевернуть её лицом вниз."""
"Determination":
text: """Когда вы получаете карту Критического повреждения
с заголовком <strong>Пилот</strong>, немедленно сбросьте её без выполнения её эффекта."""
"Swarm Tactics":
text: """В начале фазы Боя выберите дружественный корабль на Дистанции 1. %LINEBREAK%До конца этой фазы пилот выбранного корабля имеет значение Мастерства пилота такое же как, и у вас."""
"Squad Leader":
text: """<strong>Действие:</strong> Выберите один корабль на Дистанции 1-2, пилот которого имеет Мастерство ниже вашего.<br/>Выбранный корабль может немедленно выполнить 1 свободное действие."""
"Expert Handling":
text: """<strong>Действие:</strong> Выполните свободное действие Бочка. Если у вас нет пиктограммы действия %BARRELROLL%, получите 1 жетон Стресса.%LINEBREAK%Затем вы можете удалить с вашего корабля 1 жетон Захвата цели противника."""
"Marksmanship":
text: """<strong>Действие:</strong> Во время атаки в
текущем раунде вы можете поменять 1 ваш выпавший
результат %FOCUS% на %CRIT%, и все остальные ваши результаты %FOCUS% на результат %HIT%."""
"Concussion Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку. %LINEBREAK%Вы можете заменить 1 выпавший пустой результат на %HIT% результат."""
"Cluster Missiles":
text: """<strong>Атака (Захват цели): </strong> Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку
дважды."""
"Daredevil":
text: """<strong>Действие: </strong>Выполните белый
(%TURNLEFT% 1) или (%TURNRIGHT% 1) манёвр. Затем бросьте два кубика атаки, если вы не имеете действия %BOOST%. Получите
попадания %HIT% и %CRIT%, если таковые выпали."""
"Elusiveness":
text: """Во время защиты, вы можете получить 1 жетон Стресса
и выбрать 1 кубик атаки. Нападающий должен перебросить этот кубик.
Если у вас есть хотя бы 1 жетон Стресса, вы не можете использовать эту
способность."""
"Homing Missiles":
text: """<strong>Атака (Захват цели): </strong>Сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Обороняющийся корабль не
может использовать жетон Уклонения во время этой атаки."""
"Push the Limit":
text: """Единожды во время раунда, после выполнения
действия вы можете выполнить 1 из имеющихся у вас на Панели действий,
как свободное.%LINEBREAK%Затем получите 1 жетон Стресса."""
"Deadeye":
text: """Вы можете считать «Атака [Захват Цели]», как «Атака [Концентрация]:»<br/> Когда правило Атаки гласит, что жетон Захвата Цели должен быть потрачен, вы можете потратить жетон Концентрации вместо этого."""
"Expose":
text: """<strong>Действие: </strong>До конца этого раунда увеличьте величину вашего основного оружия на 1, и уменьшите на 1 показатель вашей Маневренности."""
"Gunner":
text: """Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы не можете выполнять других атак в этом раунде."""
"Ion Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Если попадаете по цели, атакованный корабль получает 1 Повреждение и
1 жетон Иона. Затем отмените все результаты кубиков."""
"Heavy Laser Cannon":
text: """<strong>Атака: </strong>Атакуйте 1 корабль. %LINEBREAK%Сразу после броска кубиков атаки вы должны заменить все ваши %CRIT% результаты, на %HIT% результаты ."""
"Seismic Charges":
text: """После вскрытия своего маневра вы можете сбросить эту карту и <strong>выставить</strong> 1 жетон Сейсмического заряда.%LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы активации."""
"Mercenary Copilot":
text: """Во время атаки на Дистанции 3, вы можете заменить один из ваших %HIT% результатов на %CRIT%."""
"Assault Missiles":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон
Захвата Цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Если эта атака попадёт, другие корабли на Дистанции 1 от обороняющегося получат 1 Повреждение."""
"Veteran Instincts":
text: """Увеличьте Мастерство вашего пилота на 2."""
"Proximity Mines":
text: """<strong>Действие:</strong> Сбросьте эту карту и <strong>выставите</strong> 1 жетон Мины.%LINEBREAK%При совершении кораблем манёвра, если его база и шаблон маневра накрывают этот жетон, мина <strong>детонирует</strong>."""
"Weapons Engineer":
text: """Вы можете иметь 2 Захвата цели (по 1 на каждом
из кораблей).<br /><br />Во время получения Захвата цели вы можете отметить 2 разных корабля."""
"Draw Their Fire":
text: """
Когда любой дружественный корабль на Дистанции 1 получает попадание от атаки, вы можете принять на себя 1 не отменённый %CRIT% результат, вместо этого корабля."""
"PI:NAME:<NAME>END_PI":
text: """%REBELONLY%%LINEBREAK%Если в результате выполнения атаки у вас нет попаданий, немедленно выполните атаку из основного оружия. Вы можете заменить 1 %FOCUS% результат на %HIT%. Вы не можете выполнять других атак в этом раунде."""
"PI:NAME:<NAME>END_PI":
text: """%REBELONLY%%LINEBREAK%Вы можете считать
любые %STRAIGHT% манёвры зелёными."""
"ChewbPI:NAME:<NAME>END_PIca":
name: "ChePI:NAME:<NAME>END_PI (Crew)"
text: """%REBELONLY%%LINEBREAK%Когда вы получаете карту Повреждения, вы можете немедленно сбросить эту карту и восстановить 1 щит.%LINEBREAK%Затем сбросьте эту карту улучшения."""
"Advanced Proton Torpedoes":
text: """<strong>Атака (Захват цели): </strong>Потратьте жетон Захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%Вы можете заменить до 3 пустых результатов на %FOCUS% результаты."""
"Autoblaster":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Ваши %HIT% результаты не могут быть отменены кубиками защиты.%LINEBREAK%Обороняющий может отменять %CRIT% результаты до %HIT% результатов."""
"Fire-Control System":
text: """После выполнение атаки вы можете получить жетон Захвата Цели на оборонявшийся корабль"""
"Blaster Turret":
text: """<strong>Атака (Концентрация): </strong>Потратьте 1 жетон Концентрации для выполнения этой атаки против 1 корабля противника (даже если противник находится вне вашего сектора обстрела)."""
"Recon Specialist":
text: """При выполнении действия Концентрация добавьте ещё 1 жетон Концентрация вашему кораблю."""
"Saboteur":
text: """<strong>Действие: </strong>Выберите один вражеский корабль на Дистанции 1 и бросьте кубик атаки. При выпадении %HIT% или %CTRIT% результата, выберите одну перевернутую карту повреждений этого корабля, положите её лицом вверх и исполните указанные в ней инструкции."""
"Intelligence Agent":
text: """В начале фазы Активации выберите один корабль на Дистанции 1-2. Вы можете посмотреть на выбранный этим кораблём манёвр."""
"Proton Bombs":
text: """После вскрытия своего маневра вы можете сбросить эту карту чтобы <strong>выставить</strong> 1 жетон Протонной бомбы. %LINEBREAK%Этот заряд <strong>детонирует</strong> в конце фазы Активации."""
"Adrenaline Rush":
text: """При вскрытии красного манёвра вы можете сбросить эту карту и считать данный манёвр белым до конца фазы Активации."""
"Advanced Sensors":
text: """Непосредственно перед вскрытием вашего манёвра вы можете выполнить 1 свободное действие.%LINEBREAK%Если вы используете эту возможность, вы должны пропустить шаг «Выполнение Действия» в текущем раунде."""
"Sensor Jammer":
text: """Во время обороны вы можете заменить 1 из %HIT% результатов атакующего на %FOCUS% результат.%LINEBREAK%Атаковавший не может перебросить этот кубик."""
"Darth Vader":
name: "Darth Vader (Crew)"
text: """%IMPERIALONLY%%LINEBREAK%После выполнения вами атаки вражеского корабля вы можете получить 2 повреждения, чтобы вражеский корабль получил 1 критическое повреждение."""
"Rebel Captive":
text: """%IMPERIALONLY%%LINEBREAK%Единожды за раунд, первый корабль, объявивший вас целью для атаки, немедленно получает 1 жетон Стресса."""
"Flight Instructor":
text: """Во время обороны вы можете перебросить 1 из ваших %FOCUS% результатов. Если величина Мастерства нападающего пилота «2» или менее, вы можете перебросить 1 из ваших пустых результатов, вместо %FOCUS%."""
"Navigator":
text: """Во время вскрытия манёвра вы можете выбрать другой манёвр такого же направления.%LINEBREAK%Красный манёвр не может быть выбран, если у вас уже есть хотя бы 1 жетон Стресса.""
"Opportunist":
text: """Во время атаки, если защищающийся не имеет жетонов Концентрации или Уклонения, вы можете получить 1 жетон Стресса и бросить 1 дополнительный кубик атаки. %LINEBREAK%Вы не можете использовать эту способность при наличии у вас жетона Стресса."""
"Comms Booster":
text: """"""<strong>Энергия:</strong> Потратьте 1 энергию и удалите все жетоны стресса на дружественном корабле на Дистанции 1-3. Затем положите 1 жетон концентрации на этот корабль."""
"Slicer Tools":
text: """<strong>Действие:</strong> Выберите 1 или более вражеских кораблей, имеющих жетоны стресса на Дистанции 1-3. Для каждого выбранного корабля вы можете потратить 1 энергию, чтобы нанести 1 Повреждение."""
"Shield Projector":
text: """Когда корабль противника объявляет своей целью маленький или большой корабль, вы можете потратить 3 энергии, чтобы принудить этот корабль выбрать целью ва, если это возможно."""
"Ion Pulse Missiles":
text: """<strong>Атака (Захват цели): </strong><br/>Сбросьте эту карту для выполнения этой атаки.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и 2 жетона иона. Затем все результаты кубиков отменяются."""
"Wingman":
text: """Вначале фазы Боя удалите 1 жетон стресса с другого дружественного корабля на Дистанции 1."""
"Decoy":
text: """В начале фазы Боя вы можете выбрать 1 дружественный корабль на Дистанции 1-2. Обменяйтесь показателями Мастерства пилота вашего и пилота выбранного корабля до конца фазы."""
"Outmaneuver":
text: """При атаке корабля, находящегося в вашем секторе обстрела, уменьшите значение Маневренности этого корабля на 1 (до минимума 0), если вы находитесь вне его сектора обстрела."""
"Predator":
text: """Во время атаки вы можете перебросить 1 кубик атаки. Если значение Мастерства защищающегося пилота равно ‘’2’’ или меньше, вы можете перебросить 2 кубика атаки."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Атака (Захват цели): </strong><br/>Потратьте жетон захвата цели и сбросьте эту карту для того, чтобы выполнить эту атаку.%LINEBREAK%После выполнения этой атаки защищающийся получает 1 жетон стресса, если значение корпуса его корабля равно 4 или меньше."""
"R7 Astromech":
text: """Один раз за раунд во время
защиты, если вы имеете захват цели на нападающем, вы можете сбросить захват цели и выбрать любые или все брошенные кубики атаки. Атакующий должен перебросить выбранные кубики."""
"R7-T1":
text: """<strong>Действие: </strong> Выберите корабль противника на Дистанции 1-2. Если вы находитесь в секторе обстрела этого корабля, вы можете получить Захват цели на этот корабль. Затем вы можете выполнить свободное действие Ускорение."""
"Tactician":
text: """После выполнения атаки по кораблю, находящемуся в вашем секторе обстрела и на Дистанции 2, этот корабль получает 1 жетон стресса."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%REBELONLY%%LINEBREAK% В конце фазы Завершения, если у вашего корабля нет щитов, вы можете восстановить один щит и кинуть кубик атаки. В случае результата %HIT% случайно выберите одну из карт повреждений, лежащих лицом вниз, и переверните. Затем выполните её инструкции."""
"C-3PO":
text: """%REBELONLY%%LINEBREAK%Один раз за раунд, до броска 1 или более кубиков защиты, назовите количестве будущих результатов %EVADE%. Если выпало ровно столько %EVADE% результатов (до изменения результатов броска), добавьте 1 результат %EVADE%."""
"Single Turbolasers":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 2 энергии этой карты, чтобы выполнить атаку. Защищающийся удваивает значение Маневренности корабля против этой атаки. Вы можете поменять 1 из ваших %FOCUS% результатов на %HIT% результат."""
"Quad Laser Cannons":
text: """<strong>Атака (Энергия): </strong>%LINEBREAK%Потратьте 1 энергию этой карты, чтобы выполнить атаку. Если атака не принесла успеха, вы можете немедленно потратить 1 энергию этой карты, чтобы выполнить атаку снова."""
"Tibanna Gas Supplies":
text: """<strong>Энергия:</strong> Вы можете сбросить эту карту чтобы получить 3 жетона энергии."""
"Ionization Reactor":
text: """<strong>Энергия:</strong> Потратье 5 жетонов энергии с этой карты и сбросьте эту карту, чтобы каждый другой корабль на Дистанции 1 получил по 1 повреждению и по 1 жетону Иона."""
"Engine Booster":
text: """До вскрытия своего диска маневров вы можете потратить 1 энергию для выполнения белого маневра (%STRAIGHT% 1). Вы не можете воспользоваться этим умением, если есть угроза наложения на другой корабль."""
"R3-A2":
text: """При объявлении цели вашей атаки, если она находится в вашем секторе обстрела, вы можете получить 1 жетон Стресса чтобы защищающийся тоже получил 1 жетон Стресса."""
"R2-D6":
text: """Вам доступно %ELITE% Улучшение.%LINEBREAK%Вы не можете использовать экипировать этого дроида если %ELITE% уже есть на панели Улучшений, или мастерство вашего пилота 2 или меньше."""
"Enhanced Scopes":
text: """Во время фазы Активации, рассматривайте Мастерство вашего пилота как "0"."""
"Chardaan Refit":
text: """A-WING only. %LINEBREAK%Эта карта имеет отрицательную стоимость."""
"Proton Rockets":
text: """<strong>Атака (Концентрация): </strong>%LINEBREAK%Сбросьте эту карту для того, чтобы выполнить эту атаку. Вы можете бросить дополнительные кубики атаки в количестве, равном показателю вашей Маневренности, но не более 3."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%REBELONLY%%LINEBREAK%После удаления жетона стресса с вашего корабля, вы можете назначить ему жетон концентрации."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%REBELONLY%%LINEBREAK%Один раз в раунд вы можете назначить дружественному кораблю на Дистанции 1-3 жетон уклонения, вместо выполнения данным кораблем действия концентрации или получения этим кораблем жетона концентрации."""
"PI:NAME:<NAME>END_PI":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%<strong>Action:</strong> Spend any amount of energy to choose that many enemy ships at Range 1-2. Remove all focus, evade, and blue target lock tokens from those ships."""
# TODO Check card formatting
"R4-D6":
text: """Когда вас атаковали и есть как минимум 3 неотмененных %HIT% результата, вы можете выбрать отменить эти результаты, пока не останется 2. За каждый отмененный таким образом %HIT% получите 1 жетон стресса."""
"R5-P9":
text: """В конце фазы Боя вы можете потратить 1 из ваших жетонов концентрации для восстановления одного щита (до максимума, доступного вам)."""
"WED-15 Repair Droid":
text: """%HUGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Spend 1 energy to discard 1 of your facedown Damage cards, or spend 3 energy to discard 1 of your faceup Damage cards."""
"PI:NAME:<NAME>END_PI":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, you may discard this card to treat each friendly ship's pilot skill value as "12" until the end of the phase."""
"PI:NAME:<NAME>END_PI":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%When another friendly ship at Range 1 is attacking, it may change 1 of its %HIT% results to a %CRIT%."""
"Expanded Cargo Hold":
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Once per round, when you would be dealt a faceup Damage card, you may draw that card from either the fore or aft Damage deck."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
text: """At the end of each round, you may spend 1 energy to recover 1 shield (up to your shield value)."""
"EM Emitter":
text: """When you obstruct an attack, the defender rolls 3 additional defense dice (instead of 1)."""
"Frequency Jammer":
text: """When you perform a jam action, choose 1 enemy ship that does not have a stress token and is at Range 1 of the jammed ship. The chosen ship receives 1 stress token."""
"Han PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%REBELONLY%%LINEBREAK%When attacking, if you have a target lock on the defender, you may spend that target lock to change all of your %FOCUS% results to %HIT% results."""
"Leia PI:NAME:<NAME>END_PIana":
text: """%REBELONLY%%LINEBREAK%В начале фазы Активации вы можете сбросить эту карту, чтобы позволить всем дружественным кораблям, раскрывающим красный маневр, рассматривать этот маневр белым до конца этой фазы."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"PI:NAME:<NAME>END_PI":
text: """%HUGESHIPONLY% %REBELONLY%%LINEBREAK%At the start of the Activation phase, choose 1 enemy ship at Range 1-3. You may look at that ship's chosen maneuver. If the maneuver is white, assign that ship 1 stress token."""
"Gunnery Team":
text: """Once per round, when attacking with a secondary weapon, you may spend 1 energy to change 1 of your blank results to a %HIT% result."""
"Sensor Team":
text: """When acquiring a target lock, you may lock onto an enemy ship at Range 1-5 instead of 1-3."""
"Engineering Team":
text: """During the Activation phase, when you reveal a %STRAIGHT% maneuver, gain 1 additional energy during the "Gain Energy" step."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Киньте два зеленых кубика. За каждый %FOCUS% результат назначьте 1 жетон Концентрации вашему кораблю. За каждый %EVADE% результат назначьте 1 жетон Уклонения вашему кораблю."""
"PI:NAME:<NAME>END_PI":
text: """%IMPERIALONLY%%LINEBREAK%В конце фазы Боя каждый вражеский корабль на Дистанции 1, не имеющий жетона Стресса, получает 1 жетон Стресса."""
"Fleet Officer":
text: """<strong>Действие: </strong>%LINEBREAK% Выберите до 2 дружественных кораблей на Дистанции 1-2, и назначьте 1 жетон Концентрации каждому из этих кораблей. Затем получите жетон Стресса."""
"Lone Wolf":
text: """При атаке или защите, если не Дистанции 1-2 не других дружественных кораблей, вы можете перебросить один пустой результат."""
"Stay On Target":
text: """Когда вы вскрываете маневр, вы можете изменить его на другой доступный вам маневр той же скорости.%LINEBREAK% Считайте этот маневр как красный маневр."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%REBELONLY%%LINEBREAK%Вы можете атаковать находясь на препятствии."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%REBELONLY%%LINEBREAK%<strong>Действие: </strong>%LINEBREAK% Осуществите свободное действие Ускорение. Затем получите 1 жетон Иона."""
"Ruthlessness":
text: """%IMPERIALONLY%%LINEBREAK%После совершения атаки, которая попала в цель, вы <strong>должны</strong> выбрать один другой корабль на Дистанции 1 от цели (кроме своего). Этот корабль получает 1 Повреждение."""
"Intimidation":
text: """Пока вы касаетесь вражеского корабля, уменьшите его значение Маневренности на 1."""
"PI:NAME:<NAME>END_PI":
text: """%IMPERIALONLY%%LINEBREAK%В начале фазы Боя, если у вас нет щитов и есть хотя бы одна карта Повреждения, вы можете выполнить свободное действие %EVADE%."""
"PI:NAME:<NAME>END_PI":
text: """%IMPERIALONLY%%LINEBREAK%Когда вы получаете карту Повреждения лицом вверх, вы можете сбросить эту карту, или другую карту %CREW% для того, чтобы перевернуть эту карту Повреждения рубашкой вверх (без применения её свойств)."""
"Ion Torpedoes":
text: """<strong>Атака (Захват цели): </strong>%LINEBREAK%Потратье захват цели и сбросьте эту карту чтобы выполнить эту атаку. %LINEBREAK%Если атака попала, то защищающийся и все корабли на Дистанции 1 от него получают по 1 жетону Иона."""
"Bodyguard":
text: """%SCUMONLY%%LINEBREAK%В начале фазы боя вы можете потратить жетон концентрации для выбора дружественного корабля на Дистанции 1, с мастерством пилота выше чем у вас. Увеличьте его значение Маневренности на 1 до конца раунда."""
"Calculation":
text: """При атаке вы можете потратить жетон Концентрации для изменения 1 значения %FOCUS% на значение %CRIT%."""
"Accuracy Corrector":
text: """При атаке, на шаге "Изменения кубиков атаки" вы можете отменить все значения ваших кубиков. Затем, вы можете добавить два результата %HIT% к броску.%LINEBREAK%Ваши кубики не могут быть модифицированы снова в течении этой атаки."""
"Inertial Dampeners":
text: """Когда вы вскрываете свой маневр, вы можете скинуть эту карту для выполнения белого маневра [0%STOP%] вместо выбранного. Затем получите 1 жетон Стресса."""
"Flechette Cannon":
text: """<strong>Атака: </strong>Атакуйте один корабль.%LINEBREAK%Если эта атака попала, защищающийся получает 1 повреждение и, если у него нет Стресса, он также получает 1 жетон Стресса. Затем отмените <strong>все</strong> результаты кубиков."""
'"Mangler" Cannon':
text: """<strong>Атака: </strong>Атакуйте один корабль%LINEBREAK%При атаке вы можете поменять один результат %HIT% на %CRIT%."""
"Dead Man's Switch":
text: """Когда ваш корабль уничтожен, каждый корабль на Дистанции 1 получает 1 Повреждение."""
"Feedback Array":
text: """В течении фазы Боя, вместо осуществления атаки вы можете получить 1 жетон Иона и 1 Повреждение для того, чтобы выбрать один вражеский корабль на Дистанции 1. Этот корабль получает 1 повреждение."""
'"Hot Shot" Blaster':
text: """<strong>Атака: </strong>%LINEBREAK%Сбросьте эту карту для атаки одного корабля (даже если он вне вашего сектора обстрела)."""
"Greedo":
text: """%SCUMONLY%%LINEBREAK%Первый раз когда вы атакуете в каждом раунде, и первый раз когда вы защищаетесь в каждом раунде, первая карта Повреждения применяется рубашкой вниз."""
"Salvaged Astromech":
text: """Когда вы получаете карту Повреждения с заголовком <strong>Корабль</strong>, вы можете немедленно сбросить эту карту (до применения её эффекта).%LINEBREAK%Затем сбросьте эту карту."""
"Bomb Loadout":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %BOMB%"""
'"Genius"':
text: """Если вы снаряжены бомбой, которая сбрасывается при вскрытии маневра, то вы можете сбросить её <strong>после</strong> выполнения маневра."""
"Unhinged Astromech":
text: """Вы можете считать все маневры со скоростью 3 как зеленые маневры."""
"R4-B11":
text: """При атаке, если у вас есть захват цели на защищающегося, вы можете сбросить этот захват цели для выбора некоторых или всех кубиков защиты. Защищающийся должен перебросить выбранные кубики."""
"Autoblaster Turret":<strong>Атака: </strong>Атакуйте один корабль (даже если он вне вашего сектора обстрела)%LINEBREAK%Ваши результаты %HIT% не могут быть отменены кубиками защиты. Защищающийся может отменить результаты %CRIT% перед результатами %HIT%."""
"R4 Agromech":
text: """При атаке, после того как вы использовали жетон Концентрации, вы можете получить Захват цели на обороняющемся."""
"K4 Security Droid":
text: """%SCUMONLY%%LINEBREAK%После выполнения зеленого маневра вы можете осуществить Захват цели."""
"Outlaw Tech":
text: """%SCUMONLY%%LINEBREAK%После выполнения красного маневра вы можете получить 1 жетон Концентрации."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%При атаке из основного оружия, если у вас есть захват цели на обороняющемся, вы можете добавить 1 результат %CRIT% к вашим результатам. Если вы делаете это, то вы не можете потратить Захват цели в течении этой атаки."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"PI:NAME:<NAME>END_PI":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent PI:NAME:<NAME>END_PI':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
text: """Ваша Маневренности увеличена на 1. Сбросьте эту карту, если вы получили попадание при атаке."""
"Shield Upgrade":
text: """Щиты вашего корабля увеличиваются на 1."""
"Engine Upgrade":
text: """На Панель Действий добавляется действие %BOOST%"""
"Anti-Pursuit Lasers":
text: """%DE_LARGESHIPONLY%%LINEBREAK%После того как вражеский корабль совершит манёвр, который приводит его к столкновению с вашим, бросьте 1 кубик атаки. В случае выпадения %HIT% или %CRIT% результата вражеский корабль получает 1 повреждение."""
"Targeting Computer":
text: """На Панель действий добавляется действие %TARGETLOCK%."""
"Hull Upgrade":
text: """Значение корпуса вашего корабля увеличивается на 1."""
"Munitions Failsafe":
text: """При атаке второстепенным оружием, по инструкции которого вам требуется сбросить карту для выполнения этой атаки, не сбрасывайте карту, если атака не принесла успеха."""
"Stygium Particle Accelerator":
text: """Когда вы выполняете любое из действий Сброса Маскировки или Маскировки, вы можете получить свободное действие Уклонения."""
"Advanced Cloaking Device":
text: """После выполнения атаки, вы можете выполнить свободное действие маскировки."""
"Combat Retrofit":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%Increase your hull value by 2 and your shield value by 1."""
"B-Wing/E2":
text: """На вашу панель Улучшений добавляется улучшение %CREW%."""
"Countermeasures":
text: """%DE_LARGESHIPONLY%%LINEBREAK%В начале фазы Боя вы можете сбросить эту карту для увеличения Маневрености вашего корабля на 1 до конца раунда. Затем вы можете скинуть 1 вражеский захват цели со своего корабля."""
"Experimental Interface":
text: """Единожды за раунд, после выполнения действия вы можете выполнить свободное действие c экипированной карты Улучшения с заголовком <strong>Действие</strong>. Затем получите 1 жетон Стресса."""
"Tactical Jammer":
text: """%DE_LARGESHIPONLY%%LINEBREAK%Ваш корабль может быть влияет на вражеские атаки как препятствие."""
"Autothrusters":
text: """При защите, если вы за пределами Дистанции 2 или вне сектора обстрела атакующего корабля, вы можете поменять один пустой результат на результат %EVADE%. Вы можете экипировать это улучшение только если корабль имеет действие %BOOST%."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель улучшений содержит пиктограмму %TORPEDO%."""
"Millennium Falcon":
text: """<span class="card-restriction">YT-1300 only</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %EVADE%"""
"Moldy Crow":
text: """<span class="card-restriction">HWK-290 only.</span>%LINEBREAK%В течении фазы Завершения не убирайте неиспользованные жетоны Концентрации с вашего корабля."""
"ST-321":
text: """<span class="card-restriction"><em>Lambda</em>-class Shuttle only.</span>%LINEBREAK%Вы можете осуществлять Захват цели на любой корабль на игровом поле."""
"Royal Guard TIE":
text: """<span class="card-restriction">TIE Interceptor only.</span>%LINEBREAK%Вы можете экипировать до двух разных Улучшений-модификации (вместо одного).%LINEBREAK%Вы не можете экипировать это улучшение если Мастерство пилота "4" и меньше."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When you perform a coordinate action, you may choose 2 friendly ships (instead of 1). Those ships may each perform 1 free action."""
"A-Wing Test Pilot":
text: """<span class="card-restriction">A-Wing only.</span>%LINEBREAK%Ваша панель Улучшений получает 1 пиктограмму %ELITE%.%LINEBREAK%Вы не можете экипировать 2 одинаковых Улучшения %ELITE%. Вы не можете экипировать это улучшение, если мастерство пилота "1" и меньше."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%Your fore section upgrade bar gains 1 additional %CREW% and 1 additional %TEAM% upgrade icon."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%A reinforce action assigned to your fore section adds 2 %EVADE% results (instead of 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%At the start of the End phase, if you have 1 or fewer energy tokens, gain 1 energy token."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">GR-75 only.</span>%LINEBREAK%When performing a jam action, you may choose an enemy ship at Range 1-3 (instead of at Range 1-2)."""
"Jaina's Light":
name: "PI:NAME:<NAME>END_PI"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">CR90 fore section only.</span>%LINEBREAK%When defending, once per attack, if you are dealt a faceup Damage card, you may discard it and draw another faceup Damage card."""
"Outrider":
text: """<span class="card-restriction">YT-2400 only.</span>%LINEBREAK%Пока вы снаряжены Дополнительным Орудием %CANNON% вы <strong>не можете</strong> атаковать основным орудием, и вы можете атаковать Дополнительным Орудием %CANNON% корабли вне вашего сектора обстрела."""
"Dauntless":
text: """<span class="card-restriction">VT-49 Decimator only.</span>%LINEBREAK%После выполнения маневра, который привел к перекрытию другого корабля вы можете осуществить 1 свободное действие. Затем получите 1 жетон Стресса."""
"Virago":
text: """<span class="card-restriction">StarViper only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограммы %SYSTEM% и %ILLICIT%.%LINEBREAK%Вы не можете экипировать это улучшение, если Мастерство пилота "3" или ниже."""
'"Heavy Scyk" Interceptor (Cannon)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
text: """<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%Ваша панель Улучшений содержит пиктограмму %CANNON%, %TORPEDO%, или %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Aggressor only.</span>%LINEBREAK%Вы обладаете способностью пилота каждого другого дружественного корабля с улучшением <em>IG-2000</em> (в дополнение к вашей способности пилота)."""
"BTL-A4 Y-Wing":
text: """<span class="card-restriction">Y-Wing only.</span>%LINEBREAK%Вы не можете атаковать корабли вне вашего сектора обстрела. После атаки основным оружием вы можете немедленно атаковать дополнительным орудием %TURRET%."""
"Andrasta":
text: """<span class="card-restriction">Firespray-31 only.</span>%LINEBREAK%Ваша панель Улучшений содержит две дополнительные пиктограммы %BOMB%."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Ваша панель улучшения содержит пиктограмму %SYSTEM%.%LINEBREAK%Если вы экипируете Улучшение %SYSTEM%, его стоимость уменьшается на 4 (до минимальной стоимости "0")."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"Mist Hunter":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
|
[
{
"context": "tials =\n url: 'http://demo.gitlab.com'\n token: 'bad-token'\n\ngitlab = new Gitlab\n url: credentials.url\n",
"end": 175,
"score": 0.9701518416404724,
"start": 166,
"tag": "PASSWORD",
"value": "bad-token"
}
] | examples/bad-token.coffee | lengyuedaidai/node-gitlab | 143 | #!/usr/bin/env coffee
# clear terminal
process.stdout.write '\u001B[2J\u001B[0;0f'
Gitlab = require('..')
credentials =
url: 'http://demo.gitlab.com'
token: 'bad-token'
gitlab = new Gitlab
url: credentials.url
token: credentials.token
gitlab.projects.all (err, resp, result) ->
console.log "having: ", err: err, resp: resp, result: result
console.log "should get: { err: '401 Unauthorized', resp: undefined, result: undefined }"
| 139376 | #!/usr/bin/env coffee
# clear terminal
process.stdout.write '\u001B[2J\u001B[0;0f'
Gitlab = require('..')
credentials =
url: 'http://demo.gitlab.com'
token: '<PASSWORD>'
gitlab = new Gitlab
url: credentials.url
token: credentials.token
gitlab.projects.all (err, resp, result) ->
console.log "having: ", err: err, resp: resp, result: result
console.log "should get: { err: '401 Unauthorized', resp: undefined, result: undefined }"
| true | #!/usr/bin/env coffee
# clear terminal
process.stdout.write '\u001B[2J\u001B[0;0f'
Gitlab = require('..')
credentials =
url: 'http://demo.gitlab.com'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
gitlab = new Gitlab
url: credentials.url
token: credentials.token
gitlab.projects.all (err, resp, result) ->
console.log "having: ", err: err, resp: resp, result: result
console.log "should get: { err: '401 Unauthorized', resp: undefined, result: undefined }"
|
[
{
"context": "oid', 'disc'] then 'ellipse' else 'rect'\n key = \"#{shapeName}-shadow\"\n SHADOW_SIZE = 10\n unless key in @layer.sp",
"end": 4652,
"score": 0.713764488697052,
"start": 4632,
"tag": "KEY",
"value": "\"#{shapeName}-shadow"
},
{
"context": "oid', 'disc'] then 'ellipse' else 'rect'\n key = \"#{shapeName}-debug-#{@lank.thang.collisionCategory}\"\n DEBUG_SIZE = 1",
"end": 7271,
"score": 0.8717347383499146,
"start": 7249,
"tag": "KEY",
"value": "\"#{shapeName}-debug-#{"
},
{
"context": "#{shapeName}-debug-#{@lank.thang.collisionCategory}\"\n DEBUG_SIZE = 10\n unless key in @layer.spri",
"end": 7300,
"score": 0.745449960231781,
"start": 7300,
"tag": "KEY",
"value": ""
},
{
"context": "ng @thangType\n thangType = markThangTypes[@thangType]\n return @loadThangType() if not thangType\n ",
"end": 8705,
"score": 0.5955942273139954,
"start": 8698,
"tag": "USERNAME",
"value": "angType"
}
] | app/lib/surface/Mark.coffee | JurianLock/codecombat | 2 | CocoClass = require 'core/CocoClass'
Camera = require './Camera'
ThangType = require 'models/ThangType'
markThangTypes = {}
module.exports = class Mark extends CocoClass
subscriptions: {}
alpha: 1
constructor: (options) ->
super()
options ?= {}
@name = options.name
@lank = options.lank
@camera = options.camera
@layer = options.layer
@thangType = options.thangType
@listenTo @layer, 'new-spritesheet', @onLayerMadeSpriteSheet
console.error @toString(), 'needs a name.' unless @name
console.error @toString(), 'needs a camera.' unless @camera
console.error @toString(), 'needs a layer.' unless @layer
@build()
destroy: ->
createjs.Tween.removeTweens @sprite if @sprite
@sprite?.parent?.removeChild @sprite
if @markLank
@layer.removeLank(@markLank)
@markLank.destroy()
@lank = null
super()
toString: -> "<Mark #{@name}: Sprite #{@lank?.thang?.id ? 'None'}>"
onLayerMadeSpriteSheet: ->
return unless @sprite
return @update() if @markLank
# rebuild sprite for new sprite sheet
@layer.removeChild @sprite
@sprite = null
@build()
@layer.addChild @sprite
@layer.updateLayerOrder()
# @updatePosition()
@update()
toggle: (to) ->
to = !!to
return @ if to is @on
return @toggleTo = to unless @sprite
@on = to
delete @toggleTo
if @on
if @markLank
@layer.addLank(@markLank)
else
@layer.addChild @sprite
@layer.updateLayerOrder()
else
if @markLank
@layer.removeLank(@markLank)
else
@layer.removeChild @sprite
if @highlightTween
@highlightDelay = @highlightTween = null
createjs.Tween.removeTweens @sprite
@sprite.visible = true
@
setLayer: (layer) ->
return if layer is @layer
wasOn = @on
@toggle false
@layer = layer
@toggle true if wasOn
setLank: (lank) ->
return if lank is @lank
@lank = lank
@build()
@
build: ->
unless @sprite
if @name is 'bounds' then @buildBounds()
else if @name is 'shadow' then @buildShadow()
else if @name is 'debug' then @buildDebug()
else if @name.match(/.+(Range|Distance|Radius)$/) then @buildRadius(@name)
else if @thangType then @buildSprite()
else console.error 'Don\'t know how to build mark for', @name
@sprite?.mouseEnabled = false
@
buildBounds: ->
@sprite = new createjs.Container()
@sprite.mouseChildren = false
style = @lank.thang.drawsBoundsStyle
@drawsBoundsIndex = @lank.thang.drawsBoundsIndex
return if style is 'corner-text' and @lank.thang.world.age is 0
# Confusingly make some semi-random colors that'll be consistent based on the drawsBoundsIndex
colors = (128 + Math.floor(('0.'+Math.sin(3 * @drawsBoundsIndex + i).toString().substr(6)) * 128) for i in [1 ... 4])
color = "rgba(#{colors[0]}, #{colors[1]}, #{colors[2]}, 0.5)"
[w, h] = [@lank.thang.width * Camera.PPM, @lank.thang.height * Camera.PPM * @camera.y2x]
if style in ['border-text', 'corner-text']
@drawsBoundsBorderShape = shape = new createjs.Shape()
shape.graphics.setStrokeStyle 5
shape.graphics.beginStroke color
if style is 'border-text'
shape.graphics.beginFill color.replace('0.5', '0.25')
else
shape.graphics.beginFill color
if @lank.thang.shape in ['ellipsoid', 'disc']
shape.drawEllipse 0, 0, w, h
else
shape.graphics.drawRect -w / 2, -h / 2, w, h
shape.graphics.endStroke()
shape.graphics.endFill()
@sprite.addChild shape
if style is 'border-text'
text = new createjs.Text '' + @drawsBoundsIndex, '20px Arial', color.replace('0.5', '1')
text.regX = text.getMeasuredWidth() / 2
text.regY = text.getMeasuredHeight() / 2
text.shadow = new createjs.Shadow('#000000', 1, 1, 0)
@sprite.addChild text
else if style is 'corner-text'
return if @lank.thang.world.age is 0
letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[@drawsBoundsIndex % 26]
text = new createjs.Text letter, '14px Arial', '#333333' # color.replace('0.5', '1')
text.x = -w / 2 + 2
text.y = -h / 2 + 2
@sprite.addChild text
else
console.warn @lank.thang.id, 'didn\'t know how to draw bounds style:', style
if w > 0 and h > 0 and style is 'border-text'
@sprite.cache -w / 2, -h / 2, w, h, 2
@lastWidth = @lank.thang.width
@lastHeight = @lank.thang.height
buildShadow: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = "#{shapeName}-shadow"
SHADOW_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
shape.graphics.beginFill "rgba(0,0,0)"
bounds = [-SHADOW_SIZE/2, - SHADOW_SIZE/2, SHADOW_SIZE, SHADOW_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
alpha = @lank.thang?.alpha ? 1
width = (@lank.thang?.width ? 0) + 0.5
height = (@lank.thang?.height ? 0) + 0.5
longest = Math.max width, height
actualLongest = @lank.thangType.get('shadow') ? longest
width = width * actualLongest / longest
height = height * actualLongest / longest
width *= Camera.PPM
height *= Camera.PPM * @camera.y2x # TODO: doesn't work with rotation
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
@sprite.mouseEnabled = false
@sprite.alpha = alpha
@baseScaleX = @sprite.scaleX = width / (@layer.resolutionFactor * SHADOW_SIZE)
@baseScaleY = @sprite.scaleY = height / (@layer.resolutionFactor * SHADOW_SIZE)
buildRadius: (range) ->
alpha = 0.15
colors =
voiceRange: "rgba(0,145,0,#{alpha})"
visualRange: "rgba(0,0,145,#{alpha})"
attackRange: "rgba(145,0,0,#{alpha})"
# Fallback colors which work on both dungeon and grass tiles
extraColors = [
"rgba(145,0,145,#{alpha})"
"rgba(0,145,145,#{alpha})"
"rgba(145,105,0,#{alpha})"
"rgba(225,125,0,#{alpha})"
]
# Find the index of this range, to find the next-smallest radius
rangeNames = @lank.ranges.map((range, index) ->
range['name']
)
i = rangeNames.indexOf(range)
@sprite = new createjs.Shape()
fillColor = colors[range] ? extraColors[i]
@sprite.graphics.beginFill fillColor
# Draw the outer circle
@sprite.graphics.drawCircle 0, 0, @lank.thang[range] * Camera.PPM
# Cut out the hollow part if necessary
if i+1 < @lank.ranges.length
@sprite.graphics.arc 0, 0, @lank.ranges[i+1]['radius'], Math.PI*2, 0, true
@sprite.graphics.endFill()
strokeColor = fillColor.replace '' + alpha, '0.75'
@sprite.graphics.setStrokeStyle 2
@sprite.graphics.beginStroke strokeColor
@sprite.graphics.arc 0, 0, @lank.thang[range] * Camera.PPM, Math.PI*2, 0, true
@sprite.graphics.endStroke()
# Add perspective
@sprite.scaleY *= @camera.y2x
buildDebug: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = "#{shapeName}-debug-#{@lank.thang.collisionCategory}"
DEBUG_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
debugColor = {
none: 'rgba(224,255,239,0.25)'
ground: 'rgba(239,171,205,0.5)'
air: 'rgba(131,205,255,0.5)'
ground_and_air: 'rgba(2391,140,239,0.5)'
obstacles: 'rgba(88,88,88,0.5)'
dead: 'rgba(89,171,100,0.25)'
}[@lank.thang.collisionCategory] or 'rgba(171,205,239,0.5)'
shape.graphics.beginFill debugColor
bounds = [-DEBUG_SIZE / 2, -DEBUG_SIZE / 2, DEBUG_SIZE, DEBUG_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
PX = 3
w = Math.max(PX, @lank.thang.width * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.cos @lank.thang.rotation)
h = Math.max(PX, @lank.thang.height * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.sin @lank.thang.rotation)
@sprite.scaleX = w / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.scaleY = h / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
buildSprite: ->
if _.isString @thangType
thangType = markThangTypes[@thangType]
return @loadThangType() if not thangType
@thangType = thangType
return @listenToOnce(@thangType, 'sync', @onLoadedThangType) if not @thangType.loaded
Lank = require './Lank'
# don't bother with making these render async for now, but maybe later for fun and more complexity of code
markLank = new Lank @thangType
markLank.queueAction 'idle'
@sprite = markLank.sprite
@markLank = markLank
@listenTo @markLank, 'new-sprite', (@sprite) ->
loadThangType: ->
name = @thangType
@thangType = new ThangType()
@thangType.url = -> "/db/thang.type/#{name}"
@listenToOnce(@thangType, 'sync', @onLoadedThangType)
@thangType.fetch()
markThangTypes[name] = @thangType
onLoadedThangType: ->
@build()
@update() if @markLank
@toggle(@toggleTo) if @toggleTo?
Backbone.Mediator.publish 'sprite:loaded', {sprite: @}
update: (pos=null) ->
return false unless @on and @sprite
return false if @lank? and not @lank.thangType.isFullyLoaded()
@sprite.visible = not @hidden
@updatePosition pos
@updateRotation()
@updateScale()
if @name is 'highlight' and @highlightDelay and not @highlightTween
@sprite.visible = false
@highlightTween = createjs.Tween.get(@sprite).to({}, @highlightDelay).call =>
return if @destroyed
@sprite.visible = true
@highlightDelay = @highlightTween = null
@updateAlpha @alpha if @name in ['shadow', 'bounds']
true
updatePosition: (pos) ->
if @lank?.thang and @name in ['shadow', 'debug', 'target', 'selection', 'repair']
pos = @camera.worldToSurface x: @lank.thang.pos.x, y: @lank.thang.pos.y
else
pos ?= @lank?.sprite
return unless pos
@sprite.x = pos.x
@sprite.y = pos.y
if @statusEffect or @name is 'highlight'
offset = @lank.getOffset 'aboveHead'
@sprite.x += offset.x
@sprite.y += offset.y
@sprite.y -= 3 if @statusEffect
updateAlpha: (@alpha) ->
return if not @sprite or @name is 'debug'
if @name is 'shadow'
worldZ = @lank.thang.pos.z - @lank.thang.depth / 2 + @lank.getBobOffset()
@sprite.alpha = @alpha * 0.451 / Math.sqrt(worldZ / 2 + 1)
else if @name is 'bounds'
@drawsBoundsBorderShape?.alpha = Math.floor @lank.thang.alpha # Stop drawing bounds as soon as alpha is reduced at all
else
@sprite.alpha = @alpha
updateRotation: ->
if @name is 'debug' or (@name is 'shadow' and @lank.thang?.shape in ['rectangle', 'box'])
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
updateScale: ->
if @name is 'bounds' and ((@lank.thang.width isnt @lastWidth or @lank.thang.height isnt @lastHeight) or (@lank.thang.drawsBoundsIndex isnt @drawsBoundsIndex))
oldMark = @sprite
@buildBounds()
oldMark.parent.addChild @sprite
oldMark.parent.swapChildren oldMark, @sprite
oldMark.parent.removeChild oldMark
if @markLank?
@markLank.scaleFactor = 1.2
@markLank.updateScale()
if @name is 'shadow' and thang = @lank.thang
@sprite.scaleX = @baseScaleX * (thang.scaleFactor ? thang.scaleFactorX ? 1)
@sprite.scaleY = @baseScaleY * (thang.scaleFactor ? thang.scaleFactorY ? 1)
return unless @name in ['selection', 'target', 'repair', 'highlight']
# scale these marks to 10m (100px). Adjust based on lank size.
factor = 0.3 # default size: 3m width, most commonly for target when pointing to a location
if @lank?.sprite
width = @lank.sprite.getBounds()?.width or 0
width /= @lank.options.resolutionFactor
# all targets should be set to have a width of 100px, and then be scaled accordingly
factor = width / 100 # normalize
factor *= 1.1 # add margin
factor = Math.max(factor, 0.3) # lower bound
@sprite.scaleX *= factor
@sprite.scaleY *= factor
if @name in ['selection', 'target', 'repair']
@sprite.scaleY *= @camera.y2x # code applies perspective
stop: -> @markLank?.stop()
play: -> @markLank?.play()
hide: -> @hidden = true
show: -> @hidden = false
| 54513 | CocoClass = require 'core/CocoClass'
Camera = require './Camera'
ThangType = require 'models/ThangType'
markThangTypes = {}
module.exports = class Mark extends CocoClass
subscriptions: {}
alpha: 1
constructor: (options) ->
super()
options ?= {}
@name = options.name
@lank = options.lank
@camera = options.camera
@layer = options.layer
@thangType = options.thangType
@listenTo @layer, 'new-spritesheet', @onLayerMadeSpriteSheet
console.error @toString(), 'needs a name.' unless @name
console.error @toString(), 'needs a camera.' unless @camera
console.error @toString(), 'needs a layer.' unless @layer
@build()
destroy: ->
createjs.Tween.removeTweens @sprite if @sprite
@sprite?.parent?.removeChild @sprite
if @markLank
@layer.removeLank(@markLank)
@markLank.destroy()
@lank = null
super()
toString: -> "<Mark #{@name}: Sprite #{@lank?.thang?.id ? 'None'}>"
onLayerMadeSpriteSheet: ->
return unless @sprite
return @update() if @markLank
# rebuild sprite for new sprite sheet
@layer.removeChild @sprite
@sprite = null
@build()
@layer.addChild @sprite
@layer.updateLayerOrder()
# @updatePosition()
@update()
toggle: (to) ->
to = !!to
return @ if to is @on
return @toggleTo = to unless @sprite
@on = to
delete @toggleTo
if @on
if @markLank
@layer.addLank(@markLank)
else
@layer.addChild @sprite
@layer.updateLayerOrder()
else
if @markLank
@layer.removeLank(@markLank)
else
@layer.removeChild @sprite
if @highlightTween
@highlightDelay = @highlightTween = null
createjs.Tween.removeTweens @sprite
@sprite.visible = true
@
setLayer: (layer) ->
return if layer is @layer
wasOn = @on
@toggle false
@layer = layer
@toggle true if wasOn
setLank: (lank) ->
return if lank is @lank
@lank = lank
@build()
@
build: ->
unless @sprite
if @name is 'bounds' then @buildBounds()
else if @name is 'shadow' then @buildShadow()
else if @name is 'debug' then @buildDebug()
else if @name.match(/.+(Range|Distance|Radius)$/) then @buildRadius(@name)
else if @thangType then @buildSprite()
else console.error 'Don\'t know how to build mark for', @name
@sprite?.mouseEnabled = false
@
buildBounds: ->
@sprite = new createjs.Container()
@sprite.mouseChildren = false
style = @lank.thang.drawsBoundsStyle
@drawsBoundsIndex = @lank.thang.drawsBoundsIndex
return if style is 'corner-text' and @lank.thang.world.age is 0
# Confusingly make some semi-random colors that'll be consistent based on the drawsBoundsIndex
colors = (128 + Math.floor(('0.'+Math.sin(3 * @drawsBoundsIndex + i).toString().substr(6)) * 128) for i in [1 ... 4])
color = "rgba(#{colors[0]}, #{colors[1]}, #{colors[2]}, 0.5)"
[w, h] = [@lank.thang.width * Camera.PPM, @lank.thang.height * Camera.PPM * @camera.y2x]
if style in ['border-text', 'corner-text']
@drawsBoundsBorderShape = shape = new createjs.Shape()
shape.graphics.setStrokeStyle 5
shape.graphics.beginStroke color
if style is 'border-text'
shape.graphics.beginFill color.replace('0.5', '0.25')
else
shape.graphics.beginFill color
if @lank.thang.shape in ['ellipsoid', 'disc']
shape.drawEllipse 0, 0, w, h
else
shape.graphics.drawRect -w / 2, -h / 2, w, h
shape.graphics.endStroke()
shape.graphics.endFill()
@sprite.addChild shape
if style is 'border-text'
text = new createjs.Text '' + @drawsBoundsIndex, '20px Arial', color.replace('0.5', '1')
text.regX = text.getMeasuredWidth() / 2
text.regY = text.getMeasuredHeight() / 2
text.shadow = new createjs.Shadow('#000000', 1, 1, 0)
@sprite.addChild text
else if style is 'corner-text'
return if @lank.thang.world.age is 0
letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[@drawsBoundsIndex % 26]
text = new createjs.Text letter, '14px Arial', '#333333' # color.replace('0.5', '1')
text.x = -w / 2 + 2
text.y = -h / 2 + 2
@sprite.addChild text
else
console.warn @lank.thang.id, 'didn\'t know how to draw bounds style:', style
if w > 0 and h > 0 and style is 'border-text'
@sprite.cache -w / 2, -h / 2, w, h, 2
@lastWidth = @lank.thang.width
@lastHeight = @lank.thang.height
buildShadow: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = <KEY>"
SHADOW_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
shape.graphics.beginFill "rgba(0,0,0)"
bounds = [-SHADOW_SIZE/2, - SHADOW_SIZE/2, SHADOW_SIZE, SHADOW_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
alpha = @lank.thang?.alpha ? 1
width = (@lank.thang?.width ? 0) + 0.5
height = (@lank.thang?.height ? 0) + 0.5
longest = Math.max width, height
actualLongest = @lank.thangType.get('shadow') ? longest
width = width * actualLongest / longest
height = height * actualLongest / longest
width *= Camera.PPM
height *= Camera.PPM * @camera.y2x # TODO: doesn't work with rotation
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
@sprite.mouseEnabled = false
@sprite.alpha = alpha
@baseScaleX = @sprite.scaleX = width / (@layer.resolutionFactor * SHADOW_SIZE)
@baseScaleY = @sprite.scaleY = height / (@layer.resolutionFactor * SHADOW_SIZE)
buildRadius: (range) ->
alpha = 0.15
colors =
voiceRange: "rgba(0,145,0,#{alpha})"
visualRange: "rgba(0,0,145,#{alpha})"
attackRange: "rgba(145,0,0,#{alpha})"
# Fallback colors which work on both dungeon and grass tiles
extraColors = [
"rgba(145,0,145,#{alpha})"
"rgba(0,145,145,#{alpha})"
"rgba(145,105,0,#{alpha})"
"rgba(225,125,0,#{alpha})"
]
# Find the index of this range, to find the next-smallest radius
rangeNames = @lank.ranges.map((range, index) ->
range['name']
)
i = rangeNames.indexOf(range)
@sprite = new createjs.Shape()
fillColor = colors[range] ? extraColors[i]
@sprite.graphics.beginFill fillColor
# Draw the outer circle
@sprite.graphics.drawCircle 0, 0, @lank.thang[range] * Camera.PPM
# Cut out the hollow part if necessary
if i+1 < @lank.ranges.length
@sprite.graphics.arc 0, 0, @lank.ranges[i+1]['radius'], Math.PI*2, 0, true
@sprite.graphics.endFill()
strokeColor = fillColor.replace '' + alpha, '0.75'
@sprite.graphics.setStrokeStyle 2
@sprite.graphics.beginStroke strokeColor
@sprite.graphics.arc 0, 0, @lank.thang[range] * Camera.PPM, Math.PI*2, 0, true
@sprite.graphics.endStroke()
# Add perspective
@sprite.scaleY *= @camera.y2x
buildDebug: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = <KEY>@lank.thang.collisionCategory<KEY>}"
DEBUG_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
debugColor = {
none: 'rgba(224,255,239,0.25)'
ground: 'rgba(239,171,205,0.5)'
air: 'rgba(131,205,255,0.5)'
ground_and_air: 'rgba(2391,140,239,0.5)'
obstacles: 'rgba(88,88,88,0.5)'
dead: 'rgba(89,171,100,0.25)'
}[@lank.thang.collisionCategory] or 'rgba(171,205,239,0.5)'
shape.graphics.beginFill debugColor
bounds = [-DEBUG_SIZE / 2, -DEBUG_SIZE / 2, DEBUG_SIZE, DEBUG_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
PX = 3
w = Math.max(PX, @lank.thang.width * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.cos @lank.thang.rotation)
h = Math.max(PX, @lank.thang.height * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.sin @lank.thang.rotation)
@sprite.scaleX = w / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.scaleY = h / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
buildSprite: ->
if _.isString @thangType
thangType = markThangTypes[@thangType]
return @loadThangType() if not thangType
@thangType = thangType
return @listenToOnce(@thangType, 'sync', @onLoadedThangType) if not @thangType.loaded
Lank = require './Lank'
# don't bother with making these render async for now, but maybe later for fun and more complexity of code
markLank = new Lank @thangType
markLank.queueAction 'idle'
@sprite = markLank.sprite
@markLank = markLank
@listenTo @markLank, 'new-sprite', (@sprite) ->
loadThangType: ->
name = @thangType
@thangType = new ThangType()
@thangType.url = -> "/db/thang.type/#{name}"
@listenToOnce(@thangType, 'sync', @onLoadedThangType)
@thangType.fetch()
markThangTypes[name] = @thangType
onLoadedThangType: ->
@build()
@update() if @markLank
@toggle(@toggleTo) if @toggleTo?
Backbone.Mediator.publish 'sprite:loaded', {sprite: @}
update: (pos=null) ->
return false unless @on and @sprite
return false if @lank? and not @lank.thangType.isFullyLoaded()
@sprite.visible = not @hidden
@updatePosition pos
@updateRotation()
@updateScale()
if @name is 'highlight' and @highlightDelay and not @highlightTween
@sprite.visible = false
@highlightTween = createjs.Tween.get(@sprite).to({}, @highlightDelay).call =>
return if @destroyed
@sprite.visible = true
@highlightDelay = @highlightTween = null
@updateAlpha @alpha if @name in ['shadow', 'bounds']
true
updatePosition: (pos) ->
if @lank?.thang and @name in ['shadow', 'debug', 'target', 'selection', 'repair']
pos = @camera.worldToSurface x: @lank.thang.pos.x, y: @lank.thang.pos.y
else
pos ?= @lank?.sprite
return unless pos
@sprite.x = pos.x
@sprite.y = pos.y
if @statusEffect or @name is 'highlight'
offset = @lank.getOffset 'aboveHead'
@sprite.x += offset.x
@sprite.y += offset.y
@sprite.y -= 3 if @statusEffect
updateAlpha: (@alpha) ->
return if not @sprite or @name is 'debug'
if @name is 'shadow'
worldZ = @lank.thang.pos.z - @lank.thang.depth / 2 + @lank.getBobOffset()
@sprite.alpha = @alpha * 0.451 / Math.sqrt(worldZ / 2 + 1)
else if @name is 'bounds'
@drawsBoundsBorderShape?.alpha = Math.floor @lank.thang.alpha # Stop drawing bounds as soon as alpha is reduced at all
else
@sprite.alpha = @alpha
updateRotation: ->
if @name is 'debug' or (@name is 'shadow' and @lank.thang?.shape in ['rectangle', 'box'])
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
updateScale: ->
if @name is 'bounds' and ((@lank.thang.width isnt @lastWidth or @lank.thang.height isnt @lastHeight) or (@lank.thang.drawsBoundsIndex isnt @drawsBoundsIndex))
oldMark = @sprite
@buildBounds()
oldMark.parent.addChild @sprite
oldMark.parent.swapChildren oldMark, @sprite
oldMark.parent.removeChild oldMark
if @markLank?
@markLank.scaleFactor = 1.2
@markLank.updateScale()
if @name is 'shadow' and thang = @lank.thang
@sprite.scaleX = @baseScaleX * (thang.scaleFactor ? thang.scaleFactorX ? 1)
@sprite.scaleY = @baseScaleY * (thang.scaleFactor ? thang.scaleFactorY ? 1)
return unless @name in ['selection', 'target', 'repair', 'highlight']
# scale these marks to 10m (100px). Adjust based on lank size.
factor = 0.3 # default size: 3m width, most commonly for target when pointing to a location
if @lank?.sprite
width = @lank.sprite.getBounds()?.width or 0
width /= @lank.options.resolutionFactor
# all targets should be set to have a width of 100px, and then be scaled accordingly
factor = width / 100 # normalize
factor *= 1.1 # add margin
factor = Math.max(factor, 0.3) # lower bound
@sprite.scaleX *= factor
@sprite.scaleY *= factor
if @name in ['selection', 'target', 'repair']
@sprite.scaleY *= @camera.y2x # code applies perspective
stop: -> @markLank?.stop()
play: -> @markLank?.play()
hide: -> @hidden = true
show: -> @hidden = false
| true | CocoClass = require 'core/CocoClass'
Camera = require './Camera'
ThangType = require 'models/ThangType'
markThangTypes = {}
module.exports = class Mark extends CocoClass
subscriptions: {}
alpha: 1
constructor: (options) ->
super()
options ?= {}
@name = options.name
@lank = options.lank
@camera = options.camera
@layer = options.layer
@thangType = options.thangType
@listenTo @layer, 'new-spritesheet', @onLayerMadeSpriteSheet
console.error @toString(), 'needs a name.' unless @name
console.error @toString(), 'needs a camera.' unless @camera
console.error @toString(), 'needs a layer.' unless @layer
@build()
destroy: ->
createjs.Tween.removeTweens @sprite if @sprite
@sprite?.parent?.removeChild @sprite
if @markLank
@layer.removeLank(@markLank)
@markLank.destroy()
@lank = null
super()
toString: -> "<Mark #{@name}: Sprite #{@lank?.thang?.id ? 'None'}>"
onLayerMadeSpriteSheet: ->
return unless @sprite
return @update() if @markLank
# rebuild sprite for new sprite sheet
@layer.removeChild @sprite
@sprite = null
@build()
@layer.addChild @sprite
@layer.updateLayerOrder()
# @updatePosition()
@update()
toggle: (to) ->
to = !!to
return @ if to is @on
return @toggleTo = to unless @sprite
@on = to
delete @toggleTo
if @on
if @markLank
@layer.addLank(@markLank)
else
@layer.addChild @sprite
@layer.updateLayerOrder()
else
if @markLank
@layer.removeLank(@markLank)
else
@layer.removeChild @sprite
if @highlightTween
@highlightDelay = @highlightTween = null
createjs.Tween.removeTweens @sprite
@sprite.visible = true
@
setLayer: (layer) ->
return if layer is @layer
wasOn = @on
@toggle false
@layer = layer
@toggle true if wasOn
setLank: (lank) ->
return if lank is @lank
@lank = lank
@build()
@
build: ->
unless @sprite
if @name is 'bounds' then @buildBounds()
else if @name is 'shadow' then @buildShadow()
else if @name is 'debug' then @buildDebug()
else if @name.match(/.+(Range|Distance|Radius)$/) then @buildRadius(@name)
else if @thangType then @buildSprite()
else console.error 'Don\'t know how to build mark for', @name
@sprite?.mouseEnabled = false
@
buildBounds: ->
@sprite = new createjs.Container()
@sprite.mouseChildren = false
style = @lank.thang.drawsBoundsStyle
@drawsBoundsIndex = @lank.thang.drawsBoundsIndex
return if style is 'corner-text' and @lank.thang.world.age is 0
# Confusingly make some semi-random colors that'll be consistent based on the drawsBoundsIndex
colors = (128 + Math.floor(('0.'+Math.sin(3 * @drawsBoundsIndex + i).toString().substr(6)) * 128) for i in [1 ... 4])
color = "rgba(#{colors[0]}, #{colors[1]}, #{colors[2]}, 0.5)"
[w, h] = [@lank.thang.width * Camera.PPM, @lank.thang.height * Camera.PPM * @camera.y2x]
if style in ['border-text', 'corner-text']
@drawsBoundsBorderShape = shape = new createjs.Shape()
shape.graphics.setStrokeStyle 5
shape.graphics.beginStroke color
if style is 'border-text'
shape.graphics.beginFill color.replace('0.5', '0.25')
else
shape.graphics.beginFill color
if @lank.thang.shape in ['ellipsoid', 'disc']
shape.drawEllipse 0, 0, w, h
else
shape.graphics.drawRect -w / 2, -h / 2, w, h
shape.graphics.endStroke()
shape.graphics.endFill()
@sprite.addChild shape
if style is 'border-text'
text = new createjs.Text '' + @drawsBoundsIndex, '20px Arial', color.replace('0.5', '1')
text.regX = text.getMeasuredWidth() / 2
text.regY = text.getMeasuredHeight() / 2
text.shadow = new createjs.Shadow('#000000', 1, 1, 0)
@sprite.addChild text
else if style is 'corner-text'
return if @lank.thang.world.age is 0
letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[@drawsBoundsIndex % 26]
text = new createjs.Text letter, '14px Arial', '#333333' # color.replace('0.5', '1')
text.x = -w / 2 + 2
text.y = -h / 2 + 2
@sprite.addChild text
else
console.warn @lank.thang.id, 'didn\'t know how to draw bounds style:', style
if w > 0 and h > 0 and style is 'border-text'
@sprite.cache -w / 2, -h / 2, w, h, 2
@lastWidth = @lank.thang.width
@lastHeight = @lank.thang.height
buildShadow: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = PI:KEY:<KEY>END_PI"
SHADOW_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
shape.graphics.beginFill "rgba(0,0,0)"
bounds = [-SHADOW_SIZE/2, - SHADOW_SIZE/2, SHADOW_SIZE, SHADOW_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
alpha = @lank.thang?.alpha ? 1
width = (@lank.thang?.width ? 0) + 0.5
height = (@lank.thang?.height ? 0) + 0.5
longest = Math.max width, height
actualLongest = @lank.thangType.get('shadow') ? longest
width = width * actualLongest / longest
height = height * actualLongest / longest
width *= Camera.PPM
height *= Camera.PPM * @camera.y2x # TODO: doesn't work with rotation
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
@sprite.mouseEnabled = false
@sprite.alpha = alpha
@baseScaleX = @sprite.scaleX = width / (@layer.resolutionFactor * SHADOW_SIZE)
@baseScaleY = @sprite.scaleY = height / (@layer.resolutionFactor * SHADOW_SIZE)
buildRadius: (range) ->
alpha = 0.15
colors =
voiceRange: "rgba(0,145,0,#{alpha})"
visualRange: "rgba(0,0,145,#{alpha})"
attackRange: "rgba(145,0,0,#{alpha})"
# Fallback colors which work on both dungeon and grass tiles
extraColors = [
"rgba(145,0,145,#{alpha})"
"rgba(0,145,145,#{alpha})"
"rgba(145,105,0,#{alpha})"
"rgba(225,125,0,#{alpha})"
]
# Find the index of this range, to find the next-smallest radius
rangeNames = @lank.ranges.map((range, index) ->
range['name']
)
i = rangeNames.indexOf(range)
@sprite = new createjs.Shape()
fillColor = colors[range] ? extraColors[i]
@sprite.graphics.beginFill fillColor
# Draw the outer circle
@sprite.graphics.drawCircle 0, 0, @lank.thang[range] * Camera.PPM
# Cut out the hollow part if necessary
if i+1 < @lank.ranges.length
@sprite.graphics.arc 0, 0, @lank.ranges[i+1]['radius'], Math.PI*2, 0, true
@sprite.graphics.endFill()
strokeColor = fillColor.replace '' + alpha, '0.75'
@sprite.graphics.setStrokeStyle 2
@sprite.graphics.beginStroke strokeColor
@sprite.graphics.arc 0, 0, @lank.thang[range] * Camera.PPM, Math.PI*2, 0, true
@sprite.graphics.endStroke()
# Add perspective
@sprite.scaleY *= @camera.y2x
buildDebug: ->
shapeName = if @lank.thang.shape in ['ellipsoid', 'disc'] then 'ellipse' else 'rect'
key = PI:KEY:<KEY>END_PI@lank.thang.collisionCategoryPI:KEY:<KEY>END_PI}"
DEBUG_SIZE = 10
unless key in @layer.spriteSheet.getAnimations()
shape = new createjs.Shape()
debugColor = {
none: 'rgba(224,255,239,0.25)'
ground: 'rgba(239,171,205,0.5)'
air: 'rgba(131,205,255,0.5)'
ground_and_air: 'rgba(2391,140,239,0.5)'
obstacles: 'rgba(88,88,88,0.5)'
dead: 'rgba(89,171,100,0.25)'
}[@lank.thang.collisionCategory] or 'rgba(171,205,239,0.5)'
shape.graphics.beginFill debugColor
bounds = [-DEBUG_SIZE / 2, -DEBUG_SIZE / 2, DEBUG_SIZE, DEBUG_SIZE]
if shapeName is 'ellipse'
shape.graphics.drawEllipse bounds...
else
shape.graphics.drawRect bounds...
shape.graphics.endFill()
@layer.addCustomGraphic(key, shape, bounds)
@sprite = new createjs.Sprite(@layer.spriteSheet)
@sprite.gotoAndStop(key)
PX = 3
w = Math.max(PX, @lank.thang.width * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.cos @lank.thang.rotation)
h = Math.max(PX, @lank.thang.height * Camera.PPM) * (@camera.y2x + (1 - @camera.y2x) * Math.abs Math.sin @lank.thang.rotation)
@sprite.scaleX = w / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.scaleY = h / (@layer.resolutionFactor * DEBUG_SIZE)
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
buildSprite: ->
if _.isString @thangType
thangType = markThangTypes[@thangType]
return @loadThangType() if not thangType
@thangType = thangType
return @listenToOnce(@thangType, 'sync', @onLoadedThangType) if not @thangType.loaded
Lank = require './Lank'
# don't bother with making these render async for now, but maybe later for fun and more complexity of code
markLank = new Lank @thangType
markLank.queueAction 'idle'
@sprite = markLank.sprite
@markLank = markLank
@listenTo @markLank, 'new-sprite', (@sprite) ->
loadThangType: ->
name = @thangType
@thangType = new ThangType()
@thangType.url = -> "/db/thang.type/#{name}"
@listenToOnce(@thangType, 'sync', @onLoadedThangType)
@thangType.fetch()
markThangTypes[name] = @thangType
onLoadedThangType: ->
@build()
@update() if @markLank
@toggle(@toggleTo) if @toggleTo?
Backbone.Mediator.publish 'sprite:loaded', {sprite: @}
update: (pos=null) ->
return false unless @on and @sprite
return false if @lank? and not @lank.thangType.isFullyLoaded()
@sprite.visible = not @hidden
@updatePosition pos
@updateRotation()
@updateScale()
if @name is 'highlight' and @highlightDelay and not @highlightTween
@sprite.visible = false
@highlightTween = createjs.Tween.get(@sprite).to({}, @highlightDelay).call =>
return if @destroyed
@sprite.visible = true
@highlightDelay = @highlightTween = null
@updateAlpha @alpha if @name in ['shadow', 'bounds']
true
updatePosition: (pos) ->
if @lank?.thang and @name in ['shadow', 'debug', 'target', 'selection', 'repair']
pos = @camera.worldToSurface x: @lank.thang.pos.x, y: @lank.thang.pos.y
else
pos ?= @lank?.sprite
return unless pos
@sprite.x = pos.x
@sprite.y = pos.y
if @statusEffect or @name is 'highlight'
offset = @lank.getOffset 'aboveHead'
@sprite.x += offset.x
@sprite.y += offset.y
@sprite.y -= 3 if @statusEffect
updateAlpha: (@alpha) ->
return if not @sprite or @name is 'debug'
if @name is 'shadow'
worldZ = @lank.thang.pos.z - @lank.thang.depth / 2 + @lank.getBobOffset()
@sprite.alpha = @alpha * 0.451 / Math.sqrt(worldZ / 2 + 1)
else if @name is 'bounds'
@drawsBoundsBorderShape?.alpha = Math.floor @lank.thang.alpha # Stop drawing bounds as soon as alpha is reduced at all
else
@sprite.alpha = @alpha
updateRotation: ->
if @name is 'debug' or (@name is 'shadow' and @lank.thang?.shape in ['rectangle', 'box'])
@sprite.rotation = -@lank.thang.rotation * 180 / Math.PI
updateScale: ->
if @name is 'bounds' and ((@lank.thang.width isnt @lastWidth or @lank.thang.height isnt @lastHeight) or (@lank.thang.drawsBoundsIndex isnt @drawsBoundsIndex))
oldMark = @sprite
@buildBounds()
oldMark.parent.addChild @sprite
oldMark.parent.swapChildren oldMark, @sprite
oldMark.parent.removeChild oldMark
if @markLank?
@markLank.scaleFactor = 1.2
@markLank.updateScale()
if @name is 'shadow' and thang = @lank.thang
@sprite.scaleX = @baseScaleX * (thang.scaleFactor ? thang.scaleFactorX ? 1)
@sprite.scaleY = @baseScaleY * (thang.scaleFactor ? thang.scaleFactorY ? 1)
return unless @name in ['selection', 'target', 'repair', 'highlight']
# scale these marks to 10m (100px). Adjust based on lank size.
factor = 0.3 # default size: 3m width, most commonly for target when pointing to a location
if @lank?.sprite
width = @lank.sprite.getBounds()?.width or 0
width /= @lank.options.resolutionFactor
# all targets should be set to have a width of 100px, and then be scaled accordingly
factor = width / 100 # normalize
factor *= 1.1 # add margin
factor = Math.max(factor, 0.3) # lower bound
@sprite.scaleX *= factor
@sprite.scaleY *= factor
if @name in ['selection', 'target', 'repair']
@sprite.scaleY *= @camera.y2x # code applies perspective
stop: -> @markLank?.stop()
play: -> @markLank?.play()
hide: -> @hidden = true
show: -> @hidden = false
|
[
{
"context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'FMsk'\n\n constructor: (layer, length) ->\n super(lay",
"end": 133,
"score": 0.7310943007469177,
"start": 129,
"tag": "KEY",
"value": "FMsk"
}
] | src/psd/layer_info/filter_mask.coffee | taofei-pro/psd.js | 0 | LayerInfo = require '../layer_info.coffee'
module.exports = class FilterMask extends LayerInfo
@shouldParse: (key) -> key is 'FMsk'
constructor: (layer, length) ->
super(layer, length)
parse: ->
@color = @file.readSpaceColor()
@opacity = @file.readShort()
| 64334 | LayerInfo = require '../layer_info.coffee'
module.exports = class FilterMask extends LayerInfo
@shouldParse: (key) -> key is '<KEY>'
constructor: (layer, length) ->
super(layer, length)
parse: ->
@color = @file.readSpaceColor()
@opacity = @file.readShort()
| true | LayerInfo = require '../layer_info.coffee'
module.exports = class FilterMask extends LayerInfo
@shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI'
constructor: (layer, length) ->
super(layer, length)
parse: ->
@color = @file.readSpaceColor()
@opacity = @file.readShort()
|
[
{
"context": "view Enforce autoFocus prop is not used.\n# @author Ethan Cohen <@evcohen>\n###\n\n# -------------------------------",
"end": 102,
"score": 0.9998877048492432,
"start": 91,
"tag": "NAME",
"value": "Ethan Cohen"
},
{
"context": "utoFocus prop is not used.\n# @author Ethan Cohen <@evcohen>\n###\n\n# -----------------------------------------",
"end": 112,
"score": 0.9995123147964478,
"start": 104,
"tag": "USERNAME",
"value": "@evcohen"
}
] | src/tests/rules/no-autofocus.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce autoFocus prop is not used.
# @author Ethan Cohen <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-autofocus'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'The autoFocus prop should not be used, as it can reduce usability and accessibility for users.'
type: 'JSXAttribute'
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'no-autofocus', rule,
valid: [
code: '<div />'
,
code: '<div autofocus />'
,
code: '<input autofocus="true" />'
,
code: '<Foo bar />'
,
code: '<Foo autoFocus />', options: ignoreNonDOMSchema
,
code: '<div><div autofocus /></div>', options: ignoreNonDOMSchema
].map parserOptionsMapper
invalid: [
code: '<div autoFocus />', errors: [expectedError]
,
code: '<div autoFocus={true} />', errors: [expectedError]
,
code: '<div autoFocus={false} />', errors: [expectedError]
,
code: '<div autoFocus={undefined} />', errors: [expectedError]
,
code: '<div autoFocus="true" />', errors: [expectedError]
,
code: '<div autoFocus="false" />', errors: [expectedError]
,
code: '<input autoFocus />', errors: [expectedError]
,
code: '<Foo autoFocus />', errors: [expectedError]
].map parserOptionsMapper
| 160564 | ### eslint-env jest ###
###*
# @fileoverview Enforce autoFocus prop is not used.
# @author <NAME> <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-autofocus'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'The autoFocus prop should not be used, as it can reduce usability and accessibility for users.'
type: 'JSXAttribute'
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'no-autofocus', rule,
valid: [
code: '<div />'
,
code: '<div autofocus />'
,
code: '<input autofocus="true" />'
,
code: '<Foo bar />'
,
code: '<Foo autoFocus />', options: ignoreNonDOMSchema
,
code: '<div><div autofocus /></div>', options: ignoreNonDOMSchema
].map parserOptionsMapper
invalid: [
code: '<div autoFocus />', errors: [expectedError]
,
code: '<div autoFocus={true} />', errors: [expectedError]
,
code: '<div autoFocus={false} />', errors: [expectedError]
,
code: '<div autoFocus={undefined} />', errors: [expectedError]
,
code: '<div autoFocus="true" />', errors: [expectedError]
,
code: '<div autoFocus="false" />', errors: [expectedError]
,
code: '<input autoFocus />', errors: [expectedError]
,
code: '<Foo autoFocus />', errors: [expectedError]
].map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce autoFocus prop is not used.
# @author PI:NAME:<NAME>END_PI <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-autofocus'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'The autoFocus prop should not be used, as it can reduce usability and accessibility for users.'
type: 'JSXAttribute'
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'no-autofocus', rule,
valid: [
code: '<div />'
,
code: '<div autofocus />'
,
code: '<input autofocus="true" />'
,
code: '<Foo bar />'
,
code: '<Foo autoFocus />', options: ignoreNonDOMSchema
,
code: '<div><div autofocus /></div>', options: ignoreNonDOMSchema
].map parserOptionsMapper
invalid: [
code: '<div autoFocus />', errors: [expectedError]
,
code: '<div autoFocus={true} />', errors: [expectedError]
,
code: '<div autoFocus={false} />', errors: [expectedError]
,
code: '<div autoFocus={undefined} />', errors: [expectedError]
,
code: '<div autoFocus="true" />', errors: [expectedError]
,
code: '<div autoFocus="false" />', errors: [expectedError]
,
code: '<input autoFocus />', errors: [expectedError]
,
code: '<Foo autoFocus />', errors: [expectedError]
].map parserOptionsMapper
|
[
{
"context": "\n and: \"og\"\n back: \"tilbake\"\n changePassword: \"Bytt passord\"\n choosePassword: \"Velg passord\"\n clickAgree: \"",
"end": 140,
"score": 0.9973692893981934,
"start": 128,
"tag": "PASSWORD",
"value": "Bytt passord"
},
{
"context": "changePassword: \"Bytt passord\"\n choosePassword: \"Velg passord\"\n clickAgree: \"Ved å klikke meld på godtar du vå",
"end": 173,
"score": 0.9989013671875,
"start": 161,
"tag": "PASSWORD",
"value": "Velg passord"
},
{
"context": "createAccount: \"Oprett konto\"\n currentPassword: \"Nåværende passord\"\n dontHaveAnAccount: \"Har du ikke en konto?\"\n e",
"end": 321,
"score": 0.9990030527114868,
"start": 304,
"tag": "PASSWORD",
"value": "Nåværende passord"
},
{
"context": "nk: \"Epost nullstillingslenke\"\n forgotPassword: \"Glemt passord?\"\n ifYouAlreadyHaveAnAccount: \"Hvis du allerede ha",
"end": 495,
"score": 0.949390172958374,
"start": 482,
"tag": "PASSWORD",
"value": "Glemt passord"
},
{
"context": ": \"Hvis du allerede har en konto\"\n newPassword: \"Nytt passord\"\n newPasswordAgain: \"Gjengi nytt passord\"\n opti",
"end": 587,
"score": 0.9990843534469604,
"start": 575,
"tag": "PASSWORD",
"value": "Nytt passord"
},
{
"context": " newPassword: \"Nytt passord\"\n newPasswordAgain: \"Gjengi nytt passord\"\n optional: \"Frivillig\"\n OR: \"eller\"\n password",
"end": 629,
"score": 0.9986542463302612,
"start": 610,
"tag": "PASSWORD",
"value": "Gjengi nytt passord"
},
{
"context": " optional: \"Frivillig\"\n OR: \"eller\"\n password: \"Passord\"\n passwordAgain: \"Gjengi passord\"\n privacyPolic",
"end": 689,
"score": 0.9991350173950195,
"start": 682,
"tag": "PASSWORD",
"value": "Passord"
},
{
"context": ": \"eller\"\n password: \"Passord\"\n passwordAgain: \"Gjengi passord\"\n privacyPolicy: \"Personvern\"\n remove: \"fjern\"\n",
"end": 723,
"score": 0.9991893768310547,
"start": 709,
"tag": "PASSWORD",
"value": "Gjengi passord"
},
{
"context": "rsonvern\"\n remove: \"fjern\"\n resetYourPassword: \"Nullstill passord\"\n setPassword: \"Sett passord\"\n sign: \"Logg\"\n s",
"end": 812,
"score": 0.9992122650146484,
"start": 795,
"tag": "PASSWORD",
"value": "Nullstill passord"
},
{
"context": "YourPassword: \"Nullstill passord\"\n setPassword: \"Sett passord\"\n sign: \"Logg\"\n signIn: \"Logg inn\"\n signin: \"L",
"end": 842,
"score": 0.9991182088851929,
"start": 830,
"tag": "PASSWORD",
"value": "Sett passord"
},
{
"context": "ms: \"Betingelser for bruk\"\n updateYourPassword: \"Oppdater passord\"\n username: \"Brukernavn\"\n usernameOrEmail: \"Bru",
"end": 1106,
"score": 0.9978910684585571,
"start": 1090,
"tag": "PASSWORD",
"value": "Oppdater passord"
},
{
"context": "dateYourPassword: \"Oppdater passord\"\n username: \"Brukernavn\"\n usernameOrEmail: \"Brukernavn eller e-epost\"\n ",
"end": 1131,
"score": 0.9996238946914673,
"start": 1121,
"tag": "USERNAME",
"value": "Brukernavn"
},
{
"context": "ord\"\n username: \"Brukernavn\"\n usernameOrEmail: \"Brukernavn eller e-epost\"\n with: \"med\"\n\n\n info:\n emailS",
"end": 1163,
"score": 0.9867525100708008,
"start": 1153,
"tag": "USERNAME",
"value": "Brukernavn"
},
{
"context": "erified: \"E-post bekreftet\"\n passwordChanged: \"Passord endret\"\n passwordReset: \"Passord nullstillt\"\n\n\n erro",
"end": 1307,
"score": 0.9991669654846191,
"start": 1293,
"tag": "PASSWORD",
"value": "Passord endret"
},
{
"context": "wordChanged: \"Passord endret\"\n passwordReset: \"Passord nullstillt\"\n\n\n error:\n emailRequired: \"E-post obligatori",
"end": 1347,
"score": 0.9991371035575867,
"start": 1329,
"tag": "PASSWORD",
"value": "Passord nullstillt"
},
{
"context": "d: \"Påmeldingskode kreves.\"\n usernameIsEmail: \"Brukernavn kan ikke være en e-postadresse.\"\n usernameRequ",
"end": 1788,
"score": 0.994269073009491,
"start": 1778,
"tag": "USERNAME",
"value": "Brukernavn"
},
{
"context": "ke være en e-postadresse.\"\n usernameRequired: \"Brukernavn må utfylles.\"\n\n\n accounts:\n\n #---- accoun",
"end": 1855,
"score": 0.9741552472114563,
"start": 1845,
"tag": "USERNAME",
"value": "Brukernavn"
},
{
"context": "er ikke kriteriet.\"\n \"Invalid login token\": \"Ugyldig innloggingstegn\"\n \"Login forbidden\": \"Innlogging forbudt\"\n ",
"end": 2214,
"score": 0.9148895740509033,
"start": 2191,
"tag": "PASSWORD",
"value": "Ugyldig innloggingstegn"
},
{
"context": "ing gikk galt\"\n \"Username already exists.\": \"Brukernavnet finnes allerede.\"\n \"You are not logged in.\":",
"end": 2560,
"score": 0.9904876947402954,
"start": 2548,
"tag": "USERNAME",
"value": "Brukernavnet"
},
{
"context": "-- accounts-password\n \"Incorrect password\": \"Feil passord\"\n \"Invalid email\": \"Ugyldig e-postadresse\"\n ",
"end": 3171,
"score": 0.9979454874992371,
"start": 3159,
"tag": "PASSWORD",
"value": "Feil passord"
}
] | t9n/no_NB.coffee | tnedich/meteor-accounts-t9n | 0 | #Language: Norwegian bokmål
#Translators: Kjetilge
no_NB =
add: "legg til"
and: "og"
back: "tilbake"
changePassword: "Bytt passord"
choosePassword: "Velg passord"
clickAgree: "Ved å klikke meld på godtar du vår"
configure: "Konfigurer"
createAccount: "Oprett konto"
currentPassword: "Nåværende passord"
dontHaveAnAccount: "Har du ikke en konto?"
email: "E-post"
emailAddress: "E-postadresse"
emailResetLink: "Epost nullstillingslenke"
forgotPassword: "Glemt passord?"
ifYouAlreadyHaveAnAccount: "Hvis du allerede har en konto"
newPassword: "Nytt passord"
newPasswordAgain: "Gjengi nytt passord"
optional: "Frivillig"
OR: "eller"
password: "Passord"
passwordAgain: "Gjengi passord"
privacyPolicy: "Personvern"
remove: "fjern"
resetYourPassword: "Nullstill passord"
setPassword: "Sett passord"
sign: "Logg"
signIn: "Logg inn"
signin: "Logg inn"
signOut: "Logg ut"
signUp: "Meld på"
signupCode: "Påmeldingskode"
signUpWithYourEmailAddress: "Meld på med din e-postadresse"
terms: "Betingelser for bruk"
updateYourPassword: "Oppdater passord"
username: "Brukernavn"
usernameOrEmail: "Brukernavn eller e-epost"
with: "med"
info:
emailSent: "E-post sendt"
emailVerified: "E-post bekreftet"
passwordChanged: "Passord endret"
passwordReset: "Passord nullstillt"
error:
emailRequired: "E-post obligatorisk."
minChar: "Passordet må ha minst 7 tegn."
pwdsDontMatch: "Passordene er ikke like."
pwOneDigit: "Passordet må ha minst ett tall."
pwOneLetter: "Passordet må ha minst en bokstav."
signInRequired: "Du må være logget inn for å gjøre dette."
signupCodeIncorrect: "Påmelding gikk galt."
signupCodeRequired: "Påmeldingskode kreves."
usernameIsEmail: "Brukernavn kan ikke være en e-postadresse."
usernameRequired: "Brukernavn må utfylles."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-postadressen finnes allerede."
"Email doesn't match the criteria.": "E-postadressen møter ikke kriteriet."
"Invalid login token": "Ugyldig innloggingstegn"
"Login forbidden": "Innlogging forbudt"
#"Service " + options.service + " already configured"
"Service unknown": "Ukjent tjeneste"
"Unrecognized options for login request": "Ukjendte valg ved innloggingsforsøk"
"User validation failed": "Brukergodkjenning gikk galt"
"Username already exists.": "Brukernavnet finnes allerede."
"You are not logged in.": "Du er ikke logget inn."
"You've been logged out by the server. Please log in again.": "Tjeneren loggt deg ut. Logg inn på ny."
"Your session has expired. Please log in again.": "Din økt er utløpt. Logg inn på ny."
#---- accounts-oauth
"No matching login attempt found": "Fant ingen samsvarende innloggingsførsøk"
#---- accounts-password-client
"Password is old. Please reset your password.": "Passordet er for gammelt. Nullstill passordet ditt."
#---- accounts-password
"Incorrect password": "Feil passord"
"Invalid email": "Ugyldig e-postadresse"
"Must be logged in": "Du må være innlogget"
"Need to set a username or email": "Oppgi brukernavn eller e-postadresse"
"old password format": "gammelt passordformat"
"Password may not be empty": "Passord må være utfyllt"
"Signups forbidden": "Påmeldinger ikke tillatt"
"Token expired": "Økten er utløpt"
"Token has invalid email address": "Innloggingstegnet har ugyldig e-postadresse"
"User has no password set": "Brukeren har ikke angitt passord"
"User not found": "Bruker ikke funnet"
"Verify email link expired": "Lenke for e-postbekreftelse er utløpt"
"Verify email link is for unknown address": "Lenke for e-postbekreftelse er for en ukjent adresse"
#---- match
"Match failed": "Ikke samsvar"
#---- Misc...
"Unknown error": "Ukjent feil"
T9n.map "no_NB", no_NB
| 98307 | #Language: Norwegian bokmål
#Translators: Kjetilge
no_NB =
add: "legg til"
and: "og"
back: "tilbake"
changePassword: "<PASSWORD>"
choosePassword: "<PASSWORD>"
clickAgree: "Ved å klikke meld på godtar du vår"
configure: "Konfigurer"
createAccount: "Oprett konto"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Har du ikke en konto?"
email: "E-post"
emailAddress: "E-postadresse"
emailResetLink: "Epost nullstillingslenke"
forgotPassword: "<PASSWORD>?"
ifYouAlreadyHaveAnAccount: "Hvis du allerede har en konto"
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD>"
optional: "Frivillig"
OR: "eller"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD>"
privacyPolicy: "Personvern"
remove: "fjern"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD>"
sign: "Logg"
signIn: "Logg inn"
signin: "Logg inn"
signOut: "Logg ut"
signUp: "Meld på"
signupCode: "Påmeldingskode"
signUpWithYourEmailAddress: "Meld på med din e-postadresse"
terms: "Betingelser for bruk"
updateYourPassword: "<PASSWORD>"
username: "Brukernavn"
usernameOrEmail: "Brukernavn eller e-epost"
with: "med"
info:
emailSent: "E-post sendt"
emailVerified: "E-post bekreftet"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "E-post obligatorisk."
minChar: "Passordet må ha minst 7 tegn."
pwdsDontMatch: "Passordene er ikke like."
pwOneDigit: "Passordet må ha minst ett tall."
pwOneLetter: "Passordet må ha minst en bokstav."
signInRequired: "Du må være logget inn for å gjøre dette."
signupCodeIncorrect: "Påmelding gikk galt."
signupCodeRequired: "Påmeldingskode kreves."
usernameIsEmail: "Brukernavn kan ikke være en e-postadresse."
usernameRequired: "Brukernavn må utfylles."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-postadressen finnes allerede."
"Email doesn't match the criteria.": "E-postadressen møter ikke kriteriet."
"Invalid login token": "<PASSWORD>"
"Login forbidden": "Innlogging forbudt"
#"Service " + options.service + " already configured"
"Service unknown": "Ukjent tjeneste"
"Unrecognized options for login request": "Ukjendte valg ved innloggingsforsøk"
"User validation failed": "Brukergodkjenning gikk galt"
"Username already exists.": "Brukernavnet finnes allerede."
"You are not logged in.": "Du er ikke logget inn."
"You've been logged out by the server. Please log in again.": "Tjeneren loggt deg ut. Logg inn på ny."
"Your session has expired. Please log in again.": "Din økt er utløpt. Logg inn på ny."
#---- accounts-oauth
"No matching login attempt found": "Fant ingen samsvarende innloggingsførsøk"
#---- accounts-password-client
"Password is old. Please reset your password.": "Passordet er for gammelt. Nullstill passordet ditt."
#---- accounts-password
"Incorrect password": "<PASSWORD>"
"Invalid email": "Ugyldig e-postadresse"
"Must be logged in": "Du må være innlogget"
"Need to set a username or email": "Oppgi brukernavn eller e-postadresse"
"old password format": "gammelt passordformat"
"Password may not be empty": "Passord må være utfyllt"
"Signups forbidden": "Påmeldinger ikke tillatt"
"Token expired": "Økten er utløpt"
"Token has invalid email address": "Innloggingstegnet har ugyldig e-postadresse"
"User has no password set": "Brukeren har ikke angitt passord"
"User not found": "Bruker ikke funnet"
"Verify email link expired": "Lenke for e-postbekreftelse er utløpt"
"Verify email link is for unknown address": "Lenke for e-postbekreftelse er for en ukjent adresse"
#---- match
"Match failed": "Ikke samsvar"
#---- Misc...
"Unknown error": "Ukjent feil"
T9n.map "no_NB", no_NB
| true | #Language: Norwegian bokmål
#Translators: Kjetilge
no_NB =
add: "legg til"
and: "og"
back: "tilbake"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "Ved å klikke meld på godtar du vår"
configure: "Konfigurer"
createAccount: "Oprett konto"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Har du ikke en konto?"
email: "E-post"
emailAddress: "E-postadresse"
emailResetLink: "Epost nullstillingslenke"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?"
ifYouAlreadyHaveAnAccount: "Hvis du allerede har en konto"
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI"
optional: "Frivillig"
OR: "eller"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI"
privacyPolicy: "Personvern"
remove: "fjern"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Logg"
signIn: "Logg inn"
signin: "Logg inn"
signOut: "Logg ut"
signUp: "Meld på"
signupCode: "Påmeldingskode"
signUpWithYourEmailAddress: "Meld på med din e-postadresse"
terms: "Betingelser for bruk"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
username: "Brukernavn"
usernameOrEmail: "Brukernavn eller e-epost"
with: "med"
info:
emailSent: "E-post sendt"
emailVerified: "E-post bekreftet"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "E-post obligatorisk."
minChar: "Passordet må ha minst 7 tegn."
pwdsDontMatch: "Passordene er ikke like."
pwOneDigit: "Passordet må ha minst ett tall."
pwOneLetter: "Passordet må ha minst en bokstav."
signInRequired: "Du må være logget inn for å gjøre dette."
signupCodeIncorrect: "Påmelding gikk galt."
signupCodeRequired: "Påmeldingskode kreves."
usernameIsEmail: "Brukernavn kan ikke være en e-postadresse."
usernameRequired: "Brukernavn må utfylles."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-postadressen finnes allerede."
"Email doesn't match the criteria.": "E-postadressen møter ikke kriteriet."
"Invalid login token": "PI:PASSWORD:<PASSWORD>END_PI"
"Login forbidden": "Innlogging forbudt"
#"Service " + options.service + " already configured"
"Service unknown": "Ukjent tjeneste"
"Unrecognized options for login request": "Ukjendte valg ved innloggingsforsøk"
"User validation failed": "Brukergodkjenning gikk galt"
"Username already exists.": "Brukernavnet finnes allerede."
"You are not logged in.": "Du er ikke logget inn."
"You've been logged out by the server. Please log in again.": "Tjeneren loggt deg ut. Logg inn på ny."
"Your session has expired. Please log in again.": "Din økt er utløpt. Logg inn på ny."
#---- accounts-oauth
"No matching login attempt found": "Fant ingen samsvarende innloggingsførsøk"
#---- accounts-password-client
"Password is old. Please reset your password.": "Passordet er for gammelt. Nullstill passordet ditt."
#---- accounts-password
"Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI"
"Invalid email": "Ugyldig e-postadresse"
"Must be logged in": "Du må være innlogget"
"Need to set a username or email": "Oppgi brukernavn eller e-postadresse"
"old password format": "gammelt passordformat"
"Password may not be empty": "Passord må være utfyllt"
"Signups forbidden": "Påmeldinger ikke tillatt"
"Token expired": "Økten er utløpt"
"Token has invalid email address": "Innloggingstegnet har ugyldig e-postadresse"
"User has no password set": "Brukeren har ikke angitt passord"
"User not found": "Bruker ikke funnet"
"Verify email link expired": "Lenke for e-postbekreftelse er utløpt"
"Verify email link is for unknown address": "Lenke for e-postbekreftelse er for en ukjent adresse"
#---- match
"Match failed": "Ikke samsvar"
#---- Misc...
"Unknown error": "Ukjent feil"
T9n.map "no_NB", no_NB
|
[
{
"context": "iew Prevent missing React when using JSX\n# @author Glen Mailer\n###\n'use strict'\n\nvariableUtil = require 'eslint-",
"end": 79,
"score": 0.9997812509536743,
"start": 68,
"tag": "NAME",
"value": "Glen Mailer"
}
] | src/rules/react-in-jsx-scope.coffee | helixbass/eslint-plugin-known-imports | 4 | ###*
# @fileoverview Prevent missing React when using JSX
# @author Glen Mailer
###
'use strict'
variableUtil = require 'eslint-plugin-react/lib/util/variable'
pragmaUtil = require 'eslint-plugin-react/lib/util/pragma'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# -----------------------------------------------------------------------------
# Rule Definition
# -----------------------------------------------------------------------------
getFix = ({pragma, context, allImports}) ->
return null unless pragma is 'React'
sourceCode = context.getSourceCode()
firstToken = sourceCode.getFirstToken sourceCode.ast
existingReactImport = allImports.find ({source: {value}}) -> value is 'react'
unless existingReactImport
return (fixer) ->
fixer.insertTextBefore firstToken, "import React from 'react'\n"
firstSpecifier = existingReactImport.specifiers[0]
openingBrace = sourceCode.getTokenBefore firstSpecifier
(fixer) -> fixer.insertTextBefore openingBrace, 'React, '
module.exports =
meta:
docs:
description: 'Prevent missing React when using JSX'
category: 'Possible Errors'
recommended: yes
url: docsUrl 'react-in-jsx-scope'
schema: []
fixable: 'code'
create: (context) ->
pragma = pragmaUtil.getFromContext context
NOT_DEFINED_MESSAGE = "'{{name}}' must be in scope when using JSX"
allImports = []
checkIfReactIsInScope = (node) ->
variables = variableUtil.variablesInScope context
return if variableUtil.findVariable variables, pragma
context.report {
node
message: NOT_DEFINED_MESSAGE
data:
name: pragma
fix: getFix {pragma, context, allImports}
}
ImportDeclaration: (node) -> allImports.push node
JSXOpeningElement: checkIfReactIsInScope
JSXOpeningFragment: checkIfReactIsInScope
| 123218 | ###*
# @fileoverview Prevent missing React when using JSX
# @author <NAME>
###
'use strict'
variableUtil = require 'eslint-plugin-react/lib/util/variable'
pragmaUtil = require 'eslint-plugin-react/lib/util/pragma'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# -----------------------------------------------------------------------------
# Rule Definition
# -----------------------------------------------------------------------------
getFix = ({pragma, context, allImports}) ->
return null unless pragma is 'React'
sourceCode = context.getSourceCode()
firstToken = sourceCode.getFirstToken sourceCode.ast
existingReactImport = allImports.find ({source: {value}}) -> value is 'react'
unless existingReactImport
return (fixer) ->
fixer.insertTextBefore firstToken, "import React from 'react'\n"
firstSpecifier = existingReactImport.specifiers[0]
openingBrace = sourceCode.getTokenBefore firstSpecifier
(fixer) -> fixer.insertTextBefore openingBrace, 'React, '
module.exports =
meta:
docs:
description: 'Prevent missing React when using JSX'
category: 'Possible Errors'
recommended: yes
url: docsUrl 'react-in-jsx-scope'
schema: []
fixable: 'code'
create: (context) ->
pragma = pragmaUtil.getFromContext context
NOT_DEFINED_MESSAGE = "'{{name}}' must be in scope when using JSX"
allImports = []
checkIfReactIsInScope = (node) ->
variables = variableUtil.variablesInScope context
return if variableUtil.findVariable variables, pragma
context.report {
node
message: NOT_DEFINED_MESSAGE
data:
name: pragma
fix: getFix {pragma, context, allImports}
}
ImportDeclaration: (node) -> allImports.push node
JSXOpeningElement: checkIfReactIsInScope
JSXOpeningFragment: checkIfReactIsInScope
| true | ###*
# @fileoverview Prevent missing React when using JSX
# @author PI:NAME:<NAME>END_PI
###
'use strict'
variableUtil = require 'eslint-plugin-react/lib/util/variable'
pragmaUtil = require 'eslint-plugin-react/lib/util/pragma'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# -----------------------------------------------------------------------------
# Rule Definition
# -----------------------------------------------------------------------------
getFix = ({pragma, context, allImports}) ->
return null unless pragma is 'React'
sourceCode = context.getSourceCode()
firstToken = sourceCode.getFirstToken sourceCode.ast
existingReactImport = allImports.find ({source: {value}}) -> value is 'react'
unless existingReactImport
return (fixer) ->
fixer.insertTextBefore firstToken, "import React from 'react'\n"
firstSpecifier = existingReactImport.specifiers[0]
openingBrace = sourceCode.getTokenBefore firstSpecifier
(fixer) -> fixer.insertTextBefore openingBrace, 'React, '
module.exports =
meta:
docs:
description: 'Prevent missing React when using JSX'
category: 'Possible Errors'
recommended: yes
url: docsUrl 'react-in-jsx-scope'
schema: []
fixable: 'code'
create: (context) ->
pragma = pragmaUtil.getFromContext context
NOT_DEFINED_MESSAGE = "'{{name}}' must be in scope when using JSX"
allImports = []
checkIfReactIsInScope = (node) ->
variables = variableUtil.variablesInScope context
return if variableUtil.findVariable variables, pragma
context.report {
node
message: NOT_DEFINED_MESSAGE
data:
name: pragma
fix: getFix {pragma, context, allImports}
}
ImportDeclaration: (node) -> allImports.push node
JSXOpeningElement: checkIfReactIsInScope
JSXOpeningFragment: checkIfReactIsInScope
|
[
{
"context": "e '#clone()', ->\n a =\n 'name': 'Jim'\n 'age': 18\n 'score': \n ",
"end": 5069,
"score": 0.9995874762535095,
"start": 5066,
"tag": "NAME",
"value": "Jim"
},
{
"context": "e(a)\n\n b.should.have.property('name', 'Jim')\n b.should.have.property('age', 18)\n ",
"end": 5317,
"score": 0.9996997117996216,
"start": 5314,
"tag": "NAME",
"value": "Jim"
},
{
"context": "ep')\n\n b.should.have.property('name', 'Jim')\n b.should.have.property('age', 18)\n ",
"end": 5543,
"score": 0.9997999668121338,
"start": 5540,
"tag": "NAME",
"value": "Jim"
}
] | test/MObjectUtilSpec.coffee | zhongxingdou/mayjs | 0 | describe 'MObjectUtil', ->
util = require('../may.js').MObjectUtil
describe '#isPrivate()', ->
it 'should assert a name whether it can be a private method name', ->
isPrivate = util.isPrivate.bind util
isPrivate('__fn').should.be.true
isPrivate('__').should.be.true
isPrivate('_fn').should.be.false
isPrivate('_fn__').should.be.false
isPrivate('fn').should.be.false
isPrivate('fn__').should.be.false
describe '#isProtected()', ->
it 'should assert a name whether it can be a protected method name', ->
isProtected = util.isProtected.bind util
isProtected('_fn').should.be.true
isProtected('_').should.be.true
isProtected('__fn').should.be.false
isProtected('fn').should.be.false
isProtected('fn_').should.be.false
describe '#isPublic()', ->
it 'should assert a name whether it can be a public method name', ->
isPublic = util.isPublic.bind util
isPublic('fn').should.be.true
isPublic('fn__').should.be.true
isPublic('fn_').should.be.true
isPublic('__fn').should.be.false
isPublic('_fn').should.be.false
describe '#has()', ->
has = util.has
it 'should assert an object whether it has a property with given name', ->
o = 'p' : {}
has(o, 'p').should.be.true
has(o, 'toString').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: {}
has(a, 'b.c.d').should.be.true
b =
a:
__proto__:
d: {}
has(a, 'a.d').should.be.false
describe "#can()", ->
it 'should assert an object whether it have a method with given name', ->
can = util.can
o = 'doAction' : ->
can(o, 'doAction').should.be.true
can(o, 'doAny').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: ->
util.can(a, 'b.c.d').should.be.true
util.can(a, 'b.c').should.be.false
describe "#eachAll()", ->
it 'should each every member of an object unless it is not enumerably', ->
eachAll = util.eachAll
o =
'p1': {}
'p2': {}
keys = []
members = []
eachAll o, (k, v) ->
keys.push k
members.push v
keys.should.containEql 'p1'
members[0].should.equal o.p1
keys.should.containEql 'p2'
members[1].should.equal o.p2
keys.should.not.containEql 'pOther'
keys.should.not.containEql 'toString'
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
keys = []
eachAll obj, (k, v) ->
keys.push k
keys.should.containEql 'baseFn'
keys.should.containEql 'ownFn'
describe "#eachOwn()", ->
it 'should each every own member of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
eachOwn = util.eachOwn.bind util
keys = []
eachOwn obj, (k, v) ->
keys.push k
keys.should.containEql('ownFn')
keys.should.not.containEql('baseFn')
describe '#eachProp()', ->
it 'should each every property of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
'baseP': {}
obj = new clazz
obj.ownFn = ->
obj.ownP = {}
eachProp = util.eachProp.bind util
keys = []
eachProp obj, (k, v) ->
keys.push k
keys.should.containEql 'ownP'
keys.should.not.containEql 'baseP'
keys.should.not.containEql 'ownFn'
keys.should.not.containEql 'baseFn'
describe '#traverseChain()', ->
it 'should traversing value chain using specify property', ->
a = name: 'a'
b =
name: 'b'
parent : a
c =
parent : b
name: 'c'
d =
parent : c
name: 'd'
traverseChain = util.traverseChain
keys = []
traverseChain d, 'parent', (parent) ->
keys.push parent
keys[0].should.equal c
keys[1].should.equal b
keys[2].should.equal a
describe '#clone()', ->
a =
'name': 'Jim'
'age': 18
'score':
'math': 98
'english': 77
clone = util.clone
it 'should shadow clone object', ->
b = clone(a)
b.should.have.property('name', 'Jim')
b.should.have.property('age', 18)
b.should.have.property('score', a.score)
it 'should deep clone object', ->
b = clone(a, 'deep')
b.should.have.property('name', 'Jim')
b.should.have.property('age', 18)
b.score.should.not.equal('score', a.score)
b.score.math.should.equal(a.score.math)
it 'should shadow clone an array', ->
now = new Date()
o = {}
array = [1, o, now]
b = clone(array)
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.equal(o)
b[2].should.equal(now)
it 'should deep clone an array', ->
now = new Date()
o = {name: 'o'}
array = [1, o, now]
op = {name: 'op'}
array.ownProp = op
b = clone(array, 'deep')
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.not.equal(o)
b[1].should.have.property('name', 'o')
b[2].should.not.equal(now)
b[2].getTime().should.equal(now.getTime())
b.should.have.property('ownProp')
b.ownProp.should.not.equal(op)
b.ownProp.should.have.property('name', op.name)
describe '#mix()', ->
mix = util.mix
src =
dollars: 8
pounds: 9
dest = {}
beforeEach ->
dest = {}
it 'should mix source to destination', ->
mix(dest, src)
dest.should.have.property('dollars', 8)
dest.should.have.property('pounds', 9)
it 'should mix source to destination unless member be in whitelist', ->
mix(dest, src, ['pounds'])
dest.should.have.property('dollars')
dest.should.not.have.property('pounds')
describe '#merge(a, b, c, d)', ->
it 'should merge a to b, and merge to c, and merge to d', ->
merge = util.merge
a = a : {}
b = b : {}
c = c : {}
d = d : {}
o = merge(a, b, c, d)
o.should.have.property('a')
o.should.have.property('b')
o.should.have.property('c')
o.should.have.property('d')
o.should.not.eql(a)
| 183394 | describe 'MObjectUtil', ->
util = require('../may.js').MObjectUtil
describe '#isPrivate()', ->
it 'should assert a name whether it can be a private method name', ->
isPrivate = util.isPrivate.bind util
isPrivate('__fn').should.be.true
isPrivate('__').should.be.true
isPrivate('_fn').should.be.false
isPrivate('_fn__').should.be.false
isPrivate('fn').should.be.false
isPrivate('fn__').should.be.false
describe '#isProtected()', ->
it 'should assert a name whether it can be a protected method name', ->
isProtected = util.isProtected.bind util
isProtected('_fn').should.be.true
isProtected('_').should.be.true
isProtected('__fn').should.be.false
isProtected('fn').should.be.false
isProtected('fn_').should.be.false
describe '#isPublic()', ->
it 'should assert a name whether it can be a public method name', ->
isPublic = util.isPublic.bind util
isPublic('fn').should.be.true
isPublic('fn__').should.be.true
isPublic('fn_').should.be.true
isPublic('__fn').should.be.false
isPublic('_fn').should.be.false
describe '#has()', ->
has = util.has
it 'should assert an object whether it has a property with given name', ->
o = 'p' : {}
has(o, 'p').should.be.true
has(o, 'toString').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: {}
has(a, 'b.c.d').should.be.true
b =
a:
__proto__:
d: {}
has(a, 'a.d').should.be.false
describe "#can()", ->
it 'should assert an object whether it have a method with given name', ->
can = util.can
o = 'doAction' : ->
can(o, 'doAction').should.be.true
can(o, 'doAny').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: ->
util.can(a, 'b.c.d').should.be.true
util.can(a, 'b.c').should.be.false
describe "#eachAll()", ->
it 'should each every member of an object unless it is not enumerably', ->
eachAll = util.eachAll
o =
'p1': {}
'p2': {}
keys = []
members = []
eachAll o, (k, v) ->
keys.push k
members.push v
keys.should.containEql 'p1'
members[0].should.equal o.p1
keys.should.containEql 'p2'
members[1].should.equal o.p2
keys.should.not.containEql 'pOther'
keys.should.not.containEql 'toString'
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
keys = []
eachAll obj, (k, v) ->
keys.push k
keys.should.containEql 'baseFn'
keys.should.containEql 'ownFn'
describe "#eachOwn()", ->
it 'should each every own member of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
eachOwn = util.eachOwn.bind util
keys = []
eachOwn obj, (k, v) ->
keys.push k
keys.should.containEql('ownFn')
keys.should.not.containEql('baseFn')
describe '#eachProp()', ->
it 'should each every property of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
'baseP': {}
obj = new clazz
obj.ownFn = ->
obj.ownP = {}
eachProp = util.eachProp.bind util
keys = []
eachProp obj, (k, v) ->
keys.push k
keys.should.containEql 'ownP'
keys.should.not.containEql 'baseP'
keys.should.not.containEql 'ownFn'
keys.should.not.containEql 'baseFn'
describe '#traverseChain()', ->
it 'should traversing value chain using specify property', ->
a = name: 'a'
b =
name: 'b'
parent : a
c =
parent : b
name: 'c'
d =
parent : c
name: 'd'
traverseChain = util.traverseChain
keys = []
traverseChain d, 'parent', (parent) ->
keys.push parent
keys[0].should.equal c
keys[1].should.equal b
keys[2].should.equal a
describe '#clone()', ->
a =
'name': '<NAME>'
'age': 18
'score':
'math': 98
'english': 77
clone = util.clone
it 'should shadow clone object', ->
b = clone(a)
b.should.have.property('name', '<NAME>')
b.should.have.property('age', 18)
b.should.have.property('score', a.score)
it 'should deep clone object', ->
b = clone(a, 'deep')
b.should.have.property('name', '<NAME>')
b.should.have.property('age', 18)
b.score.should.not.equal('score', a.score)
b.score.math.should.equal(a.score.math)
it 'should shadow clone an array', ->
now = new Date()
o = {}
array = [1, o, now]
b = clone(array)
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.equal(o)
b[2].should.equal(now)
it 'should deep clone an array', ->
now = new Date()
o = {name: 'o'}
array = [1, o, now]
op = {name: 'op'}
array.ownProp = op
b = clone(array, 'deep')
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.not.equal(o)
b[1].should.have.property('name', 'o')
b[2].should.not.equal(now)
b[2].getTime().should.equal(now.getTime())
b.should.have.property('ownProp')
b.ownProp.should.not.equal(op)
b.ownProp.should.have.property('name', op.name)
describe '#mix()', ->
mix = util.mix
src =
dollars: 8
pounds: 9
dest = {}
beforeEach ->
dest = {}
it 'should mix source to destination', ->
mix(dest, src)
dest.should.have.property('dollars', 8)
dest.should.have.property('pounds', 9)
it 'should mix source to destination unless member be in whitelist', ->
mix(dest, src, ['pounds'])
dest.should.have.property('dollars')
dest.should.not.have.property('pounds')
describe '#merge(a, b, c, d)', ->
it 'should merge a to b, and merge to c, and merge to d', ->
merge = util.merge
a = a : {}
b = b : {}
c = c : {}
d = d : {}
o = merge(a, b, c, d)
o.should.have.property('a')
o.should.have.property('b')
o.should.have.property('c')
o.should.have.property('d')
o.should.not.eql(a)
| true | describe 'MObjectUtil', ->
util = require('../may.js').MObjectUtil
describe '#isPrivate()', ->
it 'should assert a name whether it can be a private method name', ->
isPrivate = util.isPrivate.bind util
isPrivate('__fn').should.be.true
isPrivate('__').should.be.true
isPrivate('_fn').should.be.false
isPrivate('_fn__').should.be.false
isPrivate('fn').should.be.false
isPrivate('fn__').should.be.false
describe '#isProtected()', ->
it 'should assert a name whether it can be a protected method name', ->
isProtected = util.isProtected.bind util
isProtected('_fn').should.be.true
isProtected('_').should.be.true
isProtected('__fn').should.be.false
isProtected('fn').should.be.false
isProtected('fn_').should.be.false
describe '#isPublic()', ->
it 'should assert a name whether it can be a public method name', ->
isPublic = util.isPublic.bind util
isPublic('fn').should.be.true
isPublic('fn__').should.be.true
isPublic('fn_').should.be.true
isPublic('__fn').should.be.false
isPublic('_fn').should.be.false
describe '#has()', ->
has = util.has
it 'should assert an object whether it has a property with given name', ->
o = 'p' : {}
has(o, 'p').should.be.true
has(o, 'toString').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: {}
has(a, 'b.c.d').should.be.true
b =
a:
__proto__:
d: {}
has(a, 'a.d').should.be.false
describe "#can()", ->
it 'should assert an object whether it have a method with given name', ->
can = util.can
o = 'doAction' : ->
can(o, 'doAction').should.be.true
can(o, 'doAny').should.be.false
it 'should supported namepath like a.b.c', ->
a =
b:
c:
d: ->
util.can(a, 'b.c.d').should.be.true
util.can(a, 'b.c').should.be.false
describe "#eachAll()", ->
it 'should each every member of an object unless it is not enumerably', ->
eachAll = util.eachAll
o =
'p1': {}
'p2': {}
keys = []
members = []
eachAll o, (k, v) ->
keys.push k
members.push v
keys.should.containEql 'p1'
members[0].should.equal o.p1
keys.should.containEql 'p2'
members[1].should.equal o.p2
keys.should.not.containEql 'pOther'
keys.should.not.containEql 'toString'
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
keys = []
eachAll obj, (k, v) ->
keys.push k
keys.should.containEql 'baseFn'
keys.should.containEql 'ownFn'
describe "#eachOwn()", ->
it 'should each every own member of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
obj = new clazz
obj.ownFn = ->
eachOwn = util.eachOwn.bind util
keys = []
eachOwn obj, (k, v) ->
keys.push k
keys.should.containEql('ownFn')
keys.should.not.containEql('baseFn')
describe '#eachProp()', ->
it 'should each every property of an object unless it is not enumerably', ->
clazz = ->
clazz.prototype =
'baseFn': ->
'baseP': {}
obj = new clazz
obj.ownFn = ->
obj.ownP = {}
eachProp = util.eachProp.bind util
keys = []
eachProp obj, (k, v) ->
keys.push k
keys.should.containEql 'ownP'
keys.should.not.containEql 'baseP'
keys.should.not.containEql 'ownFn'
keys.should.not.containEql 'baseFn'
describe '#traverseChain()', ->
it 'should traversing value chain using specify property', ->
a = name: 'a'
b =
name: 'b'
parent : a
c =
parent : b
name: 'c'
d =
parent : c
name: 'd'
traverseChain = util.traverseChain
keys = []
traverseChain d, 'parent', (parent) ->
keys.push parent
keys[0].should.equal c
keys[1].should.equal b
keys[2].should.equal a
describe '#clone()', ->
a =
'name': 'PI:NAME:<NAME>END_PI'
'age': 18
'score':
'math': 98
'english': 77
clone = util.clone
it 'should shadow clone object', ->
b = clone(a)
b.should.have.property('name', 'PI:NAME:<NAME>END_PI')
b.should.have.property('age', 18)
b.should.have.property('score', a.score)
it 'should deep clone object', ->
b = clone(a, 'deep')
b.should.have.property('name', 'PI:NAME:<NAME>END_PI')
b.should.have.property('age', 18)
b.score.should.not.equal('score', a.score)
b.score.math.should.equal(a.score.math)
it 'should shadow clone an array', ->
now = new Date()
o = {}
array = [1, o, now]
b = clone(array)
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.equal(o)
b[2].should.equal(now)
it 'should deep clone an array', ->
now = new Date()
o = {name: 'o'}
array = [1, o, now]
op = {name: 'op'}
array.ownProp = op
b = clone(array, 'deep')
b.should.not.equal(array)
b.length.should.equal(3)
b[0].should.equal(1)
b[1].should.not.equal(o)
b[1].should.have.property('name', 'o')
b[2].should.not.equal(now)
b[2].getTime().should.equal(now.getTime())
b.should.have.property('ownProp')
b.ownProp.should.not.equal(op)
b.ownProp.should.have.property('name', op.name)
describe '#mix()', ->
mix = util.mix
src =
dollars: 8
pounds: 9
dest = {}
beforeEach ->
dest = {}
it 'should mix source to destination', ->
mix(dest, src)
dest.should.have.property('dollars', 8)
dest.should.have.property('pounds', 9)
it 'should mix source to destination unless member be in whitelist', ->
mix(dest, src, ['pounds'])
dest.should.have.property('dollars')
dest.should.not.have.property('pounds')
describe '#merge(a, b, c, d)', ->
it 'should merge a to b, and merge to c, and merge to d', ->
merge = util.merge
a = a : {}
b = b : {}
c = c : {}
d = d : {}
o = merge(a, b, c, d)
o.should.have.property('a')
o.should.have.property('b')
o.should.have.property('c')
o.should.have.property('d')
o.should.not.eql(a)
|
[
{
"context": "Administrator({name: name, email: email, password: password})\n administrator.save((error) ->\n\n if err",
"end": 1000,
"score": 0.9983704686164856,
"start": 992,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "tor.email = email\n administrator.password = password\n\n administrator.save((error) ->\n\n ",
"end": 1515,
"score": 0.9986112117767334,
"start": 1507,
"tag": "PASSWORD",
"value": "password"
}
] | server/controllers/management/administrators.coffee | gertu/gertu | 1 | mongoose = require 'mongoose'
Administrator = mongoose.model 'Administrator'
exports.list = (req, res) ->
Administrator.find({}).exec( (err, administrators) ->
if err
res.status(500).send('Database error')
else
res.render 'pages/management/administrators/list', {administrators: administrators}
)
exports.add = (req, res) ->
administrator =
_id: 0,
name: '',
email: '',
password: ''
res.render 'pages/management/administrators/edit', {administrator: administrator}
exports.edit = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/edit', {administrator: administrator}
)
exports.editDo = (req, res) ->
id = req.params.id
name = req.body.name
email = req.body.email
password = req.body.password
if id == '0'
administrator = new Administrator({name: name, email: email, password: password})
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit', {administrator: administrator, errors: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
else
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err? or not administrator?
res.status(404)
else
administrator.name = name
administrator.email = email
administrator.password = password
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit/' + administrator._id ,
{administrator: administrator, errorMsg: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
)
exports.remove = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/remove', {administrator: administrator}
)
exports.removeDo = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
administrator.remove(()->
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
) | 221101 | mongoose = require 'mongoose'
Administrator = mongoose.model 'Administrator'
exports.list = (req, res) ->
Administrator.find({}).exec( (err, administrators) ->
if err
res.status(500).send('Database error')
else
res.render 'pages/management/administrators/list', {administrators: administrators}
)
exports.add = (req, res) ->
administrator =
_id: 0,
name: '',
email: '',
password: ''
res.render 'pages/management/administrators/edit', {administrator: administrator}
exports.edit = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/edit', {administrator: administrator}
)
exports.editDo = (req, res) ->
id = req.params.id
name = req.body.name
email = req.body.email
password = req.body.password
if id == '0'
administrator = new Administrator({name: name, email: email, password: <PASSWORD>})
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit', {administrator: administrator, errors: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
else
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err? or not administrator?
res.status(404)
else
administrator.name = name
administrator.email = email
administrator.password = <PASSWORD>
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit/' + administrator._id ,
{administrator: administrator, errorMsg: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
)
exports.remove = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/remove', {administrator: administrator}
)
exports.removeDo = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
administrator.remove(()->
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
) | true | mongoose = require 'mongoose'
Administrator = mongoose.model 'Administrator'
exports.list = (req, res) ->
Administrator.find({}).exec( (err, administrators) ->
if err
res.status(500).send('Database error')
else
res.render 'pages/management/administrators/list', {administrators: administrators}
)
exports.add = (req, res) ->
administrator =
_id: 0,
name: '',
email: '',
password: ''
res.render 'pages/management/administrators/edit', {administrator: administrator}
exports.edit = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/edit', {administrator: administrator}
)
exports.editDo = (req, res) ->
id = req.params.id
name = req.body.name
email = req.body.email
password = req.body.password
if id == '0'
administrator = new Administrator({name: name, email: email, password: PI:PASSWORD:<PASSWORD>END_PI})
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit', {administrator: administrator, errors: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
else
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err? or not administrator?
res.status(404)
else
administrator.name = name
administrator.email = email
administrator.password = PI:PASSWORD:<PASSWORD>END_PI
administrator.save((error) ->
if error?
res.render 'pages/management/administrators/edit/' + administrator._id ,
{administrator: administrator, errorMsg: error.errors}
else
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
)
exports.remove = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
res.render 'pages/management/administrators/remove', {administrator: administrator}
)
exports.removeDo = (req, res) ->
id = req.params.id
Administrator.findOne({_id: id}).exec( (err, administrator) ->
if err
res.status(404)
else
administrator.remove(()->
res.redirect '/management/administrators/list?rnd=' + Math.random()
)
) |
[
{
"context": "'spark'\n @loginPromise = spark.login { username:@email, password:@password }\n @loginPromise.done (e) ",
"end": 4819,
"score": 0.6753714084625244,
"start": 4813,
"tag": "USERNAME",
"value": "@email"
},
{
"context": "nPromise = spark.login { username:@email, password:@password }\n @loginPromise.done (e) =>\n @spinner.ad",
"end": 4839,
"score": 0.9459707140922546,
"start": 4830,
"tag": "PASSWORD",
"value": "@password"
}
] | lib/views/login-view.coffee | lukehoban/spark-dev | 1 | {View, TextEditorView} = require 'atom'
$ = null
_s = null
Subscriber = null
spark = null
SettingsHelper = null
validator = null
module.exports =
class LoginView extends View
@content: ->
@div id: 'spark-dev-login-view', class: 'overlay from-top', =>
@div class: 'block', =>
@span 'Log in to Spark Cloud '
@span class: 'text-subtle', =>
@text 'Close this dialog with the '
@span class: 'highlight', 'esc'
@span ' key'
@subview 'emailEditor', new TextEditorView(mini: true, placeholderText: 'Could I please have an email address?')
@subview 'passwordEditor', new TextEditorView(mini: true, placeholderText: 'and a password?')
@div class: 'text-error block', outlet: 'errorLabel'
@div class: 'block', =>
@button click: 'login', id: 'loginButton', class: 'btn btn-primary', outlet: 'loginButton', 'Log in'
@button click: 'cancel', id: 'cancelButton', class: 'btn', outlet: 'cancelButton', 'Cancel'
@span class: 'three-quarters inline-block hidden', outlet: 'spinner'
@a href: 'https://www.spark.io/forgot-password', class: 'pull-right', 'Forgot password?'
initialize: (serializeState) ->
{Subscriber} = require 'emissary'
$ ?= require('atom').$
_s ?= require 'underscore.string'
SettingsHelper = require '../utils/settings-helper'
@subscriber = new Subscriber()
@subscriber.subscribeToCommand atom.workspaceView, 'core:cancel core:close', ({target}) =>
atom.workspaceView.trigger 'spark-dev:cancel-login'
@loginPromise = null
# As Atom doesn't provide password input, we have to hack TextEditorView to act as one
#
# Known issues:
# * doesn't support pasting (it will show plain text)
# * doesn't work with multiple selections
@passwordEditor.originalText = ''
@passwordEditor.hiddenInput.on 'keypress', (e) =>
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column, String.fromCharCode(e.which))
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column, 0, String.fromCharCode(e.which))
@passwordEditor.insertText '*'
false
@passwordEditor.hiddenInput.on 'keydown', (e) =>
if e.which == 8
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column)
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column - 1, 1)
@passwordEditor.backspace
else if e.which == 13
@login()
true
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@remove()
show: =>
if !@hasParent()
atom.workspaceView.append(this)
@emailEditor.getEditor().setText ''
@passwordEditor.getEditor().setText ''
@passwordEditor.originalText = ''
@errorLabel.hide()
@emailEditor.focus()
hide: ->
if @hasParent()
@detach()
cancel: (event, element) =>
if !!@loginPromise
@loginPromise = null
@unlockUi()
@clearErrors()
@hide()
cancelCommand: ->
@cancel()
# Remove errors from inputs
clearErrors: ->
@emailEditor.removeClass 'editor-error'
@passwordEditor.removeClass 'editor-error'
# Test input's values
validateInputs: ->
validator ?= require 'validator'
@clearErrors()
@email = _s.trim(@emailEditor.getText())
@password = _s.trim(@passwordEditor.originalText)
isOk = true
if (@email == '') || (!validator.isEmail(@email))
@emailEditor.addClass 'editor-error'
isOk = false
if @password == ''
@passwordEditor.addClass 'editor-error'
isOk = false
isOk
# Unlock inputs and buttons
unlockUi: ->
@emailEditor.hiddenInput.removeAttr 'disabled'
@passwordEditor.hiddenInput.removeAttr 'disabled'
@loginButton.removeAttr 'disabled'
# Login via the cloud
login: (event, element) =>
if !@validateInputs()
return false
@emailEditor.hiddenInput.attr 'disabled', 'disabled'
@passwordEditor.hiddenInput.attr 'disabled', 'disabled'
@loginButton.attr 'disabled', 'disabled'
@spinner.removeClass 'hidden'
@errorLabel.hide()
spark = require 'spark'
@loginPromise = spark.login { username:@email, password:@password }
@loginPromise.done (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
SettingsHelper.setCredentials @email, e.access_token
atom.workspaceView.trigger 'spark-dev:update-login-status'
@loginPromise = null
@cancel()
, (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
@unlockUi()
if e.code == 'ENOTFOUND'
@errorLabel.text 'Error while connecting to ' + e.hostname
else if e.message == 'invalid_grant'
@errorLabel.text 'Invalid email or password'
else
@errorLabel.text e
@errorLabel.show()
@loginPromise = null
# Logout
logout: =>
SettingsHelper.clearCredentials()
atom.workspaceView.trigger 'spark-dev:update-login-status'
| 104084 | {View, TextEditorView} = require 'atom'
$ = null
_s = null
Subscriber = null
spark = null
SettingsHelper = null
validator = null
module.exports =
class LoginView extends View
@content: ->
@div id: 'spark-dev-login-view', class: 'overlay from-top', =>
@div class: 'block', =>
@span 'Log in to Spark Cloud '
@span class: 'text-subtle', =>
@text 'Close this dialog with the '
@span class: 'highlight', 'esc'
@span ' key'
@subview 'emailEditor', new TextEditorView(mini: true, placeholderText: 'Could I please have an email address?')
@subview 'passwordEditor', new TextEditorView(mini: true, placeholderText: 'and a password?')
@div class: 'text-error block', outlet: 'errorLabel'
@div class: 'block', =>
@button click: 'login', id: 'loginButton', class: 'btn btn-primary', outlet: 'loginButton', 'Log in'
@button click: 'cancel', id: 'cancelButton', class: 'btn', outlet: 'cancelButton', 'Cancel'
@span class: 'three-quarters inline-block hidden', outlet: 'spinner'
@a href: 'https://www.spark.io/forgot-password', class: 'pull-right', 'Forgot password?'
initialize: (serializeState) ->
{Subscriber} = require 'emissary'
$ ?= require('atom').$
_s ?= require 'underscore.string'
SettingsHelper = require '../utils/settings-helper'
@subscriber = new Subscriber()
@subscriber.subscribeToCommand atom.workspaceView, 'core:cancel core:close', ({target}) =>
atom.workspaceView.trigger 'spark-dev:cancel-login'
@loginPromise = null
# As Atom doesn't provide password input, we have to hack TextEditorView to act as one
#
# Known issues:
# * doesn't support pasting (it will show plain text)
# * doesn't work with multiple selections
@passwordEditor.originalText = ''
@passwordEditor.hiddenInput.on 'keypress', (e) =>
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column, String.fromCharCode(e.which))
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column, 0, String.fromCharCode(e.which))
@passwordEditor.insertText '*'
false
@passwordEditor.hiddenInput.on 'keydown', (e) =>
if e.which == 8
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column)
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column - 1, 1)
@passwordEditor.backspace
else if e.which == 13
@login()
true
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@remove()
show: =>
if !@hasParent()
atom.workspaceView.append(this)
@emailEditor.getEditor().setText ''
@passwordEditor.getEditor().setText ''
@passwordEditor.originalText = ''
@errorLabel.hide()
@emailEditor.focus()
hide: ->
if @hasParent()
@detach()
cancel: (event, element) =>
if !!@loginPromise
@loginPromise = null
@unlockUi()
@clearErrors()
@hide()
cancelCommand: ->
@cancel()
# Remove errors from inputs
clearErrors: ->
@emailEditor.removeClass 'editor-error'
@passwordEditor.removeClass 'editor-error'
# Test input's values
validateInputs: ->
validator ?= require 'validator'
@clearErrors()
@email = _s.trim(@emailEditor.getText())
@password = _s.trim(@passwordEditor.originalText)
isOk = true
if (@email == '') || (!validator.isEmail(@email))
@emailEditor.addClass 'editor-error'
isOk = false
if @password == ''
@passwordEditor.addClass 'editor-error'
isOk = false
isOk
# Unlock inputs and buttons
unlockUi: ->
@emailEditor.hiddenInput.removeAttr 'disabled'
@passwordEditor.hiddenInput.removeAttr 'disabled'
@loginButton.removeAttr 'disabled'
# Login via the cloud
login: (event, element) =>
if !@validateInputs()
return false
@emailEditor.hiddenInput.attr 'disabled', 'disabled'
@passwordEditor.hiddenInput.attr 'disabled', 'disabled'
@loginButton.attr 'disabled', 'disabled'
@spinner.removeClass 'hidden'
@errorLabel.hide()
spark = require 'spark'
@loginPromise = spark.login { username:@email, password:<PASSWORD> }
@loginPromise.done (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
SettingsHelper.setCredentials @email, e.access_token
atom.workspaceView.trigger 'spark-dev:update-login-status'
@loginPromise = null
@cancel()
, (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
@unlockUi()
if e.code == 'ENOTFOUND'
@errorLabel.text 'Error while connecting to ' + e.hostname
else if e.message == 'invalid_grant'
@errorLabel.text 'Invalid email or password'
else
@errorLabel.text e
@errorLabel.show()
@loginPromise = null
# Logout
logout: =>
SettingsHelper.clearCredentials()
atom.workspaceView.trigger 'spark-dev:update-login-status'
| true | {View, TextEditorView} = require 'atom'
$ = null
_s = null
Subscriber = null
spark = null
SettingsHelper = null
validator = null
module.exports =
class LoginView extends View
@content: ->
@div id: 'spark-dev-login-view', class: 'overlay from-top', =>
@div class: 'block', =>
@span 'Log in to Spark Cloud '
@span class: 'text-subtle', =>
@text 'Close this dialog with the '
@span class: 'highlight', 'esc'
@span ' key'
@subview 'emailEditor', new TextEditorView(mini: true, placeholderText: 'Could I please have an email address?')
@subview 'passwordEditor', new TextEditorView(mini: true, placeholderText: 'and a password?')
@div class: 'text-error block', outlet: 'errorLabel'
@div class: 'block', =>
@button click: 'login', id: 'loginButton', class: 'btn btn-primary', outlet: 'loginButton', 'Log in'
@button click: 'cancel', id: 'cancelButton', class: 'btn', outlet: 'cancelButton', 'Cancel'
@span class: 'three-quarters inline-block hidden', outlet: 'spinner'
@a href: 'https://www.spark.io/forgot-password', class: 'pull-right', 'Forgot password?'
initialize: (serializeState) ->
{Subscriber} = require 'emissary'
$ ?= require('atom').$
_s ?= require 'underscore.string'
SettingsHelper = require '../utils/settings-helper'
@subscriber = new Subscriber()
@subscriber.subscribeToCommand atom.workspaceView, 'core:cancel core:close', ({target}) =>
atom.workspaceView.trigger 'spark-dev:cancel-login'
@loginPromise = null
# As Atom doesn't provide password input, we have to hack TextEditorView to act as one
#
# Known issues:
# * doesn't support pasting (it will show plain text)
# * doesn't work with multiple selections
@passwordEditor.originalText = ''
@passwordEditor.hiddenInput.on 'keypress', (e) =>
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column, String.fromCharCode(e.which))
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column, 0, String.fromCharCode(e.which))
@passwordEditor.insertText '*'
false
@passwordEditor.hiddenInput.on 'keydown', (e) =>
if e.which == 8
editor = @passwordEditor.getEditor()
selection = editor.getSelectedBufferRange()
cursor = editor.getCursorBufferPosition()
if !selection.isEmpty()
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, selection.start.column, selection.end.column - selection.start.column)
else
@passwordEditor.originalText = _s.splice(@passwordEditor.originalText, cursor.column - 1, 1)
@passwordEditor.backspace
else if e.which == 13
@login()
true
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@remove()
show: =>
if !@hasParent()
atom.workspaceView.append(this)
@emailEditor.getEditor().setText ''
@passwordEditor.getEditor().setText ''
@passwordEditor.originalText = ''
@errorLabel.hide()
@emailEditor.focus()
hide: ->
if @hasParent()
@detach()
cancel: (event, element) =>
if !!@loginPromise
@loginPromise = null
@unlockUi()
@clearErrors()
@hide()
cancelCommand: ->
@cancel()
# Remove errors from inputs
clearErrors: ->
@emailEditor.removeClass 'editor-error'
@passwordEditor.removeClass 'editor-error'
# Test input's values
validateInputs: ->
validator ?= require 'validator'
@clearErrors()
@email = _s.trim(@emailEditor.getText())
@password = _s.trim(@passwordEditor.originalText)
isOk = true
if (@email == '') || (!validator.isEmail(@email))
@emailEditor.addClass 'editor-error'
isOk = false
if @password == ''
@passwordEditor.addClass 'editor-error'
isOk = false
isOk
# Unlock inputs and buttons
unlockUi: ->
@emailEditor.hiddenInput.removeAttr 'disabled'
@passwordEditor.hiddenInput.removeAttr 'disabled'
@loginButton.removeAttr 'disabled'
# Login via the cloud
login: (event, element) =>
if !@validateInputs()
return false
@emailEditor.hiddenInput.attr 'disabled', 'disabled'
@passwordEditor.hiddenInput.attr 'disabled', 'disabled'
@loginButton.attr 'disabled', 'disabled'
@spinner.removeClass 'hidden'
@errorLabel.hide()
spark = require 'spark'
@loginPromise = spark.login { username:@email, password:PI:PASSWORD:<PASSWORD>END_PI }
@loginPromise.done (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
SettingsHelper.setCredentials @email, e.access_token
atom.workspaceView.trigger 'spark-dev:update-login-status'
@loginPromise = null
@cancel()
, (e) =>
@spinner.addClass 'hidden'
if !@loginPromise
return
@unlockUi()
if e.code == 'ENOTFOUND'
@errorLabel.text 'Error while connecting to ' + e.hostname
else if e.message == 'invalid_grant'
@errorLabel.text 'Invalid email or password'
else
@errorLabel.text e
@errorLabel.show()
@loginPromise = null
# Logout
logout: =>
SettingsHelper.clearCredentials()
atom.workspaceView.trigger 'spark-dev:update-login-status'
|
[
{
"context": "hListView\":\n \"core:confirm\": \"Umieść w poczekalni\"\n \"github:resolve-file-as-ours\": \"Rozwiąż konf",
"end": 8026,
"score": 0.6036476492881775,
"start": 8024,
"tag": "NAME",
"value": "ni"
}
] | def/pl/context.cson | Vegebutcher/atom-i18n | 0 | Context:
"atom-workspace":
"application:inspect": "Zbadaj element"
"atom-text-editor":
"color-picker:open": "Próbnik koloru"
"minimap:toggle": "Przełącz minimapę"
# added for atom/bookmarks
"bookmarks:toggle-bookmark": "Przełącz zakładkę"
"atom-text-editor, .overlayer":
"core:undo": "Cofnij"
"core:redo": "Ponów"
"core:cut": "Wytnij"
"core:copy": "Kopiuj"
"core:paste": "Wklej"
"core:delete": "Skasuj"
"core:select-all": "Zaznacz wszystko"
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-pane":
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-text-editor:not([mini])":
"encoding-selector:show": "Zmień kodowanie"
"spell-check:correct-misspelling": "Popraw pisownię"
"symbols-view:go-to-declaration": "Idź do deklaracji"
".overlayer":
"grammar-selector:show": "Zmień składnię"
".image-view":
"image-view:reload": "Przeładuj obraz"
".tab":
"tabs:close-tab": "Zamknij kartę"
"tabs:close-other-tabs": "Zamknij inne karty"
"tabs:close-tabs-to-right": "Zamknij karty po prawej"
"tabs:close-tabs-to-left": "Zamknij karty po lewej"
"tabs:close-saved-tabs": "Zamknij zapisane karty"
"tabs:close-all-tabs": "Zamknij wszystkie karty"
"tabs:split-up": "Podziel na górze"
"tabs:split-down": "Podziel na dole"
"tabs:split-left": "Podziel po lewej"
"tabs:split-right": "Podziel po prawej"
".tab.texteditor":
"tabs:open-in-new-window": "Otwórz w nowym oknie"
".tab.pending-tab":
"tabs:keep-pending-tab": "Zachowaj oczekującą kartę"
".tab-bar":
"pane:reopen-closed-item": "Otwórz zamkniętą kartę"
".tree-view .full-menu":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
'.tree-view .full-menu [is="tree-view-file"]':
"tree-view:open-selected-entry-up": "Podziel na górze"
"tree-view:open-selected-entry-down": "Podziel na dole"
"tree-view:open-selected-entry-left": "Podziel po lewej"
"tree-view:open-selected-entry-right": "Podziel po prawej"
".tree-view .full-menu .project-root > .header":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:remove-project-folder": "Usuń folder projektu"
# added for atom/tree-view
"tree-view:collapse-all": "Zwiń wszystkie foldery projektów"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
".platform-darwin .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Finderze"
".platform-win32 .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w menedżerze plików"
# ".tree-view li.directory":
# "project-find:show-in-current-directory": "Szukaj w katalogu"
".tree-view .multi-select":
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
"atom-pane[data-active-item-path] .item-views":
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
"atom-pane[data-active-item-path] .tab.active":
"tree-view:rename": "Zmień nazwę"
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
".platform-darwin atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
".platform-darwin atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
# added for atom/find-and-replace
".tree-view li.directory":
"project-find:show-in-current-directory": "Szukaj w folderze"
".list-item.match-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"core:copy": "'Kopiuj"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
".list-item.path-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
# added for atom/github/menu/git.cson
".github-FilePatchListView-item":
"github:jump-to-file": "Przejdź do pliku"
".github-FilePatchView--staged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
".github-FilePatchView--unstaged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
"github:discard-selected-lines": "Odrzuć zaznaczone"
"github-DotComMarkdownHtml .issue-link":
"github:open-link-in-new-tab": "Otwórz w nowej karcie"
"github:open-link-in-this-tab": "Otwórz w tej karcie"
"github:open-link-in-browser": "Otwórz w przeglądarce"
".github-CommitView":
"github:toggle-expanded-commit-message-editor": "Przełącz rozszerzony edytor wiadomości zatwierdzenia"
".item-views > atom-text-editor":
"github:view-unstaged-changes-for-current-file": "Zobacz zmiany nieumieszczone w przechowalni"
"github:view-staged-changes-for-current-file": "Zobacz zmiany umieszczone w przechowalni"
".github-PushPull":
"github:fetch": "Pobierz"
"github:pull": "Pobierz i scal"
"github:push": "Wyślij"
"github:force-push": "Wymuś wysłanie"
".most-recent":
"github:amend-last-commit": "Popraw"
".github-RecentCommit":
"github:copy-commit-sha": "Skopiuj SHA zatwierdzenia"
"github:copy-commit-subject": "Skopiuj wiadomość zatwierdzenia"
# added for atom/github/lib/github-package.js
".github-UnstagedChanges .github-FilePatchListView":
"core:confirm": "Umieść w poczekalni"
"github:discard-changes-in-selected-files": "Odrzuć zmiany"
".github-StagedChanges .github-FilePatchListView":
"core:confirm": "Usuń z poczekalni"
".github-MergeConflictPaths .github-FilePatchListView":
"core:confirm": "Umieść w poczekalni"
"github:resolve-file-as-ours": "Rozwiąż konflikt na swoją korzyść"
"github:resolve-file-as-theirs": "Rozwiąż konflikt na ich korzyść"
# added for packages/link
"atom-text-editor .syntax--markup.syntax--underline.syntax--link":
"link:open": "Otwórz łącze"
# added for atom/markdown-preview
".markdown-preview":
"markdown-preview:select-all": "Zaznacz wszystko"
"core:save-as": "Zapisz jako HTML\u2026"
".markdown-preview.has-selection":
"core:copy": "Kopiuj"
".markdown-preview:not(.has-selection)":
"core:copy": "Kopiuj jako HTML"
".tree-view .file .name[data-name$=\\.markdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.md]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkd]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.ron]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.txt]":
"markdown-preview:preview-file": "Podgląd Markdown"
| 591 | Context:
"atom-workspace":
"application:inspect": "Zbadaj element"
"atom-text-editor":
"color-picker:open": "Próbnik koloru"
"minimap:toggle": "Przełącz minimapę"
# added for atom/bookmarks
"bookmarks:toggle-bookmark": "Przełącz zakładkę"
"atom-text-editor, .overlayer":
"core:undo": "Cofnij"
"core:redo": "Ponów"
"core:cut": "Wytnij"
"core:copy": "Kopiuj"
"core:paste": "Wklej"
"core:delete": "Skasuj"
"core:select-all": "Zaznacz wszystko"
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-pane":
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-text-editor:not([mini])":
"encoding-selector:show": "Zmień kodowanie"
"spell-check:correct-misspelling": "Popraw pisownię"
"symbols-view:go-to-declaration": "Idź do deklaracji"
".overlayer":
"grammar-selector:show": "Zmień składnię"
".image-view":
"image-view:reload": "Przeładuj obraz"
".tab":
"tabs:close-tab": "Zamknij kartę"
"tabs:close-other-tabs": "Zamknij inne karty"
"tabs:close-tabs-to-right": "Zamknij karty po prawej"
"tabs:close-tabs-to-left": "Zamknij karty po lewej"
"tabs:close-saved-tabs": "Zamknij zapisane karty"
"tabs:close-all-tabs": "Zamknij wszystkie karty"
"tabs:split-up": "Podziel na górze"
"tabs:split-down": "Podziel na dole"
"tabs:split-left": "Podziel po lewej"
"tabs:split-right": "Podziel po prawej"
".tab.texteditor":
"tabs:open-in-new-window": "Otwórz w nowym oknie"
".tab.pending-tab":
"tabs:keep-pending-tab": "Zachowaj oczekującą kartę"
".tab-bar":
"pane:reopen-closed-item": "Otwórz zamkniętą kartę"
".tree-view .full-menu":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
'.tree-view .full-menu [is="tree-view-file"]':
"tree-view:open-selected-entry-up": "Podziel na górze"
"tree-view:open-selected-entry-down": "Podziel na dole"
"tree-view:open-selected-entry-left": "Podziel po lewej"
"tree-view:open-selected-entry-right": "Podziel po prawej"
".tree-view .full-menu .project-root > .header":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:remove-project-folder": "Usuń folder projektu"
# added for atom/tree-view
"tree-view:collapse-all": "Zwiń wszystkie foldery projektów"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
".platform-darwin .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Finderze"
".platform-win32 .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w menedżerze plików"
# ".tree-view li.directory":
# "project-find:show-in-current-directory": "Szukaj w katalogu"
".tree-view .multi-select":
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
"atom-pane[data-active-item-path] .item-views":
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
"atom-pane[data-active-item-path] .tab.active":
"tree-view:rename": "Zmień nazwę"
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
".platform-darwin atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
".platform-darwin atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
# added for atom/find-and-replace
".tree-view li.directory":
"project-find:show-in-current-directory": "Szukaj w folderze"
".list-item.match-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"core:copy": "'Kopiuj"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
".list-item.path-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
# added for atom/github/menu/git.cson
".github-FilePatchListView-item":
"github:jump-to-file": "Przejdź do pliku"
".github-FilePatchView--staged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
".github-FilePatchView--unstaged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
"github:discard-selected-lines": "Odrzuć zaznaczone"
"github-DotComMarkdownHtml .issue-link":
"github:open-link-in-new-tab": "Otwórz w nowej karcie"
"github:open-link-in-this-tab": "Otwórz w tej karcie"
"github:open-link-in-browser": "Otwórz w przeglądarce"
".github-CommitView":
"github:toggle-expanded-commit-message-editor": "Przełącz rozszerzony edytor wiadomości zatwierdzenia"
".item-views > atom-text-editor":
"github:view-unstaged-changes-for-current-file": "Zobacz zmiany nieumieszczone w przechowalni"
"github:view-staged-changes-for-current-file": "Zobacz zmiany umieszczone w przechowalni"
".github-PushPull":
"github:fetch": "Pobierz"
"github:pull": "Pobierz i scal"
"github:push": "Wyślij"
"github:force-push": "Wymuś wysłanie"
".most-recent":
"github:amend-last-commit": "Popraw"
".github-RecentCommit":
"github:copy-commit-sha": "Skopiuj SHA zatwierdzenia"
"github:copy-commit-subject": "Skopiuj wiadomość zatwierdzenia"
# added for atom/github/lib/github-package.js
".github-UnstagedChanges .github-FilePatchListView":
"core:confirm": "Umieść w poczekalni"
"github:discard-changes-in-selected-files": "Odrzuć zmiany"
".github-StagedChanges .github-FilePatchListView":
"core:confirm": "Usuń z poczekalni"
".github-MergeConflictPaths .github-FilePatchListView":
"core:confirm": "Umieść w poczekal<NAME>"
"github:resolve-file-as-ours": "Rozwiąż konflikt na swoją korzyść"
"github:resolve-file-as-theirs": "Rozwiąż konflikt na ich korzyść"
# added for packages/link
"atom-text-editor .syntax--markup.syntax--underline.syntax--link":
"link:open": "Otwórz łącze"
# added for atom/markdown-preview
".markdown-preview":
"markdown-preview:select-all": "Zaznacz wszystko"
"core:save-as": "Zapisz jako HTML\u2026"
".markdown-preview.has-selection":
"core:copy": "Kopiuj"
".markdown-preview:not(.has-selection)":
"core:copy": "Kopiuj jako HTML"
".tree-view .file .name[data-name$=\\.markdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.md]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkd]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.ron]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.txt]":
"markdown-preview:preview-file": "Podgląd Markdown"
| true | Context:
"atom-workspace":
"application:inspect": "Zbadaj element"
"atom-text-editor":
"color-picker:open": "Próbnik koloru"
"minimap:toggle": "Przełącz minimapę"
# added for atom/bookmarks
"bookmarks:toggle-bookmark": "Przełącz zakładkę"
"atom-text-editor, .overlayer":
"core:undo": "Cofnij"
"core:redo": "Ponów"
"core:cut": "Wytnij"
"core:copy": "Kopiuj"
"core:paste": "Wklej"
"core:delete": "Skasuj"
"core:select-all": "Zaznacz wszystko"
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-pane":
"pane:split-up-and-copy-active-item": "Podziel na górze"
"pane:split-down-and-copy-active-item": "Podziel na dole"
"pane:split-left-and-copy-active-item": "Podziel po lewej"
"pane:split-right-and-copy-active-item": "Podziel po prawej"
"pane:close": "Zamknij panel"
"atom-text-editor:not([mini])":
"encoding-selector:show": "Zmień kodowanie"
"spell-check:correct-misspelling": "Popraw pisownię"
"symbols-view:go-to-declaration": "Idź do deklaracji"
".overlayer":
"grammar-selector:show": "Zmień składnię"
".image-view":
"image-view:reload": "Przeładuj obraz"
".tab":
"tabs:close-tab": "Zamknij kartę"
"tabs:close-other-tabs": "Zamknij inne karty"
"tabs:close-tabs-to-right": "Zamknij karty po prawej"
"tabs:close-tabs-to-left": "Zamknij karty po lewej"
"tabs:close-saved-tabs": "Zamknij zapisane karty"
"tabs:close-all-tabs": "Zamknij wszystkie karty"
"tabs:split-up": "Podziel na górze"
"tabs:split-down": "Podziel na dole"
"tabs:split-left": "Podziel po lewej"
"tabs:split-right": "Podziel po prawej"
".tab.texteditor":
"tabs:open-in-new-window": "Otwórz w nowym oknie"
".tab.pending-tab":
"tabs:keep-pending-tab": "Zachowaj oczekującą kartę"
".tab-bar":
"pane:reopen-closed-item": "Otwórz zamkniętą kartę"
".tree-view .full-menu":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
'.tree-view .full-menu [is="tree-view-file"]':
"tree-view:open-selected-entry-up": "Podziel na górze"
"tree-view:open-selected-entry-down": "Podziel na dole"
"tree-view:open-selected-entry-left": "Podziel po lewej"
"tree-view:open-selected-entry-right": "Podziel po prawej"
".tree-view .full-menu .project-root > .header":
"tree-view:add-file": "Nowy plik"
"tree-view:add-folder": "Nowy folder"
"tree-view:move": "Zmień nazwę"
"tree-view:duplicate": "Powiel"
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
# "tree-view:open-selected-entry-up": "Podziel na górze"
# "tree-view:open-selected-entry-down": "Podziel na dole"
# "tree-view:open-selected-entry-left": "Podziel po lewej"
# "tree-view:open-selected-entry-right": "Podziel po prawej"
"application:add-project-folder": "Dodaj folder projektu"
"tree-view:remove-project-folder": "Usuń folder projektu"
# added for atom/tree-view
"tree-view:collapse-all": "Zwiń wszystkie foldery projektów"
"tree-view:copy-full-path": "Skopiuj pełną ścieżkę"
"tree-view:copy-project-path": "Skopiuj ścieżkę projektu"
"tree-view:open-in-new-window": "Otwórz w nowym oknie"
".platform-darwin .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Finderze"
".platform-win32 .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux .tree-view .full-menu":
"tree-view:show-in-file-manager": "Pokaż w menedżerze plików"
# ".tree-view li.directory":
# "project-find:show-in-current-directory": "Szukaj w katalogu"
".tree-view .multi-select":
"tree-view:remove": "Usuń"
"tree-view:copy": "Kopiuj"
"tree-view:cut": "Wytnij"
"tree-view:paste": "Wklej"
"atom-pane[data-active-item-path] .item-views":
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
"atom-pane[data-active-item-path] .tab.active":
"tree-view:rename": "Zmień nazwę"
"tree-view:reveal-active-file": "Pokaż w widoku drzewa"
".platform-darwin atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-pane[data-active-item-path] .tab.active":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
".platform-darwin atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Finderze"
".platform-win32 atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w Eksploratorze"
".platform-linux atom-text-editor:not([mini])":
"tree-view:show-current-file-in-file-manager": "Pokaż w menedżerze plików"
# added for atom/find-and-replace
".tree-view li.directory":
"project-find:show-in-current-directory": "Szukaj w folderze"
".list-item.match-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"core:copy": "'Kopiuj"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
".list-item.path-row":
"find-and-replace:open-in-new-tab": "Otwórz w nowej karcie"
"find-and-replace:copy-path": "Kopiuj ścieżkę"
# added for atom/github/menu/git.cson
".github-FilePatchListView-item":
"github:jump-to-file": "Przejdź do pliku"
".github-FilePatchView--staged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
".github-FilePatchView--unstaged":
"github:jump-to-file": "Przejdź do pliku"
"core:confirm": "Przenieś zaznaczone do przechowalni"
"github:discard-selected-lines": "Odrzuć zaznaczone"
"github-DotComMarkdownHtml .issue-link":
"github:open-link-in-new-tab": "Otwórz w nowej karcie"
"github:open-link-in-this-tab": "Otwórz w tej karcie"
"github:open-link-in-browser": "Otwórz w przeglądarce"
".github-CommitView":
"github:toggle-expanded-commit-message-editor": "Przełącz rozszerzony edytor wiadomości zatwierdzenia"
".item-views > atom-text-editor":
"github:view-unstaged-changes-for-current-file": "Zobacz zmiany nieumieszczone w przechowalni"
"github:view-staged-changes-for-current-file": "Zobacz zmiany umieszczone w przechowalni"
".github-PushPull":
"github:fetch": "Pobierz"
"github:pull": "Pobierz i scal"
"github:push": "Wyślij"
"github:force-push": "Wymuś wysłanie"
".most-recent":
"github:amend-last-commit": "Popraw"
".github-RecentCommit":
"github:copy-commit-sha": "Skopiuj SHA zatwierdzenia"
"github:copy-commit-subject": "Skopiuj wiadomość zatwierdzenia"
# added for atom/github/lib/github-package.js
".github-UnstagedChanges .github-FilePatchListView":
"core:confirm": "Umieść w poczekalni"
"github:discard-changes-in-selected-files": "Odrzuć zmiany"
".github-StagedChanges .github-FilePatchListView":
"core:confirm": "Usuń z poczekalni"
".github-MergeConflictPaths .github-FilePatchListView":
"core:confirm": "Umieść w poczekalPI:NAME:<NAME>END_PI"
"github:resolve-file-as-ours": "Rozwiąż konflikt na swoją korzyść"
"github:resolve-file-as-theirs": "Rozwiąż konflikt na ich korzyść"
# added for packages/link
"atom-text-editor .syntax--markup.syntax--underline.syntax--link":
"link:open": "Otwórz łącze"
# added for atom/markdown-preview
".markdown-preview":
"markdown-preview:select-all": "Zaznacz wszystko"
"core:save-as": "Zapisz jako HTML\u2026"
".markdown-preview.has-selection":
"core:copy": "Kopiuj"
".markdown-preview:not(.has-selection)":
"core:copy": "Kopiuj jako HTML"
".tree-view .file .name[data-name$=\\.markdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.md]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkd]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.mkdown]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.ron]":
"markdown-preview:preview-file": "Podgląd Markdown"
".tree-view .file .name[data-name$=\\.txt]":
"markdown-preview:preview-file": "Podgląd Markdown"
|
[
{
"context": ": $('#user_name').val()\n password: $('#password').val()\n }\n success: (r)->\n ",
"end": 1207,
"score": 0.8768926858901978,
"start": 1199,
"tag": "PASSWORD",
"value": "password"
}
] | static/coffee/www/reg.coffee | tonghuashuai/51xuehuahua | 0 | sec = 59
intval = null
getCaptcha =->
$.ajax({
url: '/j/captcha'
method: 'POST'
success: (r)->
$('#captcha').attr('src', "data:image/gif;base64,#{r.img}")
$('#key').val(r.key)
})
getSmsCode =->
$._ajax({
url: '/j/sms_code'
method: 'POST'
data: {
token: $('#token').val(),
key: $('#key').val(),
user_name: $('#user_name').val()
}
success: (r)->
$('#btn-sms-code').attr('disabled', 'true')
$('#btn-sms-code').addClass('disabled')
$('#btn-sms-code').val('已发送(60)')
intval = setInterval(countDown, 1000)
})
countDown = ->
if sec == 0
clearInterval(intval)
$('#btn-sms-code').removeAttr('disabled')
$('#btn-sms-code').removeClass('disabled')
$('#btn-sms-code').val('获取动态验证码')
sec = 59
else
$('#btn-sms-code').val("已发送(#{sec})")
sec--
$('form').submit (e)->
$._ajax({
url: '/j/reg'
method: 'POST'
data: {
sms_code: $('#sms_code').val(),
user_name: $('#user_name').val()
password: $('#password').val()
}
success: (r)->
window.locatin.href='/login'
})
e.preventDefault()
$(document).ready ->
getCaptcha()
$('#captcha').click ->
getCaptcha()
$('#btn-sms-code').click ->
getSmsCode()
| 148208 | sec = 59
intval = null
getCaptcha =->
$.ajax({
url: '/j/captcha'
method: 'POST'
success: (r)->
$('#captcha').attr('src', "data:image/gif;base64,#{r.img}")
$('#key').val(r.key)
})
getSmsCode =->
$._ajax({
url: '/j/sms_code'
method: 'POST'
data: {
token: $('#token').val(),
key: $('#key').val(),
user_name: $('#user_name').val()
}
success: (r)->
$('#btn-sms-code').attr('disabled', 'true')
$('#btn-sms-code').addClass('disabled')
$('#btn-sms-code').val('已发送(60)')
intval = setInterval(countDown, 1000)
})
countDown = ->
if sec == 0
clearInterval(intval)
$('#btn-sms-code').removeAttr('disabled')
$('#btn-sms-code').removeClass('disabled')
$('#btn-sms-code').val('获取动态验证码')
sec = 59
else
$('#btn-sms-code').val("已发送(#{sec})")
sec--
$('form').submit (e)->
$._ajax({
url: '/j/reg'
method: 'POST'
data: {
sms_code: $('#sms_code').val(),
user_name: $('#user_name').val()
password: $('#<PASSWORD>').val()
}
success: (r)->
window.locatin.href='/login'
})
e.preventDefault()
$(document).ready ->
getCaptcha()
$('#captcha').click ->
getCaptcha()
$('#btn-sms-code').click ->
getSmsCode()
| true | sec = 59
intval = null
getCaptcha =->
$.ajax({
url: '/j/captcha'
method: 'POST'
success: (r)->
$('#captcha').attr('src', "data:image/gif;base64,#{r.img}")
$('#key').val(r.key)
})
getSmsCode =->
$._ajax({
url: '/j/sms_code'
method: 'POST'
data: {
token: $('#token').val(),
key: $('#key').val(),
user_name: $('#user_name').val()
}
success: (r)->
$('#btn-sms-code').attr('disabled', 'true')
$('#btn-sms-code').addClass('disabled')
$('#btn-sms-code').val('已发送(60)')
intval = setInterval(countDown, 1000)
})
countDown = ->
if sec == 0
clearInterval(intval)
$('#btn-sms-code').removeAttr('disabled')
$('#btn-sms-code').removeClass('disabled')
$('#btn-sms-code').val('获取动态验证码')
sec = 59
else
$('#btn-sms-code').val("已发送(#{sec})")
sec--
$('form').submit (e)->
$._ajax({
url: '/j/reg'
method: 'POST'
data: {
sms_code: $('#sms_code').val(),
user_name: $('#user_name').val()
password: $('#PI:PASSWORD:<PASSWORD>END_PI').val()
}
success: (r)->
window.locatin.href='/login'
})
e.preventDefault()
$(document).ready ->
getCaptcha()
$('#captcha').click ->
getCaptcha()
$('#btn-sms-code').click ->
getSmsCode()
|
[
{
"context": "lection([\n new Backbone.Model({id: 2, name: \"Luccas Marks\", role_name: \"user\"})\n ])\n\n @myRegion = new",
"end": 429,
"score": 0.9997995495796204,
"start": 417,
"tag": "NAME",
"value": "Luccas Marks"
}
] | spec/javascripts/core/apps/admin/user-view.spec.coffee | houzelio/houzel | 2 | import UserView from 'javascripts/core/apps/admin/user-view'
import { AppChan } from 'javascripts/core/channels'
describe("Admin User View", () ->
MyRegion = Marionette.Region.extend({
el: '#setting-region'
})
beforeAll ->
$('#main-region').empty()
beforeEach ->
setFixtures(__html__['setting-region.html'])
myCollection = new Backbone.Collection([
new Backbone.Model({id: 2, name: "Luccas Marks", role_name: "user"})
])
@myRegion = new MyRegion
@myView = new UserView {collection: myCollection }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView.grid, 'showView').and.callThrough()
myRegion = new MyRegion
myRegion.show(@myView)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(1)
)
)
describe("when the user is an admin", () ->
beforeAll ->
@user = _.clone(gon.user)
gon.user.admin = true
afterAll ->
gon.user = @user
beforeEach ->
@myRegion.show(@myView)
it("allows to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(1)
)
describe("after showing the warn dialog", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpy('spy')
@myObject.listenTo(@myView, 'admin:remove:user', @spy)
@myView.$el.find('a[data-click="button_0"]').click()
it("triggers the Remove User event whether it's agreed ", () ->
$('button[data-bb-handler="confirm"]').click()
expect(@spy).toHaveBeenCalled()
)
it("does not trigger the Remove User event whether it's canceled", () ->
$('button[data-bb-handler="cancel"]').click()
expect(@spy).not.toHaveBeenCalled()
)
)
)
describe("when the user ain't an admin", () ->
it("allows not to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(0)
)
)
)
| 202593 | import UserView from 'javascripts/core/apps/admin/user-view'
import { AppChan } from 'javascripts/core/channels'
describe("Admin User View", () ->
MyRegion = Marionette.Region.extend({
el: '#setting-region'
})
beforeAll ->
$('#main-region').empty()
beforeEach ->
setFixtures(__html__['setting-region.html'])
myCollection = new Backbone.Collection([
new Backbone.Model({id: 2, name: "<NAME>", role_name: "user"})
])
@myRegion = new MyRegion
@myView = new UserView {collection: myCollection }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView.grid, 'showView').and.callThrough()
myRegion = new MyRegion
myRegion.show(@myView)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(1)
)
)
describe("when the user is an admin", () ->
beforeAll ->
@user = _.clone(gon.user)
gon.user.admin = true
afterAll ->
gon.user = @user
beforeEach ->
@myRegion.show(@myView)
it("allows to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(1)
)
describe("after showing the warn dialog", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpy('spy')
@myObject.listenTo(@myView, 'admin:remove:user', @spy)
@myView.$el.find('a[data-click="button_0"]').click()
it("triggers the Remove User event whether it's agreed ", () ->
$('button[data-bb-handler="confirm"]').click()
expect(@spy).toHaveBeenCalled()
)
it("does not trigger the Remove User event whether it's canceled", () ->
$('button[data-bb-handler="cancel"]').click()
expect(@spy).not.toHaveBeenCalled()
)
)
)
describe("when the user ain't an admin", () ->
it("allows not to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(0)
)
)
)
| true | import UserView from 'javascripts/core/apps/admin/user-view'
import { AppChan } from 'javascripts/core/channels'
describe("Admin User View", () ->
MyRegion = Marionette.Region.extend({
el: '#setting-region'
})
beforeAll ->
$('#main-region').empty()
beforeEach ->
setFixtures(__html__['setting-region.html'])
myCollection = new Backbone.Collection([
new Backbone.Model({id: 2, name: "PI:NAME:<NAME>END_PI", role_name: "user"})
])
@myRegion = new MyRegion
@myView = new UserView {collection: myCollection }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView.grid, 'showView').and.callThrough()
myRegion = new MyRegion
myRegion.show(@myView)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(1)
)
)
describe("when the user is an admin", () ->
beforeAll ->
@user = _.clone(gon.user)
gon.user.admin = true
afterAll ->
gon.user = @user
beforeEach ->
@myRegion.show(@myView)
it("allows to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(1)
)
describe("after showing the warn dialog", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpy('spy')
@myObject.listenTo(@myView, 'admin:remove:user', @spy)
@myView.$el.find('a[data-click="button_0"]').click()
it("triggers the Remove User event whether it's agreed ", () ->
$('button[data-bb-handler="confirm"]').click()
expect(@spy).toHaveBeenCalled()
)
it("does not trigger the Remove User event whether it's canceled", () ->
$('button[data-bb-handler="cancel"]').click()
expect(@spy).not.toHaveBeenCalled()
)
)
)
describe("when the user ain't an admin", () ->
it("allows not to remove an user", () ->
expect(@myView.$el.find('a[data-click="button_0"]').length).toBe(0)
)
)
)
|
[
{
"context": "ideoScraper\n collection: 'video'\n key: 'videoId'\n .use authors()\n .use newPage\n outp",
"end": 5981,
"score": 0.8041571974754333,
"start": 5976,
"tag": "KEY",
"value": "video"
}
] | .metalsmith/metal.coffee | priyadarshan/kdlearn | 40 | #
# # Metal
#
# Our metalsmith build code.
#
path = require 'path'
highlightjs = require 'highlight.js'
marked = require 'marked'
metalsmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
excerpts = require 'metalsmith-excerpts'
ignore = require 'metalsmith-ignore'
markdown = require 'metalsmith-markdown'
metadata = require 'metalsmith-metadata'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
aboutSchema = require './plugins/about-schema'
authors = require './plugins/authors'
autoDate = require './plugins/autodate'
defaultMeta = require './plugins/defaultmeta'
descMeta = require './plugins/descriptionMeta'
paginate = require './plugins/paginate'
paginateTags = require './plugins/paginatetags'
popularApi = require './plugins/popularapi'
moment = require './plugins/moment'
feed = require './plugins/feed'
filename = require './plugins/filename'
newPage = require './plugins/new-page'
recentApi = require './plugins/recentapi'
redirects = require './plugins/redirects'
series = require './plugins/series'
snapshot = require './plugins/snapshot'
tags = require './plugins/tags'
titleify = require './plugins/titleify'
videoScraper = require './plugins/video-scraper'
# Configure highlightjs with some language aliases
highlightjs.registerLanguage 'coffee', (hljs) ->
hljs.getLanguage('coffeescript')
# Create a renderer instance which we'll use to modify the output of
# the markdown.
markedRenderer = new marked.Renderer()
markedRenderer.heading = (text, level) ->
# var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
#
# return '<h' + level + '><a name="' +
# escapedText +
# '" class="anchor" href="#' +
# escapedText +
# '"><span class="header-link"></span></a>' +
# text + '</h' + level + '>';
link = text.toLowerCase().replace /[^\w]+/g, '-'
"
<h#{level} class='heading'>
<a name='#{link}' class='anchor' href='##{link}'></a>
#{text}
</h#{level}>
"
# In our version of blockquote, we're looking for `type:foo` strings
# and styling the blockquote based on that string.
#
# It's also worth noting that we're *only* looking at that string if
# it starts a paragraph on a line of it's own. This is mainly for
# implementation simplicity, but also helps provide a sane way to
# split up the markdown. If you want two blockquotes, add a newline to
# ensure a new paragraph.
markedRenderer.blockquote = (quote) ->
quoteTypes =
"tip": "tip fa fa-check-circle"
"alert": "alert fa fa-exclamation-circle"
# Blocks is the final list of blockquotes that we're going to return
blocks = []
# Split the quote based on `<p>type:`, since we know that is what
# starts any quote types. We can then iterate over it, with the
# knowledge that each item in the array is a potentially blockquote
for block, i in quote.split "<p>type:"
# If block is empty, skip it. This means that <p>type: was at
# the beginning of the quote, and we can ignore it
continue if block == ""
typeMatch = false
classes = ""
for quoteType, _classes of quoteTypes
# If the blockquote starts with our type, we found it!
if block.indexOf("#{quoteType}\n") == 0
typeMatch = true
classes = _classes
# Remove the quoteType\n from the block. Eg,
# `good\nfoo\nbar` becomes `foo\nbar`
block = block[quoteType.length+1...]
# Add back the <p> that we stole, but ignore the type, since
# we don't want that in the final quote for matches
block = "<p><span class='label'>" + quoteType + "</span>" + block
# If there was no match for any quoteType, then add back the
# <p>type: that we stole
# Note that the zero index (0) wasn't actually split on the type,
# so make sure not to add type back.
if not typeMatch and i != 0 then block = "<p>type:" + block
# Now add our block to the final list
blocks.push "
<blockquote class=\"#{classes}\">
#{block}
</blockquote>
"
# And finally, return our blocks
blocks.join '\n'
# ## build
#
# Build our metalsmith project. Exported as a module.
#
# - callback(err, files): A function which is given an error
# or a list of files when metalsmith is done.
module.exports = build = (callback=->) ->
metalsmith __dirname
.source '..'
.destination 'build'
# Ignore files from ever entering the stream
.ignore ['.agignore', '.gitignore', '.git', '.metalsmith', 'legacy']
.clean false
# Place before the ignore plugin that removes non-markdown
# from the stream
.use metadata
tagNames: 'categories.yaml'
# Filename creates meta information about the originalFilename.
# originalFilename is needed for linking to github for this file.
.use filename()
# Remove files from the stream
.use ignore [
'**/*'
'!**/*.md'
]
.use drafts()
.use markdown
renderer: markedRenderer
langPrefix: ''
highlight: (code, lang) ->
lang = [lang] if lang?
highlightjs.highlightAuto(code, lang).value
.use autoDate()
.use excerpts()
.use titleify()
.use moment()
.use series()
.use collections
faq:
pattern: 'faq/**/*.html'
sortBy: 'importance'
guide:
pattern: 'guides/**/*.html'
sortBy: 'date'
reverse: true
.use defaultMeta
collection: 'faq'
metadata:
improvable: true
template: 'faq.toffee'
.use defaultMeta
collection: 'guide'
metadata:
improvable: true
template: 'page.toffee'
.use tags
metaKey: 'categories'
sort: 'date'
reverse: true
.use videoScraper
collection: 'video'
key: 'videoId'
.use authors()
.use newPage
output: 'index'
metadata: template: 'index.toffee'
.use newPage
output: 'search'
metadata: template: 'search.toffee'
.use newPage
output: '404'
metadata: template: '404.toffee'
.use newPage
output: '404-tag'
metadata: template: '404-tag.toffee'
.use snapshot collection: 'faq'
.use snapshot collection: 'guide'
.use paginateTags
collectionSource: 'tags'
perPage: 10
output: 'categories'
metadata: template: 'tag.toffee'
.use paginate
collection: 'faq'
limit: 10
output: 'faq'
metadata: template: 'faqs.toffee'
.use paginate
collection: 'video'
limit: 30
output: 'videos'
metadata: template: 'videos.toffee'
.use paginate
collection: 'guide'
output: 'guides'
metadata: template: 'guides.toffee'
# Create our redirects
.use redirects()
.use permalinks()
.use filename()
.use aboutSchema() # Add itemprop='about' to the first para
.use descMeta() # Add Description Metatag to each Document
# Adding the scripts array to all the pages, means that you can
# Append the script array with some code, and not worry about the
# execution order.
.use defaultMeta
clone: true
metadata:
scripts: []
.use feed
collections: ['guide', 'faq']
output: 'rss.xml'
metadata: template: 'feed.toffee'
# foo
.use feed
collections: ['guide', 'faq']
output: 'sitemap.xml'
metadata: template: 'sitemap.toffee'
# Exposes /api/recent and all variants
.use recentApi()
# Exposes /api/popular and all variants
.use popularApi()
.use templates 'toffee'
.build callback
# If this file is executed directly, run the build script.
if require.main is module then build()
| 27218 | #
# # Metal
#
# Our metalsmith build code.
#
path = require 'path'
highlightjs = require 'highlight.js'
marked = require 'marked'
metalsmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
excerpts = require 'metalsmith-excerpts'
ignore = require 'metalsmith-ignore'
markdown = require 'metalsmith-markdown'
metadata = require 'metalsmith-metadata'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
aboutSchema = require './plugins/about-schema'
authors = require './plugins/authors'
autoDate = require './plugins/autodate'
defaultMeta = require './plugins/defaultmeta'
descMeta = require './plugins/descriptionMeta'
paginate = require './plugins/paginate'
paginateTags = require './plugins/paginatetags'
popularApi = require './plugins/popularapi'
moment = require './plugins/moment'
feed = require './plugins/feed'
filename = require './plugins/filename'
newPage = require './plugins/new-page'
recentApi = require './plugins/recentapi'
redirects = require './plugins/redirects'
series = require './plugins/series'
snapshot = require './plugins/snapshot'
tags = require './plugins/tags'
titleify = require './plugins/titleify'
videoScraper = require './plugins/video-scraper'
# Configure highlightjs with some language aliases
highlightjs.registerLanguage 'coffee', (hljs) ->
hljs.getLanguage('coffeescript')
# Create a renderer instance which we'll use to modify the output of
# the markdown.
markedRenderer = new marked.Renderer()
markedRenderer.heading = (text, level) ->
# var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
#
# return '<h' + level + '><a name="' +
# escapedText +
# '" class="anchor" href="#' +
# escapedText +
# '"><span class="header-link"></span></a>' +
# text + '</h' + level + '>';
link = text.toLowerCase().replace /[^\w]+/g, '-'
"
<h#{level} class='heading'>
<a name='#{link}' class='anchor' href='##{link}'></a>
#{text}
</h#{level}>
"
# In our version of blockquote, we're looking for `type:foo` strings
# and styling the blockquote based on that string.
#
# It's also worth noting that we're *only* looking at that string if
# it starts a paragraph on a line of it's own. This is mainly for
# implementation simplicity, but also helps provide a sane way to
# split up the markdown. If you want two blockquotes, add a newline to
# ensure a new paragraph.
markedRenderer.blockquote = (quote) ->
quoteTypes =
"tip": "tip fa fa-check-circle"
"alert": "alert fa fa-exclamation-circle"
# Blocks is the final list of blockquotes that we're going to return
blocks = []
# Split the quote based on `<p>type:`, since we know that is what
# starts any quote types. We can then iterate over it, with the
# knowledge that each item in the array is a potentially blockquote
for block, i in quote.split "<p>type:"
# If block is empty, skip it. This means that <p>type: was at
# the beginning of the quote, and we can ignore it
continue if block == ""
typeMatch = false
classes = ""
for quoteType, _classes of quoteTypes
# If the blockquote starts with our type, we found it!
if block.indexOf("#{quoteType}\n") == 0
typeMatch = true
classes = _classes
# Remove the quoteType\n from the block. Eg,
# `good\nfoo\nbar` becomes `foo\nbar`
block = block[quoteType.length+1...]
# Add back the <p> that we stole, but ignore the type, since
# we don't want that in the final quote for matches
block = "<p><span class='label'>" + quoteType + "</span>" + block
# If there was no match for any quoteType, then add back the
# <p>type: that we stole
# Note that the zero index (0) wasn't actually split on the type,
# so make sure not to add type back.
if not typeMatch and i != 0 then block = "<p>type:" + block
# Now add our block to the final list
blocks.push "
<blockquote class=\"#{classes}\">
#{block}
</blockquote>
"
# And finally, return our blocks
blocks.join '\n'
# ## build
#
# Build our metalsmith project. Exported as a module.
#
# - callback(err, files): A function which is given an error
# or a list of files when metalsmith is done.
module.exports = build = (callback=->) ->
metalsmith __dirname
.source '..'
.destination 'build'
# Ignore files from ever entering the stream
.ignore ['.agignore', '.gitignore', '.git', '.metalsmith', 'legacy']
.clean false
# Place before the ignore plugin that removes non-markdown
# from the stream
.use metadata
tagNames: 'categories.yaml'
# Filename creates meta information about the originalFilename.
# originalFilename is needed for linking to github for this file.
.use filename()
# Remove files from the stream
.use ignore [
'**/*'
'!**/*.md'
]
.use drafts()
.use markdown
renderer: markedRenderer
langPrefix: ''
highlight: (code, lang) ->
lang = [lang] if lang?
highlightjs.highlightAuto(code, lang).value
.use autoDate()
.use excerpts()
.use titleify()
.use moment()
.use series()
.use collections
faq:
pattern: 'faq/**/*.html'
sortBy: 'importance'
guide:
pattern: 'guides/**/*.html'
sortBy: 'date'
reverse: true
.use defaultMeta
collection: 'faq'
metadata:
improvable: true
template: 'faq.toffee'
.use defaultMeta
collection: 'guide'
metadata:
improvable: true
template: 'page.toffee'
.use tags
metaKey: 'categories'
sort: 'date'
reverse: true
.use videoScraper
collection: 'video'
key: '<KEY>Id'
.use authors()
.use newPage
output: 'index'
metadata: template: 'index.toffee'
.use newPage
output: 'search'
metadata: template: 'search.toffee'
.use newPage
output: '404'
metadata: template: '404.toffee'
.use newPage
output: '404-tag'
metadata: template: '404-tag.toffee'
.use snapshot collection: 'faq'
.use snapshot collection: 'guide'
.use paginateTags
collectionSource: 'tags'
perPage: 10
output: 'categories'
metadata: template: 'tag.toffee'
.use paginate
collection: 'faq'
limit: 10
output: 'faq'
metadata: template: 'faqs.toffee'
.use paginate
collection: 'video'
limit: 30
output: 'videos'
metadata: template: 'videos.toffee'
.use paginate
collection: 'guide'
output: 'guides'
metadata: template: 'guides.toffee'
# Create our redirects
.use redirects()
.use permalinks()
.use filename()
.use aboutSchema() # Add itemprop='about' to the first para
.use descMeta() # Add Description Metatag to each Document
# Adding the scripts array to all the pages, means that you can
# Append the script array with some code, and not worry about the
# execution order.
.use defaultMeta
clone: true
metadata:
scripts: []
.use feed
collections: ['guide', 'faq']
output: 'rss.xml'
metadata: template: 'feed.toffee'
# foo
.use feed
collections: ['guide', 'faq']
output: 'sitemap.xml'
metadata: template: 'sitemap.toffee'
# Exposes /api/recent and all variants
.use recentApi()
# Exposes /api/popular and all variants
.use popularApi()
.use templates 'toffee'
.build callback
# If this file is executed directly, run the build script.
if require.main is module then build()
| true | #
# # Metal
#
# Our metalsmith build code.
#
path = require 'path'
highlightjs = require 'highlight.js'
marked = require 'marked'
metalsmith = require 'metalsmith'
collections = require 'metalsmith-collections'
drafts = require 'metalsmith-drafts'
excerpts = require 'metalsmith-excerpts'
ignore = require 'metalsmith-ignore'
markdown = require 'metalsmith-markdown'
metadata = require 'metalsmith-metadata'
permalinks = require 'metalsmith-permalinks'
templates = require 'metalsmith-templates'
aboutSchema = require './plugins/about-schema'
authors = require './plugins/authors'
autoDate = require './plugins/autodate'
defaultMeta = require './plugins/defaultmeta'
descMeta = require './plugins/descriptionMeta'
paginate = require './plugins/paginate'
paginateTags = require './plugins/paginatetags'
popularApi = require './plugins/popularapi'
moment = require './plugins/moment'
feed = require './plugins/feed'
filename = require './plugins/filename'
newPage = require './plugins/new-page'
recentApi = require './plugins/recentapi'
redirects = require './plugins/redirects'
series = require './plugins/series'
snapshot = require './plugins/snapshot'
tags = require './plugins/tags'
titleify = require './plugins/titleify'
videoScraper = require './plugins/video-scraper'
# Configure highlightjs with some language aliases
highlightjs.registerLanguage 'coffee', (hljs) ->
hljs.getLanguage('coffeescript')
# Create a renderer instance which we'll use to modify the output of
# the markdown.
markedRenderer = new marked.Renderer()
markedRenderer.heading = (text, level) ->
# var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
#
# return '<h' + level + '><a name="' +
# escapedText +
# '" class="anchor" href="#' +
# escapedText +
# '"><span class="header-link"></span></a>' +
# text + '</h' + level + '>';
link = text.toLowerCase().replace /[^\w]+/g, '-'
"
<h#{level} class='heading'>
<a name='#{link}' class='anchor' href='##{link}'></a>
#{text}
</h#{level}>
"
# In our version of blockquote, we're looking for `type:foo` strings
# and styling the blockquote based on that string.
#
# It's also worth noting that we're *only* looking at that string if
# it starts a paragraph on a line of it's own. This is mainly for
# implementation simplicity, but also helps provide a sane way to
# split up the markdown. If you want two blockquotes, add a newline to
# ensure a new paragraph.
markedRenderer.blockquote = (quote) ->
quoteTypes =
"tip": "tip fa fa-check-circle"
"alert": "alert fa fa-exclamation-circle"
# Blocks is the final list of blockquotes that we're going to return
blocks = []
# Split the quote based on `<p>type:`, since we know that is what
# starts any quote types. We can then iterate over it, with the
# knowledge that each item in the array is a potentially blockquote
for block, i in quote.split "<p>type:"
# If block is empty, skip it. This means that <p>type: was at
# the beginning of the quote, and we can ignore it
continue if block == ""
typeMatch = false
classes = ""
for quoteType, _classes of quoteTypes
# If the blockquote starts with our type, we found it!
if block.indexOf("#{quoteType}\n") == 0
typeMatch = true
classes = _classes
# Remove the quoteType\n from the block. Eg,
# `good\nfoo\nbar` becomes `foo\nbar`
block = block[quoteType.length+1...]
# Add back the <p> that we stole, but ignore the type, since
# we don't want that in the final quote for matches
block = "<p><span class='label'>" + quoteType + "</span>" + block
# If there was no match for any quoteType, then add back the
# <p>type: that we stole
# Note that the zero index (0) wasn't actually split on the type,
# so make sure not to add type back.
if not typeMatch and i != 0 then block = "<p>type:" + block
# Now add our block to the final list
blocks.push "
<blockquote class=\"#{classes}\">
#{block}
</blockquote>
"
# And finally, return our blocks
blocks.join '\n'
# ## build
#
# Build our metalsmith project. Exported as a module.
#
# - callback(err, files): A function which is given an error
# or a list of files when metalsmith is done.
module.exports = build = (callback=->) ->
metalsmith __dirname
.source '..'
.destination 'build'
# Ignore files from ever entering the stream
.ignore ['.agignore', '.gitignore', '.git', '.metalsmith', 'legacy']
.clean false
# Place before the ignore plugin that removes non-markdown
# from the stream
.use metadata
tagNames: 'categories.yaml'
# Filename creates meta information about the originalFilename.
# originalFilename is needed for linking to github for this file.
.use filename()
# Remove files from the stream
.use ignore [
'**/*'
'!**/*.md'
]
.use drafts()
.use markdown
renderer: markedRenderer
langPrefix: ''
highlight: (code, lang) ->
lang = [lang] if lang?
highlightjs.highlightAuto(code, lang).value
.use autoDate()
.use excerpts()
.use titleify()
.use moment()
.use series()
.use collections
faq:
pattern: 'faq/**/*.html'
sortBy: 'importance'
guide:
pattern: 'guides/**/*.html'
sortBy: 'date'
reverse: true
.use defaultMeta
collection: 'faq'
metadata:
improvable: true
template: 'faq.toffee'
.use defaultMeta
collection: 'guide'
metadata:
improvable: true
template: 'page.toffee'
.use tags
metaKey: 'categories'
sort: 'date'
reverse: true
.use videoScraper
collection: 'video'
key: 'PI:KEY:<KEY>END_PIId'
.use authors()
.use newPage
output: 'index'
metadata: template: 'index.toffee'
.use newPage
output: 'search'
metadata: template: 'search.toffee'
.use newPage
output: '404'
metadata: template: '404.toffee'
.use newPage
output: '404-tag'
metadata: template: '404-tag.toffee'
.use snapshot collection: 'faq'
.use snapshot collection: 'guide'
.use paginateTags
collectionSource: 'tags'
perPage: 10
output: 'categories'
metadata: template: 'tag.toffee'
.use paginate
collection: 'faq'
limit: 10
output: 'faq'
metadata: template: 'faqs.toffee'
.use paginate
collection: 'video'
limit: 30
output: 'videos'
metadata: template: 'videos.toffee'
.use paginate
collection: 'guide'
output: 'guides'
metadata: template: 'guides.toffee'
# Create our redirects
.use redirects()
.use permalinks()
.use filename()
.use aboutSchema() # Add itemprop='about' to the first para
.use descMeta() # Add Description Metatag to each Document
# Adding the scripts array to all the pages, means that you can
# Append the script array with some code, and not worry about the
# execution order.
.use defaultMeta
clone: true
metadata:
scripts: []
.use feed
collections: ['guide', 'faq']
output: 'rss.xml'
metadata: template: 'feed.toffee'
# foo
.use feed
collections: ['guide', 'faq']
output: 'sitemap.xml'
metadata: template: 'sitemap.toffee'
# Exposes /api/recent and all variants
.use recentApi()
# Exposes /api/popular and all variants
.use popularApi()
.use templates 'toffee'
.build callback
# If this file is executed directly, run the build script.
if require.main is module then build()
|
[
{
"context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.",
"end": 17,
"score": 0.9274728298187256,
"start": 16,
"tag": "EMAIL",
"value": "j"
},
{
"context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Per",
"end": 25,
"score": 0.813740611076355,
"start": 17,
"tag": "USERNAME",
"value": "tlebi.fr"
},
{
"context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Permission is hereby",
"end": 42,
"score": 0.9999141693115234,
"start": 27,
"tag": "EMAIL",
"value": "admin@jtlebi.fr"
}
] | static/js/app/core/render.coffee | yadutaf/Weathermap-archive | 1 | ###
# Copyright jtlebi.fr <admin@jtlebi.fr> and other 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.
###
#depends on: core; router
###
Renders are expected to :
* be of View type
* be stored in js file './render/name.js'
* be namespaced as 'WM.render.name'
* register there source handlebar code via "registerTemplate"
* having a templateName of the form "map-render-name"
* handle themeselves their updates. Em provides enough tools !
###
WM.render = Em.Object.create {
selectedBinding: Em.Binding.oneWay 'WM.times.selected'
currentStateBinding: Em.Binding.oneWay 'WM.routeManager.currentState'
renderEngines: []
currentType: ''
views: {}
registerTemplate: (name, source) ->
WM.api.registerTemplate 'map-render-'+name, source
#re-inits the render on route switches to get the image back (was detached from DOM)
initRender: (->
state = @get 'currentState'
current = @get 'currentType'
return if not current.length
while state
if state.name and state.name == "map"
if current.length
WM.render.views[current].remove()
WM.render.views[current].appendTo '#map-render'
return
else
state = state.parentState
).observes 'currentState'
refreshRender: (->
selected = @get 'selected'
prevType = @get 'currentType'
#did the render type change ?
if not selected or selected.type == prevType
return
#if type changed -> unload render engine and load the new one
if WM.render.views[prevType]
WM.render.views[prevType].remove()
@set 'currentType', selected.type
#if we do not know yet the render engine, load it
engines = @get 'renderEngines'
if selected.type not in @get 'renderEngines'
engines.push selected.type
@set 'renderEngines', engines
$.getScript basedir+'/plugins/render/'+selected.type+'.js', ->
WM.render.views[selected.type].appendTo '#map-render'
else
WM.render.views[selected.type].appendTo '#map-render'
return ""
).observes 'selected'
} | 217819 | ###
# Copyright <EMAIL>tlebi.fr <<EMAIL>> and other 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.
###
#depends on: core; router
###
Renders are expected to :
* be of View type
* be stored in js file './render/name.js'
* be namespaced as 'WM.render.name'
* register there source handlebar code via "registerTemplate"
* having a templateName of the form "map-render-name"
* handle themeselves their updates. Em provides enough tools !
###
WM.render = Em.Object.create {
selectedBinding: Em.Binding.oneWay 'WM.times.selected'
currentStateBinding: Em.Binding.oneWay 'WM.routeManager.currentState'
renderEngines: []
currentType: ''
views: {}
registerTemplate: (name, source) ->
WM.api.registerTemplate 'map-render-'+name, source
#re-inits the render on route switches to get the image back (was detached from DOM)
initRender: (->
state = @get 'currentState'
current = @get 'currentType'
return if not current.length
while state
if state.name and state.name == "map"
if current.length
WM.render.views[current].remove()
WM.render.views[current].appendTo '#map-render'
return
else
state = state.parentState
).observes 'currentState'
refreshRender: (->
selected = @get 'selected'
prevType = @get 'currentType'
#did the render type change ?
if not selected or selected.type == prevType
return
#if type changed -> unload render engine and load the new one
if WM.render.views[prevType]
WM.render.views[prevType].remove()
@set 'currentType', selected.type
#if we do not know yet the render engine, load it
engines = @get 'renderEngines'
if selected.type not in @get 'renderEngines'
engines.push selected.type
@set 'renderEngines', engines
$.getScript basedir+'/plugins/render/'+selected.type+'.js', ->
WM.render.views[selected.type].appendTo '#map-render'
else
WM.render.views[selected.type].appendTo '#map-render'
return ""
).observes 'selected'
} | true | ###
# Copyright PI:EMAIL:<EMAIL>END_PItlebi.fr <PI:EMAIL:<EMAIL>END_PI> and other 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.
###
#depends on: core; router
###
Renders are expected to :
* be of View type
* be stored in js file './render/name.js'
* be namespaced as 'WM.render.name'
* register there source handlebar code via "registerTemplate"
* having a templateName of the form "map-render-name"
* handle themeselves their updates. Em provides enough tools !
###
WM.render = Em.Object.create {
selectedBinding: Em.Binding.oneWay 'WM.times.selected'
currentStateBinding: Em.Binding.oneWay 'WM.routeManager.currentState'
renderEngines: []
currentType: ''
views: {}
registerTemplate: (name, source) ->
WM.api.registerTemplate 'map-render-'+name, source
#re-inits the render on route switches to get the image back (was detached from DOM)
initRender: (->
state = @get 'currentState'
current = @get 'currentType'
return if not current.length
while state
if state.name and state.name == "map"
if current.length
WM.render.views[current].remove()
WM.render.views[current].appendTo '#map-render'
return
else
state = state.parentState
).observes 'currentState'
refreshRender: (->
selected = @get 'selected'
prevType = @get 'currentType'
#did the render type change ?
if not selected or selected.type == prevType
return
#if type changed -> unload render engine and load the new one
if WM.render.views[prevType]
WM.render.views[prevType].remove()
@set 'currentType', selected.type
#if we do not know yet the render engine, load it
engines = @get 'renderEngines'
if selected.type not in @get 'renderEngines'
engines.push selected.type
@set 'renderEngines', engines
$.getScript basedir+'/plugins/render/'+selected.type+'.js', ->
WM.render.views[selected.type].appendTo '#map-render'
else
WM.render.views[selected.type].appendTo '#map-render'
return ""
).observes 'selected'
} |
[
{
"context": " subsequent requests:\n @auth.password = password\n\n # Void method:\n cb null\n\n",
"end": 4272,
"score": 0.8786374926567078,
"start": 4264,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "for now.\n # https://github.com/clutchski/coffeelint/issues/459\n {\n ",
"end": 8130,
"score": 0.9995232224464417,
"start": 8121,
"tag": "USERNAME",
"value": "clutchski"
},
{
"context": "is for constraints).\n # https://github.com/neo4j/neo4j/issues/4214\n @getIndexes {label}, (e",
"end": 14494,
"score": 0.9991628527641296,
"start": 14489,
"tag": "USERNAME",
"value": "neo4j"
},
{
"context": "04 if no constraint.\n # https://github.com/neo4j/neo4j/issues/4214\n # For those reasons, it",
"end": 18398,
"score": 0.9996271133422852,
"start": 18393,
"tag": "USERNAME",
"value": "neo4j"
}
] | Lambda Functions/searchlocales/node_modules/neo4j/lib-new/GraphDatabase.coffee | RussellPhipps/PilgrimAdminTools | 0 | $ = require 'underscore'
assert = require 'assert'
Constraint = require './Constraint'
{Error} = require './errors'
Index = require './Index'
lib = require '../package.json'
Node = require './Node'
Relationship = require './Relationship'
Request = require 'request'
Transaction = require './Transaction'
URL = require 'url'
module.exports = class GraphDatabase
## CORE
# Default HTTP headers:
headers:
'User-Agent': "node-neo4j/#{lib.version}"
constructor: (opts={}) ->
if typeof opts is 'string'
opts = {url: opts}
{@url, @auth, @headers, @proxy, @agent} = opts
if not @url
throw new TypeError 'URL to Neo4j required'
# Process auth, whether through option or URL creds or both.
# Option takes precedence, and we clear the URL creds if option given.
uri = URL.parse @url
if uri.auth and @auth?
delete uri.auth
@url = URL.format uri
# We also normalize any given auth to an object or null:
@auth = _normalizeAuth @auth ? uri.auth
# Extend the given headers with our defaults, but clone first:
# TODO: Do we want to special-case User-Agent? Or reject if includes
# reserved headers like Accept, Content-Type, X-Stream?
@headers or= {}
@headers = $(@headers)
.chain()
.clone()
.defaults @constructor::headers
.value()
## HTTP
http: (opts={}, cb) ->
if typeof opts is 'string'
opts = {path: opts}
{method, path, headers, body, raw} = opts
if not path
throw new TypeError 'Path required'
method or= 'GET'
headers or= {}
# Extend the given headers, both with both required and optional
# defaults, but do so without modifying the input object:
headers = $(headers)
.chain()
.clone()
.defaults @headers # These headers can be overridden...
.extend # ...while these can't.
'X-Stream': 'true'
.value()
# TODO: Would be good to test custom proxy and agent, but difficult.
# Same with Neo4j returning gzipped responses (e.g. through an LB).
Request
method: method
url: URL.resolve @url, path
proxy: @proxy
auth: @auth
headers: headers
agent: @agent
json: body ? true
encoding: 'utf8'
gzip: true # This is only for responses: decode if gzipped.
# Important: only pass a callback to Request if a callback was passed
# to us. This prevents Request from buffering the response in memory
# (to parse JSON) if the caller prefers to stream the response instead.
, cb and (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
return cb err
if raw
# TODO: Do we want to return our own Response object?
return cb null, resp
if err = Error._fromResponse resp
return cb err
cb null, _transform resp.body
## AUTH
checkPasswordChangeNeeded: (cb) ->
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
@http
method: 'GET'
path: "/user/#{encodeURIComponent @auth.username}"
, (err, user) ->
if err
return cb err
cb null, user.password_change_required
changePassword: (opts={}, cb) ->
if typeof opts is 'string'
opts = {password: opts}
{password} = opts
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
if not password
throw new TypeError 'Password required'
@http
method: 'POST'
path: "/user/#{encodeURIComponent @auth.username}/password"
body: {password}
, (err) =>
if err
return cb err
# Since successful, update our saved state for subsequent requests:
@auth.password = password
# Void method:
cb null
## CYPHER
# NOTE: This method is fairly complex, in part out of necessity.
# We're okay with it since we test it throughly and emphasize its coverage.
# coffeelint: disable=cyclomatic_complexity
cypher: (opts={}, cb, _tx) ->
# coffeelint: enable=cyclomatic_complexity
if typeof opts is 'string'
opts = {query: opts}
if opts instanceof Array
opts = {queries: opts}
{queries, query, params, headers, lean, commit, rollback} = opts
if not _tx and rollback
throw new Error 'Illegal state: rolling back without a transaction!'
if commit and rollback
throw new Error 'Illegal state: both committing and rolling back!'
if rollback and (query or queries)
throw new Error 'Illegal state: rolling back with query/queries!'
if not _tx and commit is false
throw new TypeError 'Can’t refuse to commit without a transaction!
To begin a new transaction without committing, call
`db.beginTransaction()`, and then call `cypher` on that.'
if not _tx and not (query or queries)
throw new TypeError 'Query or queries required'
if query and queries
throw new TypeError 'Can’t supply both a single query
and a batch of queries! Do you have a bug in your code?'
if queries and params
throw new TypeError 'When batching multiple queries,
params must be supplied with each query, not globally.'
if queries and lean
throw new TypeError 'When batching multiple queries,
`lean` must be specified with each query, not globally.'
if (commit or rollback) and not (query or queries) and not _tx._id
# (Note that we've already required query or queries if no
# transaction present, so this means a transaction is present.)
# This transaction hasn't even been created yet from Neo4j's POV
# (because transactions are created lazily), so nothing to do.
cb null, null
return
method = 'POST'
method = 'DELETE' if rollback
path = '/db/data/transaction'
path += "/#{_tx._id}" if _tx?._id
path += '/commit' if commit or not _tx
# Normalize input query or queries to an array of queries always,
# but remember whether a single query was given (not a batch).
# Also handle the case where no queries were given; this is either a
# void action (e.g. rollback), or legitimately an empty batch.
if query
queries = [{query, params, lean}]
single = true
else
single = not queries # void action, *not* empty [] given
queries or= []
# Generate the request body by transforming each query (which is
# potentially a simple string) into Neo4j's `statement` format.
# We need to remember what result format we requested for each query.
formats = []
body =
statements:
for query in queries
if typeof query is 'string'
query = {query}
if query.headers
throw new TypeError 'When batching multiple queries,
custom request headers cannot be supplied per query;
they must be supplied globally.'
{query, params, lean} = query
# NOTE: Lowercase 'rest' matters here for parsing.
formats.push format = if lean then 'row' else 'rest'
# NOTE: Braces needed by CoffeeLint for now.
# https://github.com/clutchski/coffeelint/issues/459
{
statement: query
parameters: params or {}
resultDataContents: [format]
}
# TODO: Support streaming!
#
# NOTE: Specifying `raw: true` to save on parsing work (see `_transform`
# helper at the bottom of this file) if any queries are `lean: true`.
# Easy enough for us to parse ourselves, which we do, when needed.
#
@http {method, path, headers, body, raw: true}, (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
# NOTE: This includes our own errors for non-2xx responses.
return cb err
if err = Error._fromResponse resp
return cb err
_tx?._updateFromResponse resp
{results, errors} = resp.body
# Parse any results first, before errors, in case this is a batch
# request, where we want to return results alongside errors.
# The top-level `results` is an array of results corresponding to
# the `statements` (queries) inputted.
# We want to transform each query's results from Neo4j's complex
# format to a simple array of dictionaries.
results =
for result, i in results
{columns, data} = result
format = formats[i]
# The `data` for each query is an array of rows, but each of
# its elements is actually a dictionary of results keyed by
# response format. We only request one format per query.
# The value of each format is an array of rows, where each
# row is an array of column values. We transform those rows
# into dictionaries keyed by column names. Finally, we also
# parse nodes & relationships into object instances if this
# query didn't request a raw format. Phew!
$(data).pluck(format).map (row) ->
result = {}
for column, j in columns
result[column] = row[j]
if format is 'rest'
result = _transform result
result
# What exactly we return depends on how we were called:
#
# - Batch: if an array of queries were given, we always return an
# array of each query's results.
#
# - Single: if a single query was given, we always return just that
# query's results.
#
# - Void: if neither was given, we explicitly return null.
# This is for transaction actions, e.g. commit, rollback, renew.
#
# We're already set up for the batch case by default, so we only
# need to account for the other cases.
#
if single
# This means a batch of queries was *not* given, but we still
# normalized to an array of queries...
if queries.length
# This means a single query was given:
assert.equal queries.length, 1,
'There should be *exactly* one query given.'
assert results.length <= 1,
'There should be *at most* one set of results.'
results = results[0]
else
# This means no query was given:
assert.equal results.length, 0,
'There should be *no* results.'
results = null
if errors.length
# TODO: Is it possible to get back more than one error?
# If so, is it fine for us to just use the first one?
[error] = errors
err = Error._fromObject error
cb err, results
beginTransaction: ->
new Transaction @
## SCHEMA
getLabels: (cb) ->
# This endpoint returns the array of labels directly:
# http://neo4j.com/docs/stable/rest-api-node-labels.html#rest-api-list-all-labels
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/labels'
, cb
getPropertyKeys: (cb) ->
# This endpoint returns the array of property keys directly:
# http://neo4j.com/docs/stable/rest-api-property-values.html#rest-api-list-all-property-keys
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/propertykeys'
, cb
getRelationshipTypes: (cb) ->
# This endpoint returns the array of relationship types directly:
# http://neo4j.com/docs/stable/rest-api-relationship-types.html#rest-api-get-relationship-types
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/relationship/types'
, cb
## INDEXES
getIndexes: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
{label} = opts
# Support both querying for a given label, and across all labels:
path = '/db/data/schema/index'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, indexes) ->
cb err, indexes?.map Index._fromRaw
hasIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to query whether an index exists.'
# NOTE: This is just a convenience method; there is no REST API endpoint
# for this directly (surprisingly, since there is for constraints).
# https://github.com/neo4j/neo4j/issues/4214
@getIndexes {label}, (err, indexes) ->
cb err, indexes?.some (index) ->
index.label is label and index.property is property
createIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create an index.'
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/index/#{encodeURIComponent label}"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this index already exists (including for a constraint).
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Index._fromRaw resp.body
dropIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to drop an index.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-indexes.html#rest-api-drop-index
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/index\
/#{encodeURIComponent label}/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this index doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Index existed and was dropped
## CONSTRAINTS
getConstraints: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
# TODO: We may need to support querying within a particular `type` too,
# if any other types beyond uniqueness get added.
{label} = opts
# Support both querying for a given label, and across all labels.
#
# NOTE: We're explicitly *not* assuming uniqueness type here, since we
# couldn't achieve consistency with vs. without a label provided.
# (The `/uniqueness` part of the path can only come after a label.)
#
path = '/db/data/schema/constraint'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, constraints) ->
cb err, constraints?.map Constraint._fromRaw
hasConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to query
whether a constraint exists.'
# NOTE: A REST API endpoint *does* exist to get a specific constraint:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html
# But it (a) returns an array, and (b) throws a 404 if no constraint.
# https://github.com/neo4j/neo4j/issues/4214
# For those reasons, it's actually easier to just fetch all constraints;
# no error handling needed, and array processing either way.
#
# NOTE: We explicitly *are* assuming uniqueness type here, since we
# also would if we were querying for a specific constraint.
# (The `/uniqueness` part of the path comes before the property.)
#
@http
method: 'GET'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
, (err, constraints) ->
if err
cb err
else
cb null, constraints.some (constraint) ->
constraint = Constraint._fromRaw constraint
constraint.label is label and
constraint.property is property
createConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create a constraint.'
# NOTE: We explicitly *are* assuming uniqueness type here, since
# that's our only option today for creating constraints.
# NOTE: Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this constraint already exists.
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Constraint._fromRaw resp.body
dropConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to drop a constraint.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html#rest-api-drop-constraint
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/constraint/#{encodeURIComponent label}\
/uniqueness/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this constraint doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Constraint existed and was dropped
# TODO: Legacy indexing
## HELPERS
#
# Normalizes the given auth value, which can be a 'username:password' string
# or a {username, password} object, to an object or null always.
#
_normalizeAuth = (auth) ->
# Support empty string for no auth:
return null if not auth
# Parse string if given, being robust to colons in the password:
if typeof auth is 'string'
[username, passwordParts...] = auth.split ':'
password = passwordParts.join ':'
auth = {username, password}
# Support empty object for no auth also:
return null if (Object.keys auth).length is 0
auth
#
# Deep inspects the given object -- which could be a simple primitive, a map,
# an array with arbitrary other objects, etc. -- and transforms any objects that
# look like nodes and relationships into Node and Relationship instances.
# Returns the transformed object, and does not mutate the input object.
#
_transform = (obj) ->
# Nothing to transform for primitives and null:
if (not obj) or (typeof obj isnt 'object')
return obj
# Process arrays:
# (NOTE: Not bothering to detect arrays made in other JS contexts.)
if obj instanceof Array
return obj.map _transform
# Feature-detect (AKA "duck-type") Node & Relationship objects, by simply
# trying to parse them as such.
# Important: check relationships first, for precision/specificity.
# TODO: If we add a Path class, we'll need to check for that here too.
if rel = Relationship._fromRaw obj
return rel
if node = Node._fromRaw obj
return node
# Otherwise, process as a dictionary/map:
map = {}
for key, val of obj
map[key] = _transform val
map
| 134898 | $ = require 'underscore'
assert = require 'assert'
Constraint = require './Constraint'
{Error} = require './errors'
Index = require './Index'
lib = require '../package.json'
Node = require './Node'
Relationship = require './Relationship'
Request = require 'request'
Transaction = require './Transaction'
URL = require 'url'
module.exports = class GraphDatabase
## CORE
# Default HTTP headers:
headers:
'User-Agent': "node-neo4j/#{lib.version}"
constructor: (opts={}) ->
if typeof opts is 'string'
opts = {url: opts}
{@url, @auth, @headers, @proxy, @agent} = opts
if not @url
throw new TypeError 'URL to Neo4j required'
# Process auth, whether through option or URL creds or both.
# Option takes precedence, and we clear the URL creds if option given.
uri = URL.parse @url
if uri.auth and @auth?
delete uri.auth
@url = URL.format uri
# We also normalize any given auth to an object or null:
@auth = _normalizeAuth @auth ? uri.auth
# Extend the given headers with our defaults, but clone first:
# TODO: Do we want to special-case User-Agent? Or reject if includes
# reserved headers like Accept, Content-Type, X-Stream?
@headers or= {}
@headers = $(@headers)
.chain()
.clone()
.defaults @constructor::headers
.value()
## HTTP
http: (opts={}, cb) ->
if typeof opts is 'string'
opts = {path: opts}
{method, path, headers, body, raw} = opts
if not path
throw new TypeError 'Path required'
method or= 'GET'
headers or= {}
# Extend the given headers, both with both required and optional
# defaults, but do so without modifying the input object:
headers = $(headers)
.chain()
.clone()
.defaults @headers # These headers can be overridden...
.extend # ...while these can't.
'X-Stream': 'true'
.value()
# TODO: Would be good to test custom proxy and agent, but difficult.
# Same with Neo4j returning gzipped responses (e.g. through an LB).
Request
method: method
url: URL.resolve @url, path
proxy: @proxy
auth: @auth
headers: headers
agent: @agent
json: body ? true
encoding: 'utf8'
gzip: true # This is only for responses: decode if gzipped.
# Important: only pass a callback to Request if a callback was passed
# to us. This prevents Request from buffering the response in memory
# (to parse JSON) if the caller prefers to stream the response instead.
, cb and (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
return cb err
if raw
# TODO: Do we want to return our own Response object?
return cb null, resp
if err = Error._fromResponse resp
return cb err
cb null, _transform resp.body
## AUTH
checkPasswordChangeNeeded: (cb) ->
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
@http
method: 'GET'
path: "/user/#{encodeURIComponent @auth.username}"
, (err, user) ->
if err
return cb err
cb null, user.password_change_required
changePassword: (opts={}, cb) ->
if typeof opts is 'string'
opts = {password: opts}
{password} = opts
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
if not password
throw new TypeError 'Password required'
@http
method: 'POST'
path: "/user/#{encodeURIComponent @auth.username}/password"
body: {password}
, (err) =>
if err
return cb err
# Since successful, update our saved state for subsequent requests:
@auth.password = <PASSWORD>
# Void method:
cb null
## CYPHER
# NOTE: This method is fairly complex, in part out of necessity.
# We're okay with it since we test it throughly and emphasize its coverage.
# coffeelint: disable=cyclomatic_complexity
cypher: (opts={}, cb, _tx) ->
# coffeelint: enable=cyclomatic_complexity
if typeof opts is 'string'
opts = {query: opts}
if opts instanceof Array
opts = {queries: opts}
{queries, query, params, headers, lean, commit, rollback} = opts
if not _tx and rollback
throw new Error 'Illegal state: rolling back without a transaction!'
if commit and rollback
throw new Error 'Illegal state: both committing and rolling back!'
if rollback and (query or queries)
throw new Error 'Illegal state: rolling back with query/queries!'
if not _tx and commit is false
throw new TypeError 'Can’t refuse to commit without a transaction!
To begin a new transaction without committing, call
`db.beginTransaction()`, and then call `cypher` on that.'
if not _tx and not (query or queries)
throw new TypeError 'Query or queries required'
if query and queries
throw new TypeError 'Can’t supply both a single query
and a batch of queries! Do you have a bug in your code?'
if queries and params
throw new TypeError 'When batching multiple queries,
params must be supplied with each query, not globally.'
if queries and lean
throw new TypeError 'When batching multiple queries,
`lean` must be specified with each query, not globally.'
if (commit or rollback) and not (query or queries) and not _tx._id
# (Note that we've already required query or queries if no
# transaction present, so this means a transaction is present.)
# This transaction hasn't even been created yet from Neo4j's POV
# (because transactions are created lazily), so nothing to do.
cb null, null
return
method = 'POST'
method = 'DELETE' if rollback
path = '/db/data/transaction'
path += "/#{_tx._id}" if _tx?._id
path += '/commit' if commit or not _tx
# Normalize input query or queries to an array of queries always,
# but remember whether a single query was given (not a batch).
# Also handle the case where no queries were given; this is either a
# void action (e.g. rollback), or legitimately an empty batch.
if query
queries = [{query, params, lean}]
single = true
else
single = not queries # void action, *not* empty [] given
queries or= []
# Generate the request body by transforming each query (which is
# potentially a simple string) into Neo4j's `statement` format.
# We need to remember what result format we requested for each query.
formats = []
body =
statements:
for query in queries
if typeof query is 'string'
query = {query}
if query.headers
throw new TypeError 'When batching multiple queries,
custom request headers cannot be supplied per query;
they must be supplied globally.'
{query, params, lean} = query
# NOTE: Lowercase 'rest' matters here for parsing.
formats.push format = if lean then 'row' else 'rest'
# NOTE: Braces needed by CoffeeLint for now.
# https://github.com/clutchski/coffeelint/issues/459
{
statement: query
parameters: params or {}
resultDataContents: [format]
}
# TODO: Support streaming!
#
# NOTE: Specifying `raw: true` to save on parsing work (see `_transform`
# helper at the bottom of this file) if any queries are `lean: true`.
# Easy enough for us to parse ourselves, which we do, when needed.
#
@http {method, path, headers, body, raw: true}, (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
# NOTE: This includes our own errors for non-2xx responses.
return cb err
if err = Error._fromResponse resp
return cb err
_tx?._updateFromResponse resp
{results, errors} = resp.body
# Parse any results first, before errors, in case this is a batch
# request, where we want to return results alongside errors.
# The top-level `results` is an array of results corresponding to
# the `statements` (queries) inputted.
# We want to transform each query's results from Neo4j's complex
# format to a simple array of dictionaries.
results =
for result, i in results
{columns, data} = result
format = formats[i]
# The `data` for each query is an array of rows, but each of
# its elements is actually a dictionary of results keyed by
# response format. We only request one format per query.
# The value of each format is an array of rows, where each
# row is an array of column values. We transform those rows
# into dictionaries keyed by column names. Finally, we also
# parse nodes & relationships into object instances if this
# query didn't request a raw format. Phew!
$(data).pluck(format).map (row) ->
result = {}
for column, j in columns
result[column] = row[j]
if format is 'rest'
result = _transform result
result
# What exactly we return depends on how we were called:
#
# - Batch: if an array of queries were given, we always return an
# array of each query's results.
#
# - Single: if a single query was given, we always return just that
# query's results.
#
# - Void: if neither was given, we explicitly return null.
# This is for transaction actions, e.g. commit, rollback, renew.
#
# We're already set up for the batch case by default, so we only
# need to account for the other cases.
#
if single
# This means a batch of queries was *not* given, but we still
# normalized to an array of queries...
if queries.length
# This means a single query was given:
assert.equal queries.length, 1,
'There should be *exactly* one query given.'
assert results.length <= 1,
'There should be *at most* one set of results.'
results = results[0]
else
# This means no query was given:
assert.equal results.length, 0,
'There should be *no* results.'
results = null
if errors.length
# TODO: Is it possible to get back more than one error?
# If so, is it fine for us to just use the first one?
[error] = errors
err = Error._fromObject error
cb err, results
beginTransaction: ->
new Transaction @
## SCHEMA
getLabels: (cb) ->
# This endpoint returns the array of labels directly:
# http://neo4j.com/docs/stable/rest-api-node-labels.html#rest-api-list-all-labels
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/labels'
, cb
getPropertyKeys: (cb) ->
# This endpoint returns the array of property keys directly:
# http://neo4j.com/docs/stable/rest-api-property-values.html#rest-api-list-all-property-keys
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/propertykeys'
, cb
getRelationshipTypes: (cb) ->
# This endpoint returns the array of relationship types directly:
# http://neo4j.com/docs/stable/rest-api-relationship-types.html#rest-api-get-relationship-types
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/relationship/types'
, cb
## INDEXES
getIndexes: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
{label} = opts
# Support both querying for a given label, and across all labels:
path = '/db/data/schema/index'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, indexes) ->
cb err, indexes?.map Index._fromRaw
hasIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to query whether an index exists.'
# NOTE: This is just a convenience method; there is no REST API endpoint
# for this directly (surprisingly, since there is for constraints).
# https://github.com/neo4j/neo4j/issues/4214
@getIndexes {label}, (err, indexes) ->
cb err, indexes?.some (index) ->
index.label is label and index.property is property
createIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create an index.'
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/index/#{encodeURIComponent label}"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this index already exists (including for a constraint).
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Index._fromRaw resp.body
dropIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to drop an index.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-indexes.html#rest-api-drop-index
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/index\
/#{encodeURIComponent label}/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this index doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Index existed and was dropped
## CONSTRAINTS
getConstraints: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
# TODO: We may need to support querying within a particular `type` too,
# if any other types beyond uniqueness get added.
{label} = opts
# Support both querying for a given label, and across all labels.
#
# NOTE: We're explicitly *not* assuming uniqueness type here, since we
# couldn't achieve consistency with vs. without a label provided.
# (The `/uniqueness` part of the path can only come after a label.)
#
path = '/db/data/schema/constraint'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, constraints) ->
cb err, constraints?.map Constraint._fromRaw
hasConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to query
whether a constraint exists.'
# NOTE: A REST API endpoint *does* exist to get a specific constraint:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html
# But it (a) returns an array, and (b) throws a 404 if no constraint.
# https://github.com/neo4j/neo4j/issues/4214
# For those reasons, it's actually easier to just fetch all constraints;
# no error handling needed, and array processing either way.
#
# NOTE: We explicitly *are* assuming uniqueness type here, since we
# also would if we were querying for a specific constraint.
# (The `/uniqueness` part of the path comes before the property.)
#
@http
method: 'GET'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
, (err, constraints) ->
if err
cb err
else
cb null, constraints.some (constraint) ->
constraint = Constraint._fromRaw constraint
constraint.label is label and
constraint.property is property
createConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create a constraint.'
# NOTE: We explicitly *are* assuming uniqueness type here, since
# that's our only option today for creating constraints.
# NOTE: Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this constraint already exists.
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Constraint._fromRaw resp.body
dropConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to drop a constraint.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html#rest-api-drop-constraint
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/constraint/#{encodeURIComponent label}\
/uniqueness/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this constraint doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Constraint existed and was dropped
# TODO: Legacy indexing
## HELPERS
#
# Normalizes the given auth value, which can be a 'username:password' string
# or a {username, password} object, to an object or null always.
#
_normalizeAuth = (auth) ->
# Support empty string for no auth:
return null if not auth
# Parse string if given, being robust to colons in the password:
if typeof auth is 'string'
[username, passwordParts...] = auth.split ':'
password = passwordParts.join ':'
auth = {username, password}
# Support empty object for no auth also:
return null if (Object.keys auth).length is 0
auth
#
# Deep inspects the given object -- which could be a simple primitive, a map,
# an array with arbitrary other objects, etc. -- and transforms any objects that
# look like nodes and relationships into Node and Relationship instances.
# Returns the transformed object, and does not mutate the input object.
#
_transform = (obj) ->
# Nothing to transform for primitives and null:
if (not obj) or (typeof obj isnt 'object')
return obj
# Process arrays:
# (NOTE: Not bothering to detect arrays made in other JS contexts.)
if obj instanceof Array
return obj.map _transform
# Feature-detect (AKA "duck-type") Node & Relationship objects, by simply
# trying to parse them as such.
# Important: check relationships first, for precision/specificity.
# TODO: If we add a Path class, we'll need to check for that here too.
if rel = Relationship._fromRaw obj
return rel
if node = Node._fromRaw obj
return node
# Otherwise, process as a dictionary/map:
map = {}
for key, val of obj
map[key] = _transform val
map
| true | $ = require 'underscore'
assert = require 'assert'
Constraint = require './Constraint'
{Error} = require './errors'
Index = require './Index'
lib = require '../package.json'
Node = require './Node'
Relationship = require './Relationship'
Request = require 'request'
Transaction = require './Transaction'
URL = require 'url'
module.exports = class GraphDatabase
## CORE
# Default HTTP headers:
headers:
'User-Agent': "node-neo4j/#{lib.version}"
constructor: (opts={}) ->
if typeof opts is 'string'
opts = {url: opts}
{@url, @auth, @headers, @proxy, @agent} = opts
if not @url
throw new TypeError 'URL to Neo4j required'
# Process auth, whether through option or URL creds or both.
# Option takes precedence, and we clear the URL creds if option given.
uri = URL.parse @url
if uri.auth and @auth?
delete uri.auth
@url = URL.format uri
# We also normalize any given auth to an object or null:
@auth = _normalizeAuth @auth ? uri.auth
# Extend the given headers with our defaults, but clone first:
# TODO: Do we want to special-case User-Agent? Or reject if includes
# reserved headers like Accept, Content-Type, X-Stream?
@headers or= {}
@headers = $(@headers)
.chain()
.clone()
.defaults @constructor::headers
.value()
## HTTP
http: (opts={}, cb) ->
if typeof opts is 'string'
opts = {path: opts}
{method, path, headers, body, raw} = opts
if not path
throw new TypeError 'Path required'
method or= 'GET'
headers or= {}
# Extend the given headers, both with both required and optional
# defaults, but do so without modifying the input object:
headers = $(headers)
.chain()
.clone()
.defaults @headers # These headers can be overridden...
.extend # ...while these can't.
'X-Stream': 'true'
.value()
# TODO: Would be good to test custom proxy and agent, but difficult.
# Same with Neo4j returning gzipped responses (e.g. through an LB).
Request
method: method
url: URL.resolve @url, path
proxy: @proxy
auth: @auth
headers: headers
agent: @agent
json: body ? true
encoding: 'utf8'
gzip: true # This is only for responses: decode if gzipped.
# Important: only pass a callback to Request if a callback was passed
# to us. This prevents Request from buffering the response in memory
# (to parse JSON) if the caller prefers to stream the response instead.
, cb and (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
return cb err
if raw
# TODO: Do we want to return our own Response object?
return cb null, resp
if err = Error._fromResponse resp
return cb err
cb null, _transform resp.body
## AUTH
checkPasswordChangeNeeded: (cb) ->
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
@http
method: 'GET'
path: "/user/#{encodeURIComponent @auth.username}"
, (err, user) ->
if err
return cb err
cb null, user.password_change_required
changePassword: (opts={}, cb) ->
if typeof opts is 'string'
opts = {password: opts}
{password} = opts
if not @auth?.username
throw new TypeError 'No `auth` specified in constructor!'
if not password
throw new TypeError 'Password required'
@http
method: 'POST'
path: "/user/#{encodeURIComponent @auth.username}/password"
body: {password}
, (err) =>
if err
return cb err
# Since successful, update our saved state for subsequent requests:
@auth.password = PI:PASSWORD:<PASSWORD>END_PI
# Void method:
cb null
## CYPHER
# NOTE: This method is fairly complex, in part out of necessity.
# We're okay with it since we test it throughly and emphasize its coverage.
# coffeelint: disable=cyclomatic_complexity
cypher: (opts={}, cb, _tx) ->
# coffeelint: enable=cyclomatic_complexity
if typeof opts is 'string'
opts = {query: opts}
if opts instanceof Array
opts = {queries: opts}
{queries, query, params, headers, lean, commit, rollback} = opts
if not _tx and rollback
throw new Error 'Illegal state: rolling back without a transaction!'
if commit and rollback
throw new Error 'Illegal state: both committing and rolling back!'
if rollback and (query or queries)
throw new Error 'Illegal state: rolling back with query/queries!'
if not _tx and commit is false
throw new TypeError 'Can’t refuse to commit without a transaction!
To begin a new transaction without committing, call
`db.beginTransaction()`, and then call `cypher` on that.'
if not _tx and not (query or queries)
throw new TypeError 'Query or queries required'
if query and queries
throw new TypeError 'Can’t supply both a single query
and a batch of queries! Do you have a bug in your code?'
if queries and params
throw new TypeError 'When batching multiple queries,
params must be supplied with each query, not globally.'
if queries and lean
throw new TypeError 'When batching multiple queries,
`lean` must be specified with each query, not globally.'
if (commit or rollback) and not (query or queries) and not _tx._id
# (Note that we've already required query or queries if no
# transaction present, so this means a transaction is present.)
# This transaction hasn't even been created yet from Neo4j's POV
# (because transactions are created lazily), so nothing to do.
cb null, null
return
method = 'POST'
method = 'DELETE' if rollback
path = '/db/data/transaction'
path += "/#{_tx._id}" if _tx?._id
path += '/commit' if commit or not _tx
# Normalize input query or queries to an array of queries always,
# but remember whether a single query was given (not a batch).
# Also handle the case where no queries were given; this is either a
# void action (e.g. rollback), or legitimately an empty batch.
if query
queries = [{query, params, lean}]
single = true
else
single = not queries # void action, *not* empty [] given
queries or= []
# Generate the request body by transforming each query (which is
# potentially a simple string) into Neo4j's `statement` format.
# We need to remember what result format we requested for each query.
formats = []
body =
statements:
for query in queries
if typeof query is 'string'
query = {query}
if query.headers
throw new TypeError 'When batching multiple queries,
custom request headers cannot be supplied per query;
they must be supplied globally.'
{query, params, lean} = query
# NOTE: Lowercase 'rest' matters here for parsing.
formats.push format = if lean then 'row' else 'rest'
# NOTE: Braces needed by CoffeeLint for now.
# https://github.com/clutchski/coffeelint/issues/459
{
statement: query
parameters: params or {}
resultDataContents: [format]
}
# TODO: Support streaming!
#
# NOTE: Specifying `raw: true` to save on parsing work (see `_transform`
# helper at the bottom of this file) if any queries are `lean: true`.
# Easy enough for us to parse ourselves, which we do, when needed.
#
@http {method, path, headers, body, raw: true}, (err, resp) =>
if err
# TODO: Do we want to wrap or modify native errors?
# NOTE: This includes our own errors for non-2xx responses.
return cb err
if err = Error._fromResponse resp
return cb err
_tx?._updateFromResponse resp
{results, errors} = resp.body
# Parse any results first, before errors, in case this is a batch
# request, where we want to return results alongside errors.
# The top-level `results` is an array of results corresponding to
# the `statements` (queries) inputted.
# We want to transform each query's results from Neo4j's complex
# format to a simple array of dictionaries.
results =
for result, i in results
{columns, data} = result
format = formats[i]
# The `data` for each query is an array of rows, but each of
# its elements is actually a dictionary of results keyed by
# response format. We only request one format per query.
# The value of each format is an array of rows, where each
# row is an array of column values. We transform those rows
# into dictionaries keyed by column names. Finally, we also
# parse nodes & relationships into object instances if this
# query didn't request a raw format. Phew!
$(data).pluck(format).map (row) ->
result = {}
for column, j in columns
result[column] = row[j]
if format is 'rest'
result = _transform result
result
# What exactly we return depends on how we were called:
#
# - Batch: if an array of queries were given, we always return an
# array of each query's results.
#
# - Single: if a single query was given, we always return just that
# query's results.
#
# - Void: if neither was given, we explicitly return null.
# This is for transaction actions, e.g. commit, rollback, renew.
#
# We're already set up for the batch case by default, so we only
# need to account for the other cases.
#
if single
# This means a batch of queries was *not* given, but we still
# normalized to an array of queries...
if queries.length
# This means a single query was given:
assert.equal queries.length, 1,
'There should be *exactly* one query given.'
assert results.length <= 1,
'There should be *at most* one set of results.'
results = results[0]
else
# This means no query was given:
assert.equal results.length, 0,
'There should be *no* results.'
results = null
if errors.length
# TODO: Is it possible to get back more than one error?
# If so, is it fine for us to just use the first one?
[error] = errors
err = Error._fromObject error
cb err, results
beginTransaction: ->
new Transaction @
## SCHEMA
getLabels: (cb) ->
# This endpoint returns the array of labels directly:
# http://neo4j.com/docs/stable/rest-api-node-labels.html#rest-api-list-all-labels
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/labels'
, cb
getPropertyKeys: (cb) ->
# This endpoint returns the array of property keys directly:
# http://neo4j.com/docs/stable/rest-api-property-values.html#rest-api-list-all-property-keys
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/propertykeys'
, cb
getRelationshipTypes: (cb) ->
# This endpoint returns the array of relationship types directly:
# http://neo4j.com/docs/stable/rest-api-relationship-types.html#rest-api-get-relationship-types
# Hence passing the callback directly. `http` handles 4xx, 5xx errors.
@http
method: 'GET'
path: '/db/data/relationship/types'
, cb
## INDEXES
getIndexes: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
{label} = opts
# Support both querying for a given label, and across all labels:
path = '/db/data/schema/index'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, indexes) ->
cb err, indexes?.map Index._fromRaw
hasIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to query whether an index exists.'
# NOTE: This is just a convenience method; there is no REST API endpoint
# for this directly (surprisingly, since there is for constraints).
# https://github.com/neo4j/neo4j/issues/4214
@getIndexes {label}, (err, indexes) ->
cb err, indexes?.some (index) ->
index.label is label and index.property is property
createIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create an index.'
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/index/#{encodeURIComponent label}"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this index already exists (including for a constraint).
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Index._fromRaw resp.body
dropIndex: (opts={}, cb) ->
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to drop an index.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-indexes.html#rest-api-drop-index
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/index\
/#{encodeURIComponent label}/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this index doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Index existed and was dropped
## CONSTRAINTS
getConstraints: (opts={}, cb) ->
# Support passing no options at all, to mean "across all labels":
if typeof opts is 'function'
cb = opts
opts = {}
# Also support passing a label directory:
if typeof opts is 'string'
opts = {label: opts}
# TODO: We may need to support querying within a particular `type` too,
# if any other types beyond uniqueness get added.
{label} = opts
# Support both querying for a given label, and across all labels.
#
# NOTE: We're explicitly *not* assuming uniqueness type here, since we
# couldn't achieve consistency with vs. without a label provided.
# (The `/uniqueness` part of the path can only come after a label.)
#
path = '/db/data/schema/constraint'
path += "/#{encodeURIComponent label}" if label
@http
method: 'GET'
path: path
, (err, constraints) ->
cb err, constraints?.map Constraint._fromRaw
hasConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError 'Label and property required to query
whether a constraint exists.'
# NOTE: A REST API endpoint *does* exist to get a specific constraint:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html
# But it (a) returns an array, and (b) throws a 404 if no constraint.
# https://github.com/neo4j/neo4j/issues/4214
# For those reasons, it's actually easier to just fetch all constraints;
# no error handling needed, and array processing either way.
#
# NOTE: We explicitly *are* assuming uniqueness type here, since we
# also would if we were querying for a specific constraint.
# (The `/uniqueness` part of the path comes before the property.)
#
@http
method: 'GET'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
, (err, constraints) ->
if err
cb err
else
cb null, constraints.some (constraint) ->
constraint = Constraint._fromRaw constraint
constraint.label is label and
constraint.property is property
createConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to create a constraint.'
# NOTE: We explicitly *are* assuming uniqueness type here, since
# that's our only option today for creating constraints.
# NOTE: Passing `raw: true` so we can handle the 409 case below.
@http
method: 'POST'
path: "/db/data/schema/constraint\
/#{encodeURIComponent label}/uniqueness"
body: {'property_keys': [property]}
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 409 error (w/ varying code across versions)
# if this constraint already exists.
if resp.statusCode is 409
return cb null, null
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, if resp.body then Constraint._fromRaw resp.body
dropConstraint: (opts={}, cb) ->
# TODO: We may need to support an additional `type` param too,
# if any other types beyond uniqueness get added.
{label, property} = opts
if not (label and property)
throw new TypeError \
'Label and property required to drop a constraint.'
# This endpoint is void, i.e. returns nothing:
# http://neo4j.com/docs/stable/rest-api-schema-constraints.html#rest-api-drop-constraint
# Passing `raw: true` so we can handle the 409 case below.
@http
method: 'DELETE'
path: "/db/data/schema/constraint/#{encodeURIComponent label}\
/uniqueness/#{encodeURIComponent property}"
raw: true
, (err, resp) ->
if err
return cb err
# Neo4j returns a 404 response (with an empty body)
# if this constraint doesn't exist (has already been dropped).
if resp.statusCode is 404
return cb null, false
# Translate all other error responses as legitimate errors:
if err = Error._fromResponse resp
return cb err
cb err, true # Constraint existed and was dropped
# TODO: Legacy indexing
## HELPERS
#
# Normalizes the given auth value, which can be a 'username:password' string
# or a {username, password} object, to an object or null always.
#
_normalizeAuth = (auth) ->
# Support empty string for no auth:
return null if not auth
# Parse string if given, being robust to colons in the password:
if typeof auth is 'string'
[username, passwordParts...] = auth.split ':'
password = passwordParts.join ':'
auth = {username, password}
# Support empty object for no auth also:
return null if (Object.keys auth).length is 0
auth
#
# Deep inspects the given object -- which could be a simple primitive, a map,
# an array with arbitrary other objects, etc. -- and transforms any objects that
# look like nodes and relationships into Node and Relationship instances.
# Returns the transformed object, and does not mutate the input object.
#
_transform = (obj) ->
# Nothing to transform for primitives and null:
if (not obj) or (typeof obj isnt 'object')
return obj
# Process arrays:
# (NOTE: Not bothering to detect arrays made in other JS contexts.)
if obj instanceof Array
return obj.map _transform
# Feature-detect (AKA "duck-type") Node & Relationship objects, by simply
# trying to parse them as such.
# Important: check relationships first, for precision/specificity.
# TODO: If we add a Path class, we'll need to check for that here too.
if rel = Relationship._fromRaw obj
return rel
if node = Node._fromRaw obj
return node
# Otherwise, process as a dictionary/map:
map = {}
for key, val of obj
map[key] = _transform val
map
|
[
{
"context": "/DuplicateError\n@extends restify/RestError\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n{ RestError } = ",
"end": 666,
"score": 0.9998784065246582,
"start": 652,
"tag": "NAME",
"value": "Isaac Johnston"
},
{
"context": "extends restify/RestError\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n{ RestError } = require( 'restify' )\n\nmodul",
"end": 693,
"score": 0.9999335408210754,
"start": 668,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
}
] | src/error/DuplicateError.coffee | joukou/joukou-api | 0 | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
@class joukou-api/error/DuplicateError
@extends restify/RestError
@author Isaac Johnston <isaac.johnston@joukou.com>
###
{ RestError } = require( 'restify' )
module.exports = class extends RestError
###*
@private
@static
@property {joukou-api.error.DuplicateError} self
###
self = @
###*
@method constructor
@param {String} indexName
###
constructor: (@indexName) ->
super(
restCode: 'DuplicateError'
statusCode: 409
message: @indexName
constructorOpt: self.DuplicateError
) | 168276 | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
@class joukou-api/error/DuplicateError
@extends restify/RestError
@author <NAME> <<EMAIL>>
###
{ RestError } = require( 'restify' )
module.exports = class extends RestError
###*
@private
@static
@property {joukou-api.error.DuplicateError} self
###
self = @
###*
@method constructor
@param {String} indexName
###
constructor: (@indexName) ->
super(
restCode: 'DuplicateError'
statusCode: 409
message: @indexName
constructorOpt: self.DuplicateError
) | true | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
@class joukou-api/error/DuplicateError
@extends restify/RestError
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
{ RestError } = require( 'restify' )
module.exports = class extends RestError
###*
@private
@static
@property {joukou-api.error.DuplicateError} self
###
self = @
###*
@method constructor
@param {String} indexName
###
constructor: (@indexName) ->
super(
restCode: 'DuplicateError'
statusCode: 409
message: @indexName
constructorOpt: self.DuplicateError
) |
[
{
"context": "preserve\nBrauhaus.js BeerXML Plugin\nCopyright 2013 Daniel G. Taylor <danielgtaylor@gmail.com>\nhttps://github.com/home",
"end": 72,
"score": 0.9998127222061157,
"start": 56,
"tag": "NAME",
"value": "Daniel G. Taylor"
},
{
"context": "s BeerXML Plugin\nCopyright 2013 Daniel G. Taylor <danielgtaylor@gmail.com>\nhttps://github.com/homebrewing/brauhausjs-beerxm",
"end": 97,
"score": 0.9999321699142456,
"start": 74,
"tag": "EMAIL",
"value": "danielgtaylor@gmail.com"
},
{
"context": "nielgtaylor@gmail.com>\nhttps://github.com/homebrewing/brauhausjs-beerxml\n###\n\n# Import Brauhaus if it h",
"end": 129,
"score": 0.6129202842712402,
"start": 126,
"tag": "USERNAME",
"value": "ing"
}
] | src/globals.coffee | pedesen/brauhaus-beerxml | 0 | ###
@preserve
Brauhaus.js BeerXML Plugin
Copyright 2013 Daniel G. Taylor <danielgtaylor@gmail.com>
https://github.com/homebrewing/brauhausjs-beerxml
###
# Import Brauhaus if it hasn't already been defined
Brauhaus = @Brauhaus ? require 'brauhaus'
# Import DOM parser if needed to process BeerXML input
# Works in Node.js, Chrome, Firefox, IE9+, etc
DOMParser = window?.DOMParser ? require('xmldom').DOMParser
| 109106 | ###
@preserve
Brauhaus.js BeerXML Plugin
Copyright 2013 <NAME> <<EMAIL>>
https://github.com/homebrewing/brauhausjs-beerxml
###
# Import Brauhaus if it hasn't already been defined
Brauhaus = @Brauhaus ? require 'brauhaus'
# Import DOM parser if needed to process BeerXML input
# Works in Node.js, Chrome, Firefox, IE9+, etc
DOMParser = window?.DOMParser ? require('xmldom').DOMParser
| true | ###
@preserve
Brauhaus.js BeerXML Plugin
Copyright 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
https://github.com/homebrewing/brauhausjs-beerxml
###
# Import Brauhaus if it hasn't already been defined
Brauhaus = @Brauhaus ? require 'brauhaus'
# Import DOM parser if needed to process BeerXML input
# Works in Node.js, Chrome, Firefox, IE9+, etc
DOMParser = window?.DOMParser ? require('xmldom').DOMParser
|
[
{
"context": "fore saving', ->\n user = new User\n name: 'Brian'\n resume: \"Line one\\r\\n\\r\\r\\r\\nLine two\"\n ",
"end": 666,
"score": 0.9994869232177734,
"start": 661,
"tag": "NAME",
"value": "Brian"
},
{
"context": "fter saving', ->\n user = new User\n name: 'Brian'\n \n user.save (success) ->\n expect(use",
"end": 1015,
"score": 0.9994463920593262,
"start": 1010,
"tag": "NAME",
"value": "Brian"
},
{
"context": "ave (success) ->\n expect(user.name).toEqual 'nairB'\n expect(user._dirty).toContain 'name'",
"end": 1087,
"score": 0.99933260679245,
"start": 1082,
"tag": "USERNAME",
"value": "nairB"
}
] | spec/callbacks.spec.coffee | brianewing/footrest | 1 | footrest = require('../lib/index')
Model = require('../lib/model').Model
class User extends Model
@type 'User'
@database = footrest.database('footrest')
@attr 'name', 'password', 'email', 'resume'
@beforeSave 'cleanResume'
@afterSave 'reverseName'
cleanResume: ->
@resume = @resume.replace /\r\n?/g, "\n" if @resume
reverseName: ->
@name = @name.split('').reverse().join('')
describe 'callbacks', ->
beforeEach ->
@database = User.database
@database.destroy => @database.create => @recreated = true
waitsFor -> @recreated?
it 'should call beforeSave callbacks before saving', ->
user = new User
name: 'Brian'
resume: "Line one\r\n\r\r\r\nLine two"
expect(user.resume).toEqual "Line one\r\n\r\r\r\nLine two"
user.save (success) ->
expect(user.resume).toEqual "Line one\n\n\n\nLine two"
expect(user._dirty).not.toContain 'resume'
it 'should call afterSave callbacks after saving', ->
user = new User
name: 'Brian'
user.save (success) ->
expect(user.name).toEqual 'nairB'
expect(user._dirty).toContain 'name' | 194949 | footrest = require('../lib/index')
Model = require('../lib/model').Model
class User extends Model
@type 'User'
@database = footrest.database('footrest')
@attr 'name', 'password', 'email', 'resume'
@beforeSave 'cleanResume'
@afterSave 'reverseName'
cleanResume: ->
@resume = @resume.replace /\r\n?/g, "\n" if @resume
reverseName: ->
@name = @name.split('').reverse().join('')
describe 'callbacks', ->
beforeEach ->
@database = User.database
@database.destroy => @database.create => @recreated = true
waitsFor -> @recreated?
it 'should call beforeSave callbacks before saving', ->
user = new User
name: '<NAME>'
resume: "Line one\r\n\r\r\r\nLine two"
expect(user.resume).toEqual "Line one\r\n\r\r\r\nLine two"
user.save (success) ->
expect(user.resume).toEqual "Line one\n\n\n\nLine two"
expect(user._dirty).not.toContain 'resume'
it 'should call afterSave callbacks after saving', ->
user = new User
name: '<NAME>'
user.save (success) ->
expect(user.name).toEqual 'nairB'
expect(user._dirty).toContain 'name' | true | footrest = require('../lib/index')
Model = require('../lib/model').Model
class User extends Model
@type 'User'
@database = footrest.database('footrest')
@attr 'name', 'password', 'email', 'resume'
@beforeSave 'cleanResume'
@afterSave 'reverseName'
cleanResume: ->
@resume = @resume.replace /\r\n?/g, "\n" if @resume
reverseName: ->
@name = @name.split('').reverse().join('')
describe 'callbacks', ->
beforeEach ->
@database = User.database
@database.destroy => @database.create => @recreated = true
waitsFor -> @recreated?
it 'should call beforeSave callbacks before saving', ->
user = new User
name: 'PI:NAME:<NAME>END_PI'
resume: "Line one\r\n\r\r\r\nLine two"
expect(user.resume).toEqual "Line one\r\n\r\r\r\nLine two"
user.save (success) ->
expect(user.resume).toEqual "Line one\n\n\n\nLine two"
expect(user._dirty).not.toContain 'resume'
it 'should call afterSave callbacks after saving', ->
user = new User
name: 'PI:NAME:<NAME>END_PI'
user.save (success) ->
expect(user.name).toEqual 'nairB'
expect(user._dirty).toContain 'name' |
[
{
"context": " beforeEach ->\n _data = [\n {name: \"Jim\"}\n {name: \"Some Dude\"}\n ]\n\n $htt",
"end": 1225,
"score": 0.9994045495986938,
"start": 1222,
"tag": "NAME",
"value": "Jim"
},
{
"context": " _data = [\n {name: \"Jim\"}\n {name: \"Some Dude\"}\n ]\n\n $httpBackend.whenGET('/me/friend",
"end": 1253,
"score": 0.9975326061248779,
"start": 1244,
"tag": "NAME",
"value": "Some Dude"
}
] | test/unit/extras_spec.coffee | killercup/angular-epicmodel | 0 | describe "Extras", ->
angular.module 'Stuff', ['EpicModel']
beforeEach module('Stuff')
beforeEach addHelpers()
Collection = $httpBackend = null
beforeEach inject (_$httpBackend_, _Collection_) ->
Collection = _Collection_
$httpBackend = _$httpBackend_
describe 'as functions', ->
it 'should be available', ->
Specials = Collection.new "Specials", {},
calculateStuff: (data) ->
if _.isArray(data)
_.reduce data, ((memo, val) -> memo + +val.count), 0
else 42
sum = Specials.calculateStuff [{count: 3}, {count: 2}]
expect(sum).to.eql 5
num = Specials.calculateStuff "hi"
expect(num).to.eql 42
it 'should have Collection config as scope', ->
specialBaseUrl = 'https://example.com/api/v42'
specialUrl = '/1337'
Thingy = Collection.new "Thingy", {
baseUrl: specialBaseUrl
url: specialUrl
},
allYourBases: -> @baseUrl
whatsThisUrl: -> @url
expect(Thingy.allYourBases()).to.eql specialBaseUrl
expect(Thingy.whatsThisUrl()).to.eql specialUrl
describe 'as HTTP calls', ->
# Mock Server on `/me/friends`
beforeEach ->
_data = [
{name: "Jim"}
{name: "Some Dude"}
]
$httpBackend.whenGET('/me/friends').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
friendsUrl = /^\/user\/(\d*)\/friends$/
$httpBackend.whenGET(friendsUrl).respond (method, url, data) ->
id = +friendsUrl.exec(url)[1]
log "GET #{url}"
[200, {msg: "friends for #{id}"}, {}]
$httpBackend.whenPATCH('/user/payout').respond (method, url, data) ->
log "GET #{url}"
if data.payout
[200, {payout: {status: 'success'}}, {}]
else
[400, {err: 'no payout'}, {}]
it 'should work', (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
url: '/me/friends'
expect(Me.friends).to.be.a('function')
friends = Me.friends()
expect(friends).to.respondTo('then')
friends.then (response) ->
expect(response.data).to.exist
expect(response.data).to.have.deep.property('[1].name')
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should guess URLs", (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
$httpBackend.expectGET('/me/friends')
.respond ->
done(null)
Me.friends()
.then null, (err) ->
done new Error JSON.stringify err
tick()
it 'should work with URL matching', (done) ->
User = Collection.new "User", {},
friends:
method: 'GET'
url: '/user/{id}/friends'
theUser = 1
friends = User.friends(id: theUser)
friends.then ({data}) ->
expect(data).to.exist
expect(data.msg).to.eql "friends for #{theUser}"
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "can use cool HTTP methods", (done) ->
User = Collection.new 'User', {is_singleton: true},
payout:
method: 'PATCH'
data:
payout: true
$httpBackend.expectPATCH('/user/payout')
.respond ->
done(null)
User.payout()
.then null, (err) ->
done new Error JSON.stringify err
tick()
describe "with bound callbacks", ->
Messages = null
early = 20131220
okay = 20131222
late = 20131224
errorCheck = "It failed."
# Mock Server on `/messages`
beforeEach inject ($httpBackend) ->
id = 0
_data = [
{id: ++id, created: early}
{id: ++id, created: okay}
]
$httpBackend.whenGET('/messages').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
messagesSinceUrl = /\/messages\?since=(\d.*)/
$httpBackend.whenGET(messagesSinceUrl).respond (method, url, data) ->
log "GET #{url}"
since = +messagesSinceUrl.exec(url)[1]
if since is 42
return [403, {err: 'Classified'}, {}]
[
200
[{id: ++id, created: late}]
{}
]
# Messages Collection
beforeEach ->
Messages = Collection.new "Messages", {},
update:
method: 'GET'
url: "/messages"
###
# @method Incremental Updates
#
# @description This is a great example on how to incremetally update
# date using callbacks, since they are bound to have `this` point
# to the Collection's `config` object!
# @param {Object} response HTTP response
# @return {Object} HTTP response (can be used in chained promises)
###
onSuccess: (response) ->
if _.isArray response.data
_.each response.data, (item) =>
@Data.updateEntry item, @matchingCriteria(item)
return response
# Test failure callback by manipulating return value
onFail: (response) ->
response.data = errorCheck
return response
it "should enable incremental updates", (done) ->
messages = Messages.all()
messages.$promise
.then ->
expect(messages.all).to.not.contain late
Messages.update {}, params: since: late
.then (response) ->
# console.log response.data
expect(
_.pluck messages.all, 'created'
).to.contain late
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should offer failure handling", (done) ->
Messages.update({}, params: since: 42)
.then ->
done new Error "Should have been an error."
.then null, ({data}) ->
expect(data).to.eql errorCheck
done(null)
tick()
| 170779 | describe "Extras", ->
angular.module 'Stuff', ['EpicModel']
beforeEach module('Stuff')
beforeEach addHelpers()
Collection = $httpBackend = null
beforeEach inject (_$httpBackend_, _Collection_) ->
Collection = _Collection_
$httpBackend = _$httpBackend_
describe 'as functions', ->
it 'should be available', ->
Specials = Collection.new "Specials", {},
calculateStuff: (data) ->
if _.isArray(data)
_.reduce data, ((memo, val) -> memo + +val.count), 0
else 42
sum = Specials.calculateStuff [{count: 3}, {count: 2}]
expect(sum).to.eql 5
num = Specials.calculateStuff "hi"
expect(num).to.eql 42
it 'should have Collection config as scope', ->
specialBaseUrl = 'https://example.com/api/v42'
specialUrl = '/1337'
Thingy = Collection.new "Thingy", {
baseUrl: specialBaseUrl
url: specialUrl
},
allYourBases: -> @baseUrl
whatsThisUrl: -> @url
expect(Thingy.allYourBases()).to.eql specialBaseUrl
expect(Thingy.whatsThisUrl()).to.eql specialUrl
describe 'as HTTP calls', ->
# Mock Server on `/me/friends`
beforeEach ->
_data = [
{name: "<NAME>"}
{name: "<NAME>"}
]
$httpBackend.whenGET('/me/friends').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
friendsUrl = /^\/user\/(\d*)\/friends$/
$httpBackend.whenGET(friendsUrl).respond (method, url, data) ->
id = +friendsUrl.exec(url)[1]
log "GET #{url}"
[200, {msg: "friends for #{id}"}, {}]
$httpBackend.whenPATCH('/user/payout').respond (method, url, data) ->
log "GET #{url}"
if data.payout
[200, {payout: {status: 'success'}}, {}]
else
[400, {err: 'no payout'}, {}]
it 'should work', (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
url: '/me/friends'
expect(Me.friends).to.be.a('function')
friends = Me.friends()
expect(friends).to.respondTo('then')
friends.then (response) ->
expect(response.data).to.exist
expect(response.data).to.have.deep.property('[1].name')
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should guess URLs", (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
$httpBackend.expectGET('/me/friends')
.respond ->
done(null)
Me.friends()
.then null, (err) ->
done new Error JSON.stringify err
tick()
it 'should work with URL matching', (done) ->
User = Collection.new "User", {},
friends:
method: 'GET'
url: '/user/{id}/friends'
theUser = 1
friends = User.friends(id: theUser)
friends.then ({data}) ->
expect(data).to.exist
expect(data.msg).to.eql "friends for #{theUser}"
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "can use cool HTTP methods", (done) ->
User = Collection.new 'User', {is_singleton: true},
payout:
method: 'PATCH'
data:
payout: true
$httpBackend.expectPATCH('/user/payout')
.respond ->
done(null)
User.payout()
.then null, (err) ->
done new Error JSON.stringify err
tick()
describe "with bound callbacks", ->
Messages = null
early = 20131220
okay = 20131222
late = 20131224
errorCheck = "It failed."
# Mock Server on `/messages`
beforeEach inject ($httpBackend) ->
id = 0
_data = [
{id: ++id, created: early}
{id: ++id, created: okay}
]
$httpBackend.whenGET('/messages').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
messagesSinceUrl = /\/messages\?since=(\d.*)/
$httpBackend.whenGET(messagesSinceUrl).respond (method, url, data) ->
log "GET #{url}"
since = +messagesSinceUrl.exec(url)[1]
if since is 42
return [403, {err: 'Classified'}, {}]
[
200
[{id: ++id, created: late}]
{}
]
# Messages Collection
beforeEach ->
Messages = Collection.new "Messages", {},
update:
method: 'GET'
url: "/messages"
###
# @method Incremental Updates
#
# @description This is a great example on how to incremetally update
# date using callbacks, since they are bound to have `this` point
# to the Collection's `config` object!
# @param {Object} response HTTP response
# @return {Object} HTTP response (can be used in chained promises)
###
onSuccess: (response) ->
if _.isArray response.data
_.each response.data, (item) =>
@Data.updateEntry item, @matchingCriteria(item)
return response
# Test failure callback by manipulating return value
onFail: (response) ->
response.data = errorCheck
return response
it "should enable incremental updates", (done) ->
messages = Messages.all()
messages.$promise
.then ->
expect(messages.all).to.not.contain late
Messages.update {}, params: since: late
.then (response) ->
# console.log response.data
expect(
_.pluck messages.all, 'created'
).to.contain late
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should offer failure handling", (done) ->
Messages.update({}, params: since: 42)
.then ->
done new Error "Should have been an error."
.then null, ({data}) ->
expect(data).to.eql errorCheck
done(null)
tick()
| true | describe "Extras", ->
angular.module 'Stuff', ['EpicModel']
beforeEach module('Stuff')
beforeEach addHelpers()
Collection = $httpBackend = null
beforeEach inject (_$httpBackend_, _Collection_) ->
Collection = _Collection_
$httpBackend = _$httpBackend_
describe 'as functions', ->
it 'should be available', ->
Specials = Collection.new "Specials", {},
calculateStuff: (data) ->
if _.isArray(data)
_.reduce data, ((memo, val) -> memo + +val.count), 0
else 42
sum = Specials.calculateStuff [{count: 3}, {count: 2}]
expect(sum).to.eql 5
num = Specials.calculateStuff "hi"
expect(num).to.eql 42
it 'should have Collection config as scope', ->
specialBaseUrl = 'https://example.com/api/v42'
specialUrl = '/1337'
Thingy = Collection.new "Thingy", {
baseUrl: specialBaseUrl
url: specialUrl
},
allYourBases: -> @baseUrl
whatsThisUrl: -> @url
expect(Thingy.allYourBases()).to.eql specialBaseUrl
expect(Thingy.whatsThisUrl()).to.eql specialUrl
describe 'as HTTP calls', ->
# Mock Server on `/me/friends`
beforeEach ->
_data = [
{name: "PI:NAME:<NAME>END_PI"}
{name: "PI:NAME:<NAME>END_PI"}
]
$httpBackend.whenGET('/me/friends').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
friendsUrl = /^\/user\/(\d*)\/friends$/
$httpBackend.whenGET(friendsUrl).respond (method, url, data) ->
id = +friendsUrl.exec(url)[1]
log "GET #{url}"
[200, {msg: "friends for #{id}"}, {}]
$httpBackend.whenPATCH('/user/payout').respond (method, url, data) ->
log "GET #{url}"
if data.payout
[200, {payout: {status: 'success'}}, {}]
else
[400, {err: 'no payout'}, {}]
it 'should work', (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
url: '/me/friends'
expect(Me.friends).to.be.a('function')
friends = Me.friends()
expect(friends).to.respondTo('then')
friends.then (response) ->
expect(response.data).to.exist
expect(response.data).to.have.deep.property('[1].name')
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should guess URLs", (done) ->
Me = Collection.new "Me", {is_singleton: true},
friends:
method: 'GET'
$httpBackend.expectGET('/me/friends')
.respond ->
done(null)
Me.friends()
.then null, (err) ->
done new Error JSON.stringify err
tick()
it 'should work with URL matching', (done) ->
User = Collection.new "User", {},
friends:
method: 'GET'
url: '/user/{id}/friends'
theUser = 1
friends = User.friends(id: theUser)
friends.then ({data}) ->
expect(data).to.exist
expect(data.msg).to.eql "friends for #{theUser}"
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "can use cool HTTP methods", (done) ->
User = Collection.new 'User', {is_singleton: true},
payout:
method: 'PATCH'
data:
payout: true
$httpBackend.expectPATCH('/user/payout')
.respond ->
done(null)
User.payout()
.then null, (err) ->
done new Error JSON.stringify err
tick()
describe "with bound callbacks", ->
Messages = null
early = 20131220
okay = 20131222
late = 20131224
errorCheck = "It failed."
# Mock Server on `/messages`
beforeEach inject ($httpBackend) ->
id = 0
_data = [
{id: ++id, created: early}
{id: ++id, created: okay}
]
$httpBackend.whenGET('/messages').respond (method, url, data) ->
log "GET #{url}"
[200, _data, {}]
messagesSinceUrl = /\/messages\?since=(\d.*)/
$httpBackend.whenGET(messagesSinceUrl).respond (method, url, data) ->
log "GET #{url}"
since = +messagesSinceUrl.exec(url)[1]
if since is 42
return [403, {err: 'Classified'}, {}]
[
200
[{id: ++id, created: late}]
{}
]
# Messages Collection
beforeEach ->
Messages = Collection.new "Messages", {},
update:
method: 'GET'
url: "/messages"
###
# @method Incremental Updates
#
# @description This is a great example on how to incremetally update
# date using callbacks, since they are bound to have `this` point
# to the Collection's `config` object!
# @param {Object} response HTTP response
# @return {Object} HTTP response (can be used in chained promises)
###
onSuccess: (response) ->
if _.isArray response.data
_.each response.data, (item) =>
@Data.updateEntry item, @matchingCriteria(item)
return response
# Test failure callback by manipulating return value
onFail: (response) ->
response.data = errorCheck
return response
it "should enable incremental updates", (done) ->
messages = Messages.all()
messages.$promise
.then ->
expect(messages.all).to.not.contain late
Messages.update {}, params: since: late
.then (response) ->
# console.log response.data
expect(
_.pluck messages.all, 'created'
).to.contain late
done(null)
.then null, (err) ->
done new Error JSON.stringify err
tick()
it "should offer failure handling", (done) ->
Messages.update({}, params: since: 42)
.then ->
done new Error "Should have been an error."
.then null, ({data}) ->
expect(data).to.eql errorCheck
done(null)
tick()
|
[
{
"context": " (done)->\n process.env.HUBOT_FORECAST_KEY = '234f931fed3c5c7b54c846c9100f8b50'\n process.env.HUBOT_LATITUDE = '42.351170'\n ",
"end": 1274,
"score": 0.9997336268424988,
"start": 1242,
"tag": "KEY",
"value": "234f931fed3c5c7b54c846c9100f8b50"
},
{
"context": "r = robot.brain.userForId '1', {\n name: 'jeff'\n room: '#mocha'\n }\n adapt",
"end": 1544,
"score": 0.7023296356201172,
"start": 1540,
"tag": "NAME",
"value": "jeff"
}
] | test/forecast-test.coffee | jeffbyrnes/hubot-forecast | 3 | path = require 'path'
fs = require 'fs'
Robot = require 'hubot/src/robot'
TextMessage = require('hubot/src/message').TextMessage
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
loadFixture = (name)->
JSON.parse fs.readFileSync "spec/fixtures/#{name}.json"
describe 'forecast', ->
robot = undefined
user = undefined
adapter = undefined
beforeEach ->
# create new robot, without http, using the mock adapter
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
afterEach ->
robot.server.close()
robot.shutdown()
describe 'when ENV is not set', ->
it 'should throw error', (done)->
sinon.spy robot.logger, 'error'
robot.adapter.on 'connected', ->
try
delete process.env.HUBOT_LATITUDE
delete process.env.HUBOT_LONGITUDE
delete process.env.HUBOT_FORECAST_KEY
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
expect(robot.logger.error).to.have.been.called
expect(robot.forecast).not.to.be.defined
do done
catch e
done e
do robot.run
describe 'when ENV is set', ->
beforeEach (done)->
process.env.HUBOT_FORECAST_KEY = '234f931fed3c5c7b54c846c9100f8b50'
process.env.HUBOT_LATITUDE = '42.351170'
process.env.HUBOT_LONGITUDE = '-71.049298'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
user = robot.brain.userForId '1', {
name: 'jeff'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
describe 'help', ->
it 'should have 2', (done)->
expect(robot.helpCommands()).to.have.length 2
do done
it 'has help messages', ->
expect(robot.helpCommands()).to.eql [
'hubot forecast - same as hubot weather'
'hubot weather - shows brief weather forecast from last cached data'
]
| 16738 | path = require 'path'
fs = require 'fs'
Robot = require 'hubot/src/robot'
TextMessage = require('hubot/src/message').TextMessage
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
loadFixture = (name)->
JSON.parse fs.readFileSync "spec/fixtures/#{name}.json"
describe 'forecast', ->
robot = undefined
user = undefined
adapter = undefined
beforeEach ->
# create new robot, without http, using the mock adapter
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
afterEach ->
robot.server.close()
robot.shutdown()
describe 'when ENV is not set', ->
it 'should throw error', (done)->
sinon.spy robot.logger, 'error'
robot.adapter.on 'connected', ->
try
delete process.env.HUBOT_LATITUDE
delete process.env.HUBOT_LONGITUDE
delete process.env.HUBOT_FORECAST_KEY
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
expect(robot.logger.error).to.have.been.called
expect(robot.forecast).not.to.be.defined
do done
catch e
done e
do robot.run
describe 'when ENV is set', ->
beforeEach (done)->
process.env.HUBOT_FORECAST_KEY = '<KEY>'
process.env.HUBOT_LATITUDE = '42.351170'
process.env.HUBOT_LONGITUDE = '-71.049298'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
user = robot.brain.userForId '1', {
name: '<NAME>'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
describe 'help', ->
it 'should have 2', (done)->
expect(robot.helpCommands()).to.have.length 2
do done
it 'has help messages', ->
expect(robot.helpCommands()).to.eql [
'hubot forecast - same as hubot weather'
'hubot weather - shows brief weather forecast from last cached data'
]
| true | path = require 'path'
fs = require 'fs'
Robot = require 'hubot/src/robot'
TextMessage = require('hubot/src/message').TextMessage
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
loadFixture = (name)->
JSON.parse fs.readFileSync "spec/fixtures/#{name}.json"
describe 'forecast', ->
robot = undefined
user = undefined
adapter = undefined
beforeEach ->
# create new robot, without http, using the mock adapter
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
afterEach ->
robot.server.close()
robot.shutdown()
describe 'when ENV is not set', ->
it 'should throw error', (done)->
sinon.spy robot.logger, 'error'
robot.adapter.on 'connected', ->
try
delete process.env.HUBOT_LATITUDE
delete process.env.HUBOT_LONGITUDE
delete process.env.HUBOT_FORECAST_KEY
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
expect(robot.logger.error).to.have.been.called
expect(robot.forecast).not.to.be.defined
do done
catch e
done e
do robot.run
describe 'when ENV is set', ->
beforeEach (done)->
process.env.HUBOT_FORECAST_KEY = 'PI:KEY:<KEY>END_PI'
process.env.HUBOT_LATITUDE = '42.351170'
process.env.HUBOT_LONGITUDE = '-71.049298'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src'), 'forecast.coffee'
user = robot.brain.userForId '1', {
name: 'PI:NAME:<NAME>END_PI'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
describe 'help', ->
it 'should have 2', (done)->
expect(robot.helpCommands()).to.have.length 2
do done
it 'has help messages', ->
expect(robot.helpCommands()).to.eql [
'hubot forecast - same as hubot weather'
'hubot weather - shows brief weather forecast from last cached data'
]
|
[
{
"context": "ys.lua\"]\n\ntemplates =\n init:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n lib",
"end": 319,
"score": 0.9829738140106201,
"start": 303,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": "\n init:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"r",
"end": 324,
"score": 0.6366285085678101,
"start": 324,
"tag": "KEY",
"value": ""
},
{
"context": ":\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"refresh_capaci",
"end": 338,
"score": 0.515204668045044,
"start": 331,
"tag": "KEY",
"value": "running"
},
{
"context": " lua[\"init.lua\"]\n heartbeat:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n lib",
"end": 490,
"score": 0.9877178072929382,
"start": 474,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": "artbeat:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 509,
"score": 0.5830937027931213,
"start": 496,
"tag": "KEY",
"value": "#{id}_running"
},
{
"context": "(id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refre",
"end": 517,
"score": 0.5795586705207825,
"start": 515,
"tag": "KEY",
"value": "#{"
},
{
"context": " [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\"]",
"end": 530,
"score": 0.6387674808502197,
"start": 521,
"tag": "KEY",
"value": "executing"
},
{
"context": "beat.lua\"]\n update_settings:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 669,
"score": 0.94228595495224,
"start": 651,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "ettings:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 686,
"score": 0.8446536064147949,
"start": 673,
"tag": "KEY",
"value": "#{id}_running"
},
{
"context": "(id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refre",
"end": 694,
"score": 0.613385796546936,
"start": 692,
"tag": "KEY",
"value": "#{"
},
{
"context": " [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\",",
"end": 707,
"score": 0.6289681196212769,
"start": 698,
"tag": "KEY",
"value": "executing"
},
{
"context": "ate_settings.lua\"]\n running:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 866,
"score": 0.957822322845459,
"start": 848,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": " running:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 883,
"score": 0.8628614544868469,
"start": 868,
"tag": "KEY",
"value": "b_#{id}_running"
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\"]",
"end": 904,
"score": 0.9428895115852356,
"start": 887,
"tag": "KEY",
"value": "b_#{id}_executing"
},
{
"context": "e: lua[\"running.lua\"]\n done:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 1030,
"score": 0.9245143532752991,
"start": 1012,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "]\n done:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 1047,
"score": 0.9352462887763977,
"start": 1032,
"tag": "KEY",
"value": "b_#{id}_running"
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\"]",
"end": 1068,
"score": 0.902186393737793,
"start": 1051,
"tag": "KEY",
"value": "b_#{id}_executing"
},
{
"context": "ua[\"done.lua\"]\n group_check:\n keys: (id) -> [\"b_#{id}_settings\"]\n libs: []\n code: lua[\"group_check.lua\"]\n ",
"end": 1196,
"score": 0.993873119354248,
"start": 1180,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": "eck.lua\"]\n group_delete_key:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 1303,
"score": 0.9817336797714233,
"start": 1285,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "lete_key:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: []\n code: lua[\"",
"end": 1322,
"score": 0.9499792456626892,
"start": 1305,
"tag": "KEY",
"value": "b_#{id}_running\","
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: []\n code: lua[\"group_delete_key.lu",
"end": 1341,
"score": 0.9854745864868164,
"start": 1324,
"tag": "KEY",
"value": "b_#{id}_executing"
},
{
"context": "oup_delete_key.lua\"]\n check:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n lib",
"end": 1440,
"score": 0.9868479371070862,
"start": 1424,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": " check:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"v",
"end": 1445,
"score": 0.6649991869926453,
"start": 1445,
"tag": "KEY",
"value": ""
},
{
"context": ":\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 1459,
"score": 0.5385470986366272,
"start": 1452,
"tag": "KEY",
"value": "running"
},
{
"context": "e: lua[\"check.lua\"]\n submit:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n lib",
"end": 1624,
"score": 0.9931040406227112,
"start": 1608,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": " submit:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"val",
"end": 1632,
"score": 0.64668869972229,
"start": 1628,
"tag": "KEY",
"value": "b_#{"
},
{
"context": ":\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 1643,
"score": 0.7974275946617126,
"start": 1636,
"tag": "KEY",
"value": "running"
},
{
"context": "lua[\"submit.lua\"]\n register:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 1835,
"score": 0.9854735732078552,
"start": 1817,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "register:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", ",
"end": 1854,
"score": 0.9083828330039978,
"start": 1837,
"tag": "KEY",
"value": "b_#{id}_running\","
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\",",
"end": 1873,
"score": 0.9060341715812683,
"start": 1856,
"tag": "KEY",
"value": "b_#{id}_executing"
},
{
"context": ": lua[\"register.lua\"]\n free:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 2042,
"score": 0.9545578360557556,
"start": 2024,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "]\n free:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\"",
"end": 2059,
"score": 0.9307565093040466,
"start": 2044,
"tag": "KEY",
"value": "b_#{id}_running"
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\"]",
"end": 2080,
"score": 0.8940364718437195,
"start": 2063,
"tag": "KEY",
"value": "b_#{id}_executing"
},
{
"context": "ee.lua\"]\n current_reservoir:\n keys: (id) -> [\"b_#{id}_settings\"]\n libs: [\"validate_keys\"]\n code: lua[\"curr",
"end": 2214,
"score": 0.9957859516143799,
"start": 2198,
"tag": "KEY",
"value": "b_#{id}_settings"
},
{
"context": ".lua\"]\n increment_reservoir:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs:",
"end": 2345,
"score": 0.9907050728797913,
"start": 2327,
"tag": "KEY",
"value": "b_#{id}_settings\","
},
{
"context": "eservoir:\n keys: (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", ",
"end": 2364,
"score": 0.9716948866844177,
"start": 2347,
"tag": "KEY",
"value": "b_#{id}_running\","
},
{
"context": " (id) -> [\"b_#{id}_settings\", \"b_#{id}_running\", \"b_#{id}_executing\"]\n libs: [\"validate_keys\", \"refresh_capacity\",",
"end": 2383,
"score": 0.9944890141487122,
"start": 2366,
"tag": "KEY",
"value": "b_#{id}_executing"
}
] | node_modules/bottleneck/src/Scripts.coffee | martinch-kth/probot-app | 0 | lua = require "./lua.json"
libraries =
get_time: lua["get_time.lua"]
refresh_capacity: lua["refresh_capacity.lua"]
conditions_check: lua["conditions_check.lua"]
refresh_expiration: lua["refresh_expiration.lua"]
validate_keys: lua["validate_keys.lua"]
templates =
init:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["refresh_capacity", "refresh_expiration"]
code: lua["init.lua"]
heartbeat:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["heartbeat.lua"]
update_settings:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["update_settings.lua"]
running:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["running.lua"]
done:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["done.lua"]
group_check:
keys: (id) -> ["b_#{id}_settings"]
libs: []
code: lua["group_check.lua"]
group_delete_key:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: []
code: lua["group_delete_key.lua"]
check:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check"]
code: lua["check.lua"]
submit:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["submit.lua"]
register:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["register.lua"]
free:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["free.lua"]
current_reservoir:
keys: (id) -> ["b_#{id}_settings"]
libs: ["validate_keys"]
code: lua["current_reservoir.lua"]
increment_reservoir:
keys: (id) -> ["b_#{id}_settings", "b_#{id}_running", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["increment_reservoir.lua"]
exports.names = Object.keys templates
exports.keys = (name, id) ->
templates[name].keys id
exports.payload = (name) ->
templates[name].libs.map (lib) -> libraries[lib]
.join("\n") + templates[name].code
| 7345 | lua = require "./lua.json"
libraries =
get_time: lua["get_time.lua"]
refresh_capacity: lua["refresh_capacity.lua"]
conditions_check: lua["conditions_check.lua"]
refresh_expiration: lua["refresh_expiration.lua"]
validate_keys: lua["validate_keys.lua"]
templates =
init:
keys: (id) -> ["<KEY>", "b<KEY>_#{id}_<KEY>", "b_#{id}_executing"]
libs: ["refresh_capacity", "refresh_expiration"]
code: lua["init.lua"]
heartbeat:
keys: (id) -> ["<KEY>", "b_<KEY>", "b_<KEY>id}_<KEY>"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["heartbeat.lua"]
update_settings:
keys: (id) -> ["<KEY> "b_<KEY>", "b_<KEY>id}_<KEY>"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["update_settings.lua"]
running:
keys: (id) -> ["<KEY> "<KEY>", "<KEY>"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["running.lua"]
done:
keys: (id) -> ["<KEY> "<KEY>", "<KEY>"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["done.lua"]
group_check:
keys: (id) -> ["<KEY>"]
libs: []
code: lua["group_check.lua"]
group_delete_key:
keys: (id) -> ["<KEY> "<KEY> "<KEY>"]
libs: []
code: lua["group_delete_key.lua"]
check:
keys: (id) -> ["<KEY>", "b<KEY>_#{id}_<KEY>", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check"]
code: lua["check.lua"]
submit:
keys: (id) -> ["<KEY>", "<KEY>id}_<KEY>", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["submit.lua"]
register:
keys: (id) -> ["<KEY> "<KEY> "<KEY>"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["register.lua"]
free:
keys: (id) -> ["<KEY> "<KEY>", "<KEY>"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["free.lua"]
current_reservoir:
keys: (id) -> ["<KEY>"]
libs: ["validate_keys"]
code: lua["current_reservoir.lua"]
increment_reservoir:
keys: (id) -> ["<KEY> "<KEY> "<KEY>"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["increment_reservoir.lua"]
exports.names = Object.keys templates
exports.keys = (name, id) ->
templates[name].keys id
exports.payload = (name) ->
templates[name].libs.map (lib) -> libraries[lib]
.join("\n") + templates[name].code
| true | lua = require "./lua.json"
libraries =
get_time: lua["get_time.lua"]
refresh_capacity: lua["refresh_capacity.lua"]
conditions_check: lua["conditions_check.lua"]
refresh_expiration: lua["refresh_expiration.lua"]
validate_keys: lua["validate_keys.lua"]
templates =
init:
keys: (id) -> ["PI:KEY:<KEY>END_PI", "bPI:KEY:<KEY>END_PI_#{id}_PI:KEY:<KEY>END_PI", "b_#{id}_executing"]
libs: ["refresh_capacity", "refresh_expiration"]
code: lua["init.lua"]
heartbeat:
keys: (id) -> ["PI:KEY:<KEY>END_PI", "b_PI:KEY:<KEY>END_PI", "b_PI:KEY:<KEY>END_PIid}_PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["heartbeat.lua"]
update_settings:
keys: (id) -> ["PI:KEY:<KEY>END_PI "b_PI:KEY:<KEY>END_PI", "b_PI:KEY:<KEY>END_PIid}_PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["update_settings.lua"]
running:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["running.lua"]
done:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["done.lua"]
group_check:
keys: (id) -> ["PI:KEY:<KEY>END_PI"]
libs: []
code: lua["group_check.lua"]
group_delete_key:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"]
libs: []
code: lua["group_delete_key.lua"]
check:
keys: (id) -> ["PI:KEY:<KEY>END_PI", "bPI:KEY:<KEY>END_PI_#{id}_PI:KEY:<KEY>END_PI", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check"]
code: lua["check.lua"]
submit:
keys: (id) -> ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PIid}_PI:KEY:<KEY>END_PI", "b_#{id}_executing"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["submit.lua"]
register:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity", "conditions_check", "refresh_expiration"]
code: lua["register.lua"]
free:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity"]
code: lua["free.lua"]
current_reservoir:
keys: (id) -> ["PI:KEY:<KEY>END_PI"]
libs: ["validate_keys"]
code: lua["current_reservoir.lua"]
increment_reservoir:
keys: (id) -> ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"]
libs: ["validate_keys", "refresh_capacity", "refresh_expiration"]
code: lua["increment_reservoir.lua"]
exports.names = Object.keys templates
exports.keys = (name, id) ->
templates[name].keys id
exports.payload = (name) ->
templates[name].libs.map (lib) -> libraries[lib]
.join("\n") + templates[name].code
|
[
{
"context": "w err\n\nusers = [\n {\n 'id': 1\n \"fullName\": \"Ogburn, Aaron\",\n \"sso\": 'rhn-support-aogburn'\n #\"sso\": [\n ",
"end": 1624,
"score": 0.9998683929443359,
"start": 1611,
"tag": "NAME",
"value": "Ogburn, Aaron"
},
{
"context": "2, }},\n ]\n }\n {\n 'id': 2\n \"fullName\": \"Sutherland, Coty\",\n \"sso\": 'rhn-support-csutherl'\n \"outOfOff",
"end": 2396,
"score": 0.9998629689216614,
"start": 2380,
"tag": "NAME",
"value": "Sutherland, Coty"
}
] | test/com/redhat/ascension/scoring/scoringTest.coffee | pbathia/ascension | 0 | chai = require 'chai'
expect = chai.expect
should = chai.should()
fs = require 'fs'
yaml = require 'js-yaml'
path = require('path')
assert = require 'assert'
should = require 'should'
moment = require 'moment'
logger = require('tracer').colorConsole()
mongoose = require 'mongoose'
prettyjson = require 'prettyjson'
_ = require 'lodash'
Q = require 'q'
MongoOperations = require '../../../../../src/com/redhat/ascension/db/MongoOperations'
ScoringLogic = require '../../../../../src/com/redhat/ascension/rules/scoring/scoringLogic'
TaskCounts = require '../../../../../src/com/redhat/ascension/db/taskCounts'
UserLogic = require '../../../../../src/com/redhat/ascension/rest/userLogic'
CaseRules = require '../../../../../src/com/redhat/ascension/rules/case/caseRules'
TaskUtils = require '../../../../../src/com/redhat/ascension/utils/taskUtils'
TaskRules = require '../../../../../src/com/redhat/ascension/rules/taskRules'
TaskOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskOpEnum'
EntityOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/ResourceOpEnum'
TaskStateEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskStateEnum'
TaskTypeEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskTypeEnum'
TaskActionsEnum = require '../../../../../src/com/redhat/ascension/rest/enums/taskActionsEnum'
errorHandler = (err) -> throw err
users = [
{
'id': 1
"fullName": "Ogburn, Aaron",
"sso": 'rhn-support-aogburn'
#"sso": [
# "rhn-support-aogburn",
# "support_aogburn"
#]
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "memory", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "nsapi_redirector", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "ipa", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "scsi_disk", "skillType": "kcsdw", "level": 0, }},
{ "resource": { "name": "mdraid", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 2, }},
]
}
{
'id': 2
"fullName": "Sutherland, Coty",
"sso": 'rhn-support-csutherl'
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_jk", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_cluster", "skillType": "kcsdw", "level": 2, }},
]
}
]
userTaskCounts =
1:
taskCount: 0
2:
taskCount: 1
#mocha --require coffee-script/register --compilers coffee:coffee-script/register test/com/redhat/ascension/scoring/scoringTest.coffee
describe "Scoring Logic", ->
before (done) ->
MongoOperations.init({mongoDebug: true, testDb: true})
db = mongoose['connection']
db.on 'error', logger.error.bind(logger, 'connection error:')
db.once 'open', () ->
MongoOperations.defineCollections()
TaskRules.initFlow()
MongoOperations.reset().done(->
done()
, (err) ->
logger.error err.stack
)
describe "Score a httpd task higher for higher skill user", () ->
it "Score aogburn higher", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['httpd']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
aogburn.score.should.be.above coty.score
done()
it "Score coty equal to aogburn due to tasks owned", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['mod_cluster']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
coty.score.should.equal aogburn.score
done()
# TODO -- never finished this, it errors out right I believe on the getTaskCounts but now that I am using the test
# db it may not anymore, I switched gears at this point
it "rmanes should show up in a Kernel case", (done) ->
@timeout(5000)
CaseRules.fetchCase({caseNumber: '01167752'})
.then((c) ->
t = TaskRules.makeTaskFromCase(c)
sbrs = t['sbrs']
uqlParts = []
_.each sbrs, (sbr) -> uqlParts.push "(sbrName is \"#{sbr}\")"
uql = uqlParts.join(' OR ')
[t, UserLogic.fetchUsersUql({where: uql})]
).spread((task, users) ->
ssos = _.chain(users).pluck('sso').value()
# rmanes is in Kernel, Networking
expect(ssos).to.contain('rhn-support-rmanes')
userIds = _.chain(users).pluck('id').unique().value()
logger.debug "Discovered #{userIds} userIds"
[task, users, TaskCounts.getTaskCounts(userIds)]
)
.spread((task, users, userTaskCounts) ->
ScoringLogic.determinePotentialOwners({
task: task
userTaskCounts: {'005A0000002a7XZIAY': 0}
users: users
})
potentialOwnersSsos = _.chain(task.potentialOwners).pluck('sso').value()
logger.debug "Potential Owners: #{potentialOwnersSsos}"
potentialOwnersSsos.should.contain('rhn-support-rmanes')
done()
).done()
| 126469 | chai = require 'chai'
expect = chai.expect
should = chai.should()
fs = require 'fs'
yaml = require 'js-yaml'
path = require('path')
assert = require 'assert'
should = require 'should'
moment = require 'moment'
logger = require('tracer').colorConsole()
mongoose = require 'mongoose'
prettyjson = require 'prettyjson'
_ = require 'lodash'
Q = require 'q'
MongoOperations = require '../../../../../src/com/redhat/ascension/db/MongoOperations'
ScoringLogic = require '../../../../../src/com/redhat/ascension/rules/scoring/scoringLogic'
TaskCounts = require '../../../../../src/com/redhat/ascension/db/taskCounts'
UserLogic = require '../../../../../src/com/redhat/ascension/rest/userLogic'
CaseRules = require '../../../../../src/com/redhat/ascension/rules/case/caseRules'
TaskUtils = require '../../../../../src/com/redhat/ascension/utils/taskUtils'
TaskRules = require '../../../../../src/com/redhat/ascension/rules/taskRules'
TaskOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskOpEnum'
EntityOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/ResourceOpEnum'
TaskStateEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskStateEnum'
TaskTypeEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskTypeEnum'
TaskActionsEnum = require '../../../../../src/com/redhat/ascension/rest/enums/taskActionsEnum'
errorHandler = (err) -> throw err
users = [
{
'id': 1
"fullName": "<NAME>",
"sso": 'rhn-support-aogburn'
#"sso": [
# "rhn-support-aogburn",
# "support_aogburn"
#]
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "memory", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "nsapi_redirector", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "ipa", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "scsi_disk", "skillType": "kcsdw", "level": 0, }},
{ "resource": { "name": "mdraid", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 2, }},
]
}
{
'id': 2
"fullName": "<NAME>",
"sso": 'rhn-support-csutherl'
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_jk", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_cluster", "skillType": "kcsdw", "level": 2, }},
]
}
]
userTaskCounts =
1:
taskCount: 0
2:
taskCount: 1
#mocha --require coffee-script/register --compilers coffee:coffee-script/register test/com/redhat/ascension/scoring/scoringTest.coffee
describe "Scoring Logic", ->
before (done) ->
MongoOperations.init({mongoDebug: true, testDb: true})
db = mongoose['connection']
db.on 'error', logger.error.bind(logger, 'connection error:')
db.once 'open', () ->
MongoOperations.defineCollections()
TaskRules.initFlow()
MongoOperations.reset().done(->
done()
, (err) ->
logger.error err.stack
)
describe "Score a httpd task higher for higher skill user", () ->
it "Score aogburn higher", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['httpd']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
aogburn.score.should.be.above coty.score
done()
it "Score coty equal to aogburn due to tasks owned", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['mod_cluster']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
coty.score.should.equal aogburn.score
done()
# TODO -- never finished this, it errors out right I believe on the getTaskCounts but now that I am using the test
# db it may not anymore, I switched gears at this point
it "rmanes should show up in a Kernel case", (done) ->
@timeout(5000)
CaseRules.fetchCase({caseNumber: '01167752'})
.then((c) ->
t = TaskRules.makeTaskFromCase(c)
sbrs = t['sbrs']
uqlParts = []
_.each sbrs, (sbr) -> uqlParts.push "(sbrName is \"#{sbr}\")"
uql = uqlParts.join(' OR ')
[t, UserLogic.fetchUsersUql({where: uql})]
).spread((task, users) ->
ssos = _.chain(users).pluck('sso').value()
# rmanes is in Kernel, Networking
expect(ssos).to.contain('rhn-support-rmanes')
userIds = _.chain(users).pluck('id').unique().value()
logger.debug "Discovered #{userIds} userIds"
[task, users, TaskCounts.getTaskCounts(userIds)]
)
.spread((task, users, userTaskCounts) ->
ScoringLogic.determinePotentialOwners({
task: task
userTaskCounts: {'005A0000002a7XZIAY': 0}
users: users
})
potentialOwnersSsos = _.chain(task.potentialOwners).pluck('sso').value()
logger.debug "Potential Owners: #{potentialOwnersSsos}"
potentialOwnersSsos.should.contain('rhn-support-rmanes')
done()
).done()
| true | chai = require 'chai'
expect = chai.expect
should = chai.should()
fs = require 'fs'
yaml = require 'js-yaml'
path = require('path')
assert = require 'assert'
should = require 'should'
moment = require 'moment'
logger = require('tracer').colorConsole()
mongoose = require 'mongoose'
prettyjson = require 'prettyjson'
_ = require 'lodash'
Q = require 'q'
MongoOperations = require '../../../../../src/com/redhat/ascension/db/MongoOperations'
ScoringLogic = require '../../../../../src/com/redhat/ascension/rules/scoring/scoringLogic'
TaskCounts = require '../../../../../src/com/redhat/ascension/db/taskCounts'
UserLogic = require '../../../../../src/com/redhat/ascension/rest/userLogic'
CaseRules = require '../../../../../src/com/redhat/ascension/rules/case/caseRules'
TaskUtils = require '../../../../../src/com/redhat/ascension/utils/taskUtils'
TaskRules = require '../../../../../src/com/redhat/ascension/rules/taskRules'
TaskOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskOpEnum'
EntityOpEnum = require '../../../../../src/com/redhat/ascension/rules/enums/ResourceOpEnum'
TaskStateEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskStateEnum'
TaskTypeEnum = require '../../../../../src/com/redhat/ascension/rules/enums/TaskTypeEnum'
TaskActionsEnum = require '../../../../../src/com/redhat/ascension/rest/enums/taskActionsEnum'
errorHandler = (err) -> throw err
users = [
{
'id': 1
"fullName": "PI:NAME:<NAME>END_PI",
"sso": 'rhn-support-aogburn'
#"sso": [
# "rhn-support-aogburn",
# "support_aogburn"
#]
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "memory", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "nsapi_redirector", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "ipa", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "scsi_disk", "skillType": "kcsdw", "level": 0, }},
{ "resource": { "name": "mdraid", "skillType": "kcsdw", "level": 2, }},
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 2, }},
]
}
{
'id': 2
"fullName": "PI:NAME:<NAME>END_PI",
"sso": 'rhn-support-csutherl'
"outOfOffice": false,
"sbrs": [
"Webservers",
"JVM & Diagnostics",
"JBoss Base AS"
],
"skills": [
{ "resource": { "name": "httpd", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_jk", "skillType": "kcsdw", "level": 1, }},
{ "resource": { "name": "mod_cluster", "skillType": "kcsdw", "level": 2, }},
]
}
]
userTaskCounts =
1:
taskCount: 0
2:
taskCount: 1
#mocha --require coffee-script/register --compilers coffee:coffee-script/register test/com/redhat/ascension/scoring/scoringTest.coffee
describe "Scoring Logic", ->
before (done) ->
MongoOperations.init({mongoDebug: true, testDb: true})
db = mongoose['connection']
db.on 'error', logger.error.bind(logger, 'connection error:')
db.once 'open', () ->
MongoOperations.defineCollections()
TaskRules.initFlow()
MongoOperations.reset().done(->
done()
, (err) ->
logger.error err.stack
)
describe "Score a httpd task higher for higher skill user", () ->
it "Score aogburn higher", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['httpd']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
aogburn.score.should.be.above coty.score
done()
it "Score coty equal to aogburn due to tasks owned", (done) ->
t = TaskUtils.generateMockTask
'case':
'status': 'Waiting on Red Hat'
'internalStatus': 'Unassigned'
'task':
'type': TaskTypeEnum.CASE.name
'taskOp': TaskOpEnum.NOOP.name
'state': TaskStateEnum.UNASSIGNED.name
'sbrs': ['Webservers']
'tags': ['mod_cluster']
ScoringLogic.determinePotentialOwners({
task: t
userTaskCounts: userTaskCounts
users: users
})
logger.debug prettyjson.render t
aogburn = _.find t.potentialOwners, (p) -> p.id is 1
coty = _.find t.potentialOwners, (p) -> p.id is 2
coty.score.should.equal aogburn.score
done()
# TODO -- never finished this, it errors out right I believe on the getTaskCounts but now that I am using the test
# db it may not anymore, I switched gears at this point
it "rmanes should show up in a Kernel case", (done) ->
@timeout(5000)
CaseRules.fetchCase({caseNumber: '01167752'})
.then((c) ->
t = TaskRules.makeTaskFromCase(c)
sbrs = t['sbrs']
uqlParts = []
_.each sbrs, (sbr) -> uqlParts.push "(sbrName is \"#{sbr}\")"
uql = uqlParts.join(' OR ')
[t, UserLogic.fetchUsersUql({where: uql})]
).spread((task, users) ->
ssos = _.chain(users).pluck('sso').value()
# rmanes is in Kernel, Networking
expect(ssos).to.contain('rhn-support-rmanes')
userIds = _.chain(users).pluck('id').unique().value()
logger.debug "Discovered #{userIds} userIds"
[task, users, TaskCounts.getTaskCounts(userIds)]
)
.spread((task, users, userTaskCounts) ->
ScoringLogic.determinePotentialOwners({
task: task
userTaskCounts: {'005A0000002a7XZIAY': 0}
users: users
})
potentialOwnersSsos = _.chain(task.potentialOwners).pluck('sso').value()
logger.debug "Potential Owners: #{potentialOwnersSsos}"
potentialOwnersSsos.should.contain('rhn-support-rmanes')
done()
).done()
|
[
{
"context": "n\": \"true\"\n # \"results\": [\n # {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_",
"end": 25243,
"score": 0.9977566599845886,
"start": 25229,
"tag": "KEY",
"value": "20_jahre_feste"
},
{
"context": ": [\n # {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"v",
"end": 25261,
"score": 0.8646113872528076,
"start": 25255,
"tag": "KEY",
"value": "value2"
},
{
"context": "hre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_",
"end": 25298,
"score": 0.9976513385772705,
"start": 25284,
"tag": "KEY",
"value": "30_jahre_feste"
},
{
"context": "2\"}\n # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"v",
"end": 25316,
"score": 0.8460673093795776,
"start": 25310,
"tag": "KEY",
"value": "value2"
},
{
"context": "hre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n # ]\n # }\n # dataExpecte",
"end": 25353,
"score": 0.9979681372642517,
"start": 25339,
"tag": "KEY",
"value": "40_jahre_feste"
},
{
"context": "2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n # ]\n # }\n # dataExpected: JSON.stringify ",
"end": 25371,
"score": 0.888169527053833,
"start": 25365,
"tag": "KEY",
"value": "value2"
},
{
"context": "n\": \"true\"\n # \"results\": [\n # {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_",
"end": 25498,
"score": 0.9971739649772644,
"start": 25484,
"tag": "KEY",
"value": "20_jahre_feste"
},
{
"context": ": [\n # {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"v",
"end": 25516,
"score": 0.9325801134109497,
"start": 25510,
"tag": "KEY",
"value": "value2"
},
{
"context": "hre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_",
"end": 25553,
"score": 0.9956780672073364,
"start": 25539,
"tag": "KEY",
"value": "30_jahre_feste"
},
{
"context": " # {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"v",
"end": 25571,
"score": 0.9247157573699951,
"start": 25570,
"tag": "KEY",
"value": "2"
},
{
"context": "hre_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n # ]\n # }\n f",
"end": 25596,
"score": 0.99820876121521,
"start": 25594,
"tag": "KEY",
"value": "40"
},
{
"context": "_feste\", \"key2\": \"value2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n # ]\n # }\n fie",
"end": 25598,
"score": 0.6055479645729065,
"start": 25597,
"tag": "KEY",
"value": "j"
},
{
"context": "2\"}\n # {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n # ]\n # }\n fieldName: 'body'\n fieldResult",
"end": 25626,
"score": 0.7768479585647583,
"start": 25620,
"tag": "KEY",
"value": "value2"
},
{
"context": "\"true\"\n \"results\": [\n {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahr",
"end": 25812,
"score": 0.9926042556762695,
"start": 25798,
"tag": "KEY",
"value": "20_jahre_feste"
},
{
"context": "[\n {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": ",
"end": 25830,
"score": 0.8660070896148682,
"start": 25824,
"tag": "KEY",
"value": "value2"
},
{
"context": "e_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahr",
"end": 25869,
"score": 0.9739705324172974,
"start": 25855,
"tag": "KEY",
"value": "30_jahre_feste"
},
{
"context": "}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahre_feste\", \"key2\": ",
"end": 25887,
"score": 0.7478983402252197,
"start": 25881,
"tag": "KEY",
"value": "value2"
},
{
"context": "e_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n ]\n }\n \"actu",
"end": 25926,
"score": 0.9831154942512512,
"start": 25912,
"tag": "KEY",
"value": "40_jahre_feste"
},
{
"context": " {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n ]\n }\n \"actual\": JSON.stringif",
"end": 25944,
"score": 0.8107000589370728,
"start": 25943,
"tag": "KEY",
"value": "2"
},
{
"context": "\"true\"\n \"results\": [\n {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahr",
"end": 26079,
"score": 0.9946329593658447,
"start": 26065,
"tag": "KEY",
"value": "20_jahre_feste"
},
{
"context": "[\n {\"otrkey\": \"20_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": ",
"end": 26097,
"score": 0.802072286605835,
"start": 26091,
"tag": "KEY",
"value": "value2"
},
{
"context": "e_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahr",
"end": 26136,
"score": 0.9878135323524475,
"start": 26122,
"tag": "KEY",
"value": "30_jahre_feste"
},
{
"context": "}\n {\"otrkey\": \"30_jahre_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahre_feste\", \"key2\": ",
"end": 26154,
"score": 0.9085060358047485,
"start": 26148,
"tag": "KEY",
"value": "value2"
},
{
"context": "e_feste\", \"key2\": \"value2\"}\n {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n ]\n }\n },\n ",
"end": 26193,
"score": 0.9860404133796692,
"start": 26179,
"tag": "KEY",
"value": "40_jahre_feste"
},
{
"context": "}\n {\"otrkey\": \"40_jahre_feste\", \"key2\": \"value2\"}\n ]\n }\n },\n \"errors\": [],\n ",
"end": 26211,
"score": 0.8001316785812378,
"start": 26205,
"tag": "KEY",
"value": "value2"
},
{
"context": "ndTag>\n<startTag> "otrkey": "20_jahre_feste",</endTag>\n<startTag> "key2&",
"end": 26511,
"score": 0.8919157981872559,
"start": 26504,
"tag": "KEY",
"value": "0_jahre"
},
{
"context": "startTag> "otrkey": "20_jahre_feste",</endTag>\n<startTag> "key2":",
"end": 26517,
"score": 0.9393473267555237,
"start": 26512,
"tag": "KEY",
"value": "feste"
},
{
"context": "ndTag>\n<startTag> "otrkey": "30_jahre_feste",</endTag>\n<startTag> "key2":",
"end": 26703,
"score": 0.9080219268798828,
"start": 26690,
"tag": "KEY",
"value": "0_jahre_feste"
},
{
"context": "endTag>\n<startTag> "otrkey": "40_jahre_feste",</endTag>\n<startTag> "key2":",
"end": 26889,
"score": 0.9316828846931458,
"start": 26875,
"tag": "KEY",
"value": "40_jahre_feste"
}
] | test/fixtures/gavel2html-pointers.coffee | apiaryio/gavel2html | 1 | h = {}
gavel2htmlOutputOptions =
wrapWith: '<wrapStart>##data<wrapEnd>',
startTag: '<startTag>',
endTag: '</endTag>',
missingStartTag: '<missingStartTag>',
addedStartTag: "<addedStartTag>",
changedStartTag: '<changedStartTag>',
comments: true,
commentStartTag: '<commentStartTag>',
commentEndTag: '</commentEndTag>'
headersExpected =
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
headersExpectedEmpty = {}
h.headersRealOK =
testDesc: 'when expected headers are non empty and real data are the same in real headers'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
# fieldName: 'headers'
fieldResult: {
"kind": "json"
"values": {
"expected": headersExpected
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
}
"errors": []
}
expectedOutput: '<wrapStart><startTag>{"testHeader1":"testHeader1Val","testHeader2":"testHeader2Val"}</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKMore =
testDesc: 'when expected headers are non empty and real data extends it'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# testHeader3: 'testHEader3Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult:{
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
"testHeader3": 'testHEader3Val'
}
}
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHeader1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><addedStartTag>testHeader3: testHEader3Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKKeyCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of key'
# dataReal:
# testHEAder1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
fieldName: 'headers',
fieldResult: {
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHEAder1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
},
},
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHEAder1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealFailValueCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of value'
# dataReal:
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'tEstHeader1Val'
"testHeader2": 'testHEader2Val'
}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "Value of the ‘testheader1’ must be 'testHeader1Val'.",
"location": {
"pointer": "/testheader1"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><changedStartTag>testHeader1: tEstHeader1Val</endTag><changedStartTag>testHeader2: testHEader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailMiss =
testDesc: 'when expected headers are non empty and key missing in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailChanged =
testDesc: 'when expected headers are non empty and data changed in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHEader2ValChanged'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHEader2ValChanged'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><changedStartTag>testHeader2: testHEader2ValChanged</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailEmpty =
testDesc: 'when expected headers are non empty and real data are empty'
# dataReal: {}
# dataExpected:
# testHeader2: 'testHeader2Val'
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {
"testHeader2": 'testHeader2Val'
}
"actual": {}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealOKNoEmpty =
testDesc: 'when expected headers are empty and real data are not empty'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: {}
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {}
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
},
"errors": [],
"kind": "json"
}
expectedOutput: '<wrapStart><addedStartTag>testHeader1: testHeader1Val</endTag><addedStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
headersWrapHeaderKeys =
testHeader1: '<b>testHeader1Val</b>'
testHeader2: '<i>testHeader2Val</i>'
h.headersWrapKeys =
outputOptions:
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
jsonKeyStartTag: '<keyStart>'
jsonKeyEndTag: '</keyEnd>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: false
testDesc: 'when expected headers are non empty and real data are the same in real headers and I want to wrap header keys'
# dataReal: headersWrapHeaderKeys
# dataExpected: headersWrapHeaderKeys
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersWrapHeaderKeys,
"actual": headersWrapHeaderKeys
}
"errors": []
"kind": "json"
}
expectedOutput: """
<wrapStart>\
<startTag><keyStart>testHeader1</keyEnd>: <b>testHeader1Val</b></endTag>\
<startTag><keyStart>testHeader2</keyEnd>: <i>testHeader2Val</i></endTag>\
<wrapEnd>"""
usedErrors: []
#
# Body
#
b = {}
b.bodyTypeFailFailIntVsStringRoot =
testDesc: 'when expected body is integer and real is string'
# dataReal: '1'
# dataExpected: 1
schema: {
"type":"number",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": 1
"actual": '1'
}
"errors": [
{
"message": "The undefined property must be a number (current value is \"1\").",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a number (current value is "1").</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailStringVsIntRoot =
testDesc: 'when expected body is string and real is integer'
# dataReal: 1
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": '1'
"actual": 1
}
"errors": [
{
"message": "The undefined property must be a string (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a string (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailPrimitiveVsObjRoot =
testDesc: 'when expected body is primitive and real is object'
# dataReal: JSON.stringify {'key': 'val'}
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": "1"
"actual": JSON.stringify {'key': 'val'}
}
"errors": [
{
"message": "The undefined property must be a string (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsPrimitiveRoot =
testDesc: 'when expected body is object and real is primitive'
# dataReal: "1"
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": "1"
},
"errors": [
{
"message": "The property must be an object (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be an object (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: [""]
b.bodyTypeFailObjVsArrayRoot =
testDesc: 'when expected body is object and real is array'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsArrayRootNoSchema =
testDesc: 'when expected body is object and real is array (no schema)'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘key’ property is required.",
"location": {
"pointer": "/key"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailArrayVsObjRoot =
testDesc: 'when expected body is array and real is object'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
schema: {
"type":"array",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
},
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyTypeFailArrayVsObjRootNoSchema =
testDesc: 'when expected body is array and real is object (no schema)'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
}
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘0’ property is required.",
"location": {
"pointer": "/0"
}
},
{
"message": "The ‘1’ property is required.",
"location": {
"pointer": "/1"
}
},
{
"message": "The ‘2’ property is required.",
"location": {
"pointer": "/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyComplexExpected = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"simpleKeyValueOKmiss": "simpleKeyValueOKmiss",
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [1,2,3],
"keyWithArrayValueTypeFail": [1,2,3]
}
bodyComplexReal = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2",
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": [1,2,3],
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [4,5,6],
"keyWithArrayValueTypeFail": {"key": "val"}
}
b.bodyComplex =
testDesc: 'complex body test'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
}
"errors": [
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyComplexWithNonPointerError =
testDesc: 'complex body test with non pointer error in gavel results'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
},
"errors": [
{
"message": "Your mamma can't swim up the hill."
},
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyOkWithNestedObjectsInArrays =
testDesc: 'when expected and real body are the same and contains array of objects'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "20_jahre_feste", "key2": "value2"}
# {"otrkey": "30_jahre_feste", "key2": "value2"}
# {"otrkey": "40_jahre_feste", "key2": "value2"}
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "20_jahre_feste", "key2": "value2"}
# {"otrkey": "30_jahre_feste", "key2": "value2"}
# {"otrkey": "40_jahre_feste", "key2": "value2"}
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "20_jahre_feste", "key2": "value2"}
{"otrkey": "30_jahre_feste", "key2": "value2"}
{"otrkey": "40_jahre_feste", "key2": "value2"}
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "20_jahre_feste", "key2": "value2"}
{"otrkey": "30_jahre_feste", "key2": "value2"}
{"otrkey": "40_jahre_feste", "key2": "value2"}
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "20_jahre_feste",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "30_jahre_feste",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "40_jahre_feste",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> }</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArrays =
testDesc: 'when expected and real body are the same and contains array of strings'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
}
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> "MrauMrau",</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedArraysInArrays =
testDesc: 'when expected and real body are the same and contains array of arrays'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ]</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArraysWrappedKeys =
testDesc: 'when expected and real body are the same and I want to wrap object keys in additional tags'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected":JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "<keyStart>login</keyEnd>": "true",</endTag>
<startTag> "<keyStart>results</keyEnd>": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> 5,</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
outputOptions:
jsonKeyStartTag: "<keyStart>"
jsonKeyEndTag: "</keyEnd>"
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: true
commentStartTag: '<commentStartTag>'
commentEndTag: '</commentEndTag>'
module.exports = {
gavel2htmlOutputOptions
testsHeaders: h
testsBody: b
}
| 180444 | h = {}
gavel2htmlOutputOptions =
wrapWith: '<wrapStart>##data<wrapEnd>',
startTag: '<startTag>',
endTag: '</endTag>',
missingStartTag: '<missingStartTag>',
addedStartTag: "<addedStartTag>",
changedStartTag: '<changedStartTag>',
comments: true,
commentStartTag: '<commentStartTag>',
commentEndTag: '</commentEndTag>'
headersExpected =
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
headersExpectedEmpty = {}
h.headersRealOK =
testDesc: 'when expected headers are non empty and real data are the same in real headers'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
# fieldName: 'headers'
fieldResult: {
"kind": "json"
"values": {
"expected": headersExpected
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
}
"errors": []
}
expectedOutput: '<wrapStart><startTag>{"testHeader1":"testHeader1Val","testHeader2":"testHeader2Val"}</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKMore =
testDesc: 'when expected headers are non empty and real data extends it'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# testHeader3: 'testHEader3Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult:{
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
"testHeader3": 'testHEader3Val'
}
}
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHeader1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><addedStartTag>testHeader3: testHEader3Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKKeyCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of key'
# dataReal:
# testHEAder1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
fieldName: 'headers',
fieldResult: {
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHEAder1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
},
},
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHEAder1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealFailValueCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of value'
# dataReal:
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'tEstHeader1Val'
"testHeader2": 'testHEader2Val'
}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "Value of the ‘testheader1’ must be 'testHeader1Val'.",
"location": {
"pointer": "/testheader1"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><changedStartTag>testHeader1: tEstHeader1Val</endTag><changedStartTag>testHeader2: testHEader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailMiss =
testDesc: 'when expected headers are non empty and key missing in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailChanged =
testDesc: 'when expected headers are non empty and data changed in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHEader2ValChanged'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHEader2ValChanged'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><changedStartTag>testHeader2: testHEader2ValChanged</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailEmpty =
testDesc: 'when expected headers are non empty and real data are empty'
# dataReal: {}
# dataExpected:
# testHeader2: 'testHeader2Val'
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {
"testHeader2": 'testHeader2Val'
}
"actual": {}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealOKNoEmpty =
testDesc: 'when expected headers are empty and real data are not empty'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: {}
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {}
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
},
"errors": [],
"kind": "json"
}
expectedOutput: '<wrapStart><addedStartTag>testHeader1: testHeader1Val</endTag><addedStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
headersWrapHeaderKeys =
testHeader1: '<b>testHeader1Val</b>'
testHeader2: '<i>testHeader2Val</i>'
h.headersWrapKeys =
outputOptions:
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
jsonKeyStartTag: '<keyStart>'
jsonKeyEndTag: '</keyEnd>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: false
testDesc: 'when expected headers are non empty and real data are the same in real headers and I want to wrap header keys'
# dataReal: headersWrapHeaderKeys
# dataExpected: headersWrapHeaderKeys
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersWrapHeaderKeys,
"actual": headersWrapHeaderKeys
}
"errors": []
"kind": "json"
}
expectedOutput: """
<wrapStart>\
<startTag><keyStart>testHeader1</keyEnd>: <b>testHeader1Val</b></endTag>\
<startTag><keyStart>testHeader2</keyEnd>: <i>testHeader2Val</i></endTag>\
<wrapEnd>"""
usedErrors: []
#
# Body
#
b = {}
b.bodyTypeFailFailIntVsStringRoot =
testDesc: 'when expected body is integer and real is string'
# dataReal: '1'
# dataExpected: 1
schema: {
"type":"number",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": 1
"actual": '1'
}
"errors": [
{
"message": "The undefined property must be a number (current value is \"1\").",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a number (current value is "1").</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailStringVsIntRoot =
testDesc: 'when expected body is string and real is integer'
# dataReal: 1
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": '1'
"actual": 1
}
"errors": [
{
"message": "The undefined property must be a string (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a string (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailPrimitiveVsObjRoot =
testDesc: 'when expected body is primitive and real is object'
# dataReal: JSON.stringify {'key': 'val'}
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": "1"
"actual": JSON.stringify {'key': 'val'}
}
"errors": [
{
"message": "The undefined property must be a string (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsPrimitiveRoot =
testDesc: 'when expected body is object and real is primitive'
# dataReal: "1"
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": "1"
},
"errors": [
{
"message": "The property must be an object (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be an object (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: [""]
b.bodyTypeFailObjVsArrayRoot =
testDesc: 'when expected body is object and real is array'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsArrayRootNoSchema =
testDesc: 'when expected body is object and real is array (no schema)'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘key’ property is required.",
"location": {
"pointer": "/key"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailArrayVsObjRoot =
testDesc: 'when expected body is array and real is object'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
schema: {
"type":"array",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
},
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyTypeFailArrayVsObjRootNoSchema =
testDesc: 'when expected body is array and real is object (no schema)'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
}
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘0’ property is required.",
"location": {
"pointer": "/0"
}
},
{
"message": "The ‘1’ property is required.",
"location": {
"pointer": "/1"
}
},
{
"message": "The ‘2’ property is required.",
"location": {
"pointer": "/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyComplexExpected = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"simpleKeyValueOKmiss": "simpleKeyValueOKmiss",
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [1,2,3],
"keyWithArrayValueTypeFail": [1,2,3]
}
bodyComplexReal = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2",
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": [1,2,3],
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [4,5,6],
"keyWithArrayValueTypeFail": {"key": "val"}
}
b.bodyComplex =
testDesc: 'complex body test'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
}
"errors": [
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyComplexWithNonPointerError =
testDesc: 'complex body test with non pointer error in gavel results'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
},
"errors": [
{
"message": "Your mamma can't swim up the hill."
},
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyOkWithNestedObjectsInArrays =
testDesc: 'when expected and real body are the same and contains array of objects'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "<KEY>", "key2": "<KEY>"}
# {"otrkey": "<KEY>", "key2": "<KEY>"}
# {"otrkey": "<KEY>", "key2": "<KEY>"}
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "<KEY>", "key2": "<KEY>"}
# {"otrkey": "<KEY>", "key2": "value<KEY>"}
# {"otrkey": "<KEY>_<KEY>ahre_feste", "key2": "<KEY>"}
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "<KEY>", "key2": "<KEY>"}
{"otrkey": "<KEY>", "key2": "<KEY>"}
{"otrkey": "<KEY>", "key2": "value<KEY>"}
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "<KEY>", "key2": "<KEY>"}
{"otrkey": "<KEY>", "key2": "<KEY>"}
{"otrkey": "<KEY>", "key2": "<KEY>"}
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "2<KEY>_<KEY>",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "3<KEY>",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "<KEY>",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> }</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArrays =
testDesc: 'when expected and real body are the same and contains array of strings'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
}
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> "MrauMrau",</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedArraysInArrays =
testDesc: 'when expected and real body are the same and contains array of arrays'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ]</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArraysWrappedKeys =
testDesc: 'when expected and real body are the same and I want to wrap object keys in additional tags'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected":JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "<keyStart>login</keyEnd>": "true",</endTag>
<startTag> "<keyStart>results</keyEnd>": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> 5,</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
outputOptions:
jsonKeyStartTag: "<keyStart>"
jsonKeyEndTag: "</keyEnd>"
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: true
commentStartTag: '<commentStartTag>'
commentEndTag: '</commentEndTag>'
module.exports = {
gavel2htmlOutputOptions
testsHeaders: h
testsBody: b
}
| true | h = {}
gavel2htmlOutputOptions =
wrapWith: '<wrapStart>##data<wrapEnd>',
startTag: '<startTag>',
endTag: '</endTag>',
missingStartTag: '<missingStartTag>',
addedStartTag: "<addedStartTag>",
changedStartTag: '<changedStartTag>',
comments: true,
commentStartTag: '<commentStartTag>',
commentEndTag: '</commentEndTag>'
headersExpected =
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
headersExpectedEmpty = {}
h.headersRealOK =
testDesc: 'when expected headers are non empty and real data are the same in real headers'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
# fieldName: 'headers'
fieldResult: {
"kind": "json"
"values": {
"expected": headersExpected
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
}
"errors": []
}
expectedOutput: '<wrapStart><startTag>{"testHeader1":"testHeader1Val","testHeader2":"testHeader2Val"}</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKMore =
testDesc: 'when expected headers are non empty and real data extends it'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# testHeader3: 'testHEader3Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult:{
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
"testHeader3": 'testHEader3Val'
}
}
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHeader1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><addedStartTag>testHeader3: testHEader3Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealOKKeyCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of key'
# dataReal:
# testHEAder1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: headersExpected
fieldName: 'headers',
fieldResult: {
"kind": "json",
"values": {
"expected": headersExpected
"actual": {
"testHEAder1": 'testHeader1Val'
"testHeader2": 'testHeader2Val'
},
},
"errors": [],
}
expectedOutput: '<wrapStart><startTag>testHEAder1: testHeader1Val</endTag><startTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
h.headersRealFailValueCase =
testDesc: 'when expected headers are non empty and real data are the same except cAsE of value'
# dataReal:
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'tEstHeader1Val'
"testHeader2": 'testHEader2Val'
}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "Value of the ‘testheader1’ must be 'testHeader1Val'.",
"location": {
"pointer": "/testheader1"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><changedStartTag>testHeader1: tEstHeader1Val</endTag><changedStartTag>testHeader2: testHEader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailMiss =
testDesc: 'when expected headers are non empty and key missing in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailChanged =
testDesc: 'when expected headers are non empty and data changed in real data'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHEader2ValChanged'
# dataExpected: headersExpected
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersExpected
"actual": {
"testHeader1": 'testHeader1Val'
"testHeader2": 'testHEader2ValChanged'
}
}
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><startTag>testHeader1: testHeader1Val</endTag><changedStartTag>testHeader2: testHEader2ValChanged</endTag><wrapEnd>"
usedErrors: []
h.headersRealFailEmpty =
testDesc: 'when expected headers are non empty and real data are empty'
# dataReal: {}
# dataExpected:
# testHeader2: 'testHeader2Val'
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {
"testHeader2": 'testHeader2Val'
}
"actual": {}
},
"errors": [
{
"message": "Value of the ‘testheader2’ must be 'testHeader2Val'.",
"location": {
"pointer": "/testheader2"
}
},
{
"message": "The ‘testheader2’ property is required.",
"location": {
"pointer": "/testheader2"
}
}
],
"kind": "json"
}
expectedOutput: "<wrapStart><missingStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>"
usedErrors: []
h.headersRealOKNoEmpty =
testDesc: 'when expected headers are empty and real data are not empty'
# dataReal:
# testHeader1: 'testHeader1Val'
# testHeader2: 'testHeader2Val'
# dataExpected: {}
fieldName: 'headers'
fieldResult: {
"values": {
"expected": {}
"actual": {
testHeader1: 'testHeader1Val'
testHeader2: 'testHeader2Val'
}
},
"errors": [],
"kind": "json"
}
expectedOutput: '<wrapStart><addedStartTag>testHeader1: testHeader1Val</endTag><addedStartTag>testHeader2: testHeader2Val</endTag><wrapEnd>'
usedErrors: []
headersWrapHeaderKeys =
testHeader1: '<b>testHeader1Val</b>'
testHeader2: '<i>testHeader2Val</i>'
h.headersWrapKeys =
outputOptions:
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
jsonKeyStartTag: '<keyStart>'
jsonKeyEndTag: '</keyEnd>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: false
testDesc: 'when expected headers are non empty and real data are the same in real headers and I want to wrap header keys'
# dataReal: headersWrapHeaderKeys
# dataExpected: headersWrapHeaderKeys
fieldName: 'headers'
fieldResult: {
"values": {
"expected": headersWrapHeaderKeys,
"actual": headersWrapHeaderKeys
}
"errors": []
"kind": "json"
}
expectedOutput: """
<wrapStart>\
<startTag><keyStart>testHeader1</keyEnd>: <b>testHeader1Val</b></endTag>\
<startTag><keyStart>testHeader2</keyEnd>: <i>testHeader2Val</i></endTag>\
<wrapEnd>"""
usedErrors: []
#
# Body
#
b = {}
b.bodyTypeFailFailIntVsStringRoot =
testDesc: 'when expected body is integer and real is string'
# dataReal: '1'
# dataExpected: 1
schema: {
"type":"number",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": 1
"actual": '1'
}
"errors": [
{
"message": "The undefined property must be a number (current value is \"1\").",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a number (current value is "1").</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailStringVsIntRoot =
testDesc: 'when expected body is string and real is integer'
# dataReal: 1
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": '1'
"actual": 1
}
"errors": [
{
"message": "The undefined property must be a string (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be a string (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: ['']
b.bodyTypeFailPrimitiveVsObjRoot =
testDesc: 'when expected body is primitive and real is object'
# dataReal: JSON.stringify {'key': 'val'}
# dataExpected: "1"
schema: {
"type":"string",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": "1"
"actual": JSON.stringify {'key': 'val'}
}
"errors": [
{
"message": "The undefined property must be a string (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsPrimitiveRoot =
testDesc: 'when expected body is object and real is primitive'
# dataReal: "1"
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": "1"
},
"errors": [
{
"message": "The property must be an object (current value is 1).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '<wrapStart><changedStartTag>1</endTag> <commentStartTag>The property must be an object (current value is 1).</commentEndTag><wrapEnd>'
usedErrors: [""]
b.bodyTypeFailObjVsArrayRoot =
testDesc: 'when expected body is object and real is array'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
schema: {
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailObjVsArrayRootNoSchema =
testDesc: 'when expected body is object and real is array (no schema)'
# dataReal: JSON.stringify [1,2,3]
# dataExpected: JSON.stringify {"key": "val"}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify {"key": "val"}
"actual": JSON.stringify [1,2,3]
}
"errors": [
{
"message": "The property must be an object (current value is [1,2,3]).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘key’ property is required.",
"location": {
"pointer": "/key"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>[</endTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag>]</endTag><wrapEnd>
'''
usedErrors: []
b.bodyTypeFailArrayVsObjRoot =
testDesc: 'when expected body is array and real is object'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
schema: {
"type":"array",
"$schema": "http://json-schema.org/draft-03/schema",
"required":true
}
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
},
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyTypeFailArrayVsObjRootNoSchema =
testDesc: 'when expected body is array and real is object (no schema)'
# dataReal: JSON.stringify {"key": "val"}
# dataExpected: JSON.stringify [1,2,3]
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify [1,2,3]
"actual": JSON.stringify {"key": "val"}
}
"errors": [
{
"message": "The property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": ""
}
},
{
"message": "The ‘0’ property is required.",
"location": {
"pointer": "/0"
}
},
{
"message": "The ‘1’ property is required.",
"location": {
"pointer": "/1"
}
},
{
"message": "The ‘2’ property is required.",
"location": {
"pointer": "/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<addedStartTag> "key": "val"</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: []
bodyComplexExpected = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"simpleKeyValueOKmiss": "simpleKeyValueOKmiss",
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": {
"keyWithObjectValueOKnestedKeyMiss": "keyWithObjectValueOKnestedKeyMiss",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [1,2,3],
"keyWithArrayValueTypeFail": [1,2,3]
}
bodyComplexReal = {
"simpleKeyValueOK": "simpleKeyValueOK",
"simpleKeyValueNumberOK": 1,
"keyWithObjectValueOK": {
"keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2",
},
"keyWithObjectValueFail": {
"keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"
},
"keyWithObjectValueWrongTypeFail": [1,2,3],
"keyWithArrayValueOK": [1,2,3],
"keyWithArrayValueOK2": [4,5,6],
"keyWithArrayValueTypeFail": {"key": "val"}
}
b.bodyComplex =
testDesc: 'complex body test'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: "body"
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
}
"errors": [
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyComplexWithNonPointerError =
testDesc: 'complex body test with non pointer error in gavel results'
# dataReal: JSON.stringify bodyComplexReal
# dataExpected: JSON.stringify bodyComplexExpected
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify bodyComplexExpected
"actual": JSON.stringify bodyComplexReal
},
"errors": [
{
"message": "Your mamma can't swim up the hill."
},
{
"message": "The ‘simpleKeyValueOKmiss’ property is required.",
"location": {
"pointer": "/simpleKeyValueOKmiss"
}
},
{
"message": "The ‘keyWithObjectValueFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKeyMiss’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKeyMiss"
}
},
{
"message": "The ‘keyWithObjectValueWrongTypeFail,keyWithObjectValueOKnestedKey2’ property is required.",
"location": {
"pointer": "/keyWithObjectValueWrongTypeFail/keyWithObjectValueOKnestedKey2"
}
},
{
"message": "The keyWithArrayValueTypeFail property must be an array (current value is {\"key\":\"val\"}).",
"location": {
"pointer": "/keyWithArrayValueTypeFail"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,0’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/0"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,1’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/1"
}
},
{
"message": "The ‘keyWithArrayValueTypeFail,2’ property is required.",
"location": {
"pointer": "/keyWithArrayValueTypeFail/2"
}
}
],
"kind": "json"
}
expectedOutput: '''
<wrapStart><startTag>{</endTag>
<startTag> "simpleKeyValueOK": "simpleKeyValueOK",</endTag>
<startTag> "simpleKeyValueNumberOK": 1,</endTag>
<startTag> "keyWithObjectValueOK": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey": "keyWithObjectValueOKnestedKey",</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<startTag> "keyWithObjectValueFail": {</endTag>
<startTag> "keyWithObjectValueOKnestedKey2": "keyWithObjectValueOKnestedKey2"</endTag>
<startTag> },</endTag>
<changedStartTag> "keyWithObjectValueWrongTypeFail": [</endTag> <commentStartTag>The keyWithObjectValueWrongTypeFail property must be an object (current value is [1,2,3]).</commentEndTag>
<addedStartTag> 1,</endTag>
<addedStartTag> 2,</endTag>
<addedStartTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK": [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> "keyWithArrayValueOK2": [</endTag>
<startTag> 4,</endTag>
<startTag> 5,</endTag>
<startTag> 6</endTag>
<startTag> ],</endTag>
<changedStartTag> "keyWithArrayValueTypeFail": {</endTag> <commentStartTag>The keyWithArrayValueTypeFail property must be an array (current value is {"key":"val"}).</commentEndTag>
<addedStartTag> "key": "val"</endTag>
<startTag> }</endTag>
<startTag>}</endTag><wrapEnd>
'''
usedErrors: [
"/keyWithObjectValueWrongTypeFail",
"/keyWithArrayValueTypeFail"
]
b.bodyOkWithNestedObjectsInArrays =
testDesc: 'when expected and real body are the same and contains array of objects'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
# {"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
# {"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# {"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
# {"otrkey": "PI:KEY:<KEY>END_PI", "key2": "valuePI:KEY:<KEY>END_PI"}
# {"otrkey": "PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PIahre_feste", "key2": "PI:KEY:<KEY>END_PI"}
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "valuePI:KEY:<KEY>END_PI"}
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
{"otrkey": "PI:KEY:<KEY>END_PI", "key2": "PI:KEY:<KEY>END_PI"}
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "2PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "3PI:KEY:<KEY>END_PI",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> },</endTag>
<startTag> {</endTag>
<startTag> "otrkey": "PI:KEY:<KEY>END_PI",</endTag>
<startTag> "key2": "value2"</endTag>
<startTag> }</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArrays =
testDesc: 'when expected and real body are the same and contains array of strings'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# "MrauMrau"
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
"MrauMrau"
"BauBau"
]
}
}
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> "MrauMrau",</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedArraysInArrays =
testDesc: 'when expected and real body are the same and contains array of arrays'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# [1,2,3]
# [1,2,3]
# [1,2,3]
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
[1,2,3]
[1,2,3]
[1,2,3]
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "login": "true",</endTag>
<startTag> "results": [</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ],</endTag>
<startTag> [</endTag>
<startTag> 1,</endTag>
<startTag> 2,</endTag>
<startTag> 3</endTag>
<startTag> ]</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
b.bodyOkWithNestedStringsInArraysWrappedKeys =
testDesc: 'when expected and real body are the same and I want to wrap object keys in additional tags'
# dataReal: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
# dataExpected: JSON.stringify {
# "login": "true"
# "results": [
# "BooBoo"
# 5
# "BauBau"
# ]
# }
fieldName: 'body'
fieldResult: {
"values": {
"expected":JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
"actual": JSON.stringify {
"login": "true"
"results": [
"BooBoo"
5
"BauBau"
]
}
},
"errors": [],
"kind": "json"
}
expectedOutput: """
<wrapStart><startTag>{</endTag>
<startTag> "<keyStart>login</keyEnd>": "true",</endTag>
<startTag> "<keyStart>results</keyEnd>": [</endTag>
<startTag> "BooBoo",</endTag>
<startTag> 5,</endTag>
<startTag> "BauBau"</endTag>
<startTag> ]</endTag>
<startTag>}</endTag><wrapEnd>
"""
usedErrors: []
outputOptions:
jsonKeyStartTag: "<keyStart>"
jsonKeyEndTag: "</keyEnd>"
wrapWith: '<wrapStart>##data<wrapEnd>'
startTag: '<startTag>'
endTag: '</endTag>'
missingStartTag: '<missingStartTag>'
addedStartTag: "<addedStartTag>"
changedStartTag: '<changedStartTag>'
comments: true
commentStartTag: '<commentStartTag>'
commentEndTag: '</commentEndTag>'
module.exports = {
gavel2htmlOutputOptions
testsHeaders: h
testsBody: b
}
|
[
{
"context": "rocess.env['MONGOHQ_URL'] || 'mongodb://localhost/lnug'\n\nSchema = mongoose.Schema\nObjectId = Schema.Obje",
"end": 224,
"score": 0.8224402666091919,
"start": 220,
"tag": "USERNAME",
"value": "lnug"
},
{
"context": "body.password == (process.env['JOB_PASSWORD'] || 'password')\n job.save (err) ->\n if err\n cons",
"end": 2845,
"score": 0.9974152445793152,
"start": 2837,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ", (req,res) ->\n res.redirect 'https://github.com/lnug/feedback'\n\napp.get '/speak', (req,res) ->\n res.r",
"end": 3478,
"score": 0.9995005130767822,
"start": 3474,
"tag": "USERNAME",
"value": "lnug"
},
{
"context": ", (req,res) ->\n res.redirect 'https://github.com/lnug/speak' \n\nport = process.env.PORT || 8080\napp.l",
"end": 3560,
"score": 0.999504566192627,
"start": 3556,
"tag": "USERNAME",
"value": "lnug"
}
] | server.coffee | basicallydan/website | 0 | express = require 'express'
sizlate = require 'sizlate'
mongoose = require 'mongoose'
moment = require 'moment'
md = require("node-markdown").Markdown
mongoose.connect process.env['MONGOHQ_URL'] || 'mongodb://localhost/lnug'
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
app = express()
app.set('view engine', 'sizlate')
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + "/public/"))
app.use(express.urlencoded())
vimeo = require('./lib/vimeo')
vimeo.keyword = 'LNUG'
vimeo.request()
JobSchema = new Schema
job_title : { type: String, required: true }
description : { type: String, required: true }
name : { type: String, required: true }
email : { type: String, required: true }
company_name : { type: String, required: true }
company_url : { type: String, required: true }
location : { type: String, required: true }
type : { type: String, required: true }
date : { type: Date, default: Date.now }
Job = mongoose.model 'Job', JobSchema
# server routes
app.get "/", (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
jobs = docs.map (j) ->
{
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
}
videos = vimeo.videos[0..3].map (v) ->
{
'.title': v.title,
'.link': {
href: v.url
},
'.thumb': {
src: v.thumbnail_medium,
alt: v.title
}
}
res.render 'index',
layout: 'layout',
selectors: {
'ul#videos':{
partial: 'video',
data: videos
}
'ul#jobs':{
partial: 'small_job',
data: jobs
}
}
app.get '/jobs', (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
if docs
jobs = docs.map (j) ->
{
'.date': j.date.toDateString(),
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
'.apply': {
href: "mailto:#{j.email}"
}
}
else
jobs = []
res.render 'jobs',
layout: 'layout',
selectors: {
'ul#jobs':{
partial: 'job',
data: jobs
}
}
app.get '/submit', (req,res) ->
res.render 'submit',
layout: 'layout',
selectors: {}
app.post '/submit', (req,res) ->
job = new Job(req.body)
if req.body.password == (process.env['JOB_PASSWORD'] || 'password')
job.save (err) ->
if err
console.log(err)
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid submission, all fields are required'
}
else
res.redirect '/jobs'
else
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid password'
}
app.get '/code-of-conduct', (req,res) ->
res.render 'code-of-conduct',
layout: 'layout'
app.get '/newsletter', (req,res) ->
res.redirect 'http://eepurl.com/Zj9Db'
app.get '/feedback', (req,res) ->
res.redirect 'https://github.com/lnug/feedback'
app.get '/speak', (req,res) ->
res.redirect 'https://github.com/lnug/speak'
port = process.env.PORT || 8080
app.listen port
console.log "Listening on Port '#{port}'"
| 219572 | express = require 'express'
sizlate = require 'sizlate'
mongoose = require 'mongoose'
moment = require 'moment'
md = require("node-markdown").Markdown
mongoose.connect process.env['MONGOHQ_URL'] || 'mongodb://localhost/lnug'
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
app = express()
app.set('view engine', 'sizlate')
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + "/public/"))
app.use(express.urlencoded())
vimeo = require('./lib/vimeo')
vimeo.keyword = 'LNUG'
vimeo.request()
JobSchema = new Schema
job_title : { type: String, required: true }
description : { type: String, required: true }
name : { type: String, required: true }
email : { type: String, required: true }
company_name : { type: String, required: true }
company_url : { type: String, required: true }
location : { type: String, required: true }
type : { type: String, required: true }
date : { type: Date, default: Date.now }
Job = mongoose.model 'Job', JobSchema
# server routes
app.get "/", (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
jobs = docs.map (j) ->
{
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
}
videos = vimeo.videos[0..3].map (v) ->
{
'.title': v.title,
'.link': {
href: v.url
},
'.thumb': {
src: v.thumbnail_medium,
alt: v.title
}
}
res.render 'index',
layout: 'layout',
selectors: {
'ul#videos':{
partial: 'video',
data: videos
}
'ul#jobs':{
partial: 'small_job',
data: jobs
}
}
app.get '/jobs', (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
if docs
jobs = docs.map (j) ->
{
'.date': j.date.toDateString(),
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
'.apply': {
href: "mailto:#{j.email}"
}
}
else
jobs = []
res.render 'jobs',
layout: 'layout',
selectors: {
'ul#jobs':{
partial: 'job',
data: jobs
}
}
app.get '/submit', (req,res) ->
res.render 'submit',
layout: 'layout',
selectors: {}
app.post '/submit', (req,res) ->
job = new Job(req.body)
if req.body.password == (process.env['JOB_PASSWORD'] || '<PASSWORD>')
job.save (err) ->
if err
console.log(err)
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid submission, all fields are required'
}
else
res.redirect '/jobs'
else
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid password'
}
app.get '/code-of-conduct', (req,res) ->
res.render 'code-of-conduct',
layout: 'layout'
app.get '/newsletter', (req,res) ->
res.redirect 'http://eepurl.com/Zj9Db'
app.get '/feedback', (req,res) ->
res.redirect 'https://github.com/lnug/feedback'
app.get '/speak', (req,res) ->
res.redirect 'https://github.com/lnug/speak'
port = process.env.PORT || 8080
app.listen port
console.log "Listening on Port '#{port}'"
| true | express = require 'express'
sizlate = require 'sizlate'
mongoose = require 'mongoose'
moment = require 'moment'
md = require("node-markdown").Markdown
mongoose.connect process.env['MONGOHQ_URL'] || 'mongodb://localhost/lnug'
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
app = express()
app.set('view engine', 'sizlate')
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + "/public/"))
app.use(express.urlencoded())
vimeo = require('./lib/vimeo')
vimeo.keyword = 'LNUG'
vimeo.request()
JobSchema = new Schema
job_title : { type: String, required: true }
description : { type: String, required: true }
name : { type: String, required: true }
email : { type: String, required: true }
company_name : { type: String, required: true }
company_url : { type: String, required: true }
location : { type: String, required: true }
type : { type: String, required: true }
date : { type: Date, default: Date.now }
Job = mongoose.model 'Job', JobSchema
# server routes
app.get "/", (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
jobs = docs.map (j) ->
{
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
}
videos = vimeo.videos[0..3].map (v) ->
{
'.title': v.title,
'.link': {
href: v.url
},
'.thumb': {
src: v.thumbnail_medium,
alt: v.title
}
}
res.render 'index',
layout: 'layout',
selectors: {
'ul#videos':{
partial: 'video',
data: videos
}
'ul#jobs':{
partial: 'small_job',
data: jobs
}
}
app.get '/jobs', (req,res) ->
Job.where('date').gt(moment().day(-30)).sort('date').exec (err, docs) ->
if docs
jobs = docs.map (j) ->
{
'.date': j.date.toDateString(),
'.company': {
href: j.company_url,
innerHTML: j.company_name
},
'.type': j.type
'.location': j.location,
'.title': j.job_title,
'.description': md(j.description, true),
'.apply': {
href: "mailto:#{j.email}"
}
}
else
jobs = []
res.render 'jobs',
layout: 'layout',
selectors: {
'ul#jobs':{
partial: 'job',
data: jobs
}
}
app.get '/submit', (req,res) ->
res.render 'submit',
layout: 'layout',
selectors: {}
app.post '/submit', (req,res) ->
job = new Job(req.body)
if req.body.password == (process.env['JOB_PASSWORD'] || 'PI:PASSWORD:<PASSWORD>END_PI')
job.save (err) ->
if err
console.log(err)
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid submission, all fields are required'
}
else
res.redirect '/jobs'
else
res.render 'submit',
layout: 'layout',
selectors: {
'.error': 'Invalid password'
}
app.get '/code-of-conduct', (req,res) ->
res.render 'code-of-conduct',
layout: 'layout'
app.get '/newsletter', (req,res) ->
res.redirect 'http://eepurl.com/Zj9Db'
app.get '/feedback', (req,res) ->
res.redirect 'https://github.com/lnug/feedback'
app.get '/speak', (req,res) ->
res.redirect 'https://github.com/lnug/speak'
port = process.env.PORT || 8080
app.listen port
console.log "Listening on Port '#{port}'"
|
[
{
"context": "emp}, ${3:3nd3} and chain A;\n run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};\n calc_m",
"end": 11084,
"score": 0.9968249797821045,
"start": 11071,
"tag": "USERNAME",
"value": "blaine-mooers"
},
{
"context": "\".pse\");\n end python;\n $0\n '''\n \"Run Tom Holder's supercell script to generate three cells in all",
"end": 15314,
"score": 0.7062697410583496,
"start": 15304,
"tag": "NAME",
"value": "Tom Holder"
},
{
"context": "\n 'body': '''\n set fetch_path, ${1:/Users/blaine/pdbFiles};\n $0\n '''\n 'Set antialias to g",
"end": 20147,
"score": 0.8478347063064575,
"start": 20141,
"tag": "USERNAME",
"value": "blaine"
},
{
"context": "'github'\n 'body': '''\n https://github.com/MooersLab/pymolsnips/blob/master/README.md\n $0\n '''",
"end": 33154,
"score": 0.9974186420440674,
"start": 33145,
"tag": "USERNAME",
"value": "MooersLab"
}
] | atompymolsnips/pymolsnippets.cson | marevebro/pymolsnips | 0 | '.source.pymol':
'Ambient occlussion.':
'prefix': 'ao'
'body': '''
set_color oxygen, [1.0,0.4,0.4];
set_color nitrogen, [0.5,0.5,1.0];
remove solvent;
as spheres;
util.cbaw;
bg white;
set light_count,10;
set spec_count,1;
set shininess, 10;
set specular,0.25;
set ambient,0;
set direct,0;
set reflect,1.5;
set ray_shadow_decay_factor, 0.1;
set ray_shadow_decay_range, 2;
unset depth_cue;
ray;
$0
'''
'Set ellipsoid color.':
'prefix': 'ellipcol'
'body': '''
set ellipsoid_color, ${1:color};
$0
'''
'set distance labels to display 2 decimals':
'prefix': 'sigdist'
'body': '''
set label_distance_digits, ${1:2};
$0
'''
'Set angle labels to display 2 decimals places':
'prefix': 'sigang'
'body': '''
set label_angle_digits, ${1:2};
$0
'''
'Ball and stick representation. ':
'prefix': 'bs'
'body': '''
show sticks;
set stick_radius, 0.12;
set stick_ball, on;
set stick_ball_ratio, 1.9;
show nb_spheres;
set nb_spheres_size=0.33;
$0
'''
'Base-stacking figure.':
'prefix': 'stack'
'body': '''
delete all;
fetch ${1:4PCO}, type=pdb,async=0;
select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );
hide everything, element h;
remove not ${2:G2G3};
bg_color white;
show sticks;
set stick_radius=0.14;
set stick_ball, on;
set stick_ball_ratio,1.9;
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);
hide everything, element H;
select carbon1, element C and (resi ${4:3} or resi ${5:8})
# select lower base pair;
select carbon2, element C and (resi ${3:2} or resi ${6:9})
#select upper base pair;
color gray70,carbon1;
color gray10,carbon2;
space cmyk;
distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;
distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;
distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;
distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;
color black, hbond1;
color black, hbond2;
color gray70, hbond3;
color gray70, hbond4;
show nb_spheres;
set nb_spheres_size, 0.35;
hide labels;
ray 1600,1000;
png ${1:4PCO}.png
$0
'''
'Biological unit.':
'prefix': 'bu'
'body': '''
run ~/Scripts/PyMOLScripts/quat.py; quat
$0
'''
'Valence bond. ':
'prefix': 'doubleBond'
'body': '''
set valence, 1;
set valence_mode, 1;
$0
'''
'Color blindness.':
'prefix': 'cblind'
'body': '''
run ~/Pymol-script-repo/colorblindfriendly.py;
as cartoon;
color cb_red, ss H;
color cb_yellow,ss S;
color cb_green, ss L+;
$0
'''
'Center pi.':
'prefix': 'centerpi'
'body': '''
pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;
dist pi_cent////ps1, b/${4:U`15}/${5:aaa};
$0
'''
'Color ribbon H red, strand yellow, loop green.':
'prefix': 'cribbon'
'body': '''
as cartoon;
color red, ss H;
color yellow,ss S;
color green, ss L+;
$0
'''
'Colored spheres.':
'prefix': 'cspheres'
'body': '''
as spheres;
color gray30, chain %0;
color white, chain %1;
color green, name CL;
color brown, resn NAG;
color red, resi 381;
remove solvent;
unset specular;
set ray_trace_gain, 0;
set ray_trace_mode, 3;
bg_color white;
set ray_trace_color, black;
unset depth_cue;
$0
'''
'Coordinate covalent bonds to metals and H-bonds friom RNA.':
'prefix': 'coordinate'
'body': '''
viewport 900,600;
fetch 3nd4, type=pdb, async=0;
run ~/Scripts/PyMOLScripts/quat.py;
quat 3nd4;
show sticks;
set stick_radius=0.125;
hide everything, name H*;
bg_color white;
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)));
bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);
distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);
show nb_spheres;
set nb_spheres_size, .35;
distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;
distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;
distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;
distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;
distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;
distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;
distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;
distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;
distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;
distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;
distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;
distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;
distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;
distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;
distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;
distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;
distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
set depth_cue=0;
set ray_trace_fog=0;
set dash_color, black;
set label_font_id, 5;
set label_size, 36;
set label_position, (0.5, 1.0, 2.0);
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
select carbon, element C;
color yellow, carbon;
disable carbon;
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': '''
distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}
$0
'''
'Draw H-bonds. ':
'prefix': 'drawHbonds'
'body': '''
hide everything, hydrogens
hide labels
set dash_color, ${1:black}${2:yelow}
set dash_gap, 0.4
set dash_radius, 0.08
$0
'''
'Carved electron density. ':
'prefix': 'carvedDensity'
'body': '''
delete all;
fetch ${1:4dgr}, async=0;
fetch ${1:4dgr}, type=2fofc,async=0;
select ${2:LongGlycan}, resi ${3:469:477};
orient ${2:LongGlycan};
remove not ${2:LongGlycan};
remove name H*;
isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;
color density, 2fofcmap;
show sticks;
show spheres;
set stick_radius, .07;
set sphere_scale, .19;
set sphere_scale, .13, elem H;
set bg_rgb=[1, 1, 1];
set stick_quality, 50;
set sphere_quality, 4;
color gray85, elem C;
color red, elem O;
color slate, elem N;
color gray98, elem H;
set stick_color, gray50;
set ray_trace_mode, 1;
set ray_texture, 2;
set antialias, 3;
set ambient, 0.5;
set spec_count, 5;
set shininess, 50;
set specular, 1;
set reflect, .1;
set dash_gap, 0;
set dash_color, black;
set dash_gap, .15;
set dash_length, .05;
set dash_round_ends, 0;
set dash_radius, .05;
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);
preset.ball_and_stick("all",mode=1);
draw;
$0
'''
'Fetch 2FoFc map.':
'prefix': 'fetch2FoFc'
'body': '''
fetch ${1:3nd4}, type=2fofc, async=0
$0
'''
'Fetch cif file.':
'prefix': 'fetchCIF'
'body': '''
fetch ${1:3nd4}, type=cif, async=0;
$0
'''
'Fetch fofc map.':
'prefix': 'fetchFoFc'
'body': '''
fetch ${1:3nd4}, type=fofc, async=0;
$0
'''
'Filled rings in nucleic acids. ':
'prefix': 'filledRing'
'body': '''
show sticks;set cartoon_ring_mode, 3;
set cartoon_ring_finder, 1;
set cartoon_ladder_mode, 1;
set cartoon_nucleic_acid_mode, 4;
set cartoon_ring_transparency, 0.5;
as cartoon;
$0
'''
'Get coordinates. ':
'prefix': 'getCoordinates'
'body': '''
print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');
$0
'''
'H-bond dashes.':
'prefix': 'hbonddash'
'body': '''
hide everything, hydrogens;
hide labels;
set dash_color, black;
set dash_gap, 0.4;
set dash_radius, 0.08;
$0
'''
'Hbond setup. ':
'prefix': 'hbond'
'body': '''
hide labels;
set dash_color, black ;
set dash_length, ${1:0.15};
set dash_gap, ${2:0.35};
set dash_width, ${3:3.0};
$0
'''
'Hide alt loc.':
'prefix': 'hidealtloc'
'body': '''
select altconf, alt ${1:b} # select B alternative locators;
hide everything, altconf # hide alt B locators;
$0
'''
'Label CA atom with single-letter residue name and residue number.':
'prefix': 'labelResnResi'
'body': '''
label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});
$0
'''
'Label SS. ':
'prefix': 'labelSS'
'body': '''
alter ${1:}, ss='%1';
label (%2),'%3';
$0
'''
'Load PDB ball-and-stick.':
'prefix': 'loadPDBbs'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
hide (name H*);
hide lines;
show sticks;
set stick_radius, ${2:1.2};
set nb_sphere_radius, ${3:0.35};
orient;
$0
'''
'Load PDB nb spheres. ':
'prefix': 'loadPDBnb'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;
orient;
set stick_radius, ${2:1.2};
hide (name H*);
set nb_sphere_size, ${3:0.35};
set nb_spheres_quality, ${4:1};
show nb_spheres;
$0
'''
'Measure surface area. ':
'prefix': 'ms'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
select ${2:temp}, ${3:3nd3} and chain A;
run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};
calc_msms_area ${2:temp};
$0
'''
'Molscript ribbons.':
'prefix': 'molscriptRibbon'
'body': '''
set cartoon_highlight_color, grey;
show cartoon;
set cartoon_flat_sheets, 0;
set cartoon_smooth_loops, 0;
set cartoon_fancy_helices, 1;
$0
'''
'One letter amino acid. ':
'prefix': 'oneLetter'
'body': '''
one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%
'ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%
'SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%
$0
'''
'Print Fasta from PDB file. ':
'prefix': 'fasta'
'body': '''
print cmd.get_fastastr('all')
$0
'''
'Position label with pseudoatom. ':
'prefix': 'pseudolabel'
'body': '''
pseudoatom ${1:forLabel};
label ${1:forLabel}, '%0';
set label_color, ${2:red};
$0
'''
'Rotate about axis.':
'prefix': 'rotate'
'body': '''
rotate ${1:x}, ${2:45}, ${3:pept}
$0
'''
'Stereo draw.':
'prefix': 'stereoDraw'
'body': '''
stereo walleye;
set ray_shadow, off;
#draw 3200,2000;
draw ${1:1600,1000};
png ${2:aaa}.png
$0
'''
'Stereo ray.':
'prefix': 'stereoRay'
'body': '''
stereo;
set ray_shadow, off;
ray ${1:2400,1200};
png ${2:aaa}.png
$0
'''
'Three electron density. ':
'prefix': 'threeMaps'
'body': '''
load ${1:4dgr}.pdb
# Make sure to rename map file so that
# the root filename differs from pdb root filename
load ${1:4dgr}_2fofc.ccp4, 2fofc;
load ${1:4dgr}_fofc.ccp4, fofc;
select ${2:glycan}, resid 200 or (resid 469:477);
isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};
color density, ${3:mesh1};
isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};
color green, ${4:mesh2};
isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};
color red, ${5:mesh3};
$0
'''
'Turn about axis. ':
'prefix': 'turnAboutAxis'
'body': '''
turn ${1:x},${2:90};
$0
'''
'Volume ramp.':
'prefix': 'volumeRamp'
'body': '''
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': '''
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': '''
bg_color white
hide everything
show spheres
set stick_radius = 0.1
hide everything, HET
show spheres, HET
set sphere_quality=3
show sticks, resi 1102
from pymol import stored
# set the stored array equal to the b−values; or use your own values
stored.bb = [ ]
iterate, stored.bb.append(b)
# execute a python−block
python
# scale the b−values
M = max(stored.bb)
scaledBB = map(lambda x: float (x/M), stored.bb)
count = 0
# set the sphere radii independently
for x in scaledBB:
cmd.set("sphere_scale", x ,"ID %s"%count)
count = count + 1
python end
spectrum b, selection=4gdx
space cmyk
set specular_intensity , 0.25
$0
'''
'Return settings in rounded format.':
'prefix': 'rv'
'body': '''
run roundview.py;
$0
'''
'Save png flle with timestamp':
'prefix': 'spng'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".png");
end python;
$0
'''
'Save pse flle with timestamp':
'prefix': 'spse'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".pse");
end python;
$0
'''
"Run Tom Holder's supercell script to generate three cells in all directions.":
'prefix': 'sc222'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
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': '''
create ${1:sodium2}, ${2:sodium1}
set sphere_transparency, 0.4, ${1:sodium2}
set sphere_scale, 1.05, ${1:sodium2}
ray
$0
'''
'Blur the background atoms.':
'prefix': 'fog'
'body': '''
set fog, 0
$0
'''
'Remove waters from molecular object.':
'prefix': 'rmwater'
'body': '''
remove resn HOH
$0
'''
'Set color name to a RGB code.':
'prefix': 'setcolor'
'body': '''
set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}]
color ${1:bark}, ${5:protein}
$0
'''
'Duplicate object.':
'prefix': 'duplicateObject'
'body': '''
create ${1:t4l}, ${2:1lw9};
$0
'''
'Select a chain. ':
'prefix': 'selectChain'
'body': '''
select rna, chain B
$0
'''
'Select residues by name.':
'prefix': 'selectResidues'
'body': '''
select aromatic, resn phe+tyr+trp;
$0
'''
'Select residues by a range of numbers.':
'prefix': 'selectResi'
'body': '''
select se;2. resi 1-100
$0
'''
'Select atoms by elemnt.':
'prefix': 'selectElement'
'body': '''
select ${1:oxygen}, elem ${2:O}
$0
'''
'Select atoms by name.':
'prefix': 'selectName'
'body': '''
select ${1:oxygen2}, name ${2:O2}
$0
'''
'Select atoms by alpha helices.':
'prefix': 'selectHelices'
'body': '''
select ${1:helices}, ss h;
$0
'''
'Select atoms by beta strands.':
'prefix': 'selectStrands'
'body': '''
select ${1:strands}, ss s;
$0
'''
'Select atoms by beta loops.':
'prefix': 'selectLoops'
'body': '''
select ${1:loops}, ss l;
$0
'''
'Select all nitrogen atom in a selelction except from lysine.':
'prefix': 'selectAllBut'
'body': '''
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': '''
select ${1:nearby}, resn ${2:drug} around ${3:5};
$0
'''
'Select residues within a radius around a ligand.':
'prefix': 'selectResiduesAround'
'body': '''
select ${1:nearby}, br. resn ${2:drug} around ${3:5};
$0
'''
'Undo a selection.':
'prefix': 'undoSelection'
'body': '''
disable ${1:sele};
$0
'''
'Load a pdb file in the current directory.':
'prefix': 'loadPDBfile'
'body': '''
load ${1:my.pdb};
$0
'''
'Save a png file of current scene to the current directory.':
'prefix': 'savePNG'
'body': '''
png ${1:saveMe.png};
$0
'''
'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.':
'prefix': 'ringMode'
'body': '''
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': '''
set cartoon_side_chain_helper, on;
$0
'''
'Create a new object from part of an existing object.':
'prefix': 'extractPartObj'
'body': '''
extract new_obj, chain A
$0
'''
'Create a putty cartoon.':
'prefix': 'puttyCartoon'
'body': '''
show cartoon;
cartoon putty;
unset cartoon_smooth_loops;
unset cartoon_flat_sheets;
$0
'''
'Trun off magenta squares on current selection.':
'prefix': 'hideSelection'
'body': '''
indicate none
$0
'''
'Turn on discrete colors between secondary structure elements.':
'prefix': 'discreteCartoonColoring'
'body': '''
set cartoon_discrete_colors, on
$0
'''
'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.':
'prefix': 'sc111'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
supercell 1, 1, 1, , orange, supercell1, 1
$0
'''
'Display SAXS envelope':
'prefix': 'saxsEnvelope'
'body': '''
alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0
set solvent_radius = 3.0
$0
'''
'Set additional path for PyMOL to search on startup':
'prefix': 'setpath'
'body': '''
os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};
$0
'''
'Set path for location to save fetched pdb files. ':
'prefix': 'fetchPath'
'body': '''
set fetch_path, ${1:/Users/blaine/pdbFiles};
$0
'''
'Set antialias to get smooth edges':
'prefix': 'antialias'
'body': '''
set antialias, 1;
$0
'''
'Print list of active pymolrc files.':
'prefix': 'lspymolrc'
'body': '''
print invocation.options.deferred;
$0
'''
'Set number of decimals places to show in distance labels. ':
'prefix': 'sigDigits'
'body': '''
set label_distance_digits, ${1:2};
set label_angle_digits, ${2:2};
$0
'''
'Label the CA atoms with the Ala333 style format':
'prefix': 'labelCAs'
'body': '''
label name CA,"%s%s" % (resn,resi);
$0
'''
'Label waters HOH.':
'prefix': 'labelWatersHOH'
'body': '''
label resn HOH ,"%s%s" % (resn,resi);
$0
'''
'Label waters W.':
'prefix': 'labelWatersW'
'body': '''
label resn HOH ,"W%s" % (resi);
$0
'''
'Find hbonds around a residue.':
'prefix': 'findHbonds'
'body': '''
remove element h; distance hbonds, all, all, 3.2, mode=2;
$0
'''
'Print the B-factors of a residue. ':
'prefix': 'printBs'
'body': '''
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': '''
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': '''
iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;
$0
'''
"Print B-values for a residue with the B's rounded off to two decimal places.":
'prefix': 'printBs2digits'
'body': '''
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.write_html_ref('pymol-command-ref.html');
$0
'''
"Average the B-factors by using a regular list as opposed to PyMOL's stored list. Edit the selection as needed.":
'prefix': 'averageB'
'body': '''
""" Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
print("Sum = ", "%.2f" % (sum(Bfactors)));
print("Number of atoms = ", len(Bfactors));
print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));
$0
'''
'AveBResiX, prints the resiude number and the average bfactor. ':
'prefix': 'aveB4resiX'
'body': '''
""""AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
"""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
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': '''
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': '''
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': '''
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': '''
internal_gui_mode=2;
$0
'''
'Set the width of the internal gui.
':
'prefix': 'internalGUIwidth'
'body': '''
internal_gui_width=%{1:20};
$0
'''
'Print document string of a function.':
'prefix': 'printDoc'
'body': '''
print ${1:my_func}.__doc__;
$0
'''
'List all snips by tab trigger and description':
'prefix': 'lsSnips'
'body': """
Tab trigger Description
--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
antialias Set antialias to get smooth edges
ao Ambient occlussion.
aveB4resiX AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.
bs Ball and stick representation.
bu Biological unit.
carvedDensity Carved electron density.
cblind Color blindness.
centerpi Center pi.
coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.
cribbon Color ribbon H red, strand yellow, loop green.
cspheres Colored spheres.
discreteCartoonColoring Turn on discrete colors between secondary structure elements.
distance H-bond distances.
doubleBond Valence bond.
drawHbonds Draw H-bonds.
duplicateObject Duplicate object.
ellipcol Set ellipsoid color.
extractPartObj Create a new object from part of an existing object.
fasta Print Fasta from PDB file.
fetch2FoFc Fetch 2FoFc map.
fetchCIF Fetch cif file.
fetchFoFc Fetch fofc map.
fetchPath Set path for location to save fetched pdb files.
filledRing Filled rings in nucleic acids.
findHbonds Find hbonds around a residue.
fog Blur the background atoms.
getCoordinates Get coordinates.
hbond Hbond setup.
hbonddash H-bond dashes.
hideSelection Trun off magenta squares on current selection.
hidealtloc Hide alt loc.
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.
internalGUIwidth Set the width of the internal gui.
labelCAs Label the CA atoms with the Ala333 style format
labelMainChain Label the main chain atoms by resn,resi,atom name.
labelResnResi Label CA atom with residue name and residue number.
labelSS Label SS.
labelWatersHOH Label waters HOH.
labelWatersW Label waters W.
loadPDBbs Load PDB ball-and-stick.
loadPDBfile Load a pdb file in the current directory.
loadPDBnb Load PDB nb spheres.
lsSnips List all snips by tab trigger and description
lspymolrc Print list of active pymolrc files.
molscriptRibbon Molscript ribbons.
ms Measure surface area.
oneLetter One letter amino acid.
pearl The pearl effect is made with two spheres with the outer sphere being transparent.
printBs Print the B-factors of a residue.
printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.
printBspartB Print B factors of part B of a rsidues.
printDoc Print document string of a function.
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.
printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.
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.
pseudolabel Position label with pseudoatom.
puttyCartoon Create a putty cartoon.
ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.
rmwater Remove waters from molecular object.
rotate Rotate about axis.
rv Return settings in rounded format.
savePNG Save a png file of current scene to the current directory.
saxsEnvelope Display SAXS envelope
sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.
sc222 Run Tom Holder's supercell script to generate three cells in all directions.
scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.
selectAllBut Select all nitrogen atom in a selelction except from lysine.
selectAtomsAround Select atoms within a radius around a ligand.
selectChain Select a chain.
selectElement Select atoms by elemnt.
selectHelices Select atoms by alpha helices.
selectLoops Select atoms by beta loops.
selectName Select atoms by name.
selectResi Select residues by a range of numbers.
selectResidues Select residues by name.
selectResiduesAround Select residues within a radius around a ligand.
selectStrands Select atoms by beta strands.
setcolor Set color name to a RGB code.
setpath Set additional path for PyMOL to search on startup
sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.
sigDigits Set number of decimals places to show in distance labels.
sigang Set angle labels to display 2 decimals places
sigdist set distance labels to display 2 decimals
solventRadius Set radius of ball used to make solvent accessible surface.
spng Save png flle with timestamp
spse Save pse flle with timestamp
stack Base-stacking figure.
stereoDraw Stereo draw.
stereoRay Stereo ray.
threeMaps Three electron density.
turnAboutAxis Turn about axis.
undoSelection Undo a selection.
volumeRamp Volume ramp.
writeCommandReference2HTML Write the command reference to html file in the present working directory.
$0
"""
'Asp70-His31 salt-bridge from T4 lysozyme. ':
'prefix': 'his31asp70'
'body': '''
fetch 1lw9, async=0;
zoom (resi 31 or resi 70);
preset.technical(selection='all');
bg_color gray70;
clip slab, 7,(resi 31 or resi 70);
rock;
$0
'''
'triple water pentagon.':
'prefix': 'waterTriple'
'body': '''
fetch 1lw9, async=0;
zoom resi 313;
preset.technical(selection='all', mode=1);
$0
'''
'Make selection of ligand atoms.':
'prefix': 'ligandSelect'
'body': '''
select substrates, organic;
$0
'''
'Print url of README.md file of the pymolsnips repository.':
'prefix': 'github'
'body': '''
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': '''
set label_dihedral_digits, ${1:2};
$0
'''
| 203236 | '.source.pymol':
'Ambient occlussion.':
'prefix': 'ao'
'body': '''
set_color oxygen, [1.0,0.4,0.4];
set_color nitrogen, [0.5,0.5,1.0];
remove solvent;
as spheres;
util.cbaw;
bg white;
set light_count,10;
set spec_count,1;
set shininess, 10;
set specular,0.25;
set ambient,0;
set direct,0;
set reflect,1.5;
set ray_shadow_decay_factor, 0.1;
set ray_shadow_decay_range, 2;
unset depth_cue;
ray;
$0
'''
'Set ellipsoid color.':
'prefix': 'ellipcol'
'body': '''
set ellipsoid_color, ${1:color};
$0
'''
'set distance labels to display 2 decimals':
'prefix': 'sigdist'
'body': '''
set label_distance_digits, ${1:2};
$0
'''
'Set angle labels to display 2 decimals places':
'prefix': 'sigang'
'body': '''
set label_angle_digits, ${1:2};
$0
'''
'Ball and stick representation. ':
'prefix': 'bs'
'body': '''
show sticks;
set stick_radius, 0.12;
set stick_ball, on;
set stick_ball_ratio, 1.9;
show nb_spheres;
set nb_spheres_size=0.33;
$0
'''
'Base-stacking figure.':
'prefix': 'stack'
'body': '''
delete all;
fetch ${1:4PCO}, type=pdb,async=0;
select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );
hide everything, element h;
remove not ${2:G2G3};
bg_color white;
show sticks;
set stick_radius=0.14;
set stick_ball, on;
set stick_ball_ratio,1.9;
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);
hide everything, element H;
select carbon1, element C and (resi ${4:3} or resi ${5:8})
# select lower base pair;
select carbon2, element C and (resi ${3:2} or resi ${6:9})
#select upper base pair;
color gray70,carbon1;
color gray10,carbon2;
space cmyk;
distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;
distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;
distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;
distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;
color black, hbond1;
color black, hbond2;
color gray70, hbond3;
color gray70, hbond4;
show nb_spheres;
set nb_spheres_size, 0.35;
hide labels;
ray 1600,1000;
png ${1:4PCO}.png
$0
'''
'Biological unit.':
'prefix': 'bu'
'body': '''
run ~/Scripts/PyMOLScripts/quat.py; quat
$0
'''
'Valence bond. ':
'prefix': 'doubleBond'
'body': '''
set valence, 1;
set valence_mode, 1;
$0
'''
'Color blindness.':
'prefix': 'cblind'
'body': '''
run ~/Pymol-script-repo/colorblindfriendly.py;
as cartoon;
color cb_red, ss H;
color cb_yellow,ss S;
color cb_green, ss L+;
$0
'''
'Center pi.':
'prefix': 'centerpi'
'body': '''
pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;
dist pi_cent////ps1, b/${4:U`15}/${5:aaa};
$0
'''
'Color ribbon H red, strand yellow, loop green.':
'prefix': 'cribbon'
'body': '''
as cartoon;
color red, ss H;
color yellow,ss S;
color green, ss L+;
$0
'''
'Colored spheres.':
'prefix': 'cspheres'
'body': '''
as spheres;
color gray30, chain %0;
color white, chain %1;
color green, name CL;
color brown, resn NAG;
color red, resi 381;
remove solvent;
unset specular;
set ray_trace_gain, 0;
set ray_trace_mode, 3;
bg_color white;
set ray_trace_color, black;
unset depth_cue;
$0
'''
'Coordinate covalent bonds to metals and H-bonds friom RNA.':
'prefix': 'coordinate'
'body': '''
viewport 900,600;
fetch 3nd4, type=pdb, async=0;
run ~/Scripts/PyMOLScripts/quat.py;
quat 3nd4;
show sticks;
set stick_radius=0.125;
hide everything, name H*;
bg_color white;
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)));
bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);
distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);
show nb_spheres;
set nb_spheres_size, .35;
distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;
distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;
distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;
distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;
distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;
distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;
distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;
distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;
distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;
distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;
distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;
distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;
distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;
distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;
distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;
distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;
distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
set depth_cue=0;
set ray_trace_fog=0;
set dash_color, black;
set label_font_id, 5;
set label_size, 36;
set label_position, (0.5, 1.0, 2.0);
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
select carbon, element C;
color yellow, carbon;
disable carbon;
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': '''
distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}
$0
'''
'Draw H-bonds. ':
'prefix': 'drawHbonds'
'body': '''
hide everything, hydrogens
hide labels
set dash_color, ${1:black}${2:yelow}
set dash_gap, 0.4
set dash_radius, 0.08
$0
'''
'Carved electron density. ':
'prefix': 'carvedDensity'
'body': '''
delete all;
fetch ${1:4dgr}, async=0;
fetch ${1:4dgr}, type=2fofc,async=0;
select ${2:LongGlycan}, resi ${3:469:477};
orient ${2:LongGlycan};
remove not ${2:LongGlycan};
remove name H*;
isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;
color density, 2fofcmap;
show sticks;
show spheres;
set stick_radius, .07;
set sphere_scale, .19;
set sphere_scale, .13, elem H;
set bg_rgb=[1, 1, 1];
set stick_quality, 50;
set sphere_quality, 4;
color gray85, elem C;
color red, elem O;
color slate, elem N;
color gray98, elem H;
set stick_color, gray50;
set ray_trace_mode, 1;
set ray_texture, 2;
set antialias, 3;
set ambient, 0.5;
set spec_count, 5;
set shininess, 50;
set specular, 1;
set reflect, .1;
set dash_gap, 0;
set dash_color, black;
set dash_gap, .15;
set dash_length, .05;
set dash_round_ends, 0;
set dash_radius, .05;
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);
preset.ball_and_stick("all",mode=1);
draw;
$0
'''
'Fetch 2FoFc map.':
'prefix': 'fetch2FoFc'
'body': '''
fetch ${1:3nd4}, type=2fofc, async=0
$0
'''
'Fetch cif file.':
'prefix': 'fetchCIF'
'body': '''
fetch ${1:3nd4}, type=cif, async=0;
$0
'''
'Fetch fofc map.':
'prefix': 'fetchFoFc'
'body': '''
fetch ${1:3nd4}, type=fofc, async=0;
$0
'''
'Filled rings in nucleic acids. ':
'prefix': 'filledRing'
'body': '''
show sticks;set cartoon_ring_mode, 3;
set cartoon_ring_finder, 1;
set cartoon_ladder_mode, 1;
set cartoon_nucleic_acid_mode, 4;
set cartoon_ring_transparency, 0.5;
as cartoon;
$0
'''
'Get coordinates. ':
'prefix': 'getCoordinates'
'body': '''
print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');
$0
'''
'H-bond dashes.':
'prefix': 'hbonddash'
'body': '''
hide everything, hydrogens;
hide labels;
set dash_color, black;
set dash_gap, 0.4;
set dash_radius, 0.08;
$0
'''
'Hbond setup. ':
'prefix': 'hbond'
'body': '''
hide labels;
set dash_color, black ;
set dash_length, ${1:0.15};
set dash_gap, ${2:0.35};
set dash_width, ${3:3.0};
$0
'''
'Hide alt loc.':
'prefix': 'hidealtloc'
'body': '''
select altconf, alt ${1:b} # select B alternative locators;
hide everything, altconf # hide alt B locators;
$0
'''
'Label CA atom with single-letter residue name and residue number.':
'prefix': 'labelResnResi'
'body': '''
label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});
$0
'''
'Label SS. ':
'prefix': 'labelSS'
'body': '''
alter ${1:}, ss='%1';
label (%2),'%3';
$0
'''
'Load PDB ball-and-stick.':
'prefix': 'loadPDBbs'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
hide (name H*);
hide lines;
show sticks;
set stick_radius, ${2:1.2};
set nb_sphere_radius, ${3:0.35};
orient;
$0
'''
'Load PDB nb spheres. ':
'prefix': 'loadPDBnb'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;
orient;
set stick_radius, ${2:1.2};
hide (name H*);
set nb_sphere_size, ${3:0.35};
set nb_spheres_quality, ${4:1};
show nb_spheres;
$0
'''
'Measure surface area. ':
'prefix': 'ms'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
select ${2:temp}, ${3:3nd3} and chain A;
run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};
calc_msms_area ${2:temp};
$0
'''
'Molscript ribbons.':
'prefix': 'molscriptRibbon'
'body': '''
set cartoon_highlight_color, grey;
show cartoon;
set cartoon_flat_sheets, 0;
set cartoon_smooth_loops, 0;
set cartoon_fancy_helices, 1;
$0
'''
'One letter amino acid. ':
'prefix': 'oneLetter'
'body': '''
one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%
'ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%
'SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%
$0
'''
'Print Fasta from PDB file. ':
'prefix': 'fasta'
'body': '''
print cmd.get_fastastr('all')
$0
'''
'Position label with pseudoatom. ':
'prefix': 'pseudolabel'
'body': '''
pseudoatom ${1:forLabel};
label ${1:forLabel}, '%0';
set label_color, ${2:red};
$0
'''
'Rotate about axis.':
'prefix': 'rotate'
'body': '''
rotate ${1:x}, ${2:45}, ${3:pept}
$0
'''
'Stereo draw.':
'prefix': 'stereoDraw'
'body': '''
stereo walleye;
set ray_shadow, off;
#draw 3200,2000;
draw ${1:1600,1000};
png ${2:aaa}.png
$0
'''
'Stereo ray.':
'prefix': 'stereoRay'
'body': '''
stereo;
set ray_shadow, off;
ray ${1:2400,1200};
png ${2:aaa}.png
$0
'''
'Three electron density. ':
'prefix': 'threeMaps'
'body': '''
load ${1:4dgr}.pdb
# Make sure to rename map file so that
# the root filename differs from pdb root filename
load ${1:4dgr}_2fofc.ccp4, 2fofc;
load ${1:4dgr}_fofc.ccp4, fofc;
select ${2:glycan}, resid 200 or (resid 469:477);
isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};
color density, ${3:mesh1};
isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};
color green, ${4:mesh2};
isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};
color red, ${5:mesh3};
$0
'''
'Turn about axis. ':
'prefix': 'turnAboutAxis'
'body': '''
turn ${1:x},${2:90};
$0
'''
'Volume ramp.':
'prefix': 'volumeRamp'
'body': '''
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': '''
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': '''
bg_color white
hide everything
show spheres
set stick_radius = 0.1
hide everything, HET
show spheres, HET
set sphere_quality=3
show sticks, resi 1102
from pymol import stored
# set the stored array equal to the b−values; or use your own values
stored.bb = [ ]
iterate, stored.bb.append(b)
# execute a python−block
python
# scale the b−values
M = max(stored.bb)
scaledBB = map(lambda x: float (x/M), stored.bb)
count = 0
# set the sphere radii independently
for x in scaledBB:
cmd.set("sphere_scale", x ,"ID %s"%count)
count = count + 1
python end
spectrum b, selection=4gdx
space cmyk
set specular_intensity , 0.25
$0
'''
'Return settings in rounded format.':
'prefix': 'rv'
'body': '''
run roundview.py;
$0
'''
'Save png flle with timestamp':
'prefix': 'spng'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".png");
end python;
$0
'''
'Save pse flle with timestamp':
'prefix': 'spse'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".pse");
end python;
$0
'''
"Run <NAME>'s supercell script to generate three cells in all directions.":
'prefix': 'sc222'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
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': '''
create ${1:sodium2}, ${2:sodium1}
set sphere_transparency, 0.4, ${1:sodium2}
set sphere_scale, 1.05, ${1:sodium2}
ray
$0
'''
'Blur the background atoms.':
'prefix': 'fog'
'body': '''
set fog, 0
$0
'''
'Remove waters from molecular object.':
'prefix': 'rmwater'
'body': '''
remove resn HOH
$0
'''
'Set color name to a RGB code.':
'prefix': 'setcolor'
'body': '''
set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}]
color ${1:bark}, ${5:protein}
$0
'''
'Duplicate object.':
'prefix': 'duplicateObject'
'body': '''
create ${1:t4l}, ${2:1lw9};
$0
'''
'Select a chain. ':
'prefix': 'selectChain'
'body': '''
select rna, chain B
$0
'''
'Select residues by name.':
'prefix': 'selectResidues'
'body': '''
select aromatic, resn phe+tyr+trp;
$0
'''
'Select residues by a range of numbers.':
'prefix': 'selectResi'
'body': '''
select se;2. resi 1-100
$0
'''
'Select atoms by elemnt.':
'prefix': 'selectElement'
'body': '''
select ${1:oxygen}, elem ${2:O}
$0
'''
'Select atoms by name.':
'prefix': 'selectName'
'body': '''
select ${1:oxygen2}, name ${2:O2}
$0
'''
'Select atoms by alpha helices.':
'prefix': 'selectHelices'
'body': '''
select ${1:helices}, ss h;
$0
'''
'Select atoms by beta strands.':
'prefix': 'selectStrands'
'body': '''
select ${1:strands}, ss s;
$0
'''
'Select atoms by beta loops.':
'prefix': 'selectLoops'
'body': '''
select ${1:loops}, ss l;
$0
'''
'Select all nitrogen atom in a selelction except from lysine.':
'prefix': 'selectAllBut'
'body': '''
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': '''
select ${1:nearby}, resn ${2:drug} around ${3:5};
$0
'''
'Select residues within a radius around a ligand.':
'prefix': 'selectResiduesAround'
'body': '''
select ${1:nearby}, br. resn ${2:drug} around ${3:5};
$0
'''
'Undo a selection.':
'prefix': 'undoSelection'
'body': '''
disable ${1:sele};
$0
'''
'Load a pdb file in the current directory.':
'prefix': 'loadPDBfile'
'body': '''
load ${1:my.pdb};
$0
'''
'Save a png file of current scene to the current directory.':
'prefix': 'savePNG'
'body': '''
png ${1:saveMe.png};
$0
'''
'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.':
'prefix': 'ringMode'
'body': '''
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': '''
set cartoon_side_chain_helper, on;
$0
'''
'Create a new object from part of an existing object.':
'prefix': 'extractPartObj'
'body': '''
extract new_obj, chain A
$0
'''
'Create a putty cartoon.':
'prefix': 'puttyCartoon'
'body': '''
show cartoon;
cartoon putty;
unset cartoon_smooth_loops;
unset cartoon_flat_sheets;
$0
'''
'Trun off magenta squares on current selection.':
'prefix': 'hideSelection'
'body': '''
indicate none
$0
'''
'Turn on discrete colors between secondary structure elements.':
'prefix': 'discreteCartoonColoring'
'body': '''
set cartoon_discrete_colors, on
$0
'''
'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.':
'prefix': 'sc111'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
supercell 1, 1, 1, , orange, supercell1, 1
$0
'''
'Display SAXS envelope':
'prefix': 'saxsEnvelope'
'body': '''
alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0
set solvent_radius = 3.0
$0
'''
'Set additional path for PyMOL to search on startup':
'prefix': 'setpath'
'body': '''
os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};
$0
'''
'Set path for location to save fetched pdb files. ':
'prefix': 'fetchPath'
'body': '''
set fetch_path, ${1:/Users/blaine/pdbFiles};
$0
'''
'Set antialias to get smooth edges':
'prefix': 'antialias'
'body': '''
set antialias, 1;
$0
'''
'Print list of active pymolrc files.':
'prefix': 'lspymolrc'
'body': '''
print invocation.options.deferred;
$0
'''
'Set number of decimals places to show in distance labels. ':
'prefix': 'sigDigits'
'body': '''
set label_distance_digits, ${1:2};
set label_angle_digits, ${2:2};
$0
'''
'Label the CA atoms with the Ala333 style format':
'prefix': 'labelCAs'
'body': '''
label name CA,"%s%s" % (resn,resi);
$0
'''
'Label waters HOH.':
'prefix': 'labelWatersHOH'
'body': '''
label resn HOH ,"%s%s" % (resn,resi);
$0
'''
'Label waters W.':
'prefix': 'labelWatersW'
'body': '''
label resn HOH ,"W%s" % (resi);
$0
'''
'Find hbonds around a residue.':
'prefix': 'findHbonds'
'body': '''
remove element h; distance hbonds, all, all, 3.2, mode=2;
$0
'''
'Print the B-factors of a residue. ':
'prefix': 'printBs'
'body': '''
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': '''
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': '''
iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;
$0
'''
"Print B-values for a residue with the B's rounded off to two decimal places.":
'prefix': 'printBs2digits'
'body': '''
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.write_html_ref('pymol-command-ref.html');
$0
'''
"Average the B-factors by using a regular list as opposed to PyMOL's stored list. Edit the selection as needed.":
'prefix': 'averageB'
'body': '''
""" Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
print("Sum = ", "%.2f" % (sum(Bfactors)));
print("Number of atoms = ", len(Bfactors));
print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));
$0
'''
'AveBResiX, prints the resiude number and the average bfactor. ':
'prefix': 'aveB4resiX'
'body': '''
""""AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
"""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
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': '''
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': '''
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': '''
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': '''
internal_gui_mode=2;
$0
'''
'Set the width of the internal gui.
':
'prefix': 'internalGUIwidth'
'body': '''
internal_gui_width=%{1:20};
$0
'''
'Print document string of a function.':
'prefix': 'printDoc'
'body': '''
print ${1:my_func}.__doc__;
$0
'''
'List all snips by tab trigger and description':
'prefix': 'lsSnips'
'body': """
Tab trigger Description
--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
antialias Set antialias to get smooth edges
ao Ambient occlussion.
aveB4resiX AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.
bs Ball and stick representation.
bu Biological unit.
carvedDensity Carved electron density.
cblind Color blindness.
centerpi Center pi.
coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.
cribbon Color ribbon H red, strand yellow, loop green.
cspheres Colored spheres.
discreteCartoonColoring Turn on discrete colors between secondary structure elements.
distance H-bond distances.
doubleBond Valence bond.
drawHbonds Draw H-bonds.
duplicateObject Duplicate object.
ellipcol Set ellipsoid color.
extractPartObj Create a new object from part of an existing object.
fasta Print Fasta from PDB file.
fetch2FoFc Fetch 2FoFc map.
fetchCIF Fetch cif file.
fetchFoFc Fetch fofc map.
fetchPath Set path for location to save fetched pdb files.
filledRing Filled rings in nucleic acids.
findHbonds Find hbonds around a residue.
fog Blur the background atoms.
getCoordinates Get coordinates.
hbond Hbond setup.
hbonddash H-bond dashes.
hideSelection Trun off magenta squares on current selection.
hidealtloc Hide alt loc.
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.
internalGUIwidth Set the width of the internal gui.
labelCAs Label the CA atoms with the Ala333 style format
labelMainChain Label the main chain atoms by resn,resi,atom name.
labelResnResi Label CA atom with residue name and residue number.
labelSS Label SS.
labelWatersHOH Label waters HOH.
labelWatersW Label waters W.
loadPDBbs Load PDB ball-and-stick.
loadPDBfile Load a pdb file in the current directory.
loadPDBnb Load PDB nb spheres.
lsSnips List all snips by tab trigger and description
lspymolrc Print list of active pymolrc files.
molscriptRibbon Molscript ribbons.
ms Measure surface area.
oneLetter One letter amino acid.
pearl The pearl effect is made with two spheres with the outer sphere being transparent.
printBs Print the B-factors of a residue.
printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.
printBspartB Print B factors of part B of a rsidues.
printDoc Print document string of a function.
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.
printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.
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.
pseudolabel Position label with pseudoatom.
puttyCartoon Create a putty cartoon.
ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.
rmwater Remove waters from molecular object.
rotate Rotate about axis.
rv Return settings in rounded format.
savePNG Save a png file of current scene to the current directory.
saxsEnvelope Display SAXS envelope
sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.
sc222 Run Tom Holder's supercell script to generate three cells in all directions.
scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.
selectAllBut Select all nitrogen atom in a selelction except from lysine.
selectAtomsAround Select atoms within a radius around a ligand.
selectChain Select a chain.
selectElement Select atoms by elemnt.
selectHelices Select atoms by alpha helices.
selectLoops Select atoms by beta loops.
selectName Select atoms by name.
selectResi Select residues by a range of numbers.
selectResidues Select residues by name.
selectResiduesAround Select residues within a radius around a ligand.
selectStrands Select atoms by beta strands.
setcolor Set color name to a RGB code.
setpath Set additional path for PyMOL to search on startup
sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.
sigDigits Set number of decimals places to show in distance labels.
sigang Set angle labels to display 2 decimals places
sigdist set distance labels to display 2 decimals
solventRadius Set radius of ball used to make solvent accessible surface.
spng Save png flle with timestamp
spse Save pse flle with timestamp
stack Base-stacking figure.
stereoDraw Stereo draw.
stereoRay Stereo ray.
threeMaps Three electron density.
turnAboutAxis Turn about axis.
undoSelection Undo a selection.
volumeRamp Volume ramp.
writeCommandReference2HTML Write the command reference to html file in the present working directory.
$0
"""
'Asp70-His31 salt-bridge from T4 lysozyme. ':
'prefix': 'his31asp70'
'body': '''
fetch 1lw9, async=0;
zoom (resi 31 or resi 70);
preset.technical(selection='all');
bg_color gray70;
clip slab, 7,(resi 31 or resi 70);
rock;
$0
'''
'triple water pentagon.':
'prefix': 'waterTriple'
'body': '''
fetch 1lw9, async=0;
zoom resi 313;
preset.technical(selection='all', mode=1);
$0
'''
'Make selection of ligand atoms.':
'prefix': 'ligandSelect'
'body': '''
select substrates, organic;
$0
'''
'Print url of README.md file of the pymolsnips repository.':
'prefix': 'github'
'body': '''
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': '''
set label_dihedral_digits, ${1:2};
$0
'''
| true | '.source.pymol':
'Ambient occlussion.':
'prefix': 'ao'
'body': '''
set_color oxygen, [1.0,0.4,0.4];
set_color nitrogen, [0.5,0.5,1.0];
remove solvent;
as spheres;
util.cbaw;
bg white;
set light_count,10;
set spec_count,1;
set shininess, 10;
set specular,0.25;
set ambient,0;
set direct,0;
set reflect,1.5;
set ray_shadow_decay_factor, 0.1;
set ray_shadow_decay_range, 2;
unset depth_cue;
ray;
$0
'''
'Set ellipsoid color.':
'prefix': 'ellipcol'
'body': '''
set ellipsoid_color, ${1:color};
$0
'''
'set distance labels to display 2 decimals':
'prefix': 'sigdist'
'body': '''
set label_distance_digits, ${1:2};
$0
'''
'Set angle labels to display 2 decimals places':
'prefix': 'sigang'
'body': '''
set label_angle_digits, ${1:2};
$0
'''
'Ball and stick representation. ':
'prefix': 'bs'
'body': '''
show sticks;
set stick_radius, 0.12;
set stick_ball, on;
set stick_ball_ratio, 1.9;
show nb_spheres;
set nb_spheres_size=0.33;
$0
'''
'Base-stacking figure.':
'prefix': 'stack'
'body': '''
delete all;
fetch ${1:4PCO}, type=pdb,async=0;
select ${2:G2G3}, ( ((resi ${3:2} or resi ${4:3}) and chain A) or ((resi ${5:8} or resi ${6:9}) and chain B) );
hide everything, element h;
remove not ${2:G2G3};
bg_color white;
show sticks;
set stick_radius=0.14;
set stick_ball, on;
set stick_ball_ratio,1.9;
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);
hide everything, element H;
select carbon1, element C and (resi ${4:3} or resi ${5:8})
# select lower base pair;
select carbon2, element C and (resi ${3:2} or resi ${6:9})
#select upper base pair;
color gray70,carbon1;
color gray10,carbon2;
space cmyk;
distance hbond1,/${1:4PCO}//B/U`9/N3,/${1:4PCO}//A/G`2/O6;
distance hbond2,/${1:4PCO}//B/U`9/O2,/${1:4PCO}//A/G`2/N1;
distance hbond3,/${1:4PCO}//A/U`3/N3,/${1:4PCO}//B/G`8/O6;
distance hbond4,/${1:4PCO}//A/U`3/O2,/${1:4PCO}//B/G`8/N1;
color black, hbond1;
color black, hbond2;
color gray70, hbond3;
color gray70, hbond4;
show nb_spheres;
set nb_spheres_size, 0.35;
hide labels;
ray 1600,1000;
png ${1:4PCO}.png
$0
'''
'Biological unit.':
'prefix': 'bu'
'body': '''
run ~/Scripts/PyMOLScripts/quat.py; quat
$0
'''
'Valence bond. ':
'prefix': 'doubleBond'
'body': '''
set valence, 1;
set valence_mode, 1;
$0
'''
'Color blindness.':
'prefix': 'cblind'
'body': '''
run ~/Pymol-script-repo/colorblindfriendly.py;
as cartoon;
color cb_red, ss H;
color cb_yellow,ss S;
color cb_green, ss L+;
$0
'''
'Center pi.':
'prefix': 'centerpi'
'body': '''
pseudoatom pi_cent,/${1:3nd3}/${2:A}/${3:U`15}/cg+cz;
dist pi_cent////ps1, b/${4:U`15}/${5:aaa};
$0
'''
'Color ribbon H red, strand yellow, loop green.':
'prefix': 'cribbon'
'body': '''
as cartoon;
color red, ss H;
color yellow,ss S;
color green, ss L+;
$0
'''
'Colored spheres.':
'prefix': 'cspheres'
'body': '''
as spheres;
color gray30, chain %0;
color white, chain %1;
color green, name CL;
color brown, resn NAG;
color red, resi 381;
remove solvent;
unset specular;
set ray_trace_gain, 0;
set ray_trace_mode, 3;
bg_color white;
set ray_trace_color, black;
unset depth_cue;
$0
'''
'Coordinate covalent bonds to metals and H-bonds friom RNA.':
'prefix': 'coordinate'
'body': '''
viewport 900,600;
fetch 3nd4, type=pdb, async=0;
run ~/Scripts/PyMOLScripts/quat.py;
quat 3nd4;
show sticks;
set stick_radius=0.125;
hide everything, name H*;
bg_color white;
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)));
bond (coorCov//A/NA`19/NA),(coorCov//A/A`3/N7);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`119/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`219/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`319/O);
bond (coorCov//A/NA`19/NA),(coorCov//A/HOH`519/O);
distance (3nd4_1 and chain Aand resi 19 and name NA), (3nd4_1 and chain A and resi 519);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 419);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 319);
distance (3nd4_1 and chain A and resi 19 and name NA), (3nd4_1 and chain A and resi 219);
show nb_spheres;
set nb_spheres_size, .35;
distance hbond1,/3nd4_1/1/A/HOH`119/O, /3nd4_1/1/A/A`3/OP2;
distance hbond2,/3nd4_1/1/A/HOH`319/O, /3nd4_1/1/A/A`3/OP2;
distance hbond3,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/HOH`119/O;
distance hbond4,/3nd4_1/1/A/G`4/N7,/3nd4_1/1/A/HOH`91/O;
distance hbond5,/3nd4_1/1/A/G`4/O6, /3nd4_1/1/A/HOH`419/O;
distance hbond6,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
distance hbond7,/3nd4_1/1/A/HOH`319/O,/3nd4_1/1/A/G`2/OP2;
distance hbond9,/3nd4_1/1/A/HOH`419/O,/3nd4_2/2/A/HOH`74/O;
distance hbond10,/3nd4_2/2/A/C`15/O2,/3nd4_1/1/A/G`2/N2;
distance hbond11, /3nd4_2/2/A/C`15/N3,/3nd4_1/1/A/G`2/N1;
distance hbond12,/3nd4_2/2/A/C`15/N4,/3nd4_1/1/A/G`2/O6;
distance hbond13, /3nd4_2/2/A/U`14/N3,/3nd4_1/1/A/A`3/N1;
distance hbond14,3nd4_2/2/A/U`14/O4,/3nd4_1/1/A/A`3/N6;
distance hbond15, /3nd4_2/2/A/C`13/N4,/3nd4_1/1/A/G`4/O6;
distance hbond16,/3nd4_2/2/A/C`13/N3, /3nd4_1/1/A/G`4/N1;
distance hbond17, /3nd4_1/1/A/G`4/N2,/3nd4_2/2/A/C`13/O2;
distance hbond18,/3nd4_1/1/A/G`2/N2,/3nd4_2/2/A/C`15/O2;
distance hbond19,/3nd4_1/1/A/HOH`91/O,/3nd4_1/1/A/G`4/OP2;
set depth_cue=0;
set ray_trace_fog=0;
set dash_color, black;
set label_font_id, 5;
set label_size, 36;
set label_position, (0.5, 1.0, 2.0);
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
set label_color, black;
set dash_gap, 0.2;
set dash_width, 2.0;
set dash_length, 0.2;
select carbon, element C;
color yellow, carbon;
disable carbon;
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': '''
distance ${1:dist3}, ${2:/rcsb074137//B/IOD`605/I`B}, ${3:/rcsb074137//B/IOD`605/I`A}
$0
'''
'Draw H-bonds. ':
'prefix': 'drawHbonds'
'body': '''
hide everything, hydrogens
hide labels
set dash_color, ${1:black}${2:yelow}
set dash_gap, 0.4
set dash_radius, 0.08
$0
'''
'Carved electron density. ':
'prefix': 'carvedDensity'
'body': '''
delete all;
fetch ${1:4dgr}, async=0;
fetch ${1:4dgr}, type=2fofc,async=0;
select ${2:LongGlycan}, resi ${3:469:477};
orient ${2:LongGlycan};
remove not ${2:LongGlycan};
remove name H*;
isomesh 2fofcmap, ${1:4dgr}_2fofc, 1, ${2:LongGlycan}, carve = 1.8;
color density, 2fofcmap;
show sticks;
show spheres;
set stick_radius, .07;
set sphere_scale, .19;
set sphere_scale, .13, elem H;
set bg_rgb=[1, 1, 1];
set stick_quality, 50;
set sphere_quality, 4;
color gray85, elem C;
color red, elem O;
color slate, elem N;
color gray98, elem H;
set stick_color, gray50;
set ray_trace_mode, 1;
set ray_texture, 2;
set antialias, 3;
set ambient, 0.5;
set spec_count, 5;
set shininess, 50;
set specular, 1;
set reflect, .1;
set dash_gap, 0;
set dash_color, black;
set dash_gap, .15;
set dash_length, .05;
set dash_round_ends, 0;
set dash_radius, .05;
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);
preset.ball_and_stick("all",mode=1);
draw;
$0
'''
'Fetch 2FoFc map.':
'prefix': 'fetch2FoFc'
'body': '''
fetch ${1:3nd4}, type=2fofc, async=0
$0
'''
'Fetch cif file.':
'prefix': 'fetchCIF'
'body': '''
fetch ${1:3nd4}, type=cif, async=0;
$0
'''
'Fetch fofc map.':
'prefix': 'fetchFoFc'
'body': '''
fetch ${1:3nd4}, type=fofc, async=0;
$0
'''
'Filled rings in nucleic acids. ':
'prefix': 'filledRing'
'body': '''
show sticks;set cartoon_ring_mode, 3;
set cartoon_ring_finder, 1;
set cartoon_ladder_mode, 1;
set cartoon_nucleic_acid_mode, 4;
set cartoon_ring_transparency, 0.5;
as cartoon;
$0
'''
'Get coordinates. ':
'prefix': 'getCoordinates'
'body': '''
print cmd.get_atom_coords('${1:/4PCO//B/G`8/OP2}');
$0
'''
'H-bond dashes.':
'prefix': 'hbonddash'
'body': '''
hide everything, hydrogens;
hide labels;
set dash_color, black;
set dash_gap, 0.4;
set dash_radius, 0.08;
$0
'''
'Hbond setup. ':
'prefix': 'hbond'
'body': '''
hide labels;
set dash_color, black ;
set dash_length, ${1:0.15};
set dash_gap, ${2:0.35};
set dash_width, ${3:3.0};
$0
'''
'Hide alt loc.':
'prefix': 'hidealtloc'
'body': '''
select altconf, alt ${1:b} # select B alternative locators;
hide everything, altconf # hide alt B locators;
$0
'''
'Label CA atom with single-letter residue name and residue number.':
'prefix': 'labelResnResi'
'body': '''
label name ca, '%s%s' %(one_letter[${1:resn}],${2:resi});
$0
'''
'Label SS. ':
'prefix': 'labelSS'
'body': '''
alter ${1:}, ss='%1';
label (%2),'%3';
$0
'''
'Load PDB ball-and-stick.':
'prefix': 'loadPDBbs'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
hide (name H*);
hide lines;
show sticks;
set stick_radius, ${2:1.2};
set nb_sphere_radius, ${3:0.35};
orient;
$0
'''
'Load PDB nb spheres. ':
'prefix': 'loadPDBnb'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0;
orient;
set stick_radius, ${2:1.2};
hide (name H*);
set nb_sphere_size, ${3:0.35};
set nb_spheres_quality, ${4:1};
show nb_spheres;
$0
'''
'Measure surface area. ':
'prefix': 'ms'
'body': '''
fetch ${1:3nd3},name=${1:3nd3}, type=pdb, async=0
select ${2:temp}, ${3:3nd3} and chain A;
run ${3:/Users/blaine-mooers/Scripts/PyMOLScripts/msms_pymol.py};
calc_msms_area ${2:temp};
$0
'''
'Molscript ribbons.':
'prefix': 'molscriptRibbon'
'body': '''
set cartoon_highlight_color, grey;
show cartoon;
set cartoon_flat_sheets, 0;
set cartoon_smooth_loops, 0;
set cartoon_fancy_helices, 1;
$0
'''
'One letter amino acid. ':
'prefix': 'oneLetter'
'body': '''
one_leVer%={'VAL':'V',%'ILE':'I',%'LEU':'L',%'GLU':'E',%'GLN':'Q','ASP':'D',%
'ASN':'N',%'HIS':'H',%'TRP':'W',%'PHE':'F',%'TYR':'Y',%'ARG':'R',%'LYS':'K',%
'SER':'S',%'THR':'T',%'MET':'M',%'ALA':'A',%'GLY':'G',%'PRO':'P',%'CYS':'C'}%
$0
'''
'Print Fasta from PDB file. ':
'prefix': 'fasta'
'body': '''
print cmd.get_fastastr('all')
$0
'''
'Position label with pseudoatom. ':
'prefix': 'pseudolabel'
'body': '''
pseudoatom ${1:forLabel};
label ${1:forLabel}, '%0';
set label_color, ${2:red};
$0
'''
'Rotate about axis.':
'prefix': 'rotate'
'body': '''
rotate ${1:x}, ${2:45}, ${3:pept}
$0
'''
'Stereo draw.':
'prefix': 'stereoDraw'
'body': '''
stereo walleye;
set ray_shadow, off;
#draw 3200,2000;
draw ${1:1600,1000};
png ${2:aaa}.png
$0
'''
'Stereo ray.':
'prefix': 'stereoRay'
'body': '''
stereo;
set ray_shadow, off;
ray ${1:2400,1200};
png ${2:aaa}.png
$0
'''
'Three electron density. ':
'prefix': 'threeMaps'
'body': '''
load ${1:4dgr}.pdb
# Make sure to rename map file so that
# the root filename differs from pdb root filename
load ${1:4dgr}_2fofc.ccp4, 2fofc;
load ${1:4dgr}_fofc.ccp4, fofc;
select ${2:glycan}, resid 200 or (resid 469:477);
isomesh ${3:mesh1}, 2fofc, 1.0, ${2:glycan};
color density, ${3:mesh1};
isomesh ${4:mesh2}, fofc, 3.0, ${2:glycan};
color green, ${4:mesh2};
isomesh ${5:mesh3}, fofc, -3.0, ${2:glycan};
color red, ${5:mesh3};
$0
'''
'Turn about axis. ':
'prefix': 'turnAboutAxis'
'body': '''
turn ${1:x},${2:90};
$0
'''
'Volume ramp.':
'prefix': 'volumeRamp'
'body': '''
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': '''
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': '''
bg_color white
hide everything
show spheres
set stick_radius = 0.1
hide everything, HET
show spheres, HET
set sphere_quality=3
show sticks, resi 1102
from pymol import stored
# set the stored array equal to the b−values; or use your own values
stored.bb = [ ]
iterate, stored.bb.append(b)
# execute a python−block
python
# scale the b−values
M = max(stored.bb)
scaledBB = map(lambda x: float (x/M), stored.bb)
count = 0
# set the sphere radii independently
for x in scaledBB:
cmd.set("sphere_scale", x ,"ID %s"%count)
count = count + 1
python end
spectrum b, selection=4gdx
space cmyk
set specular_intensity , 0.25
$0
'''
'Return settings in rounded format.':
'prefix': 'rv'
'body': '''
run roundview.py;
$0
'''
'Save png flle with timestamp':
'prefix': 'spng'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".png");
end python;
$0
'''
'Save pse flle with timestamp':
'prefix': 'spse'
'body': '''
python;
import datetime;
from pymol import cmd;
DT =datetime.datetime.now().strftime("yr%Ymo%mday%dhr%Hmin%M");
s = str(DT);
cmd.save(stemName+s+".pse");
end python;
$0
'''
"Run PI:NAME:<NAME>END_PI's supercell script to generate three cells in all directions.":
'prefix': 'sc222'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
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': '''
create ${1:sodium2}, ${2:sodium1}
set sphere_transparency, 0.4, ${1:sodium2}
set sphere_scale, 1.05, ${1:sodium2}
ray
$0
'''
'Blur the background atoms.':
'prefix': 'fog'
'body': '''
set fog, 0
$0
'''
'Remove waters from molecular object.':
'prefix': 'rmwater'
'body': '''
remove resn HOH
$0
'''
'Set color name to a RGB code.':
'prefix': 'setcolor'
'body': '''
set_color ${1:bark}, [${2:0.1, ${3:0.1}, ${4:0.1}]
color ${1:bark}, ${5:protein}
$0
'''
'Duplicate object.':
'prefix': 'duplicateObject'
'body': '''
create ${1:t4l}, ${2:1lw9};
$0
'''
'Select a chain. ':
'prefix': 'selectChain'
'body': '''
select rna, chain B
$0
'''
'Select residues by name.':
'prefix': 'selectResidues'
'body': '''
select aromatic, resn phe+tyr+trp;
$0
'''
'Select residues by a range of numbers.':
'prefix': 'selectResi'
'body': '''
select se;2. resi 1-100
$0
'''
'Select atoms by elemnt.':
'prefix': 'selectElement'
'body': '''
select ${1:oxygen}, elem ${2:O}
$0
'''
'Select atoms by name.':
'prefix': 'selectName'
'body': '''
select ${1:oxygen2}, name ${2:O2}
$0
'''
'Select atoms by alpha helices.':
'prefix': 'selectHelices'
'body': '''
select ${1:helices}, ss h;
$0
'''
'Select atoms by beta strands.':
'prefix': 'selectStrands'
'body': '''
select ${1:strands}, ss s;
$0
'''
'Select atoms by beta loops.':
'prefix': 'selectLoops'
'body': '''
select ${1:loops}, ss l;
$0
'''
'Select all nitrogen atom in a selelction except from lysine.':
'prefix': 'selectAllBut'
'body': '''
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': '''
select ${1:nearby}, resn ${2:drug} around ${3:5};
$0
'''
'Select residues within a radius around a ligand.':
'prefix': 'selectResiduesAround'
'body': '''
select ${1:nearby}, br. resn ${2:drug} around ${3:5};
$0
'''
'Undo a selection.':
'prefix': 'undoSelection'
'body': '''
disable ${1:sele};
$0
'''
'Load a pdb file in the current directory.':
'prefix': 'loadPDBfile'
'body': '''
load ${1:my.pdb};
$0
'''
'Save a png file of current scene to the current directory.':
'prefix': 'savePNG'
'body': '''
png ${1:saveMe.png};
$0
'''
'Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.':
'prefix': 'ringMode'
'body': '''
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': '''
set cartoon_side_chain_helper, on;
$0
'''
'Create a new object from part of an existing object.':
'prefix': 'extractPartObj'
'body': '''
extract new_obj, chain A
$0
'''
'Create a putty cartoon.':
'prefix': 'puttyCartoon'
'body': '''
show cartoon;
cartoon putty;
unset cartoon_smooth_loops;
unset cartoon_flat_sheets;
$0
'''
'Trun off magenta squares on current selection.':
'prefix': 'hideSelection'
'body': '''
indicate none
$0
'''
'Turn on discrete colors between secondary structure elements.':
'prefix': 'discreteCartoonColoring'
'body': '''
set cartoon_discrete_colors, on
$0
'''
'Display all symmetry mates in one unit cell. Uses supercell.py in $HOME/Scripts/PyMOLscripts/.':
'prefix': 'sc111'
'body': '''
run $HOME/Scripts/PyMOLscripts/supercell.py
supercell 1, 1, 1, , orange, supercell1, 1
$0
'''
'Display SAXS envelope':
'prefix': 'saxsEnvelope'
'body': '''
alter ${1:refine_A_Ave_SM_015_0_370-374-0r}, vdw=3.0
set solvent_radius = 3.0
$0
'''
'Set additional path for PyMOL to search on startup':
'prefix': 'setpath'
'body': '''
os.environ["PATH"] += os.pathsep +${1: '/Applications/ATSAS/bin'};
$0
'''
'Set path for location to save fetched pdb files. ':
'prefix': 'fetchPath'
'body': '''
set fetch_path, ${1:/Users/blaine/pdbFiles};
$0
'''
'Set antialias to get smooth edges':
'prefix': 'antialias'
'body': '''
set antialias, 1;
$0
'''
'Print list of active pymolrc files.':
'prefix': 'lspymolrc'
'body': '''
print invocation.options.deferred;
$0
'''
'Set number of decimals places to show in distance labels. ':
'prefix': 'sigDigits'
'body': '''
set label_distance_digits, ${1:2};
set label_angle_digits, ${2:2};
$0
'''
'Label the CA atoms with the Ala333 style format':
'prefix': 'labelCAs'
'body': '''
label name CA,"%s%s" % (resn,resi);
$0
'''
'Label waters HOH.':
'prefix': 'labelWatersHOH'
'body': '''
label resn HOH ,"%s%s" % (resn,resi);
$0
'''
'Label waters W.':
'prefix': 'labelWatersW'
'body': '''
label resn HOH ,"W%s" % (resi);
$0
'''
'Find hbonds around a residue.':
'prefix': 'findHbonds'
'body': '''
remove element h; distance hbonds, all, all, 3.2, mode=2;
$0
'''
'Print the B-factors of a residue. ':
'prefix': 'printBs'
'body': '''
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': '''
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': '''
iterate resi %{1:38} and altloc %{2:B}, print resi, name, alt, b;
$0
'''
"Print B-values for a residue with the B's rounded off to two decimal places.":
'prefix': 'printBs2digits'
'body': '''
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.write_html_ref('pymol-command-ref.html');
$0
'''
"Average the B-factors by using a regular list as opposed to PyMOL's stored list. Edit the selection as needed.":
'prefix': 'averageB'
'body': '''
""" Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed."""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
print("Sum = ", "%.2f" % (sum(Bfactors)));
print("Number of atoms = ", len(Bfactors));
print( 'Average B =' , "%.2f" % ( sum(Bfactors)/float(len(Bfactors))));
$0
'''
'AveBResiX, prints the resiude number and the average bfactor. ':
'prefix': 'aveB4resiX'
'body': '''
""""AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
"""
Bfactors = [];
iterate (resi ${1:133}), Bfactors.append(b);
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': '''
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': '''
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': '''
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': '''
internal_gui_mode=2;
$0
'''
'Set the width of the internal gui.
':
'prefix': 'internalGUIwidth'
'body': '''
internal_gui_width=%{1:20};
$0
'''
'Print document string of a function.':
'prefix': 'printDoc'
'body': '''
print ${1:my_func}.__doc__;
$0
'''
'List all snips by tab trigger and description':
'prefix': 'lsSnips'
'body': """
Tab trigger Description
--------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
antialias Set antialias to get smooth edges
ao Ambient occlussion.
aveB4resiX AveBResiX, prints the resiude number and the average bfactor.
Uses reduce and lambda, builtin Python functional porgramming functions.
Note that you need to convert the length of the list of Bfactors from an integer to a float before division into the sum.
averageB Uses a regular list as opposed to PyMOL's stored list. Edit the selection as needed.
bs Ball and stick representation.
bu Biological unit.
carvedDensity Carved electron density.
cblind Color blindness.
centerpi Center pi.
coordinate Coordinate covalent bonds to metals and H-bonds friom RNA.
cribbon Color ribbon H red, strand yellow, loop green.
cspheres Colored spheres.
discreteCartoonColoring Turn on discrete colors between secondary structure elements.
distance H-bond distances.
doubleBond Valence bond.
drawHbonds Draw H-bonds.
duplicateObject Duplicate object.
ellipcol Set ellipsoid color.
extractPartObj Create a new object from part of an existing object.
fasta Print Fasta from PDB file.
fetch2FoFc Fetch 2FoFc map.
fetchCIF Fetch cif file.
fetchFoFc Fetch fofc map.
fetchPath Set path for location to save fetched pdb files.
filledRing Filled rings in nucleic acids.
findHbonds Find hbonds around a residue.
fog Blur the background atoms.
getCoordinates Get coordinates.
hbond Hbond setup.
hbonddash H-bond dashes.
hideSelection Trun off magenta squares on current selection.
hidealtloc Hide alt loc.
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.
internalGUIwidth Set the width of the internal gui.
labelCAs Label the CA atoms with the Ala333 style format
labelMainChain Label the main chain atoms by resn,resi,atom name.
labelResnResi Label CA atom with residue name and residue number.
labelSS Label SS.
labelWatersHOH Label waters HOH.
labelWatersW Label waters W.
loadPDBbs Load PDB ball-and-stick.
loadPDBfile Load a pdb file in the current directory.
loadPDBnb Load PDB nb spheres.
lsSnips List all snips by tab trigger and description
lspymolrc Print list of active pymolrc files.
molscriptRibbon Molscript ribbons.
ms Measure surface area.
oneLetter One letter amino acid.
pearl The pearl effect is made with two spheres with the outer sphere being transparent.
printBs Print the B-factors of a residue.
printBs2digits Print B-values for a residue with the B's rounded off to two decimal places.
printBspartB Print B factors of part B of a rsidues.
printDoc Print document string of a function.
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.
printResiResnNameB4ResiX Print resn, resi, atom name, and b-factor.
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.
pseudolabel Position label with pseudoatom.
puttyCartoon Create a putty cartoon.
ringMode Set the ring mode to a value between 0 and 6 in cartoons of nucleic acids.
rmwater Remove waters from molecular object.
rotate Rotate about axis.
rv Return settings in rounded format.
savePNG Save a png file of current scene to the current directory.
saxsEnvelope Display SAXS envelope
sc111 Display all symmetry mates in one unit cell. Asumes supercell.py (sse PyMOL Wiki) is in $HOME/Scripts/PyMOLscripts/.
sc222 Run Tom Holder's supercell script to generate three cells in all directions.
scaleRadiusColor Scale the radius and color of atoms as spheres by property in the B-value column.
selectAllBut Select all nitrogen atom in a selelction except from lysine.
selectAtomsAround Select atoms within a radius around a ligand.
selectChain Select a chain.
selectElement Select atoms by elemnt.
selectHelices Select atoms by alpha helices.
selectLoops Select atoms by beta loops.
selectName Select atoms by name.
selectResi Select residues by a range of numbers.
selectResidues Select residues by name.
selectResiduesAround Select residues within a radius around a ligand.
selectStrands Select atoms by beta strands.
setcolor Set color name to a RGB code.
setpath Set additional path for PyMOL to search on startup
sidehChainHelper In cartoons, hide the backbone atoms of selected residues when showing then as sticks.
sigDigits Set number of decimals places to show in distance labels.
sigang Set angle labels to display 2 decimals places
sigdist set distance labels to display 2 decimals
solventRadius Set radius of ball used to make solvent accessible surface.
spng Save png flle with timestamp
spse Save pse flle with timestamp
stack Base-stacking figure.
stereoDraw Stereo draw.
stereoRay Stereo ray.
threeMaps Three electron density.
turnAboutAxis Turn about axis.
undoSelection Undo a selection.
volumeRamp Volume ramp.
writeCommandReference2HTML Write the command reference to html file in the present working directory.
$0
"""
'Asp70-His31 salt-bridge from T4 lysozyme. ':
'prefix': 'his31asp70'
'body': '''
fetch 1lw9, async=0;
zoom (resi 31 or resi 70);
preset.technical(selection='all');
bg_color gray70;
clip slab, 7,(resi 31 or resi 70);
rock;
$0
'''
'triple water pentagon.':
'prefix': 'waterTriple'
'body': '''
fetch 1lw9, async=0;
zoom resi 313;
preset.technical(selection='all', mode=1);
$0
'''
'Make selection of ligand atoms.':
'prefix': 'ligandSelect'
'body': '''
select substrates, organic;
$0
'''
'Print url of README.md file of the pymolsnips repository.':
'prefix': 'github'
'body': '''
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': '''
set label_dihedral_digits, ${1:2};
$0
'''
|
[
{
"context": "ateRes = (msg) ->\n args: ['#test', msg]\n user: 'Test'\n prefix: '!test@test.com'\n\ndescribe 'Domo basic",
"end": 137,
"score": 0.9990560412406921,
"start": 133,
"tag": "USERNAME",
"value": "Test"
},
{
"context": " args: ['#test', msg]\n user: 'Test'\n prefix: '!test@test.com'\n\ndescribe 'Domo basic routes', ->\n it 'should p",
"end": 164,
"score": 0.9982280731201172,
"start": 151,
"tag": "EMAIL",
"value": "test@test.com"
}
] | test/basic-routes.coffee | rikukissa/domo | 4 | _ = require 'underscore'
assert = require 'assert'
Domo = require '../'
createRes = (msg) ->
args: ['#test', msg]
user: 'Test'
prefix: '!test@test.com'
describe 'Domo basic routes', ->
it 'should print information about domo when !domo is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
domo.say = (chan, msg) ->
assert.ok msg.length > 0
done()
domo.matchRoutes '!domo', createRes()
it 'should join a channel when !join is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.join = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!join #foo', res
it 'should not join a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.join = (chan) ->
throw new Error 'should not join a channel when user is not auther'
domo.matchRoutes '!join #foo', res
done()
it 'should part a channel when !part is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.part = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!part #foo', res
it 'should not part a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.part = (chan) ->
throw new Error 'should not part a channel when user is not auther'
domo.matchRoutes '!part #foo', res
done()
| 178846 | _ = require 'underscore'
assert = require 'assert'
Domo = require '../'
createRes = (msg) ->
args: ['#test', msg]
user: 'Test'
prefix: '!<EMAIL>'
describe 'Domo basic routes', ->
it 'should print information about domo when !domo is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
domo.say = (chan, msg) ->
assert.ok msg.length > 0
done()
domo.matchRoutes '!domo', createRes()
it 'should join a channel when !join is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.join = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!join #foo', res
it 'should not join a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.join = (chan) ->
throw new Error 'should not join a channel when user is not auther'
domo.matchRoutes '!join #foo', res
done()
it 'should part a channel when !part is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.part = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!part #foo', res
it 'should not part a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.part = (chan) ->
throw new Error 'should not part a channel when user is not auther'
domo.matchRoutes '!part #foo', res
done()
| true | _ = require 'underscore'
assert = require 'assert'
Domo = require '../'
createRes = (msg) ->
args: ['#test', msg]
user: 'Test'
prefix: '!PI:EMAIL:<EMAIL>END_PI'
describe 'Domo basic routes', ->
it 'should print information about domo when !domo is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
domo.say = (chan, msg) ->
assert.ok msg.length > 0
done()
domo.matchRoutes '!domo', createRes()
it 'should join a channel when !join is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.join = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!join #foo', res
it 'should not join a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.join = (chan) ->
throw new Error 'should not join a channel when user is not auther'
domo.matchRoutes '!join #foo', res
done()
it 'should part a channel when !part is called', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.authedClients[res.prefix] = true
domo.part = (chan) ->
assert.equal chan, '#foo'
done()
catch: ->
domo.matchRoutes '!part #foo', res
it 'should not part a channel when user is not auther', (done) ->
domo = new Domo()
domo.use domo.basicRoutes()
res = createRes()
domo.part = (chan) ->
throw new Error 'should not part a channel when user is not auther'
domo.matchRoutes '!part #foo', res
done()
|
[
{
"context": "ue\n# from v_variables\n# where key = 'v7')\n# select * from v1, json_each( v1.value );\"",
"end": 4160,
"score": 0.8732911944389343,
"start": 4159,
"tag": "KEY",
"value": "7"
}
] | dev/icql-dba-vars/src/main.tests.coffee | loveencounterflow/hengist | 0 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL-DBA-TAGS/TESTS'
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
#...........................................................................................................
test = require '../../../apps/guy-test'
PATH = require 'path'
types = new ( require 'intertype' ).Intertype
{ isa
type_of
validate
validate_list_of
equals } = types.export()
# { to_width } = require 'to-width'
on_process_exit = require 'exit-hook'
sleep = ( dts ) -> new Promise ( done ) => setTimeout done, dts * 1000
SQL = String.raw
jr = JSON.stringify
jp = JSON.parse
dbv_path = '../../../apps/icql-dba-vars'
dba_path = '../../../apps/icql-dba'
debug CND.reverse '^89435^', { dbv_path, }
debug CND.reverse '^89435^', { dba_path, }
{ lets
freeze } = require 'letsfreezethat'
def = Object.defineProperty
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@[ "getting and setting single values" ] = ( T, done ) ->
T?.halt_on_error()
#.........................................................................................................
probes_and_matchers = [
[ [ 'v1', true, ], true, ]
[ [ 'v2', false, ], false, ]
[ [ 'v3', null, ], null, ]
[ [ 'v4', 42, ], 42, ]
[ [ 'v5', '42', ], '42', ]
[ [ 'v6', { bar: '42'}, ], { bar: '42'}, ]
[ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
]
{ Dbv, } = require dbv_path
{ Dba, } = require dba_path
dba = new Dba()
dbv = new Dbv { dba, }
debug '4476^', dbv
debug '4476^', ( k for k of dbv )
console.table dba.list dba.query SQL"select * from v_variables;"
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
[ key, value, ] = probe
dbv.set key, value
result = dbv.get key
resolve result
console.table dba.list dba.query SQL"select * from v_variables;"
#.........................................................................................................
done?()
# #-----------------------------------------------------------------------------------------------------------
# @[ "getting and setting multiple values" ] = ( T, done ) ->
# T?.halt_on_error()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
# ]
# { Dbv, } = require dbv_path
# dbv = new Dbv()
# { dba, } = dbv
# debug '4476^', dbv
# debug '4476^', ( k for k of dbv )
# console.table dba.list dba.query SQL"select * from v_variables;"
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
# [ key, value, ] = probe
# dbv.set key, value
# result = dbv.get key
# resolve result
# console.table dba.list dba.query SQL"select * from v_variables;"
# console.table dba.list dba.query SQL"""
# with v1 as ( select
# value
# from v_variables
# where key = 'v7')
# select * from v1, json_each( v1.value );"""
# # console.table dba.list dba.query SQL"select * from v_get_many( 'v7' );"
# #.........................................................................................................
# done?()
############################################################################################################
if module is require.main then do =>
# info '^3443^', JSON.parse '"helo world"'
test @, { timeout: 10e3, }
# test @[ "DBA: tags must be declared" ]
| 21990 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL-DBA-TAGS/TESTS'
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
#...........................................................................................................
test = require '../../../apps/guy-test'
PATH = require 'path'
types = new ( require 'intertype' ).Intertype
{ isa
type_of
validate
validate_list_of
equals } = types.export()
# { to_width } = require 'to-width'
on_process_exit = require 'exit-hook'
sleep = ( dts ) -> new Promise ( done ) => setTimeout done, dts * 1000
SQL = String.raw
jr = JSON.stringify
jp = JSON.parse
dbv_path = '../../../apps/icql-dba-vars'
dba_path = '../../../apps/icql-dba'
debug CND.reverse '^89435^', { dbv_path, }
debug CND.reverse '^89435^', { dba_path, }
{ lets
freeze } = require 'letsfreezethat'
def = Object.defineProperty
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@[ "getting and setting single values" ] = ( T, done ) ->
T?.halt_on_error()
#.........................................................................................................
probes_and_matchers = [
[ [ 'v1', true, ], true, ]
[ [ 'v2', false, ], false, ]
[ [ 'v3', null, ], null, ]
[ [ 'v4', 42, ], 42, ]
[ [ 'v5', '42', ], '42', ]
[ [ 'v6', { bar: '42'}, ], { bar: '42'}, ]
[ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
]
{ Dbv, } = require dbv_path
{ Dba, } = require dba_path
dba = new Dba()
dbv = new Dbv { dba, }
debug '4476^', dbv
debug '4476^', ( k for k of dbv )
console.table dba.list dba.query SQL"select * from v_variables;"
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
[ key, value, ] = probe
dbv.set key, value
result = dbv.get key
resolve result
console.table dba.list dba.query SQL"select * from v_variables;"
#.........................................................................................................
done?()
# #-----------------------------------------------------------------------------------------------------------
# @[ "getting and setting multiple values" ] = ( T, done ) ->
# T?.halt_on_error()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
# ]
# { Dbv, } = require dbv_path
# dbv = new Dbv()
# { dba, } = dbv
# debug '4476^', dbv
# debug '4476^', ( k for k of dbv )
# console.table dba.list dba.query SQL"select * from v_variables;"
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
# [ key, value, ] = probe
# dbv.set key, value
# result = dbv.get key
# resolve result
# console.table dba.list dba.query SQL"select * from v_variables;"
# console.table dba.list dba.query SQL"""
# with v1 as ( select
# value
# from v_variables
# where key = 'v<KEY>')
# select * from v1, json_each( v1.value );"""
# # console.table dba.list dba.query SQL"select * from v_get_many( 'v7' );"
# #.........................................................................................................
# done?()
############################################################################################################
if module is require.main then do =>
# info '^3443^', JSON.parse '"helo world"'
test @, { timeout: 10e3, }
# test @[ "DBA: tags must be declared" ]
| true |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL-DBA-TAGS/TESTS'
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
#...........................................................................................................
test = require '../../../apps/guy-test'
PATH = require 'path'
types = new ( require 'intertype' ).Intertype
{ isa
type_of
validate
validate_list_of
equals } = types.export()
# { to_width } = require 'to-width'
on_process_exit = require 'exit-hook'
sleep = ( dts ) -> new Promise ( done ) => setTimeout done, dts * 1000
SQL = String.raw
jr = JSON.stringify
jp = JSON.parse
dbv_path = '../../../apps/icql-dba-vars'
dba_path = '../../../apps/icql-dba'
debug CND.reverse '^89435^', { dbv_path, }
debug CND.reverse '^89435^', { dba_path, }
{ lets
freeze } = require 'letsfreezethat'
def = Object.defineProperty
#===========================================================================================================
#
#-----------------------------------------------------------------------------------------------------------
@[ "getting and setting single values" ] = ( T, done ) ->
T?.halt_on_error()
#.........................................................................................................
probes_and_matchers = [
[ [ 'v1', true, ], true, ]
[ [ 'v2', false, ], false, ]
[ [ 'v3', null, ], null, ]
[ [ 'v4', 42, ], 42, ]
[ [ 'v5', '42', ], '42', ]
[ [ 'v6', { bar: '42'}, ], { bar: '42'}, ]
[ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
]
{ Dbv, } = require dbv_path
{ Dba, } = require dba_path
dba = new Dba()
dbv = new Dbv { dba, }
debug '4476^', dbv
debug '4476^', ( k for k of dbv )
console.table dba.list dba.query SQL"select * from v_variables;"
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
[ key, value, ] = probe
dbv.set key, value
result = dbv.get key
resolve result
console.table dba.list dba.query SQL"select * from v_variables;"
#.........................................................................................................
done?()
# #-----------------------------------------------------------------------------------------------------------
# @[ "getting and setting multiple values" ] = ( T, done ) ->
# T?.halt_on_error()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 'v7', [ 1, 2, 108, ], ], [ 1, 2, 108, ], ]
# ]
# { Dbv, } = require dbv_path
# dbv = new Dbv()
# { dba, } = dbv
# debug '4476^', dbv
# debug '4476^', ( k for k of dbv )
# console.table dba.list dba.query SQL"select * from v_variables;"
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> new Promise ( resolve ) ->
# [ key, value, ] = probe
# dbv.set key, value
# result = dbv.get key
# resolve result
# console.table dba.list dba.query SQL"select * from v_variables;"
# console.table dba.list dba.query SQL"""
# with v1 as ( select
# value
# from v_variables
# where key = 'vPI:KEY:<KEY>END_PI')
# select * from v1, json_each( v1.value );"""
# # console.table dba.list dba.query SQL"select * from v_get_many( 'v7' );"
# #.........................................................................................................
# done?()
############################################################################################################
if module is require.main then do =>
# info '^3443^', JSON.parse '"helo world"'
test @, { timeout: 10e3, }
# test @[ "DBA: tags must be declared" ]
|
[
{
"context": "############\n#\n#\tMooqita publications\n# Created by Markus on 26/10/2016.\n#\n################################",
"end": 100,
"score": 0.9993622303009033,
"start": 94,
"tag": "NAME",
"value": "Markus"
}
] | server/publications/solution.coffee | agottschalk10/worklearn | 0 | #######################################################
#
# Mooqita publications
# Created by Markus on 26/10/2016.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_solution_fields =
fields:
content: 1
material: 1
owner_id: 1
completed: 1
published: 1
parent_id: 1
challenge_id: 1
#######################################################
# publications
#######################################################
#######################################################
Meteor.publish "my_solutions", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions", user_id
return crs
#######################################################
Meteor.publish "solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
if !user_id
throw new Meteor.Error("Not permitted.")
#TODO: only user that are eligible should see this.
filter =
_id: solution_id
published: true
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
restrict =
_id: solution_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solutions_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
restrict =
owner_id: user_id
challenge_id: challenge_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "solutions_for_tutor", (parameter) ->
throw new Meteor.Error("solutions_for_tutor is not implemented at the moment")
pattern =
query: Match.Optional(String)
challenge_id: String
page: Number
size: Number
check parameter, pattern
self = this
user_id = this.userId
if not Roles.userIsInRole user_id, "tutor"
throw new Meteor.Error("Not permitted.")
gen_tut = (id) ->
review = Reviews.findOne id
solution = Solutions.findOne review.solution_id
date = review.requested
now = new Date()
difference = now - date
item =
solution_id: rr.solution_id
content: solution.content
material: solution.material
date: date
wait: how_much_time difference
return item
filter =
challenge_id: parameter.challenge_id
owner_id:
$ne: user_id
review_done: false
mod =
sort:
under_review_since: 1
crs = find_documents_paged_unprotected ReviewRequests, filter, mod, parameter
handler = crs.observeChanges
added: (id, fields) ->
credit = gen_tut id
self.added "tutor_solutions", id, credit
changed: (id, fields) ->
credit = gen_credit id
self.changed "tutor_solutions", id, credit
removed: (id) ->
self.removed "tutor_solutions", id
self.ready()
self.onStop ->
handler.stop()
| 19883 | #######################################################
#
# Mooqita publications
# Created by <NAME> on 26/10/2016.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_solution_fields =
fields:
content: 1
material: 1
owner_id: 1
completed: 1
published: 1
parent_id: 1
challenge_id: 1
#######################################################
# publications
#######################################################
#######################################################
Meteor.publish "my_solutions", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions", user_id
return crs
#######################################################
Meteor.publish "solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
if !user_id
throw new Meteor.Error("Not permitted.")
#TODO: only user that are eligible should see this.
filter =
_id: solution_id
published: true
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
restrict =
_id: solution_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solutions_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
restrict =
owner_id: user_id
challenge_id: challenge_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "solutions_for_tutor", (parameter) ->
throw new Meteor.Error("solutions_for_tutor is not implemented at the moment")
pattern =
query: Match.Optional(String)
challenge_id: String
page: Number
size: Number
check parameter, pattern
self = this
user_id = this.userId
if not Roles.userIsInRole user_id, "tutor"
throw new Meteor.Error("Not permitted.")
gen_tut = (id) ->
review = Reviews.findOne id
solution = Solutions.findOne review.solution_id
date = review.requested
now = new Date()
difference = now - date
item =
solution_id: rr.solution_id
content: solution.content
material: solution.material
date: date
wait: how_much_time difference
return item
filter =
challenge_id: parameter.challenge_id
owner_id:
$ne: user_id
review_done: false
mod =
sort:
under_review_since: 1
crs = find_documents_paged_unprotected ReviewRequests, filter, mod, parameter
handler = crs.observeChanges
added: (id, fields) ->
credit = gen_tut id
self.added "tutor_solutions", id, credit
changed: (id, fields) ->
credit = gen_credit id
self.changed "tutor_solutions", id, credit
removed: (id) ->
self.removed "tutor_solutions", id
self.ready()
self.onStop ->
handler.stop()
| true | #######################################################
#
# Mooqita publications
# Created by PI:NAME:<NAME>END_PI on 26/10/2016.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_solution_fields =
fields:
content: 1
material: 1
owner_id: 1
completed: 1
published: 1
parent_id: 1
challenge_id: 1
#######################################################
# publications
#######################################################
#######################################################
Meteor.publish "my_solutions", () ->
user_id = this.userId
restrict =
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions", user_id
return crs
#######################################################
Meteor.publish "solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
if !user_id
throw new Meteor.Error("Not permitted.")
#TODO: only user that are eligible should see this.
filter =
_id: solution_id
published: true
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solution_by_id", (solution_id) ->
check solution_id, String
user_id = this.userId
restrict =
_id: solution_id
owner_id: user_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solution_by_id", user_id
return crs
#######################################################
Meteor.publish "my_solutions_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
restrict =
owner_id: user_id
challenge_id: challenge_id
filter = filter_visible_documents user_id, restrict
crs = Solutions.find filter, _solution_fields
log_publication "Solutions", crs, filter,
_solution_fields, "my_solutions_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "solutions_for_tutor", (parameter) ->
throw new Meteor.Error("solutions_for_tutor is not implemented at the moment")
pattern =
query: Match.Optional(String)
challenge_id: String
page: Number
size: Number
check parameter, pattern
self = this
user_id = this.userId
if not Roles.userIsInRole user_id, "tutor"
throw new Meteor.Error("Not permitted.")
gen_tut = (id) ->
review = Reviews.findOne id
solution = Solutions.findOne review.solution_id
date = review.requested
now = new Date()
difference = now - date
item =
solution_id: rr.solution_id
content: solution.content
material: solution.material
date: date
wait: how_much_time difference
return item
filter =
challenge_id: parameter.challenge_id
owner_id:
$ne: user_id
review_done: false
mod =
sort:
under_review_since: 1
crs = find_documents_paged_unprotected ReviewRequests, filter, mod, parameter
handler = crs.observeChanges
added: (id, fields) ->
credit = gen_tut id
self.added "tutor_solutions", id, credit
changed: (id, fields) ->
credit = gen_credit id
self.changed "tutor_solutions", id, credit
removed: (id) ->
self.removed "tutor_solutions", id
self.ready()
self.onStop ->
handler.stop()
|
[
{
"context": " pony\"\n DerpyHooves = {}\n\n result =\n ```\n Dear Princess Celestia, \n\n I said \"Hello from FiMscript\"!\n\n Did you kn",
"end": 181,
"score": 0.998494029045105,
"start": 164,
"tag": "NAME",
"value": "Princess Celestia"
},
{
"context": " Then I got somepony.\n\n Your faithful student,\n Twilight Sparkle\n ```\n\n console.log \"Derpy is #{Derpy} and her v",
"end": 556,
"score": 0.9997252225875854,
"start": 540,
"tag": "NAME",
"value": "Twilight Sparkle"
},
{
"context": "lank program without ticks', ->\n ok not Dear Princess Celestia,\n Your faithful student,\n Blank Fl",
"end": 840,
"score": 0.5981935858726501,
"start": 834,
"tag": "NAME",
"value": "incess"
},
{
"context": "gram without ticks', ->\n ok not Dear Princess Celestia,\n Your faithful student,\n Blank Flank\n\n te",
"end": 849,
"score": 0.7180843353271484,
"start": 842,
"tag": "NAME",
"value": "elestia"
},
{
"context": "ction, returns last value', ->\n ok ```\n Dear Princess Celestia,\n\n I learned how to dance.\n That's how to d",
"end": 980,
"score": 0.9873340725898743,
"start": 963,
"tag": "NAME",
"value": "Princess Celestia"
},
{
"context": "ine function with return value', ->\n ok Dear Princess Celestia: I got true. Your faithful student, Inline Pony\n\n",
"end": 1185,
"score": 0.7907645106315613,
"start": 1170,
"tag": "NAME",
"value": "incess Celestia"
},
{
"context": "unction invocation and assignment', ->\n ok Dear Princess Celestia: Today, I learned that Derpy was true. Your faith",
"end": 1312,
"score": 0.8319898247718811,
"start": 1295,
"tag": "NAME",
"value": "Princess Celestia"
},
{
"context": "earned that Derpy was true. Your faithful student, Twilight Sparkle.\n",
"end": 1391,
"score": 0.9992939233779907,
"start": 1375,
"tag": "NAME",
"value": "Twilight Sparkle"
}
] | test/friendscript.coffee | btown-side-projects/friendscript | 0 |
# Basic example, then a test suite.
do ->
console.log "Hello from CoffeeScript"
Derpy = "a perfectly normal pony"
DerpyHooves = {}
result =
```
Dear Princess Celestia,
I said "Hello from FiMscript"!
Did you know that Derpy was "wall-eyed"?
I learned that Derpy Hooves's vision was "MUFFINS".
I learned to make friends.
I said "Making friends!".
Then you got "Friendship is Magic".
That's how to make friends.
I learned that somepony would make friends.
Then I got somepony.
Your faithful student,
Twilight Sparkle
```
console.log "Derpy is #{Derpy} and her vision is #{DerpyHooves.vision}"
console.log "When you make friends: #{result}"
### BEGIN TEST SUITE ###
{ok} = require 'assert'
suite "Friendscript/FiMscript", ->
test 'Blank program without ticks', ->
ok not Dear Princess Celestia,
Your faithful student,
Blank Flank
test 'Blank function, returns last value', ->
ok ```
Dear Princess Celestia,
I learned how to dance.
That's how to dance.
Your faithful student,
Blank Flank
``` instanceof Function
test 'Inline function with return value', ->
ok Dear Princess Celestia: I got true. Your faithful student, Inline Pony
test 'Function invocation and assignment', ->
ok Dear Princess Celestia: Today, I learned that Derpy was true. Your faithful student, Twilight Sparkle.
| 132705 |
# Basic example, then a test suite.
do ->
console.log "Hello from CoffeeScript"
Derpy = "a perfectly normal pony"
DerpyHooves = {}
result =
```
Dear <NAME>,
I said "Hello from FiMscript"!
Did you know that Derpy was "wall-eyed"?
I learned that Derpy Hooves's vision was "MUFFINS".
I learned to make friends.
I said "Making friends!".
Then you got "Friendship is Magic".
That's how to make friends.
I learned that somepony would make friends.
Then I got somepony.
Your faithful student,
<NAME>
```
console.log "Derpy is #{Derpy} and her vision is #{DerpyHooves.vision}"
console.log "When you make friends: #{result}"
### BEGIN TEST SUITE ###
{ok} = require 'assert'
suite "Friendscript/FiMscript", ->
test 'Blank program without ticks', ->
ok not Dear Pr<NAME> C<NAME>,
Your faithful student,
Blank Flank
test 'Blank function, returns last value', ->
ok ```
Dear <NAME>,
I learned how to dance.
That's how to dance.
Your faithful student,
Blank Flank
``` instanceof Function
test 'Inline function with return value', ->
ok Dear Pr<NAME>: I got true. Your faithful student, Inline Pony
test 'Function invocation and assignment', ->
ok Dear <NAME>: Today, I learned that Derpy was true. Your faithful student, <NAME>.
| true |
# Basic example, then a test suite.
do ->
console.log "Hello from CoffeeScript"
Derpy = "a perfectly normal pony"
DerpyHooves = {}
result =
```
Dear PI:NAME:<NAME>END_PI,
I said "Hello from FiMscript"!
Did you know that Derpy was "wall-eyed"?
I learned that Derpy Hooves's vision was "MUFFINS".
I learned to make friends.
I said "Making friends!".
Then you got "Friendship is Magic".
That's how to make friends.
I learned that somepony would make friends.
Then I got somepony.
Your faithful student,
PI:NAME:<NAME>END_PI
```
console.log "Derpy is #{Derpy} and her vision is #{DerpyHooves.vision}"
console.log "When you make friends: #{result}"
### BEGIN TEST SUITE ###
{ok} = require 'assert'
suite "Friendscript/FiMscript", ->
test 'Blank program without ticks', ->
ok not Dear PrPI:NAME:<NAME>END_PI CPI:NAME:<NAME>END_PI,
Your faithful student,
Blank Flank
test 'Blank function, returns last value', ->
ok ```
Dear PI:NAME:<NAME>END_PI,
I learned how to dance.
That's how to dance.
Your faithful student,
Blank Flank
``` instanceof Function
test 'Inline function with return value', ->
ok Dear PrPI:NAME:<NAME>END_PI: I got true. Your faithful student, Inline Pony
test 'Function invocation and assignment', ->
ok Dear PI:NAME:<NAME>END_PI: Today, I learned that Derpy was true. Your faithful student, PI:NAME:<NAME>END_PI.
|
[
{
"context": " for user in identity.users\n if user.id == @self.id\n @robot.logger.debug \"SlackBot#authen",
"end": 6151,
"score": 0.8835420608520508,
"start": 6146,
"tag": "USERNAME",
"value": "@self"
},
{
"context": "e comparing to the message text.\n @robot.name = @self.name\n\n @robot.logger.info \"Logged in as @#",
"end": 6605,
"score": 0.8503758907318115,
"start": 6605,
"tag": "NAME",
"value": ""
},
{
"context": "comparing to the message text.\n @robot.name = @self.name\n\n @robot.logger.info \"Logged in as @#{@robot.n",
"end": 6616,
"score": 0.6846557259559631,
"start": 6607,
"tag": "USERNAME",
"value": "self.name"
},
{
"context": "lf.name\n\n @robot.logger.info \"Logged in as @#{@robot.name} in workspace #{team.name}\"\n\n\n ###*\n # Cre",
"end": 6664,
"score": 0.6687277555465698,
"start": 6659,
"tag": "USERNAME",
"value": "robot"
},
{
"context": "e\n\n @robot.logger.info \"Logged in as @#{@robot.name} in workspace #{team.name}\"\n\n\n ###*\n # Creates ",
"end": 6669,
"score": 0.5374850034713745,
"start": 6665,
"tag": "USERNAME",
"value": "name"
}
] | src/bot.coffee | shanedewael/hubot-slack | 0 | {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, CatchAllMessage} = require.main.require "hubot"
{SlackTextMessage, ReactionMessage, PresenceMessage} = require "./message"
SlackClient = require "./client"
pkg = require "../package"
class SlackBot extends Adapter
###*
# Slackbot is an adapter for connecting Hubot to Slack
# @constructor
# @param {Robot} robot - the Hubot robot
# @param {Object} options - configuration options for the adapter
# @param {string} options.token - authentication token for Slack APIs
# @param {Boolean} options.disableUserSync - disables syncing all user data on start
# @param {Object} options.rtm - RTM configuration options for SlackClient
# @param {Object} options.rtmStart - options for `rtm.start` Web API method
###
constructor: (@robot, @options) ->
super
@robot.logger.info "hubot-slack adapter v#{pkg.version}"
@client = new SlackClient @options, @robot
###
# Hubot Adapter methods
###
###*
# Slackbot initialization
# @public
###
run: ->
# Token validation
return @robot.logger.error "No token provided to Hubot" unless @options.token
return @robot.logger.error "Invalid token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ["xoxb-", "xoxp-"])
# SlackClient event handlers
@client.rtm.on "open", @open
@client.rtm.on "close", @close
@client.rtm.on "error", @error
@client.rtm.on "authenticated", @authenticated
@client.onEvent @eventHandler
# TODO: set this to false as soon as RTM connection closes (even if reconnect will happen later)
# TODO: check this value when connection finishes (even if its a reconnection)
# TODO: build a map of enterprise users and local users
@needsUserListSync = true
unless @options.disableUserSync
# Synchronize workspace users to brain
@client.loadUsers @usersLoaded
else
@isLoaded = true
# Brain will emit 'loaded' the first time it connects to its storage and then again each time a key is set
@robot.brain.on "loaded", () =>
if not @brainIsLoaded
@brainIsLoaded = true
# The following code should only run after the first time the brain connects to its storage
# There's a race condition where the connection can happen after the above `@client.loadUsers` call finishes,
# in which case the calls to save users in `@usersLoaded` would not persist. It is still necessary to call the
# method there in the case Hubot is running without brain storage.
# NOTE: is this actually true? won't the brain have the users in memory and persist to storage as soon as the
# connection is complete?
# NOTE: this seems wasteful. when there is brain storage, it will end up loading all the users twice.
@client.loadUsers @usersLoaded
@isLoaded = true
# NOTE: will this only subscribe a partial user list because loadUsers has not yet completed? it will at least
# subscribe to the users that were stored in the brain from the last run.
@presenceSub()
# Start logging in
@client.connect()
###*
# Hubot is sending a message to Slack
#
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
send: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
# NOTE: perhaps do envelope manipulation here instead of in the client (separation of concerns)
@client.send(envelope, message) unless message is ""
###*
# Hubot is replying to a Slack message
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
reply: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
if message isnt ""
# TODO: channel prefix matching should be removed
message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is "D"
@client.send envelope, message
###*
# Hubot is setting the Slack conversation topic
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...string} strings - strings that will be newline separated and set to the conversation topic
###
setTopic: (envelope, strings...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
# TODO: this will fail if sending an object as a value in strings
@client.setTopic envelope.room, strings.join("\n")
###*
# Hubot is sending a reaction
# NOTE: the super class implementation is just an alias for send, but potentially, we can detect
# if the envelope has a specific message and send a reactji. the fallback would be to just send the
# emoji as a message in the channel
###
# emote: (envelope, strings...) ->
###
# SlackClient event handlers
###
###*
# Slack client has opened the connection
# @private
###
open: =>
@robot.logger.info "Connected to Slack RTM"
# Tell Hubot we're connected so it can load scripts
@emit "connected"
###*
# Slack client has authenticated
#
# @private
# @param {SlackRtmStart|SlackRtmConnect} identity - the response from calling the Slack Web API method `rtm.start` or
# `rtm.connect`
###
authenticated: (identity) =>
{@self, team} = identity
# Find out bot_id
# NOTE: this information can be fetched by using `bots.info` combined with `users.info`. This presents an
# alternative that decouples Hubot from `rtm.start` and would make it compatible with `rtm.connect`.
if identity.users
for user in identity.users
if user.id == @self.id
@robot.logger.debug "SlackBot#authenticated() Found self in RTM start data"
@self.bot_id = user.profile.bot_id
break
# Provide name to Hubot so it can be used for matching in `robot.respond()`. This must be a username, despite the
# deprecation, because the SlackTextMessage#buildText() will format mentions into `@username`, and that is what
# Hubot will be comparing to the message text.
@robot.name = @self.name
@robot.logger.info "Logged in as @#{@robot.name} in workspace #{team.name}"
###*
# Creates a presense subscripton for all users in the brain
# @private
###
presenceSub: =>
# Only subscribe to status changes from human users that are not deleted
ids = for own id, user of @robot.brain.data.users when (not user.is_bot and not user.deleted)
id
@robot.logger.debug "SlackBot#presenceSub() Subscribing to presence for #{ids.length} users"
@client.rtm.subscribePresence ids
###*
# Slack client has closed the connection
# @private
###
close: =>
@robot.logger.info "Disconnected from Slack RTM"
# NOTE: not confident that @options.autoReconnect works
if @options.autoReconnect
@robot.logger.info "Waiting for reconnect..."
else
@robot.logger.info "Exiting..."
@client.disconnect()
# NOTE: Node recommends not to call process.exit() but Hubot itself uses this mechanism for shutting down
# Can we make sure the brain is flushed to persistence? Do we need to cleanup any state (or timestamp anything)?
process.exit 1
###*
# Slack client received an error
#
# @private
# @param {SlackRtmError} error - An error emitted from the [Slack RTM API](https://api.slack.com/rtm)
###
error: (error) =>
@robot.logger.error "Slack RTM error: #{JSON.stringify error}"
# Assume that scripts can handle slowing themselves down, all other errors are bubbled up through Hubot
# NOTE: should rate limit errors also bubble up?
if error.code isnt -1
@robot.emit "error", error
###*
# Incoming Slack event handler
#
# This method is used to ingest Slack RTM events and prepare them as Hubot Message objects. The messages are passed
# to the Robot#receive() method, which allows executes receive middleware and eventually triggers the various
# listeners that are created by scripts.
#
# Depending on the exact type of event, additional properties may be present. The following describes the "special"
# ones that have meaningful handling across all types.
#
# @private
# @param {Object} event
# @param {string} event.type - this specifies the event type
# @param {SlackUserInfo} [event.user] - the description of the user creating this event as returned by `users.info`
# @param {string} [event.channel] - the conversation ID for where this event took place
# @param {SlackBotInfo} [event.bot] - the description of the bot creating this event as returned by `bots.info`
###
eventHandler: (event) =>
{user, channel} = event
# Ignore anything we sent
return if user?.id is @self.id
###*
# Hubot user object in Brain.
# User can represent a Slack human user or bot user
#
# The returned user from a message or reaction event is guaranteed to contain:
#
# id {String}: Slack user ID
# slack.is_bot {Boolean}: Flag indicating whether user is a bot
# name {String}: Slack username
# real_name {String}: Name of Slack user or bot
# room {String}: Slack channel ID for event (will be empty string if no channel in event)
###
user = if user? then @client.updateUserInBrain user else {}
# Send to Hubot based on message type
if event.type is "message"
# Hubot expects all user objects to have a room property that is used in the envelope for the message after it
# is received
user.room = if channel? then channel else ""
switch event.subtype
when "bot_message"
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (bot)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
# NOTE: channel_join should be replaced with a member_joined_channel event
when "channel_join", "group_join"
@robot.logger.debug "Received enter message for user: #{user.id}, joining: #{channel}"
@receive new EnterMessage user
# NOTE: channel_leave should be replaced with a member_left_channel event
when "channel_leave", "group_leave"
@robot.logger.debug "Received leave message for user: #{user.id}, leaving: #{channel}"
@receive new LeaveMessage user
when "channel_topic", "group_topic"
@robot.logger.debug "Received topic change message in conversation: #{channel}, new topic: #{event.topic}, set by: #{user.id}"
@receive new TopicMessage user, event.topic, event.ts
when undefined
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (human)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
else if event.type is "reaction_added" or event.type is "reaction_removed"
# Once again Hubot expects all user objects to have a room property that is used in the envelope for the message
# after it is received. If the reaction is to a message, then the `event.item.channel` contain a conversation ID.
# Otherwise reactions can be on files and file comments, which are "global" and aren't contained in a
# conversation. In that situation we fallback to an empty string.
user.room = if event.item.type is "message" then event.item.channel else ""
# Reaction messages may contain an `event.item_user` property containing a fetched SlackUserInfo object. Before
# the message is received by Hubot, turn that data into a Hubot User object.
item_user = if event.item_user? then @robot.brain.userForId event.item_user.id, event.item_user else {}
@robot.logger.debug "Received reaction message from: #{user.id}, reaction: #{event.reaction}, item type: #{event.item.type}"
@receive new ReactionMessage(event.type, user, event.reaction, item_user, event.item, event.event_ts)
else if event.type is "presence_change"
# Collect all Hubot User objects referenced in this presence change event
# NOTE: this does not create new Hubot User objects for any users that are not already in the brain. It should
# not be possible for this to happen since Slack will only send events for users where an explicit subscription
# was made. In the `presenceSub()` method, subscriptions are only made for users in the brain.
users = for user_id in (event.users or [event.user.id]) when @robot.brain.data.users[user_id]?
@robot.brain.data.users[user_id]
@robot.logger.debug "Received presence update message for users: #{u.id for u in users} with status: #{event.presence}"
@receive new PresenceMessage(users, event.presence)
# NOTE: we may want to wrap all other incoming events as a generic Message
# else
###*
# Callback for fetching all users in workspace. Delegates to `updateUserInBrain()` to write all users to Hubot brain
#
# @private
# @param {Error} [error] - describes an error that occurred while fetching users
# @param {SlackUsersList} [res] - the response from the Slack Web API method `users.list`
###
usersLoaded: (err, res) =>
if err || !res.members.length
@robot.logger.error "Can't fetch users"
return
@client.updateUserInBrain member for member in res.members
module.exports = SlackBot
| 3465 | {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, CatchAllMessage} = require.main.require "hubot"
{SlackTextMessage, ReactionMessage, PresenceMessage} = require "./message"
SlackClient = require "./client"
pkg = require "../package"
class SlackBot extends Adapter
###*
# Slackbot is an adapter for connecting Hubot to Slack
# @constructor
# @param {Robot} robot - the Hubot robot
# @param {Object} options - configuration options for the adapter
# @param {string} options.token - authentication token for Slack APIs
# @param {Boolean} options.disableUserSync - disables syncing all user data on start
# @param {Object} options.rtm - RTM configuration options for SlackClient
# @param {Object} options.rtmStart - options for `rtm.start` Web API method
###
constructor: (@robot, @options) ->
super
@robot.logger.info "hubot-slack adapter v#{pkg.version}"
@client = new SlackClient @options, @robot
###
# Hubot Adapter methods
###
###*
# Slackbot initialization
# @public
###
run: ->
# Token validation
return @robot.logger.error "No token provided to Hubot" unless @options.token
return @robot.logger.error "Invalid token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ["xoxb-", "xoxp-"])
# SlackClient event handlers
@client.rtm.on "open", @open
@client.rtm.on "close", @close
@client.rtm.on "error", @error
@client.rtm.on "authenticated", @authenticated
@client.onEvent @eventHandler
# TODO: set this to false as soon as RTM connection closes (even if reconnect will happen later)
# TODO: check this value when connection finishes (even if its a reconnection)
# TODO: build a map of enterprise users and local users
@needsUserListSync = true
unless @options.disableUserSync
# Synchronize workspace users to brain
@client.loadUsers @usersLoaded
else
@isLoaded = true
# Brain will emit 'loaded' the first time it connects to its storage and then again each time a key is set
@robot.brain.on "loaded", () =>
if not @brainIsLoaded
@brainIsLoaded = true
# The following code should only run after the first time the brain connects to its storage
# There's a race condition where the connection can happen after the above `@client.loadUsers` call finishes,
# in which case the calls to save users in `@usersLoaded` would not persist. It is still necessary to call the
# method there in the case Hubot is running without brain storage.
# NOTE: is this actually true? won't the brain have the users in memory and persist to storage as soon as the
# connection is complete?
# NOTE: this seems wasteful. when there is brain storage, it will end up loading all the users twice.
@client.loadUsers @usersLoaded
@isLoaded = true
# NOTE: will this only subscribe a partial user list because loadUsers has not yet completed? it will at least
# subscribe to the users that were stored in the brain from the last run.
@presenceSub()
# Start logging in
@client.connect()
###*
# Hubot is sending a message to Slack
#
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
send: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
# NOTE: perhaps do envelope manipulation here instead of in the client (separation of concerns)
@client.send(envelope, message) unless message is ""
###*
# Hubot is replying to a Slack message
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
reply: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
if message isnt ""
# TODO: channel prefix matching should be removed
message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is "D"
@client.send envelope, message
###*
# Hubot is setting the Slack conversation topic
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...string} strings - strings that will be newline separated and set to the conversation topic
###
setTopic: (envelope, strings...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
# TODO: this will fail if sending an object as a value in strings
@client.setTopic envelope.room, strings.join("\n")
###*
# Hubot is sending a reaction
# NOTE: the super class implementation is just an alias for send, but potentially, we can detect
# if the envelope has a specific message and send a reactji. the fallback would be to just send the
# emoji as a message in the channel
###
# emote: (envelope, strings...) ->
###
# SlackClient event handlers
###
###*
# Slack client has opened the connection
# @private
###
open: =>
@robot.logger.info "Connected to Slack RTM"
# Tell Hubot we're connected so it can load scripts
@emit "connected"
###*
# Slack client has authenticated
#
# @private
# @param {SlackRtmStart|SlackRtmConnect} identity - the response from calling the Slack Web API method `rtm.start` or
# `rtm.connect`
###
authenticated: (identity) =>
{@self, team} = identity
# Find out bot_id
# NOTE: this information can be fetched by using `bots.info` combined with `users.info`. This presents an
# alternative that decouples Hubot from `rtm.start` and would make it compatible with `rtm.connect`.
if identity.users
for user in identity.users
if user.id == @self.id
@robot.logger.debug "SlackBot#authenticated() Found self in RTM start data"
@self.bot_id = user.profile.bot_id
break
# Provide name to Hubot so it can be used for matching in `robot.respond()`. This must be a username, despite the
# deprecation, because the SlackTextMessage#buildText() will format mentions into `@username`, and that is what
# Hubot will be comparing to the message text.
@robot.name =<NAME> @self.name
@robot.logger.info "Logged in as @#{@robot.name} in workspace #{team.name}"
###*
# Creates a presense subscripton for all users in the brain
# @private
###
presenceSub: =>
# Only subscribe to status changes from human users that are not deleted
ids = for own id, user of @robot.brain.data.users when (not user.is_bot and not user.deleted)
id
@robot.logger.debug "SlackBot#presenceSub() Subscribing to presence for #{ids.length} users"
@client.rtm.subscribePresence ids
###*
# Slack client has closed the connection
# @private
###
close: =>
@robot.logger.info "Disconnected from Slack RTM"
# NOTE: not confident that @options.autoReconnect works
if @options.autoReconnect
@robot.logger.info "Waiting for reconnect..."
else
@robot.logger.info "Exiting..."
@client.disconnect()
# NOTE: Node recommends not to call process.exit() but Hubot itself uses this mechanism for shutting down
# Can we make sure the brain is flushed to persistence? Do we need to cleanup any state (or timestamp anything)?
process.exit 1
###*
# Slack client received an error
#
# @private
# @param {SlackRtmError} error - An error emitted from the [Slack RTM API](https://api.slack.com/rtm)
###
error: (error) =>
@robot.logger.error "Slack RTM error: #{JSON.stringify error}"
# Assume that scripts can handle slowing themselves down, all other errors are bubbled up through Hubot
# NOTE: should rate limit errors also bubble up?
if error.code isnt -1
@robot.emit "error", error
###*
# Incoming Slack event handler
#
# This method is used to ingest Slack RTM events and prepare them as Hubot Message objects. The messages are passed
# to the Robot#receive() method, which allows executes receive middleware and eventually triggers the various
# listeners that are created by scripts.
#
# Depending on the exact type of event, additional properties may be present. The following describes the "special"
# ones that have meaningful handling across all types.
#
# @private
# @param {Object} event
# @param {string} event.type - this specifies the event type
# @param {SlackUserInfo} [event.user] - the description of the user creating this event as returned by `users.info`
# @param {string} [event.channel] - the conversation ID for where this event took place
# @param {SlackBotInfo} [event.bot] - the description of the bot creating this event as returned by `bots.info`
###
eventHandler: (event) =>
{user, channel} = event
# Ignore anything we sent
return if user?.id is @self.id
###*
# Hubot user object in Brain.
# User can represent a Slack human user or bot user
#
# The returned user from a message or reaction event is guaranteed to contain:
#
# id {String}: Slack user ID
# slack.is_bot {Boolean}: Flag indicating whether user is a bot
# name {String}: Slack username
# real_name {String}: Name of Slack user or bot
# room {String}: Slack channel ID for event (will be empty string if no channel in event)
###
user = if user? then @client.updateUserInBrain user else {}
# Send to Hubot based on message type
if event.type is "message"
# Hubot expects all user objects to have a room property that is used in the envelope for the message after it
# is received
user.room = if channel? then channel else ""
switch event.subtype
when "bot_message"
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (bot)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
# NOTE: channel_join should be replaced with a member_joined_channel event
when "channel_join", "group_join"
@robot.logger.debug "Received enter message for user: #{user.id}, joining: #{channel}"
@receive new EnterMessage user
# NOTE: channel_leave should be replaced with a member_left_channel event
when "channel_leave", "group_leave"
@robot.logger.debug "Received leave message for user: #{user.id}, leaving: #{channel}"
@receive new LeaveMessage user
when "channel_topic", "group_topic"
@robot.logger.debug "Received topic change message in conversation: #{channel}, new topic: #{event.topic}, set by: #{user.id}"
@receive new TopicMessage user, event.topic, event.ts
when undefined
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (human)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
else if event.type is "reaction_added" or event.type is "reaction_removed"
# Once again Hubot expects all user objects to have a room property that is used in the envelope for the message
# after it is received. If the reaction is to a message, then the `event.item.channel` contain a conversation ID.
# Otherwise reactions can be on files and file comments, which are "global" and aren't contained in a
# conversation. In that situation we fallback to an empty string.
user.room = if event.item.type is "message" then event.item.channel else ""
# Reaction messages may contain an `event.item_user` property containing a fetched SlackUserInfo object. Before
# the message is received by Hubot, turn that data into a Hubot User object.
item_user = if event.item_user? then @robot.brain.userForId event.item_user.id, event.item_user else {}
@robot.logger.debug "Received reaction message from: #{user.id}, reaction: #{event.reaction}, item type: #{event.item.type}"
@receive new ReactionMessage(event.type, user, event.reaction, item_user, event.item, event.event_ts)
else if event.type is "presence_change"
# Collect all Hubot User objects referenced in this presence change event
# NOTE: this does not create new Hubot User objects for any users that are not already in the brain. It should
# not be possible for this to happen since Slack will only send events for users where an explicit subscription
# was made. In the `presenceSub()` method, subscriptions are only made for users in the brain.
users = for user_id in (event.users or [event.user.id]) when @robot.brain.data.users[user_id]?
@robot.brain.data.users[user_id]
@robot.logger.debug "Received presence update message for users: #{u.id for u in users} with status: #{event.presence}"
@receive new PresenceMessage(users, event.presence)
# NOTE: we may want to wrap all other incoming events as a generic Message
# else
###*
# Callback for fetching all users in workspace. Delegates to `updateUserInBrain()` to write all users to Hubot brain
#
# @private
# @param {Error} [error] - describes an error that occurred while fetching users
# @param {SlackUsersList} [res] - the response from the Slack Web API method `users.list`
###
usersLoaded: (err, res) =>
if err || !res.members.length
@robot.logger.error "Can't fetch users"
return
@client.updateUserInBrain member for member in res.members
module.exports = SlackBot
| true | {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, CatchAllMessage} = require.main.require "hubot"
{SlackTextMessage, ReactionMessage, PresenceMessage} = require "./message"
SlackClient = require "./client"
pkg = require "../package"
class SlackBot extends Adapter
###*
# Slackbot is an adapter for connecting Hubot to Slack
# @constructor
# @param {Robot} robot - the Hubot robot
# @param {Object} options - configuration options for the adapter
# @param {string} options.token - authentication token for Slack APIs
# @param {Boolean} options.disableUserSync - disables syncing all user data on start
# @param {Object} options.rtm - RTM configuration options for SlackClient
# @param {Object} options.rtmStart - options for `rtm.start` Web API method
###
constructor: (@robot, @options) ->
super
@robot.logger.info "hubot-slack adapter v#{pkg.version}"
@client = new SlackClient @options, @robot
###
# Hubot Adapter methods
###
###*
# Slackbot initialization
# @public
###
run: ->
# Token validation
return @robot.logger.error "No token provided to Hubot" unless @options.token
return @robot.logger.error "Invalid token provided, please follow the upgrade instructions" unless (@options.token.substring(0, 5) in ["xoxb-", "xoxp-"])
# SlackClient event handlers
@client.rtm.on "open", @open
@client.rtm.on "close", @close
@client.rtm.on "error", @error
@client.rtm.on "authenticated", @authenticated
@client.onEvent @eventHandler
# TODO: set this to false as soon as RTM connection closes (even if reconnect will happen later)
# TODO: check this value when connection finishes (even if its a reconnection)
# TODO: build a map of enterprise users and local users
@needsUserListSync = true
unless @options.disableUserSync
# Synchronize workspace users to brain
@client.loadUsers @usersLoaded
else
@isLoaded = true
# Brain will emit 'loaded' the first time it connects to its storage and then again each time a key is set
@robot.brain.on "loaded", () =>
if not @brainIsLoaded
@brainIsLoaded = true
# The following code should only run after the first time the brain connects to its storage
# There's a race condition where the connection can happen after the above `@client.loadUsers` call finishes,
# in which case the calls to save users in `@usersLoaded` would not persist. It is still necessary to call the
# method there in the case Hubot is running without brain storage.
# NOTE: is this actually true? won't the brain have the users in memory and persist to storage as soon as the
# connection is complete?
# NOTE: this seems wasteful. when there is brain storage, it will end up loading all the users twice.
@client.loadUsers @usersLoaded
@isLoaded = true
# NOTE: will this only subscribe a partial user list because loadUsers has not yet completed? it will at least
# subscribe to the users that were stored in the brain from the last run.
@presenceSub()
# Start logging in
@client.connect()
###*
# Hubot is sending a message to Slack
#
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
send: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
# NOTE: perhaps do envelope manipulation here instead of in the client (separation of concerns)
@client.send(envelope, message) unless message is ""
###*
# Hubot is replying to a Slack message
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...(string|Object)} messages - fully documented in SlackClient
###
reply: (envelope, messages...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
for message in messages
if message isnt ""
# TODO: channel prefix matching should be removed
message = "<@#{envelope.user.id}>: #{message}" unless envelope.room[0] is "D"
@client.send envelope, message
###*
# Hubot is setting the Slack conversation topic
# @public
# @param {Object} envelope - fully documented in SlackClient
# @param {...string} strings - strings that will be newline separated and set to the conversation topic
###
setTopic: (envelope, strings...) ->
# TODO: if the sender is interested in the completion, the last item in `messages` will be a function
# TODO: this will fail if sending an object as a value in strings
@client.setTopic envelope.room, strings.join("\n")
###*
# Hubot is sending a reaction
# NOTE: the super class implementation is just an alias for send, but potentially, we can detect
# if the envelope has a specific message and send a reactji. the fallback would be to just send the
# emoji as a message in the channel
###
# emote: (envelope, strings...) ->
###
# SlackClient event handlers
###
###*
# Slack client has opened the connection
# @private
###
open: =>
@robot.logger.info "Connected to Slack RTM"
# Tell Hubot we're connected so it can load scripts
@emit "connected"
###*
# Slack client has authenticated
#
# @private
# @param {SlackRtmStart|SlackRtmConnect} identity - the response from calling the Slack Web API method `rtm.start` or
# `rtm.connect`
###
authenticated: (identity) =>
{@self, team} = identity
# Find out bot_id
# NOTE: this information can be fetched by using `bots.info` combined with `users.info`. This presents an
# alternative that decouples Hubot from `rtm.start` and would make it compatible with `rtm.connect`.
if identity.users
for user in identity.users
if user.id == @self.id
@robot.logger.debug "SlackBot#authenticated() Found self in RTM start data"
@self.bot_id = user.profile.bot_id
break
# Provide name to Hubot so it can be used for matching in `robot.respond()`. This must be a username, despite the
# deprecation, because the SlackTextMessage#buildText() will format mentions into `@username`, and that is what
# Hubot will be comparing to the message text.
@robot.name =PI:NAME:<NAME>END_PI @self.name
@robot.logger.info "Logged in as @#{@robot.name} in workspace #{team.name}"
###*
# Creates a presense subscripton for all users in the brain
# @private
###
presenceSub: =>
# Only subscribe to status changes from human users that are not deleted
ids = for own id, user of @robot.brain.data.users when (not user.is_bot and not user.deleted)
id
@robot.logger.debug "SlackBot#presenceSub() Subscribing to presence for #{ids.length} users"
@client.rtm.subscribePresence ids
###*
# Slack client has closed the connection
# @private
###
close: =>
@robot.logger.info "Disconnected from Slack RTM"
# NOTE: not confident that @options.autoReconnect works
if @options.autoReconnect
@robot.logger.info "Waiting for reconnect..."
else
@robot.logger.info "Exiting..."
@client.disconnect()
# NOTE: Node recommends not to call process.exit() but Hubot itself uses this mechanism for shutting down
# Can we make sure the brain is flushed to persistence? Do we need to cleanup any state (or timestamp anything)?
process.exit 1
###*
# Slack client received an error
#
# @private
# @param {SlackRtmError} error - An error emitted from the [Slack RTM API](https://api.slack.com/rtm)
###
error: (error) =>
@robot.logger.error "Slack RTM error: #{JSON.stringify error}"
# Assume that scripts can handle slowing themselves down, all other errors are bubbled up through Hubot
# NOTE: should rate limit errors also bubble up?
if error.code isnt -1
@robot.emit "error", error
###*
# Incoming Slack event handler
#
# This method is used to ingest Slack RTM events and prepare them as Hubot Message objects. The messages are passed
# to the Robot#receive() method, which allows executes receive middleware and eventually triggers the various
# listeners that are created by scripts.
#
# Depending on the exact type of event, additional properties may be present. The following describes the "special"
# ones that have meaningful handling across all types.
#
# @private
# @param {Object} event
# @param {string} event.type - this specifies the event type
# @param {SlackUserInfo} [event.user] - the description of the user creating this event as returned by `users.info`
# @param {string} [event.channel] - the conversation ID for where this event took place
# @param {SlackBotInfo} [event.bot] - the description of the bot creating this event as returned by `bots.info`
###
eventHandler: (event) =>
{user, channel} = event
# Ignore anything we sent
return if user?.id is @self.id
###*
# Hubot user object in Brain.
# User can represent a Slack human user or bot user
#
# The returned user from a message or reaction event is guaranteed to contain:
#
# id {String}: Slack user ID
# slack.is_bot {Boolean}: Flag indicating whether user is a bot
# name {String}: Slack username
# real_name {String}: Name of Slack user or bot
# room {String}: Slack channel ID for event (will be empty string if no channel in event)
###
user = if user? then @client.updateUserInBrain user else {}
# Send to Hubot based on message type
if event.type is "message"
# Hubot expects all user objects to have a room property that is used in the envelope for the message after it
# is received
user.room = if channel? then channel else ""
switch event.subtype
when "bot_message"
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (bot)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
# NOTE: channel_join should be replaced with a member_joined_channel event
when "channel_join", "group_join"
@robot.logger.debug "Received enter message for user: #{user.id}, joining: #{channel}"
@receive new EnterMessage user
# NOTE: channel_leave should be replaced with a member_left_channel event
when "channel_leave", "group_leave"
@robot.logger.debug "Received leave message for user: #{user.id}, leaving: #{channel}"
@receive new LeaveMessage user
when "channel_topic", "group_topic"
@robot.logger.debug "Received topic change message in conversation: #{channel}, new topic: #{event.topic}, set by: #{user.id}"
@receive new TopicMessage user, event.topic, event.ts
when undefined
@robot.logger.debug "Received text message in channel: #{channel}, from: #{user.id} (human)"
SlackTextMessage.makeSlackTextMessage(user, undefined, undefined, event, channel, @robot.name, @robot.alias, @client, (error, message) =>
return @robot.logger.error "Dropping message due to error #{error.message}" if error
@receive message
)
else if event.type is "reaction_added" or event.type is "reaction_removed"
# Once again Hubot expects all user objects to have a room property that is used in the envelope for the message
# after it is received. If the reaction is to a message, then the `event.item.channel` contain a conversation ID.
# Otherwise reactions can be on files and file comments, which are "global" and aren't contained in a
# conversation. In that situation we fallback to an empty string.
user.room = if event.item.type is "message" then event.item.channel else ""
# Reaction messages may contain an `event.item_user` property containing a fetched SlackUserInfo object. Before
# the message is received by Hubot, turn that data into a Hubot User object.
item_user = if event.item_user? then @robot.brain.userForId event.item_user.id, event.item_user else {}
@robot.logger.debug "Received reaction message from: #{user.id}, reaction: #{event.reaction}, item type: #{event.item.type}"
@receive new ReactionMessage(event.type, user, event.reaction, item_user, event.item, event.event_ts)
else if event.type is "presence_change"
# Collect all Hubot User objects referenced in this presence change event
# NOTE: this does not create new Hubot User objects for any users that are not already in the brain. It should
# not be possible for this to happen since Slack will only send events for users where an explicit subscription
# was made. In the `presenceSub()` method, subscriptions are only made for users in the brain.
users = for user_id in (event.users or [event.user.id]) when @robot.brain.data.users[user_id]?
@robot.brain.data.users[user_id]
@robot.logger.debug "Received presence update message for users: #{u.id for u in users} with status: #{event.presence}"
@receive new PresenceMessage(users, event.presence)
# NOTE: we may want to wrap all other incoming events as a generic Message
# else
###*
# Callback for fetching all users in workspace. Delegates to `updateUserInBrain()` to write all users to Hubot brain
#
# @private
# @param {Error} [error] - describes an error that occurred while fetching users
# @param {SlackUsersList} [res] - the response from the Slack Web API method `users.list`
###
usersLoaded: (err, res) =>
if err || !res.members.length
@robot.logger.error "Can't fetch users"
return
@client.updateUserInBrain member for member in res.members
module.exports = SlackBot
|
[
{
"context": "get for displaying the current time and date\n\n\n Robin 'codeFareith' von den Bergen\n robinvonberg@gmx",
"end": 173,
"score": 0.9998326301574707,
"start": 168,
"tag": "NAME",
"value": "Robin"
},
{
"context": "displaying the current time and date\n\n\n Robin 'codeFareith' von den Bergen\n robinvonberg@gmx.de\n https",
"end": 186,
"score": 0.7539956569671631,
"start": 175,
"tag": "USERNAME",
"value": "codeFareith"
},
{
"context": "he current time and date\n\n\n Robin 'codeFareith' von den Bergen\n robinvonberg@gmx.de\n https://github.com/co",
"end": 202,
"score": 0.9972941279411316,
"start": 188,
"tag": "NAME",
"value": "von den Bergen"
},
{
"context": " date\n\n\n Robin 'codeFareith' von den Bergen\n robinvonberg@gmx.de\n https://github.com/codefareith\n\n-------------",
"end": 226,
"score": 0.9999316930770874,
"start": 207,
"tag": "EMAIL",
"value": "robinvonberg@gmx.de"
},
{
"context": "en\n robinvonberg@gmx.de\n https://github.com/codefareith\n\n------------------------------------------------",
"end": 261,
"score": 0.9995394945144653,
"start": 250,
"tag": "USERNAME",
"value": "codefareith"
}
] | fancy-datetime.widget/index.coffee | codeFareith/FancyDateTime | 2 | ###
----------------------------------------------------------------
Fancy DateTime - v1.0.0
Uebersicht-widget for displaying the current time and date
Robin 'codeFareith' von den Bergen
robinvonberg@gmx.de
https://github.com/codefareith
----------------------------------------------------------------
###
# Widget Settings
settings =
lang: 'de'
militaryTime: true
colors:
default: 'rgba(0, 0, 0, .75)'
accent: 'rgba(255, 255, 255, .75)'
background: 'rgba(255, 255, 255, .1)'
shadows:
box: '0 0 1.25em rgba(0, 0, 0, .5)'
text: '0 0 0.625em rgba(0, 0, 0, .25)'
# Locale Strings
locale =
en:
weekdays: [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
months: [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December'
]
de:
weekdays: [
'Sonntag'
'Montag'
'Dienstag'
'Mittwoch'
'Donnerstag'
'Freitag'
'Samstag'
]
months: [
'Januar'
'Februar'
'März'
'April'
'Mai'
'Juni'
'Juli'
'August'
'September'
'Oktober'
'November'
'Dezember'
]
jp:
weekdays: [
'日曜日'
'月曜日'
'火曜日'
'水曜日'
'木曜日'
'金曜日'
'土曜日'
]
months: [
'1月'
'2月'
'3月'
'4月'
'5月'
'6月'
'7月'
'8月'
'9月'
'10月'
'11月'
'12月'
]
command: ""
settings: settings
locale: locale
refreshFrequency: 1000
style: """
top: 45%
left: 50%
font-family: 'Ubuntu', sans-serif
font-size: 16px
line-height: 1
text-transform: uppercase
transform: translate(-50%, -50%)
.container
position: relative
display: table
height: 100%
padding: 1rem 2rem
border-radius: 1rem
background: #{ settings.colors.background }
box-shadow: #{ settings.shadows.box }
text-shadow: #{ settings.shadows.text }
overflow: hidden
-webkit-backdrop-filter: blur(10px)
.cell
position: relative
display: table-cell
vertical-align: middle
overflow: hidden
.left
float: left
.txt-default
color: #{ settings.colors.default }
.txt-accent
color: #{ settings.colors.accent }
.txt-small
font-size: 2rem
font-weight: 500
.txt-large
font-size: 7rem
font-weight: 700
.divider
display: block
width: 1rem
height: 100%
margin: 0 1rem
background: #{ settings.colors.accent }
box-shadow: #{ settings.shadows.text }
"""
render: () -> """
<div class='container'>
<div class='cell'>
<span class='hours txt-default txt-large left'></span>
<span class='minutes txt-accent txt-large left'></span>
<span class='suffix txt-default txt-small'></span>
</div>
<div class='cell'>
<span class='divider'></span>
</div>
<div class='cell txt-small'>
<span class='weekday txt-accent'></span>
<div class='txt-default'>
<span class='day'></span>
<span>|</span>
<span class='month'></span>
</div>
<span class='year txt-accent'></span>
</div>
</div>
"""
afterRender: (domEl) ->
update: (output, domEl) ->
date = @getDate()
$(domEl).find('.hours').text(date.hours)
$(domEl).find('.minutes').text(date.minutes)
$(domEl).find('.suffix').text(date.suffix)
$(domEl).find('.weekday').text(date.weekday)
$(domEl).find('.day').text(date.day)
$(domEl).find('.month').text(date.month)
$(domEl).find('.year').text(date.year)
# Helper-Functions
zeroFill: (value) ->
return ('0' + value).slice(-2)
getDate: () ->
date = new Date()
hour = date.getHours()
suffix = (if (hour >= 12) then 'pm' else 'am') if (@settings.militaryTime is false)
hour = (hour % 12 || 12) if (@settings.militaryTime is false)
hours = @zeroFill(hour);
minutes = @zeroFill(date.getMinutes())
seconds = @zeroFill(date.getSeconds())
weekday = @locale[@settings.lang].weekdays[date.getDay()]
day = @zeroFill(date.getDate())
month = @locale[@settings.lang].months[date.getMonth()]
year = date.getFullYear()
return {
suffix: suffix
hours: hours
minutes: minutes
seconds: seconds
weekday: weekday
day: day
month: month
year: year
}
| 62858 | ###
----------------------------------------------------------------
Fancy DateTime - v1.0.0
Uebersicht-widget for displaying the current time and date
<NAME> 'codeFareith' <NAME>
<EMAIL>
https://github.com/codefareith
----------------------------------------------------------------
###
# Widget Settings
settings =
lang: 'de'
militaryTime: true
colors:
default: 'rgba(0, 0, 0, .75)'
accent: 'rgba(255, 255, 255, .75)'
background: 'rgba(255, 255, 255, .1)'
shadows:
box: '0 0 1.25em rgba(0, 0, 0, .5)'
text: '0 0 0.625em rgba(0, 0, 0, .25)'
# Locale Strings
locale =
en:
weekdays: [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
months: [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December'
]
de:
weekdays: [
'Sonntag'
'Montag'
'Dienstag'
'Mittwoch'
'Donnerstag'
'Freitag'
'Samstag'
]
months: [
'Januar'
'Februar'
'März'
'April'
'Mai'
'Juni'
'Juli'
'August'
'September'
'Oktober'
'November'
'Dezember'
]
jp:
weekdays: [
'日曜日'
'月曜日'
'火曜日'
'水曜日'
'木曜日'
'金曜日'
'土曜日'
]
months: [
'1月'
'2月'
'3月'
'4月'
'5月'
'6月'
'7月'
'8月'
'9月'
'10月'
'11月'
'12月'
]
command: ""
settings: settings
locale: locale
refreshFrequency: 1000
style: """
top: 45%
left: 50%
font-family: 'Ubuntu', sans-serif
font-size: 16px
line-height: 1
text-transform: uppercase
transform: translate(-50%, -50%)
.container
position: relative
display: table
height: 100%
padding: 1rem 2rem
border-radius: 1rem
background: #{ settings.colors.background }
box-shadow: #{ settings.shadows.box }
text-shadow: #{ settings.shadows.text }
overflow: hidden
-webkit-backdrop-filter: blur(10px)
.cell
position: relative
display: table-cell
vertical-align: middle
overflow: hidden
.left
float: left
.txt-default
color: #{ settings.colors.default }
.txt-accent
color: #{ settings.colors.accent }
.txt-small
font-size: 2rem
font-weight: 500
.txt-large
font-size: 7rem
font-weight: 700
.divider
display: block
width: 1rem
height: 100%
margin: 0 1rem
background: #{ settings.colors.accent }
box-shadow: #{ settings.shadows.text }
"""
render: () -> """
<div class='container'>
<div class='cell'>
<span class='hours txt-default txt-large left'></span>
<span class='minutes txt-accent txt-large left'></span>
<span class='suffix txt-default txt-small'></span>
</div>
<div class='cell'>
<span class='divider'></span>
</div>
<div class='cell txt-small'>
<span class='weekday txt-accent'></span>
<div class='txt-default'>
<span class='day'></span>
<span>|</span>
<span class='month'></span>
</div>
<span class='year txt-accent'></span>
</div>
</div>
"""
afterRender: (domEl) ->
update: (output, domEl) ->
date = @getDate()
$(domEl).find('.hours').text(date.hours)
$(domEl).find('.minutes').text(date.minutes)
$(domEl).find('.suffix').text(date.suffix)
$(domEl).find('.weekday').text(date.weekday)
$(domEl).find('.day').text(date.day)
$(domEl).find('.month').text(date.month)
$(domEl).find('.year').text(date.year)
# Helper-Functions
zeroFill: (value) ->
return ('0' + value).slice(-2)
getDate: () ->
date = new Date()
hour = date.getHours()
suffix = (if (hour >= 12) then 'pm' else 'am') if (@settings.militaryTime is false)
hour = (hour % 12 || 12) if (@settings.militaryTime is false)
hours = @zeroFill(hour);
minutes = @zeroFill(date.getMinutes())
seconds = @zeroFill(date.getSeconds())
weekday = @locale[@settings.lang].weekdays[date.getDay()]
day = @zeroFill(date.getDate())
month = @locale[@settings.lang].months[date.getMonth()]
year = date.getFullYear()
return {
suffix: suffix
hours: hours
minutes: minutes
seconds: seconds
weekday: weekday
day: day
month: month
year: year
}
| true | ###
----------------------------------------------------------------
Fancy DateTime - v1.0.0
Uebersicht-widget for displaying the current time and date
PI:NAME:<NAME>END_PI 'codeFareith' PI:NAME:<NAME>END_PI
PI:EMAIL:<EMAIL>END_PI
https://github.com/codefareith
----------------------------------------------------------------
###
# Widget Settings
settings =
lang: 'de'
militaryTime: true
colors:
default: 'rgba(0, 0, 0, .75)'
accent: 'rgba(255, 255, 255, .75)'
background: 'rgba(255, 255, 255, .1)'
shadows:
box: '0 0 1.25em rgba(0, 0, 0, .5)'
text: '0 0 0.625em rgba(0, 0, 0, .25)'
# Locale Strings
locale =
en:
weekdays: [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
months: [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December'
]
de:
weekdays: [
'Sonntag'
'Montag'
'Dienstag'
'Mittwoch'
'Donnerstag'
'Freitag'
'Samstag'
]
months: [
'Januar'
'Februar'
'März'
'April'
'Mai'
'Juni'
'Juli'
'August'
'September'
'Oktober'
'November'
'Dezember'
]
jp:
weekdays: [
'日曜日'
'月曜日'
'火曜日'
'水曜日'
'木曜日'
'金曜日'
'土曜日'
]
months: [
'1月'
'2月'
'3月'
'4月'
'5月'
'6月'
'7月'
'8月'
'9月'
'10月'
'11月'
'12月'
]
command: ""
settings: settings
locale: locale
refreshFrequency: 1000
style: """
top: 45%
left: 50%
font-family: 'Ubuntu', sans-serif
font-size: 16px
line-height: 1
text-transform: uppercase
transform: translate(-50%, -50%)
.container
position: relative
display: table
height: 100%
padding: 1rem 2rem
border-radius: 1rem
background: #{ settings.colors.background }
box-shadow: #{ settings.shadows.box }
text-shadow: #{ settings.shadows.text }
overflow: hidden
-webkit-backdrop-filter: blur(10px)
.cell
position: relative
display: table-cell
vertical-align: middle
overflow: hidden
.left
float: left
.txt-default
color: #{ settings.colors.default }
.txt-accent
color: #{ settings.colors.accent }
.txt-small
font-size: 2rem
font-weight: 500
.txt-large
font-size: 7rem
font-weight: 700
.divider
display: block
width: 1rem
height: 100%
margin: 0 1rem
background: #{ settings.colors.accent }
box-shadow: #{ settings.shadows.text }
"""
render: () -> """
<div class='container'>
<div class='cell'>
<span class='hours txt-default txt-large left'></span>
<span class='minutes txt-accent txt-large left'></span>
<span class='suffix txt-default txt-small'></span>
</div>
<div class='cell'>
<span class='divider'></span>
</div>
<div class='cell txt-small'>
<span class='weekday txt-accent'></span>
<div class='txt-default'>
<span class='day'></span>
<span>|</span>
<span class='month'></span>
</div>
<span class='year txt-accent'></span>
</div>
</div>
"""
afterRender: (domEl) ->
update: (output, domEl) ->
date = @getDate()
$(domEl).find('.hours').text(date.hours)
$(domEl).find('.minutes').text(date.minutes)
$(domEl).find('.suffix').text(date.suffix)
$(domEl).find('.weekday').text(date.weekday)
$(domEl).find('.day').text(date.day)
$(domEl).find('.month').text(date.month)
$(domEl).find('.year').text(date.year)
# Helper-Functions
zeroFill: (value) ->
return ('0' + value).slice(-2)
getDate: () ->
date = new Date()
hour = date.getHours()
suffix = (if (hour >= 12) then 'pm' else 'am') if (@settings.militaryTime is false)
hour = (hour % 12 || 12) if (@settings.militaryTime is false)
hours = @zeroFill(hour);
minutes = @zeroFill(date.getMinutes())
seconds = @zeroFill(date.getSeconds())
weekday = @locale[@settings.lang].weekdays[date.getDay()]
day = @zeroFill(date.getDate())
month = @locale[@settings.lang].months[date.getMonth()]
year = date.getFullYear()
return {
suffix: suffix
hours: hours
minutes: minutes
seconds: seconds
weekday: weekday
day: day
month: month
year: year
}
|
[
{
"context": "\n\n\n#\n# * jquery.closestchild 0.1.1\n# *\n# * Author: Andrey Mikhaylov aka lolmaus\n# * Email: lolmaus@gmail.com\n# *\n#\n\n$",
"end": 3078,
"score": 0.9998400211334229,
"start": 3062,
"tag": "NAME",
"value": "Andrey Mikhaylov"
},
{
"context": "stchild 0.1.1\n# *\n# * Author: Andrey Mikhaylov aka lolmaus\n# * Email: lolmaus@gmail.com\n# *\n#\n\n$.fn.closestC",
"end": 3090,
"score": 0.9995858669281006,
"start": 3083,
"tag": "USERNAME",
"value": "lolmaus"
},
{
"context": " * Author: Andrey Mikhaylov aka lolmaus\n# * Email: lolmaus@gmail.com\n# *\n#\n\n$.fn.closestChild = (selector) ->\n $child",
"end": 3119,
"score": 0.9999316930770874,
"start": 3102,
"tag": "EMAIL",
"value": "lolmaus@gmail.com"
}
] | lib/assets/javascripts/nested_form_fields.js.coffee | Publidata/nested_form_fields | 0 | window.nested_form_fields or= {}
nested_form_fields.bind_nested_forms_links = () ->
$('body').off("click", '.add_nested_fields_link')
$('body').on 'click', '.add_nested_fields_link', (event, additional_data) ->
$link = $(this)
object_class = $link.data('object-class')
association_path = $link.data('association-path')
added_index = $(".nested_#{association_path}").length
$.event.trigger("fields_adding.nested_form_fields",{object_class: object_class, added_index: added_index, association_path: association_path, additional_data: additional_data});
if $link.data('scope')
$template = $("#{$link.data('scope')} ##{association_path}_template")
else
$template = $("##{association_path}_template")
target = $link.data('insert-into')
template_html = $template.html()
# insert association indexes
index_placeholder = "__#{association_path}_index__"
template_html = template_html.replace(new RegExp(index_placeholder,"g"), added_index)
# look for replacements in user defined code and substitute with the index
template_html = template_html.replace(new RegExp("__nested_field_for_replace_with_index__","g"), added_index)
$parsed_template = $(template_html)
if target?
$('#' + target).append($parsed_template)
else
$template.before( $parsed_template )
$parsed_template.trigger("fields_added.nested_form_fields", {object_class: object_class, added_index: added_index, association_path: association_path, event: event, additional_data: additional_data});
false
$('body').off("click", '.remove_nested_fields_link')
$('body').on 'click', '.remove_nested_fields_link', ->
$link = $(this)
return false unless $.rails.allowAction($link)
object_class = $link.data('object-class')
delete_association_field_name = $link.data('delete-association-field-name')
removed_index = parseInt(delete_association_field_name.match('(\\d+\\]\\[_destroy])')[0].match('\\d+')[0])
$.event.trigger("fields_removing.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index });
$nested_fields_container = $link.parents(".nested_fields").first()
delete_field = $nested_fields_container.find("input[type='hidden'][name='#{delete_association_field_name}']")
if delete_field.length > 0
delete_field.val('1')
else
$nested_fields_container.before "<input type='hidden' name='#{delete_association_field_name}' value='1' />"
$nested_fields_container.hide()
$nested_fields_container.find('input[required]:hidden').removeAttr('required')
$nested_fields_container.trigger("fields_removed.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index});
false
$(document).on "page:change turbolinks:load", ->
nested_form_fields.bind_nested_forms_links()
jQuery ->
nested_form_fields.bind_nested_forms_links()
#
# * jquery.closestchild 0.1.1
# *
# * Author: Andrey Mikhaylov aka lolmaus
# * Email: lolmaus@gmail.com
# *
#
$.fn.closestChild = (selector) ->
$children = undefined
$results = undefined
$children = @children()
return $() if $children.length is 0
$results = $children.filter(selector)
if $results.length > 0
$results
else
$children.closestChild selector
| 36361 | window.nested_form_fields or= {}
nested_form_fields.bind_nested_forms_links = () ->
$('body').off("click", '.add_nested_fields_link')
$('body').on 'click', '.add_nested_fields_link', (event, additional_data) ->
$link = $(this)
object_class = $link.data('object-class')
association_path = $link.data('association-path')
added_index = $(".nested_#{association_path}").length
$.event.trigger("fields_adding.nested_form_fields",{object_class: object_class, added_index: added_index, association_path: association_path, additional_data: additional_data});
if $link.data('scope')
$template = $("#{$link.data('scope')} ##{association_path}_template")
else
$template = $("##{association_path}_template")
target = $link.data('insert-into')
template_html = $template.html()
# insert association indexes
index_placeholder = "__#{association_path}_index__"
template_html = template_html.replace(new RegExp(index_placeholder,"g"), added_index)
# look for replacements in user defined code and substitute with the index
template_html = template_html.replace(new RegExp("__nested_field_for_replace_with_index__","g"), added_index)
$parsed_template = $(template_html)
if target?
$('#' + target).append($parsed_template)
else
$template.before( $parsed_template )
$parsed_template.trigger("fields_added.nested_form_fields", {object_class: object_class, added_index: added_index, association_path: association_path, event: event, additional_data: additional_data});
false
$('body').off("click", '.remove_nested_fields_link')
$('body').on 'click', '.remove_nested_fields_link', ->
$link = $(this)
return false unless $.rails.allowAction($link)
object_class = $link.data('object-class')
delete_association_field_name = $link.data('delete-association-field-name')
removed_index = parseInt(delete_association_field_name.match('(\\d+\\]\\[_destroy])')[0].match('\\d+')[0])
$.event.trigger("fields_removing.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index });
$nested_fields_container = $link.parents(".nested_fields").first()
delete_field = $nested_fields_container.find("input[type='hidden'][name='#{delete_association_field_name}']")
if delete_field.length > 0
delete_field.val('1')
else
$nested_fields_container.before "<input type='hidden' name='#{delete_association_field_name}' value='1' />"
$nested_fields_container.hide()
$nested_fields_container.find('input[required]:hidden').removeAttr('required')
$nested_fields_container.trigger("fields_removed.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index});
false
$(document).on "page:change turbolinks:load", ->
nested_form_fields.bind_nested_forms_links()
jQuery ->
nested_form_fields.bind_nested_forms_links()
#
# * jquery.closestchild 0.1.1
# *
# * Author: <NAME> aka lolmaus
# * Email: <EMAIL>
# *
#
$.fn.closestChild = (selector) ->
$children = undefined
$results = undefined
$children = @children()
return $() if $children.length is 0
$results = $children.filter(selector)
if $results.length > 0
$results
else
$children.closestChild selector
| true | window.nested_form_fields or= {}
nested_form_fields.bind_nested_forms_links = () ->
$('body').off("click", '.add_nested_fields_link')
$('body').on 'click', '.add_nested_fields_link', (event, additional_data) ->
$link = $(this)
object_class = $link.data('object-class')
association_path = $link.data('association-path')
added_index = $(".nested_#{association_path}").length
$.event.trigger("fields_adding.nested_form_fields",{object_class: object_class, added_index: added_index, association_path: association_path, additional_data: additional_data});
if $link.data('scope')
$template = $("#{$link.data('scope')} ##{association_path}_template")
else
$template = $("##{association_path}_template")
target = $link.data('insert-into')
template_html = $template.html()
# insert association indexes
index_placeholder = "__#{association_path}_index__"
template_html = template_html.replace(new RegExp(index_placeholder,"g"), added_index)
# look for replacements in user defined code and substitute with the index
template_html = template_html.replace(new RegExp("__nested_field_for_replace_with_index__","g"), added_index)
$parsed_template = $(template_html)
if target?
$('#' + target).append($parsed_template)
else
$template.before( $parsed_template )
$parsed_template.trigger("fields_added.nested_form_fields", {object_class: object_class, added_index: added_index, association_path: association_path, event: event, additional_data: additional_data});
false
$('body').off("click", '.remove_nested_fields_link')
$('body').on 'click', '.remove_nested_fields_link', ->
$link = $(this)
return false unless $.rails.allowAction($link)
object_class = $link.data('object-class')
delete_association_field_name = $link.data('delete-association-field-name')
removed_index = parseInt(delete_association_field_name.match('(\\d+\\]\\[_destroy])')[0].match('\\d+')[0])
$.event.trigger("fields_removing.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index });
$nested_fields_container = $link.parents(".nested_fields").first()
delete_field = $nested_fields_container.find("input[type='hidden'][name='#{delete_association_field_name}']")
if delete_field.length > 0
delete_field.val('1')
else
$nested_fields_container.before "<input type='hidden' name='#{delete_association_field_name}' value='1' />"
$nested_fields_container.hide()
$nested_fields_container.find('input[required]:hidden').removeAttr('required')
$nested_fields_container.trigger("fields_removed.nested_form_fields",{object_class: object_class, delete_association_field_name: delete_association_field_name, removed_index: removed_index});
false
$(document).on "page:change turbolinks:load", ->
nested_form_fields.bind_nested_forms_links()
jQuery ->
nested_form_fields.bind_nested_forms_links()
#
# * jquery.closestchild 0.1.1
# *
# * Author: PI:NAME:<NAME>END_PI aka lolmaus
# * Email: PI:EMAIL:<EMAIL>END_PI
# *
#
$.fn.closestChild = (selector) ->
$children = undefined
$results = undefined
$children = @children()
return $() if $children.length is 0
$results = $children.filter(selector)
if $results.length > 0
$results
else
$children.closestChild selector
|
[
{
"context": "are reporting here\\n' +\n 'https://github.com/Glavin001/atom-beautify/issues/\\n\\n' +\n 'Please follow",
"end": 14310,
"score": 0.9997069239616394,
"start": 14301,
"tag": "USERNAME",
"value": "Glavin001"
},
{
"context": "uidelines found at\\n' +\n 'https://github.com/Glavin001/atom-beautify/blob/master/CONTRIBUTING.md\\n\\n' +\n",
"end": 14438,
"score": 0.9997108578681946,
"start": 14429,
"tag": "USERNAME",
"value": "Glavin001"
},
{
"context": "uages[0]\n # Get language config\n key = \"atom-beautify.#{language.namespace}.beautify_on_save\"\n beauti",
"end": 15687,
"score": 0.9967957735061646,
"start": 15671,
"tag": "KEY",
"value": "atom-beautify.#{"
},
{
"context": "ig\n key = \"atom-beautify.#{language.namespace}.beautify_on_save\"\n beautifyOnSave = atom.config.get(key)\n ",
"end": 15723,
"score": 0.9961925745010376,
"start": 15707,
"tag": "KEY",
"value": "beautify_on_save"
}
] | atom/packages/atom-beautify/src/beautify.coffee | JoshAddington/dotfiles | 0 | # global atom
"use strict"
pkg = require('../package.json')
# Dependencies
plugin = module.exports
{CompositeDisposable} = require 'event-kit'
_ = require("lodash")
Beautifiers = require("./beautifiers")
beautifier = new Beautifiers()
defaultLanguageOptions = beautifier.options
logger = require('./logger')(__filename)
Promise = require('bluebird')
# Lazy loaded dependencies
fs = null
path = require("path")
strip = null
yaml = null
async = null
dir = null # Node-Dir
LoadingView = null
loadingView = null
$ = null
# function cleanOptions(data, types) {
# nopt.clean(data, types);
# return data;
# }
getScrollTop = (editor) ->
view = atom.views.getView(editor)
view.getScrollTop()
setScrollTop = (editor, value) ->
view = atom.views.getView(editor)
view.setScrollTop value
getCursors = (editor) ->
cursors = editor.getCursors()
posArray = []
for cursor in cursors
bufferPosition = cursor.getBufferPosition()
posArray.push [
bufferPosition.row
bufferPosition.column
]
posArray
setCursors = (editor, posArray) ->
# console.log "setCursors:
for bufferPosition, i in posArray
if i is 0
editor.setCursorBufferPosition bufferPosition
continue
editor.addCursorAtBufferPosition bufferPosition
return
# Show beautification progress/loading view
beautifier.on('beautify::start', ->
LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView()
loadingView.show()
)
beautifier.on('beautify::end', ->
loadingView?.hide()
)
# Show error
showError = (error) ->
if not atom.config.get("atom-beautify.general.muteAllErrors")
# console.log(e)
stack = error.stack
detail = error.description or error.message
atom.notifications?.addError(error.message, {
stack, detail, dismissable : true})
beautify = ({editor, onSave}) ->
return new Promise((resolve, reject) ->
plugin.checkUnsupportedOptions()
# Continue beautifying
path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.general.beautifyEntireFileOnSave")
# Get the path to the config file
# All of the options
# Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left.
# Atom Editor
#
# User's Home path
# Project path
# Asynchronously and callback-style
beautifyCompleted = (text) ->
if not text?
# Do nothing, is undefined
# console.log 'beautifyCompleted'
else if text instanceof Error
showError(text)
return reject(text)
else if typeof text is "string"
if oldText isnt text
# console.log "Replacing current editor's text with new text"
posArray = getCursors(editor)
# console.log "posArray:
origScrollTop = getScrollTop(editor)
# console.log "origScrollTop:
if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "selectedBufferRange:
editor.setTextInBufferRange selectedBufferRange, text
else
# console.log "setText"
editor.setText text
# console.log "setCursors"
setCursors editor, posArray
# console.log "Done setCursors"
# Let the scrollTop setting run after all the save related stuff is run,
# otherwise setScrollTop is not working, probably because the cursor
# addition happens asynchronously
setTimeout ( ->
# console.log "setScrollTop"
setScrollTop editor, origScrollTop
return resolve(text)
), 0
else
error = new Error("Unsupported beautification result '#{text}'.")
showError(error)
return reject(error)
# else
# console.log "Already Beautiful!"
return
# console.log 'Beautify time!'
#
# Get current editor
editor = editor ? atom.workspace.getActiveTextEditor()
# Check if there is an active editor
if not editor?
return showError( new Error("Active Editor not found. "
"Please select a Text Editor first to beautify."))
isSelection = !!editor.getSelectedText()
# Get editor path and configurations for paths
editedFilePath = editor.getPath()
# Get all options
allOptions = beautifier.getOptionsForPath(editedFilePath, editor)
# Get current editor's text
text = undefined
if not forceEntireFile and isSelection
text = editor.getSelectedText()
else
text = editor.getText()
oldText = text
# Get Grammar
grammarName = editor.getGrammar().name
# Finally, beautify!
try
beautifier.beautify(text, allOptions, grammarName, editedFilePath, onSave : onSave)
.then(beautifyCompleted)
.catch(beautifyCompleted)
catch e
showError(e)
return
)
beautifyFilePath = (filePath, callback) ->
logger.verbose('beautifyFilePath', filePath)
# Show in progress indicate on file's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.addClass('beautifying')
# Cleanup and return callback function
cb = (err, result) ->
logger.verbose('Cleanup beautifyFilePath', err, result)
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.removeClass('beautifying')
return callback(err, result)
# Get contents of file
fs ?= require "fs"
logger.verbose('readFile', filePath)
fs.readFile(filePath, (err, data) ->
logger.verbose('readFile completed', err, filePath)
return cb(err) if err
input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get the options
allOptions = beautifier.getOptionsForPath(filePath)
logger.verbose('beautifyFilePath allOptions', allOptions)
# Beautify File
completionFun = (output) ->
logger.verbose('beautifyFilePath completionFun', output)
if output instanceof Error
return cb(output, null ) # output == Error
else if typeof output is "string"
# do not allow empty string
if output.trim() is ''
logger.verbose('beautifyFilePath, output was empty string!')
return cb(null, output)
# save to file
fs.writeFile(filePath, output, (err) ->
return cb(err) if err
return cb( null , output)
)
else
return cb( new Error("Unknown beautification result #{output}."), output)
try
logger.verbose('beautify', input, allOptions, grammarName, filePath)
beautifier.beautify(input, allOptions, grammarName, filePath)
.then(completionFun)
.catch(completionFun)
catch e
return cb(e)
)
beautifyFile = ({target}) ->
filePath = target.dataset.path
return unless filePath
beautifyFilePath(filePath, (err, result) ->
return showError(err) if err
# console.log("Beautify File
)
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm(
message: "This will beautify all of the files found \
recursively in this directory, '#{dirPath}'. \
Do you want to continue?",
buttons: ['Yes, continue!','No, cancel!']) isnt 0
# Show in progress indicate on directory's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying')
# Process Directory
dir ?= require "node-dir"
async ?= require "async"
dir.files(dirPath, (err, files) ->
return showError(err) if err
async.each(files, (filePath, callback) ->
# Ignore errors
beautifyFilePath(filePath, -> callback())
, (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath)
)
)
return
debug = () ->
plugin.checkUnsupportedOptions()
# Get current editor
editor = atom.workspace.getActiveTextEditor()
linkifyTitle = (title) ->
title = title.toLowerCase()
p = title.split(/[\s,+#;,\/?:@&=+$]+/) # split into parts
sep = "-"
p.join(sep)
# Check if there is an active editor
if not editor?
return confirm("Active Editor not found.\n" +
"Please select a Text Editor first to beautify.")
return unless confirm('Are you ready to debug Atom Beautify?\n\n' +
'Warning: This will change your current clipboard contents.')
debugInfo = ""
headers = []
tocEl = "<TABLEOFCONTENTS/>"
addInfo = (key, val) ->
if key?
debugInfo += "**#{key}**: #{val}\n\n"
else
debugInfo += "#{val}\n\n"
addHeader = (level, title) ->
debugInfo += "#{Array(level+1).join('#')} #{title}\n\n"
headers.push({
level, title
})
addHeader(1, "Atom Beautify - Debugging information")
debugInfo += "The following debugging information was " +
"generated by `Atom Beautify` on `#{new Date()}`." +
"\n\n---\n\n" +
tocEl +
"\n\n---\n\n"
# Platform
addInfo('Platform', process.platform)
addHeader(2, "Versions")
# Atom Version
addInfo('Atom Version', atom.appVersion)
# Atom Beautify Version
addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Original file
#
# Get editor path and configurations for paths
filePath = editor.getPath()
# Path
addInfo('Original File Path', "`#{filePath}`")
# Get Grammar
grammarName = editor.getGrammar().name
# Grammar
addInfo('Original File Grammar', grammarName)
# Language
language = beautifier.getLanguage(grammarName, filePath)
addInfo('Original File Language', language?.name)
addInfo('Language namespace', language?.namespace)
# Beautifier
beautifiers = beautifier.getBeautifiers(language.name)
addInfo('Supported Beautifiers', _.map(beautifiers, 'name').join(', '))
selectedBeautifier = beautifier.getBeautifierForLanguage(language)
addInfo('Selected Beautifier', selectedBeautifier.name)
# Get current editor's text
text = editor.getText()
# Contents
codeBlockSyntax = (language?.name ? grammarName).toLowerCase().split(' ')[0]
addHeader(3, 'Original File Contents')
addInfo(null, "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(3, 'Package Settings')
addInfo(null,
"The raw package settings options\n" +
"```json\n#{JSON.stringify(atom.config.get('atom-beautify'), undefined, 4)}\n```")
# Beautification Options
addHeader(2, "Beautification options")
# Get all options
allOptions = beautifier.getOptionsForPath(filePath, editor)
# Resolve options with promises
Promise.all(allOptions)
.then((allOptions) ->
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
preTransformedOptions = beautifier.getOptionsForLanguage(allOptions, language)
if selectedBeautifier
finalOptions = beautifier.transformOptions(selectedBeautifier, language.name, preTransformedOptions)
# Show options
# addInfo('All Options', "\n" +
# "All options extracted for file\n" +
# "```json\n#{JSON.stringify(allOptions, undefined, 4)}\n```")
addInfo('Editor Options', "\n" +
"Options from Atom Editor settings\n" +
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
addInfo('Config Options', "\n" +
"Options from Atom Beautify package settings\n" +
"```json\n#{JSON.stringify(configOptions, undefined, 4)}\n```")
addInfo('Home Options', "\n" +
"Options from `#{path.resolve(beautifier.getUserHome(), '.jsbeautifyrc')}`\n" +
"```json\n#{JSON.stringify(homeOptions, undefined, 4)}\n```")
addInfo('EditorConfig Options', "\n" +
"Options from [EditorConfig](http://editorconfig.org/) file\n" +
"```json\n#{JSON.stringify(editorConfigOptions, undefined, 4)}\n```")
addInfo('Project Options', "\n" +
"Options from `.jsbeautifyrc` files starting from directory `#{path.dirname(filePath)}` and going up to root\n" +
"```json\n#{JSON.stringify(projectOptions, undefined, 4)}\n```")
addInfo('Pre-Transformed Options', "\n" +
"Combined options before transforming them given a beautifier's specifications\n" +
"```json\n#{JSON.stringify(preTransformedOptions, undefined, 4)}\n```")
if selectedBeautifier
addHeader(3, 'Final Options')
addInfo(null,
"Final combined and transformed options that are used\n" +
"```json\n#{JSON.stringify(finalOptions, undefined, 4)}\n```")
#
logs = ""
logFilePathRegex = new RegExp('\\: \\[(.*)\\]')
subscription = logger.onLogging((msg) ->
# console.log('logging', msg)
sep = path.sep
logs += msg.replace(logFilePathRegex, (a,b) ->
s = b.split(sep)
i = s.indexOf('atom-beautify')
p = s.slice(i+2).join(sep)
# console.log('logging', arguments, s, i, p)
return ': ['+p+']'
)
)
cb = (result) ->
subscription.dispose()
addHeader(2, "Results")
# Logs
addInfo('Beautified File Contents', "\n```#{codeBlockSyntax}\n#{result}\n```")
# Diff
JsDiff = require('diff')
diff = JsDiff.createPatch(filePath, text, \
result, "original", "beautified")
addInfo('Original vs. Beautified Diff', "\n```#{codeBlockSyntax}\n#{diff}\n```")
addHeader(3, "Logs")
addInfo(null, "```\n#{logs}\n```")
# Build Table of Contents
toc = "## Table Of Contents\n"
for header in headers
###
- Heading 1
- Heading 1.1
###
indent = " " # 2 spaces
bullet = "-"
indentNum = header.level - 2
if indentNum >= 0
toc += ("#{Array(indentNum+1).join(indent)}#{bullet} [#{header.title}](\##{linkifyTitle(header.title)})\n")
# Replace TABLEOFCONTENTS
debugInfo = debugInfo.replace(tocEl, toc)
# Save to clipboard
atom.clipboard.write(debugInfo)
confirm('Atom Beautify debugging information is now in your clipboard.\n' +
'You can now paste this into an Issue you are reporting here\n' +
'https://github.com/Glavin001/atom-beautify/issues/\n\n' +
'Please follow the contribution guidelines found at\n' +
'https://github.com/Glavin001/atom-beautify/blob/master/CONTRIBUTING.md\n\n' +
'Warning: Be sure to look over the debug info before you send it, '+
'to ensure you are not sharing undesirable private information.'
)
try
beautifier.beautify(text, allOptions, grammarName, filePath)
.then(cb)
.catch(cb)
catch e
return cb(e)
)
handleSaveEvent = ->
atom.workspace.observeTextEditors (editor) ->
pendingPaths = {}
beautifyOnSaveHandler = ({path: filePath}) ->
logger.verbose('Should beautify on this save?')
if pendingPaths[filePath]
logger.verbose("Editor with file path #{filePath} already beautified!")
return
buffer = editor.getBuffer()
path ?= require('path')
# Get Grammar
grammar = editor.getGrammar().name
# Get file extension
fileExtension = path.extname(filePath)
# Remove prefix "." (period) in fileExtension
fileExtension = fileExtension.substr(1)
# Get language
languages = beautifier.languages.getLanguages({grammar, extension: fileExtension})
if languages.length < 1
return
# TODO: select appropriate language
language = languages[0]
# Get language config
key = "atom-beautify.#{language.namespace}.beautify_on_save"
beautifyOnSave = atom.config.get(key)
logger.verbose('save editor positions', key, beautifyOnSave)
if beautifyOnSave
logger.verbose('Beautifying file', filePath)
beautify({editor, onSave: true})
.then(() ->
logger.verbose('Done beautifying file', filePath)
if editor.isAlive() is true
logger.verbose('Saving TextEditor...')
# Store the filePath to prevent infinite looping
# When Whitespace package has option "Ensure Single Trailing Newline" enabled
# It will add a newline and keep the file from converging on a beautified form
# and saving without emitting onDidSave event, because there were no changes.
pendingPaths[filePath] = true
editor.save()
delete pendingPaths[filePath]
logger.verbose('Saved TextEditor.')
)
.catch((error) ->
return showError(error)
)
disposable = editor.onDidSave(({path : filePath}) ->
# TODO: Implement debouncing
beautifyOnSaveHandler({path: filePath})
)
plugin.subscriptions.add disposable
getUnsupportedOptions = ->
settings = atom.config.get('atom-beautify')
schema = atom.config.getSchema('atom-beautify')
unsupportedOptions = _.filter(_.keys(settings), (key) ->
# return atom.config.getSchema("atom-beautify.${key}").type
# return typeof settings[key]
schema.properties[key] is undefined
)
return unsupportedOptions
plugin.checkUnsupportedOptions = ->
unsupportedOptions = getUnsupportedOptions()
if unsupportedOptions.length isnt 0
atom.notifications.addWarning("Please run Atom command 'Atom-Beautify: Migrate Settings'.", {
detail : "You can open the Atom command palette with `cmd-shift-p` (OSX) or `ctrl-shift-p` (Linux/Windows) in Atom. You have unsupported options: #{unsupportedOptions.join(', ')}",
dismissable : true
})
plugin.migrateSettings = ->
unsupportedOptions = getUnsupportedOptions()
namespaces = beautifier.languages.namespaces
# console.log('migrate-settings', schema, namespaces, unsupportedOptions)
if unsupportedOptions.length is 0
atom.notifications.addSuccess("No options to migrate.")
else
rex = new RegExp("(#{namespaces.join('|')})_(.*)")
rename = _.toPairs(_.zipObject(unsupportedOptions, _.map(unsupportedOptions, (key) ->
m = key.match(rex)
if m is null
# Did not match
# Put into general
return "general.#{key}"
else
return "#{m[1]}.#{m[2]}"
)))
# console.log('rename', rename)
# logger.verbose('rename', rename)
# Move all option values to renamed key
_.each(rename, ([key, newKey]) ->
# Copy to new key
val = atom.config.get("atom-beautify.#{key}")
# console.log('rename', key, newKey, val)
atom.config.set("atom-beautify.#{newKey}", val)
# Delete old key
atom.config.set("atom-beautify.#{key}", undefined)
)
atom.notifications.addSuccess("Successfully migrated options: #{unsupportedOptions.join(', ')}")
plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions)
plugin.activate = ->
@subscriptions = new CompositeDisposable
@subscriptions.add handleSaveEvent()
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:beautify-editor", beautify
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:help-debug-editor", debug
@subscriptions.add atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
@subscriptions.add atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:migrate-settings", plugin.migrateSettings
plugin.deactivate = ->
@subscriptions.dispose()
| 136650 | # global atom
"use strict"
pkg = require('../package.json')
# Dependencies
plugin = module.exports
{CompositeDisposable} = require 'event-kit'
_ = require("lodash")
Beautifiers = require("./beautifiers")
beautifier = new Beautifiers()
defaultLanguageOptions = beautifier.options
logger = require('./logger')(__filename)
Promise = require('bluebird')
# Lazy loaded dependencies
fs = null
path = require("path")
strip = null
yaml = null
async = null
dir = null # Node-Dir
LoadingView = null
loadingView = null
$ = null
# function cleanOptions(data, types) {
# nopt.clean(data, types);
# return data;
# }
getScrollTop = (editor) ->
view = atom.views.getView(editor)
view.getScrollTop()
setScrollTop = (editor, value) ->
view = atom.views.getView(editor)
view.setScrollTop value
getCursors = (editor) ->
cursors = editor.getCursors()
posArray = []
for cursor in cursors
bufferPosition = cursor.getBufferPosition()
posArray.push [
bufferPosition.row
bufferPosition.column
]
posArray
setCursors = (editor, posArray) ->
# console.log "setCursors:
for bufferPosition, i in posArray
if i is 0
editor.setCursorBufferPosition bufferPosition
continue
editor.addCursorAtBufferPosition bufferPosition
return
# Show beautification progress/loading view
beautifier.on('beautify::start', ->
LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView()
loadingView.show()
)
beautifier.on('beautify::end', ->
loadingView?.hide()
)
# Show error
showError = (error) ->
if not atom.config.get("atom-beautify.general.muteAllErrors")
# console.log(e)
stack = error.stack
detail = error.description or error.message
atom.notifications?.addError(error.message, {
stack, detail, dismissable : true})
beautify = ({editor, onSave}) ->
return new Promise((resolve, reject) ->
plugin.checkUnsupportedOptions()
# Continue beautifying
path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.general.beautifyEntireFileOnSave")
# Get the path to the config file
# All of the options
# Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left.
# Atom Editor
#
# User's Home path
# Project path
# Asynchronously and callback-style
beautifyCompleted = (text) ->
if not text?
# Do nothing, is undefined
# console.log 'beautifyCompleted'
else if text instanceof Error
showError(text)
return reject(text)
else if typeof text is "string"
if oldText isnt text
# console.log "Replacing current editor's text with new text"
posArray = getCursors(editor)
# console.log "posArray:
origScrollTop = getScrollTop(editor)
# console.log "origScrollTop:
if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "selectedBufferRange:
editor.setTextInBufferRange selectedBufferRange, text
else
# console.log "setText"
editor.setText text
# console.log "setCursors"
setCursors editor, posArray
# console.log "Done setCursors"
# Let the scrollTop setting run after all the save related stuff is run,
# otherwise setScrollTop is not working, probably because the cursor
# addition happens asynchronously
setTimeout ( ->
# console.log "setScrollTop"
setScrollTop editor, origScrollTop
return resolve(text)
), 0
else
error = new Error("Unsupported beautification result '#{text}'.")
showError(error)
return reject(error)
# else
# console.log "Already Beautiful!"
return
# console.log 'Beautify time!'
#
# Get current editor
editor = editor ? atom.workspace.getActiveTextEditor()
# Check if there is an active editor
if not editor?
return showError( new Error("Active Editor not found. "
"Please select a Text Editor first to beautify."))
isSelection = !!editor.getSelectedText()
# Get editor path and configurations for paths
editedFilePath = editor.getPath()
# Get all options
allOptions = beautifier.getOptionsForPath(editedFilePath, editor)
# Get current editor's text
text = undefined
if not forceEntireFile and isSelection
text = editor.getSelectedText()
else
text = editor.getText()
oldText = text
# Get Grammar
grammarName = editor.getGrammar().name
# Finally, beautify!
try
beautifier.beautify(text, allOptions, grammarName, editedFilePath, onSave : onSave)
.then(beautifyCompleted)
.catch(beautifyCompleted)
catch e
showError(e)
return
)
beautifyFilePath = (filePath, callback) ->
logger.verbose('beautifyFilePath', filePath)
# Show in progress indicate on file's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.addClass('beautifying')
# Cleanup and return callback function
cb = (err, result) ->
logger.verbose('Cleanup beautifyFilePath', err, result)
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.removeClass('beautifying')
return callback(err, result)
# Get contents of file
fs ?= require "fs"
logger.verbose('readFile', filePath)
fs.readFile(filePath, (err, data) ->
logger.verbose('readFile completed', err, filePath)
return cb(err) if err
input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get the options
allOptions = beautifier.getOptionsForPath(filePath)
logger.verbose('beautifyFilePath allOptions', allOptions)
# Beautify File
completionFun = (output) ->
logger.verbose('beautifyFilePath completionFun', output)
if output instanceof Error
return cb(output, null ) # output == Error
else if typeof output is "string"
# do not allow empty string
if output.trim() is ''
logger.verbose('beautifyFilePath, output was empty string!')
return cb(null, output)
# save to file
fs.writeFile(filePath, output, (err) ->
return cb(err) if err
return cb( null , output)
)
else
return cb( new Error("Unknown beautification result #{output}."), output)
try
logger.verbose('beautify', input, allOptions, grammarName, filePath)
beautifier.beautify(input, allOptions, grammarName, filePath)
.then(completionFun)
.catch(completionFun)
catch e
return cb(e)
)
beautifyFile = ({target}) ->
filePath = target.dataset.path
return unless filePath
beautifyFilePath(filePath, (err, result) ->
return showError(err) if err
# console.log("Beautify File
)
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm(
message: "This will beautify all of the files found \
recursively in this directory, '#{dirPath}'. \
Do you want to continue?",
buttons: ['Yes, continue!','No, cancel!']) isnt 0
# Show in progress indicate on directory's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying')
# Process Directory
dir ?= require "node-dir"
async ?= require "async"
dir.files(dirPath, (err, files) ->
return showError(err) if err
async.each(files, (filePath, callback) ->
# Ignore errors
beautifyFilePath(filePath, -> callback())
, (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath)
)
)
return
debug = () ->
plugin.checkUnsupportedOptions()
# Get current editor
editor = atom.workspace.getActiveTextEditor()
linkifyTitle = (title) ->
title = title.toLowerCase()
p = title.split(/[\s,+#;,\/?:@&=+$]+/) # split into parts
sep = "-"
p.join(sep)
# Check if there is an active editor
if not editor?
return confirm("Active Editor not found.\n" +
"Please select a Text Editor first to beautify.")
return unless confirm('Are you ready to debug Atom Beautify?\n\n' +
'Warning: This will change your current clipboard contents.')
debugInfo = ""
headers = []
tocEl = "<TABLEOFCONTENTS/>"
addInfo = (key, val) ->
if key?
debugInfo += "**#{key}**: #{val}\n\n"
else
debugInfo += "#{val}\n\n"
addHeader = (level, title) ->
debugInfo += "#{Array(level+1).join('#')} #{title}\n\n"
headers.push({
level, title
})
addHeader(1, "Atom Beautify - Debugging information")
debugInfo += "The following debugging information was " +
"generated by `Atom Beautify` on `#{new Date()}`." +
"\n\n---\n\n" +
tocEl +
"\n\n---\n\n"
# Platform
addInfo('Platform', process.platform)
addHeader(2, "Versions")
# Atom Version
addInfo('Atom Version', atom.appVersion)
# Atom Beautify Version
addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Original file
#
# Get editor path and configurations for paths
filePath = editor.getPath()
# Path
addInfo('Original File Path', "`#{filePath}`")
# Get Grammar
grammarName = editor.getGrammar().name
# Grammar
addInfo('Original File Grammar', grammarName)
# Language
language = beautifier.getLanguage(grammarName, filePath)
addInfo('Original File Language', language?.name)
addInfo('Language namespace', language?.namespace)
# Beautifier
beautifiers = beautifier.getBeautifiers(language.name)
addInfo('Supported Beautifiers', _.map(beautifiers, 'name').join(', '))
selectedBeautifier = beautifier.getBeautifierForLanguage(language)
addInfo('Selected Beautifier', selectedBeautifier.name)
# Get current editor's text
text = editor.getText()
# Contents
codeBlockSyntax = (language?.name ? grammarName).toLowerCase().split(' ')[0]
addHeader(3, 'Original File Contents')
addInfo(null, "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(3, 'Package Settings')
addInfo(null,
"The raw package settings options\n" +
"```json\n#{JSON.stringify(atom.config.get('atom-beautify'), undefined, 4)}\n```")
# Beautification Options
addHeader(2, "Beautification options")
# Get all options
allOptions = beautifier.getOptionsForPath(filePath, editor)
# Resolve options with promises
Promise.all(allOptions)
.then((allOptions) ->
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
preTransformedOptions = beautifier.getOptionsForLanguage(allOptions, language)
if selectedBeautifier
finalOptions = beautifier.transformOptions(selectedBeautifier, language.name, preTransformedOptions)
# Show options
# addInfo('All Options', "\n" +
# "All options extracted for file\n" +
# "```json\n#{JSON.stringify(allOptions, undefined, 4)}\n```")
addInfo('Editor Options', "\n" +
"Options from Atom Editor settings\n" +
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
addInfo('Config Options', "\n" +
"Options from Atom Beautify package settings\n" +
"```json\n#{JSON.stringify(configOptions, undefined, 4)}\n```")
addInfo('Home Options', "\n" +
"Options from `#{path.resolve(beautifier.getUserHome(), '.jsbeautifyrc')}`\n" +
"```json\n#{JSON.stringify(homeOptions, undefined, 4)}\n```")
addInfo('EditorConfig Options', "\n" +
"Options from [EditorConfig](http://editorconfig.org/) file\n" +
"```json\n#{JSON.stringify(editorConfigOptions, undefined, 4)}\n```")
addInfo('Project Options', "\n" +
"Options from `.jsbeautifyrc` files starting from directory `#{path.dirname(filePath)}` and going up to root\n" +
"```json\n#{JSON.stringify(projectOptions, undefined, 4)}\n```")
addInfo('Pre-Transformed Options', "\n" +
"Combined options before transforming them given a beautifier's specifications\n" +
"```json\n#{JSON.stringify(preTransformedOptions, undefined, 4)}\n```")
if selectedBeautifier
addHeader(3, 'Final Options')
addInfo(null,
"Final combined and transformed options that are used\n" +
"```json\n#{JSON.stringify(finalOptions, undefined, 4)}\n```")
#
logs = ""
logFilePathRegex = new RegExp('\\: \\[(.*)\\]')
subscription = logger.onLogging((msg) ->
# console.log('logging', msg)
sep = path.sep
logs += msg.replace(logFilePathRegex, (a,b) ->
s = b.split(sep)
i = s.indexOf('atom-beautify')
p = s.slice(i+2).join(sep)
# console.log('logging', arguments, s, i, p)
return ': ['+p+']'
)
)
cb = (result) ->
subscription.dispose()
addHeader(2, "Results")
# Logs
addInfo('Beautified File Contents', "\n```#{codeBlockSyntax}\n#{result}\n```")
# Diff
JsDiff = require('diff')
diff = JsDiff.createPatch(filePath, text, \
result, "original", "beautified")
addInfo('Original vs. Beautified Diff', "\n```#{codeBlockSyntax}\n#{diff}\n```")
addHeader(3, "Logs")
addInfo(null, "```\n#{logs}\n```")
# Build Table of Contents
toc = "## Table Of Contents\n"
for header in headers
###
- Heading 1
- Heading 1.1
###
indent = " " # 2 spaces
bullet = "-"
indentNum = header.level - 2
if indentNum >= 0
toc += ("#{Array(indentNum+1).join(indent)}#{bullet} [#{header.title}](\##{linkifyTitle(header.title)})\n")
# Replace TABLEOFCONTENTS
debugInfo = debugInfo.replace(tocEl, toc)
# Save to clipboard
atom.clipboard.write(debugInfo)
confirm('Atom Beautify debugging information is now in your clipboard.\n' +
'You can now paste this into an Issue you are reporting here\n' +
'https://github.com/Glavin001/atom-beautify/issues/\n\n' +
'Please follow the contribution guidelines found at\n' +
'https://github.com/Glavin001/atom-beautify/blob/master/CONTRIBUTING.md\n\n' +
'Warning: Be sure to look over the debug info before you send it, '+
'to ensure you are not sharing undesirable private information.'
)
try
beautifier.beautify(text, allOptions, grammarName, filePath)
.then(cb)
.catch(cb)
catch e
return cb(e)
)
handleSaveEvent = ->
atom.workspace.observeTextEditors (editor) ->
pendingPaths = {}
beautifyOnSaveHandler = ({path: filePath}) ->
logger.verbose('Should beautify on this save?')
if pendingPaths[filePath]
logger.verbose("Editor with file path #{filePath} already beautified!")
return
buffer = editor.getBuffer()
path ?= require('path')
# Get Grammar
grammar = editor.getGrammar().name
# Get file extension
fileExtension = path.extname(filePath)
# Remove prefix "." (period) in fileExtension
fileExtension = fileExtension.substr(1)
# Get language
languages = beautifier.languages.getLanguages({grammar, extension: fileExtension})
if languages.length < 1
return
# TODO: select appropriate language
language = languages[0]
# Get language config
key = "<KEY>language.namespace}.<KEY>"
beautifyOnSave = atom.config.get(key)
logger.verbose('save editor positions', key, beautifyOnSave)
if beautifyOnSave
logger.verbose('Beautifying file', filePath)
beautify({editor, onSave: true})
.then(() ->
logger.verbose('Done beautifying file', filePath)
if editor.isAlive() is true
logger.verbose('Saving TextEditor...')
# Store the filePath to prevent infinite looping
# When Whitespace package has option "Ensure Single Trailing Newline" enabled
# It will add a newline and keep the file from converging on a beautified form
# and saving without emitting onDidSave event, because there were no changes.
pendingPaths[filePath] = true
editor.save()
delete pendingPaths[filePath]
logger.verbose('Saved TextEditor.')
)
.catch((error) ->
return showError(error)
)
disposable = editor.onDidSave(({path : filePath}) ->
# TODO: Implement debouncing
beautifyOnSaveHandler({path: filePath})
)
plugin.subscriptions.add disposable
getUnsupportedOptions = ->
settings = atom.config.get('atom-beautify')
schema = atom.config.getSchema('atom-beautify')
unsupportedOptions = _.filter(_.keys(settings), (key) ->
# return atom.config.getSchema("atom-beautify.${key}").type
# return typeof settings[key]
schema.properties[key] is undefined
)
return unsupportedOptions
plugin.checkUnsupportedOptions = ->
unsupportedOptions = getUnsupportedOptions()
if unsupportedOptions.length isnt 0
atom.notifications.addWarning("Please run Atom command 'Atom-Beautify: Migrate Settings'.", {
detail : "You can open the Atom command palette with `cmd-shift-p` (OSX) or `ctrl-shift-p` (Linux/Windows) in Atom. You have unsupported options: #{unsupportedOptions.join(', ')}",
dismissable : true
})
plugin.migrateSettings = ->
unsupportedOptions = getUnsupportedOptions()
namespaces = beautifier.languages.namespaces
# console.log('migrate-settings', schema, namespaces, unsupportedOptions)
if unsupportedOptions.length is 0
atom.notifications.addSuccess("No options to migrate.")
else
rex = new RegExp("(#{namespaces.join('|')})_(.*)")
rename = _.toPairs(_.zipObject(unsupportedOptions, _.map(unsupportedOptions, (key) ->
m = key.match(rex)
if m is null
# Did not match
# Put into general
return "general.#{key}"
else
return "#{m[1]}.#{m[2]}"
)))
# console.log('rename', rename)
# logger.verbose('rename', rename)
# Move all option values to renamed key
_.each(rename, ([key, newKey]) ->
# Copy to new key
val = atom.config.get("atom-beautify.#{key}")
# console.log('rename', key, newKey, val)
atom.config.set("atom-beautify.#{newKey}", val)
# Delete old key
atom.config.set("atom-beautify.#{key}", undefined)
)
atom.notifications.addSuccess("Successfully migrated options: #{unsupportedOptions.join(', ')}")
plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions)
plugin.activate = ->
@subscriptions = new CompositeDisposable
@subscriptions.add handleSaveEvent()
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:beautify-editor", beautify
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:help-debug-editor", debug
@subscriptions.add atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
@subscriptions.add atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:migrate-settings", plugin.migrateSettings
plugin.deactivate = ->
@subscriptions.dispose()
| true | # global atom
"use strict"
pkg = require('../package.json')
# Dependencies
plugin = module.exports
{CompositeDisposable} = require 'event-kit'
_ = require("lodash")
Beautifiers = require("./beautifiers")
beautifier = new Beautifiers()
defaultLanguageOptions = beautifier.options
logger = require('./logger')(__filename)
Promise = require('bluebird')
# Lazy loaded dependencies
fs = null
path = require("path")
strip = null
yaml = null
async = null
dir = null # Node-Dir
LoadingView = null
loadingView = null
$ = null
# function cleanOptions(data, types) {
# nopt.clean(data, types);
# return data;
# }
getScrollTop = (editor) ->
view = atom.views.getView(editor)
view.getScrollTop()
setScrollTop = (editor, value) ->
view = atom.views.getView(editor)
view.setScrollTop value
getCursors = (editor) ->
cursors = editor.getCursors()
posArray = []
for cursor in cursors
bufferPosition = cursor.getBufferPosition()
posArray.push [
bufferPosition.row
bufferPosition.column
]
posArray
setCursors = (editor, posArray) ->
# console.log "setCursors:
for bufferPosition, i in posArray
if i is 0
editor.setCursorBufferPosition bufferPosition
continue
editor.addCursorAtBufferPosition bufferPosition
return
# Show beautification progress/loading view
beautifier.on('beautify::start', ->
LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView()
loadingView.show()
)
beautifier.on('beautify::end', ->
loadingView?.hide()
)
# Show error
showError = (error) ->
if not atom.config.get("atom-beautify.general.muteAllErrors")
# console.log(e)
stack = error.stack
detail = error.description or error.message
atom.notifications?.addError(error.message, {
stack, detail, dismissable : true})
beautify = ({editor, onSave}) ->
return new Promise((resolve, reject) ->
plugin.checkUnsupportedOptions()
# Continue beautifying
path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.general.beautifyEntireFileOnSave")
# Get the path to the config file
# All of the options
# Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left.
# Atom Editor
#
# User's Home path
# Project path
# Asynchronously and callback-style
beautifyCompleted = (text) ->
if not text?
# Do nothing, is undefined
# console.log 'beautifyCompleted'
else if text instanceof Error
showError(text)
return reject(text)
else if typeof text is "string"
if oldText isnt text
# console.log "Replacing current editor's text with new text"
posArray = getCursors(editor)
# console.log "posArray:
origScrollTop = getScrollTop(editor)
# console.log "origScrollTop:
if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "selectedBufferRange:
editor.setTextInBufferRange selectedBufferRange, text
else
# console.log "setText"
editor.setText text
# console.log "setCursors"
setCursors editor, posArray
# console.log "Done setCursors"
# Let the scrollTop setting run after all the save related stuff is run,
# otherwise setScrollTop is not working, probably because the cursor
# addition happens asynchronously
setTimeout ( ->
# console.log "setScrollTop"
setScrollTop editor, origScrollTop
return resolve(text)
), 0
else
error = new Error("Unsupported beautification result '#{text}'.")
showError(error)
return reject(error)
# else
# console.log "Already Beautiful!"
return
# console.log 'Beautify time!'
#
# Get current editor
editor = editor ? atom.workspace.getActiveTextEditor()
# Check if there is an active editor
if not editor?
return showError( new Error("Active Editor not found. "
"Please select a Text Editor first to beautify."))
isSelection = !!editor.getSelectedText()
# Get editor path and configurations for paths
editedFilePath = editor.getPath()
# Get all options
allOptions = beautifier.getOptionsForPath(editedFilePath, editor)
# Get current editor's text
text = undefined
if not forceEntireFile and isSelection
text = editor.getSelectedText()
else
text = editor.getText()
oldText = text
# Get Grammar
grammarName = editor.getGrammar().name
# Finally, beautify!
try
beautifier.beautify(text, allOptions, grammarName, editedFilePath, onSave : onSave)
.then(beautifyCompleted)
.catch(beautifyCompleted)
catch e
showError(e)
return
)
beautifyFilePath = (filePath, callback) ->
logger.verbose('beautifyFilePath', filePath)
# Show in progress indicate on file's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.addClass('beautifying')
# Cleanup and return callback function
cb = (err, result) ->
logger.verbose('Cleanup beautifyFilePath', err, result)
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.removeClass('beautifying')
return callback(err, result)
# Get contents of file
fs ?= require "fs"
logger.verbose('readFile', filePath)
fs.readFile(filePath, (err, data) ->
logger.verbose('readFile completed', err, filePath)
return cb(err) if err
input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get the options
allOptions = beautifier.getOptionsForPath(filePath)
logger.verbose('beautifyFilePath allOptions', allOptions)
# Beautify File
completionFun = (output) ->
logger.verbose('beautifyFilePath completionFun', output)
if output instanceof Error
return cb(output, null ) # output == Error
else if typeof output is "string"
# do not allow empty string
if output.trim() is ''
logger.verbose('beautifyFilePath, output was empty string!')
return cb(null, output)
# save to file
fs.writeFile(filePath, output, (err) ->
return cb(err) if err
return cb( null , output)
)
else
return cb( new Error("Unknown beautification result #{output}."), output)
try
logger.verbose('beautify', input, allOptions, grammarName, filePath)
beautifier.beautify(input, allOptions, grammarName, filePath)
.then(completionFun)
.catch(completionFun)
catch e
return cb(e)
)
beautifyFile = ({target}) ->
filePath = target.dataset.path
return unless filePath
beautifyFilePath(filePath, (err, result) ->
return showError(err) if err
# console.log("Beautify File
)
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm(
message: "This will beautify all of the files found \
recursively in this directory, '#{dirPath}'. \
Do you want to continue?",
buttons: ['Yes, continue!','No, cancel!']) isnt 0
# Show in progress indicate on directory's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying')
# Process Directory
dir ?= require "node-dir"
async ?= require "async"
dir.files(dirPath, (err, files) ->
return showError(err) if err
async.each(files, (filePath, callback) ->
# Ignore errors
beautifyFilePath(filePath, -> callback())
, (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath)
)
)
return
debug = () ->
plugin.checkUnsupportedOptions()
# Get current editor
editor = atom.workspace.getActiveTextEditor()
linkifyTitle = (title) ->
title = title.toLowerCase()
p = title.split(/[\s,+#;,\/?:@&=+$]+/) # split into parts
sep = "-"
p.join(sep)
# Check if there is an active editor
if not editor?
return confirm("Active Editor not found.\n" +
"Please select a Text Editor first to beautify.")
return unless confirm('Are you ready to debug Atom Beautify?\n\n' +
'Warning: This will change your current clipboard contents.')
debugInfo = ""
headers = []
tocEl = "<TABLEOFCONTENTS/>"
addInfo = (key, val) ->
if key?
debugInfo += "**#{key}**: #{val}\n\n"
else
debugInfo += "#{val}\n\n"
addHeader = (level, title) ->
debugInfo += "#{Array(level+1).join('#')} #{title}\n\n"
headers.push({
level, title
})
addHeader(1, "Atom Beautify - Debugging information")
debugInfo += "The following debugging information was " +
"generated by `Atom Beautify` on `#{new Date()}`." +
"\n\n---\n\n" +
tocEl +
"\n\n---\n\n"
# Platform
addInfo('Platform', process.platform)
addHeader(2, "Versions")
# Atom Version
addInfo('Atom Version', atom.appVersion)
# Atom Beautify Version
addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Original file
#
# Get editor path and configurations for paths
filePath = editor.getPath()
# Path
addInfo('Original File Path', "`#{filePath}`")
# Get Grammar
grammarName = editor.getGrammar().name
# Grammar
addInfo('Original File Grammar', grammarName)
# Language
language = beautifier.getLanguage(grammarName, filePath)
addInfo('Original File Language', language?.name)
addInfo('Language namespace', language?.namespace)
# Beautifier
beautifiers = beautifier.getBeautifiers(language.name)
addInfo('Supported Beautifiers', _.map(beautifiers, 'name').join(', '))
selectedBeautifier = beautifier.getBeautifierForLanguage(language)
addInfo('Selected Beautifier', selectedBeautifier.name)
# Get current editor's text
text = editor.getText()
# Contents
codeBlockSyntax = (language?.name ? grammarName).toLowerCase().split(' ')[0]
addHeader(3, 'Original File Contents')
addInfo(null, "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(3, 'Package Settings')
addInfo(null,
"The raw package settings options\n" +
"```json\n#{JSON.stringify(atom.config.get('atom-beautify'), undefined, 4)}\n```")
# Beautification Options
addHeader(2, "Beautification options")
# Get all options
allOptions = beautifier.getOptionsForPath(filePath, editor)
# Resolve options with promises
Promise.all(allOptions)
.then((allOptions) ->
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
preTransformedOptions = beautifier.getOptionsForLanguage(allOptions, language)
if selectedBeautifier
finalOptions = beautifier.transformOptions(selectedBeautifier, language.name, preTransformedOptions)
# Show options
# addInfo('All Options', "\n" +
# "All options extracted for file\n" +
# "```json\n#{JSON.stringify(allOptions, undefined, 4)}\n```")
addInfo('Editor Options', "\n" +
"Options from Atom Editor settings\n" +
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
addInfo('Config Options', "\n" +
"Options from Atom Beautify package settings\n" +
"```json\n#{JSON.stringify(configOptions, undefined, 4)}\n```")
addInfo('Home Options', "\n" +
"Options from `#{path.resolve(beautifier.getUserHome(), '.jsbeautifyrc')}`\n" +
"```json\n#{JSON.stringify(homeOptions, undefined, 4)}\n```")
addInfo('EditorConfig Options', "\n" +
"Options from [EditorConfig](http://editorconfig.org/) file\n" +
"```json\n#{JSON.stringify(editorConfigOptions, undefined, 4)}\n```")
addInfo('Project Options', "\n" +
"Options from `.jsbeautifyrc` files starting from directory `#{path.dirname(filePath)}` and going up to root\n" +
"```json\n#{JSON.stringify(projectOptions, undefined, 4)}\n```")
addInfo('Pre-Transformed Options', "\n" +
"Combined options before transforming them given a beautifier's specifications\n" +
"```json\n#{JSON.stringify(preTransformedOptions, undefined, 4)}\n```")
if selectedBeautifier
addHeader(3, 'Final Options')
addInfo(null,
"Final combined and transformed options that are used\n" +
"```json\n#{JSON.stringify(finalOptions, undefined, 4)}\n```")
#
logs = ""
logFilePathRegex = new RegExp('\\: \\[(.*)\\]')
subscription = logger.onLogging((msg) ->
# console.log('logging', msg)
sep = path.sep
logs += msg.replace(logFilePathRegex, (a,b) ->
s = b.split(sep)
i = s.indexOf('atom-beautify')
p = s.slice(i+2).join(sep)
# console.log('logging', arguments, s, i, p)
return ': ['+p+']'
)
)
cb = (result) ->
subscription.dispose()
addHeader(2, "Results")
# Logs
addInfo('Beautified File Contents', "\n```#{codeBlockSyntax}\n#{result}\n```")
# Diff
JsDiff = require('diff')
diff = JsDiff.createPatch(filePath, text, \
result, "original", "beautified")
addInfo('Original vs. Beautified Diff', "\n```#{codeBlockSyntax}\n#{diff}\n```")
addHeader(3, "Logs")
addInfo(null, "```\n#{logs}\n```")
# Build Table of Contents
toc = "## Table Of Contents\n"
for header in headers
###
- Heading 1
- Heading 1.1
###
indent = " " # 2 spaces
bullet = "-"
indentNum = header.level - 2
if indentNum >= 0
toc += ("#{Array(indentNum+1).join(indent)}#{bullet} [#{header.title}](\##{linkifyTitle(header.title)})\n")
# Replace TABLEOFCONTENTS
debugInfo = debugInfo.replace(tocEl, toc)
# Save to clipboard
atom.clipboard.write(debugInfo)
confirm('Atom Beautify debugging information is now in your clipboard.\n' +
'You can now paste this into an Issue you are reporting here\n' +
'https://github.com/Glavin001/atom-beautify/issues/\n\n' +
'Please follow the contribution guidelines found at\n' +
'https://github.com/Glavin001/atom-beautify/blob/master/CONTRIBUTING.md\n\n' +
'Warning: Be sure to look over the debug info before you send it, '+
'to ensure you are not sharing undesirable private information.'
)
try
beautifier.beautify(text, allOptions, grammarName, filePath)
.then(cb)
.catch(cb)
catch e
return cb(e)
)
handleSaveEvent = ->
atom.workspace.observeTextEditors (editor) ->
pendingPaths = {}
beautifyOnSaveHandler = ({path: filePath}) ->
logger.verbose('Should beautify on this save?')
if pendingPaths[filePath]
logger.verbose("Editor with file path #{filePath} already beautified!")
return
buffer = editor.getBuffer()
path ?= require('path')
# Get Grammar
grammar = editor.getGrammar().name
# Get file extension
fileExtension = path.extname(filePath)
# Remove prefix "." (period) in fileExtension
fileExtension = fileExtension.substr(1)
# Get language
languages = beautifier.languages.getLanguages({grammar, extension: fileExtension})
if languages.length < 1
return
# TODO: select appropriate language
language = languages[0]
# Get language config
key = "PI:KEY:<KEY>END_PIlanguage.namespace}.PI:KEY:<KEY>END_PI"
beautifyOnSave = atom.config.get(key)
logger.verbose('save editor positions', key, beautifyOnSave)
if beautifyOnSave
logger.verbose('Beautifying file', filePath)
beautify({editor, onSave: true})
.then(() ->
logger.verbose('Done beautifying file', filePath)
if editor.isAlive() is true
logger.verbose('Saving TextEditor...')
# Store the filePath to prevent infinite looping
# When Whitespace package has option "Ensure Single Trailing Newline" enabled
# It will add a newline and keep the file from converging on a beautified form
# and saving without emitting onDidSave event, because there were no changes.
pendingPaths[filePath] = true
editor.save()
delete pendingPaths[filePath]
logger.verbose('Saved TextEditor.')
)
.catch((error) ->
return showError(error)
)
disposable = editor.onDidSave(({path : filePath}) ->
# TODO: Implement debouncing
beautifyOnSaveHandler({path: filePath})
)
plugin.subscriptions.add disposable
getUnsupportedOptions = ->
settings = atom.config.get('atom-beautify')
schema = atom.config.getSchema('atom-beautify')
unsupportedOptions = _.filter(_.keys(settings), (key) ->
# return atom.config.getSchema("atom-beautify.${key}").type
# return typeof settings[key]
schema.properties[key] is undefined
)
return unsupportedOptions
plugin.checkUnsupportedOptions = ->
unsupportedOptions = getUnsupportedOptions()
if unsupportedOptions.length isnt 0
atom.notifications.addWarning("Please run Atom command 'Atom-Beautify: Migrate Settings'.", {
detail : "You can open the Atom command palette with `cmd-shift-p` (OSX) or `ctrl-shift-p` (Linux/Windows) in Atom. You have unsupported options: #{unsupportedOptions.join(', ')}",
dismissable : true
})
plugin.migrateSettings = ->
unsupportedOptions = getUnsupportedOptions()
namespaces = beautifier.languages.namespaces
# console.log('migrate-settings', schema, namespaces, unsupportedOptions)
if unsupportedOptions.length is 0
atom.notifications.addSuccess("No options to migrate.")
else
rex = new RegExp("(#{namespaces.join('|')})_(.*)")
rename = _.toPairs(_.zipObject(unsupportedOptions, _.map(unsupportedOptions, (key) ->
m = key.match(rex)
if m is null
# Did not match
# Put into general
return "general.#{key}"
else
return "#{m[1]}.#{m[2]}"
)))
# console.log('rename', rename)
# logger.verbose('rename', rename)
# Move all option values to renamed key
_.each(rename, ([key, newKey]) ->
# Copy to new key
val = atom.config.get("atom-beautify.#{key}")
# console.log('rename', key, newKey, val)
atom.config.set("atom-beautify.#{newKey}", val)
# Delete old key
atom.config.set("atom-beautify.#{key}", undefined)
)
atom.notifications.addSuccess("Successfully migrated options: #{unsupportedOptions.join(', ')}")
plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions)
plugin.activate = ->
@subscriptions = new CompositeDisposable
@subscriptions.add handleSaveEvent()
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:beautify-editor", beautify
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:help-debug-editor", debug
@subscriptions.add atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
@subscriptions.add atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory
@subscriptions.add atom.commands.add "atom-workspace", "atom-beautify:migrate-settings", plugin.migrateSettings
plugin.deactivate = ->
@subscriptions.dispose()
|
[
{
"context": "is.UserProvisioning\n token:\n access: 'fake access token'\n @up.retry_options = {minTimeout",
"end": 3691,
"score": 0.6413123607635498,
"start": 3687,
"tag": "KEY",
"value": "fake"
},
{
"context": "user'\n id: '1234567890'\n primaryEmail: 'george@domain.org'\n name: { givenName: 'George', familyName: '",
"end": 5175,
"score": 0.9999149441719055,
"start": 5158,
"tag": "EMAIL",
"value": "george@domain.org"
},
{
"context": "il: 'george@domain.org'\n name: { givenName: 'George', familyName: 'Washington', fullName: 'George Was",
"end": 5209,
"score": 0.9998425245285034,
"start": 5203,
"tag": "NAME",
"value": "George"
},
{
"context": "'\n name: { givenName: 'George', familyName: 'Washington', fullName: 'George Washington' }\n isAdmin: ",
"end": 5235,
"score": 0.9986287355422974,
"start": 5225,
"tag": "NAME",
"value": "Washington"
},
{
"context": "e: 'George', familyName: 'Washington', fullName: 'George Washington' }\n isAdmin: false\n isDelegatedAdmin: f",
"end": 5266,
"score": 0.9998230934143066,
"start": 5249,
"tag": "NAME",
"value": "George Washington"
},
{
"context": " ipWhitelisted: false\n emails: [{address: \"george@domain.org\", primary: true}]\n customerId: 'fake_custome",
"end": 5574,
"score": 0.9999117255210876,
"start": 5557,
"tag": "EMAIL",
"value": "george@domain.org"
},
{
"context": "dy =\n users: [\n { name: { givenName: \"George\", familyName: \"Washington\", fullName: \"George Was",
"end": 6525,
"score": 0.9998272061347961,
"start": 6519,
"tag": "NAME",
"value": "George"
},
{
"context": " { name: { givenName: \"George\", familyName: \"Washington\", fullName: \"George Washington\" } }\n { nam",
"end": 6551,
"score": 0.9986593723297119,
"start": 6541,
"tag": "NAME",
"value": "Washington"
},
{
"context": "e: \"George\", familyName: \"Washington\", fullName: \"George Washington\" } }\n { name: { givenName: \"Lhamo\", family",
"end": 6582,
"score": 0.9998244643211365,
"start": 6565,
"tag": "NAME",
"value": "George Washington"
},
{
"context": "rge Washington\" } }\n { name: { givenName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub",
"end": 6623,
"score": 0.9997969269752502,
"start": 6618,
"tag": "NAME",
"value": "Lhamo"
},
{
"context": " { name: { givenName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub\" } }\n ]\n nex",
"end": 6646,
"score": 0.9995412230491638,
"start": 6639,
"tag": "NAME",
"value": "Dondrub"
},
{
"context": "nName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub\" } }\n ]\n nextPageToken: \"next_page\"\n ",
"end": 6673,
"score": 0.9998125433921814,
"start": 6660,
"tag": "NAME",
"value": "Lhamo Dondrub"
},
{
"context": "#user'\n id: '987654321'\n primaryEmail: 'betsyross@domain.org'\n name: { givenName: 'Betsy', familyName: 'R",
"end": 7207,
"score": 0.9999136328697205,
"start": 7187,
"tag": "EMAIL",
"value": "betsyross@domain.org"
},
{
"context": " 'betsyross@domain.org'\n name: { givenName: 'Betsy', familyName: 'Ross', fullName: 'Betsy Ross' }\n ",
"end": 7240,
"score": 0.9997730255126953,
"start": 7235,
"tag": "NAME",
"value": "Betsy"
},
{
"context": "g'\n name: { givenName: 'Betsy', familyName: 'Ross', fullName: 'Betsy Ross' }\n isAdmin: false\n ",
"end": 7260,
"score": 0.999495267868042,
"start": 7256,
"tag": "NAME",
"value": "Ross"
},
{
"context": "ivenName: 'Betsy', familyName: 'Ross', fullName: 'Betsy Ross' }\n isAdmin: false\n isDelegatedAdmin: f",
"end": 7284,
"score": 0.9997493028640747,
"start": 7274,
"tag": "NAME",
"value": "Betsy Ross"
},
{
"context": " ipWhitelisted: false\n emails: [ { address: 'betsyross@domain.org', primary: true } ]\n customerId: 'fake_custo",
"end": 7597,
"score": 0.99989914894104,
"start": 7577,
"tag": "EMAIL",
"value": "betsyross@domain.org"
},
{
"context": "dy =\n users: [\n { name: { givenName: \"George\", familyName: \"Washington\", fullName: \"George Was",
"end": 8274,
"score": 0.999517560005188,
"start": 8268,
"tag": "NAME",
"value": "George"
},
{
"context": " { name: { givenName: \"George\", familyName: \"Washington\", fullName: \"George Washington\" } }\n { nam",
"end": 8300,
"score": 0.9984617829322815,
"start": 8290,
"tag": "NAME",
"value": "Washington"
},
{
"context": "e: \"George\", familyName: \"Washington\", fullName: \"George Washington\" } }\n { name: { givenName: \"Lhamo\", family",
"end": 8331,
"score": 0.9997076392173767,
"start": 8314,
"tag": "NAME",
"value": "George Washington"
},
{
"context": "rge Washington\" } }\n { name: { givenName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub",
"end": 8372,
"score": 0.9997281432151794,
"start": 8367,
"tag": "NAME",
"value": "Lhamo"
},
{
"context": " { name: { givenName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub\" } }\n ]\n nex",
"end": 8395,
"score": 0.9995103478431702,
"start": 8388,
"tag": "NAME",
"value": "Dondrub"
},
{
"context": "nName: \"Lhamo\", familyName: \"Dondrub\", fullName: \"Lhamo Dondrub\" } }\n ]\n nextPageToken: \"next_page\"\n ",
"end": 8422,
"score": 0.9997720718383789,
"start": 8409,
"tag": "NAME",
"value": "Lhamo Dondrub"
},
{
"context": "one) ->\n post_body =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersec",
"end": 8877,
"score": 0.9987115859985352,
"start": 8871,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": " =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n ",
"end": 8899,
"score": 0.9985529184341431,
"start": 8892,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": " \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n res",
"end": 8943,
"score": 0.9992357492446899,
"start": 8919,
"tag": "PASSWORD",
"value": "supersecurepassword12345"
},
{
"context": ": \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n resp_body =\n kind: \"admin#directory#use",
"end": 8984,
"score": 0.9999203681945801,
"start": 8966,
"tag": "EMAIL",
"value": "mgandhi@domain.org"
},
{
"context": "user\"\n id: \"1234567890\"\n primaryEmail: \"mgandhi@domain.org\"\n name: { givenName: \"Mahatma\", familyName: ",
"end": 9099,
"score": 0.9999198317527771,
"start": 9081,
"tag": "EMAIL",
"value": "mgandhi@domain.org"
},
{
"context": "l: \"mgandhi@domain.org\"\n name: { givenName: \"Mahatma\", familyName: \"Gandhi\" }\n isAdmin: false\n ",
"end": 9134,
"score": 0.9996337890625,
"start": 9127,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": "\n name: { givenName: \"Mahatma\", familyName: \"Gandhi\" }\n isAdmin: false\n isDelegatedAdmin: f",
"end": 9156,
"score": 0.9994441866874695,
"start": 9150,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": "is user\n post_body =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersec",
"end": 9774,
"score": 0.9967835545539856,
"start": 9768,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": " =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n ",
"end": 9796,
"score": 0.9962529540061951,
"start": 9789,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": " \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n err",
"end": 9840,
"score": 0.9993478059768677,
"start": 9816,
"tag": "PASSWORD",
"value": "supersecurepassword12345"
},
{
"context": ": \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n error =\n error:\n errors: [ { dom",
"end": 9881,
"score": 0.9998970031738281,
"start": 9863,
"tag": "EMAIL",
"value": "mgandhi@domain.org"
},
{
"context": "one) ->\n post_body =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersec",
"end": 10411,
"score": 0.9909805655479431,
"start": 10405,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": " =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n ",
"end": 10433,
"score": 0.9852317571640015,
"start": 10426,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": " \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n res",
"end": 10477,
"score": 0.9993622303009033,
"start": 10453,
"tag": "PASSWORD",
"value": "supersecurepassword12345"
},
{
"context": ": \"supersecurepassword12345\"\n primaryEmail: \"mgandhi@domain.org\"\n resp_body =\n id: \"1234567890\"\n pri",
"end": 10518,
"score": 0.9999025464057922,
"start": 10500,
"tag": "EMAIL",
"value": "mgandhi@domain.org"
},
{
"context": "ody =\n id: \"1234567890\"\n primaryEmail: \"mgandhi@domain.org\"\n name: { givenName: \"Mahatma\", familyName: ",
"end": 10598,
"score": 0.9998984336853027,
"start": 10580,
"tag": "EMAIL",
"value": "mgandhi@domain.org"
},
{
"context": "l: \"mgandhi@domain.org\"\n name: { givenName: \"Mahatma\", familyName: \"Gandhi\" }\n nock('https://www.go",
"end": 10633,
"score": 0.9991676807403564,
"start": 10626,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": "\n name: { givenName: \"Mahatma\", familyName: \"Gandhi\" }\n nock('https://www.googleapis.com:443').per",
"end": 10655,
"score": 0.9978218078613281,
"start": 10649,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": "one) ->\n post_body =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersec",
"end": 11039,
"score": 0.9939712882041931,
"start": 11033,
"tag": "NAME",
"value": "Gandhi"
},
{
"context": " =\n name: {familyName: \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n ",
"end": 11061,
"score": 0.9972778558731079,
"start": 11054,
"tag": "NAME",
"value": "Mahatma"
},
{
"context": " \"Gandhi\", givenName: \"Mahatma\"}\n password: \"supersecurepassword12345\"\n @up.insert post_body, (err, data) ->\n a",
"end": 11105,
"score": 0.9993749856948853,
"start": 11081,
"tag": "PASSWORD",
"value": "supersecurepassword12345"
},
{
"context": "r', (done) ->\n req_body = {name: {familyName: 'Thatcher', givenName: 'Margaret'}}\n resp_body =\n k",
"end": 11347,
"score": 0.9936404228210449,
"start": 11339,
"tag": "NAME",
"value": "Thatcher"
},
{
"context": "ody = {name: {familyName: 'Thatcher', givenName: 'Margaret'}}\n resp_body =\n kind: \"admin#directory#u",
"end": 11370,
"score": 0.9929892420768738,
"start": 11362,
"tag": "NAME",
"value": "Margaret"
},
{
"context": "user\"\n id: \"1234567890\"\n primaryEmail: \"mthatcher@domain.org\"\n name: { givenName: \"Margaret\", familyName:",
"end": 11489,
"score": 0.9999105334281921,
"start": 11469,
"tag": "EMAIL",
"value": "mthatcher@domain.org"
},
{
"context": " \"mthatcher@domain.org\"\n name: { givenName: \"Margaret\", familyName: \"Thatcher\" }\n isAdmin: false\n ",
"end": 11525,
"score": 0.9998064041137695,
"start": 11517,
"tag": "NAME",
"value": "Margaret"
},
{
"context": " name: { givenName: \"Margaret\", familyName: \"Thatcher\" }\n isAdmin: false\n isDelegatedAdmin: f",
"end": 11549,
"score": 0.9985327124595642,
"start": 11541,
"tag": "NAME",
"value": "Thatcher"
},
{
"context": " ipWhitelisted: false\n emails: [{ address: \"mthatcher@domain.org\", primary: true }]\n customerId: \"fake_custom",
"end": 11861,
"score": 0.999905526638031,
"start": 11841,
"tag": "EMAIL",
"value": "mthatcher@domain.org"
},
{
"context": "user'\n id: '1234567890'\n primaryEmail: 'newemail@domain.org'\n name: {givenName: 'Benjamin', familyName: ",
"end": 12905,
"score": 0.9999113082885742,
"start": 12886,
"tag": "EMAIL",
"value": "newemail@domain.org"
},
{
"context": "l: 'newemail@domain.org'\n name: {givenName: 'Benjamin', familyName: 'Newlastname', fullName: 'Benjamin ",
"end": 12940,
"score": 0.9998196959495544,
"start": 12932,
"tag": "NAME",
"value": "Benjamin"
},
{
"context": "\n name: {givenName: 'Benjamin', familyName: 'Newlastname', fullName: 'Benjamin Newlastname' }\n isAdmi",
"end": 12967,
"score": 0.9994291067123413,
"start": 12956,
"tag": "NAME",
"value": "Newlastname"
},
{
"context": "'Benjamin', familyName: 'Newlastname', fullName: 'Benjamin Newlastname' }\n isAdmin: false\n isDelegatedAdmin: f",
"end": 13001,
"score": 0.9998338222503662,
"start": 12981,
"tag": "NAME",
"value": "Benjamin Newlastname"
},
{
"context": " ipWhitelisted: false\n emails: [ { address: 'newemail@domain.org', type: 'custom', primary: true } ]\n custome",
"end": 13313,
"score": 0.9999133944511414,
"start": 13294,
"tag": "EMAIL",
"value": "newemail@domain.org"
},
{
"context": " patch_body =\n name:\n familyName: 'Newlastname'\n primaryEmail: 'newemail@domain.org'\n no",
"end": 13537,
"score": 0.9995139837265015,
"start": 13526,
"tag": "NAME",
"value": "Newlastname"
},
{
"context": " familyName: 'Newlastname'\n primaryEmail: 'newemail@domain.org'\n nock('https://www.googleapis.com:443').persi",
"end": 13579,
"score": 0.9999071955680847,
"start": 13560,
"tag": "EMAIL",
"value": "newemail@domain.org"
},
{
"context": "s, cb', (done) ->\n body =\n primaryEmail: 'newemail@domain.org'\n name:\n givenName: 'George'\n ",
"end": 13941,
"score": 0.9999096989631653,
"start": 13922,
"tag": "EMAIL",
"value": "newemail@domain.org"
},
{
"context": "email@domain.org'\n name:\n givenName: 'George'\n familyName: 'Newlastname'\n fullNa",
"end": 13981,
"score": 0.9998121857643127,
"start": 13975,
"tag": "NAME",
"value": "George"
},
{
"context": "\n givenName: 'George'\n familyName: 'Newlastname'\n fullName: 'George Newlastname'\n nock(",
"end": 14015,
"score": 0.9996278882026672,
"start": 14004,
"tag": "NAME",
"value": "Newlastname"
},
{
"context": " familyName: 'Newlastname'\n fullName: 'George Newlastname'\n nock('https://www.googleapis.com:443').persi",
"end": 14054,
"score": 0.9998267292976379,
"start": 14036,
"tag": "NAME",
"value": "George Newlastname"
},
{
"context": "->\n ou_path = \"OrgUnitName\"\n customer_id = \"customer_123\"\n\n mock_endpoint = nock('https://www.googleapi",
"end": 17246,
"score": 0.9662035703659058,
"start": 17234,
"tag": "USERNAME",
"value": "customer_123"
},
{
"context": " kind: 'admin#directory#orgUnit'\n name: 'Schoolname'\n orgUnitPath: '/Students/SchoolName'\n ",
"end": 20586,
"score": 0.7233831286430359,
"start": 20580,
"tag": "NAME",
"value": "School"
},
{
"context": "\n parentOrgUnitPath: '/'\n\n customer_id = \"fake_customer_id\"\n\n nock('https://www.googleapis.com",
"end": 21457,
"score": 0.5610688924789429,
"start": 21452,
"tag": "USERNAME",
"value": "fake_"
},
{
"context": "OrgUnitPath: '/'\n\n customer_id = \"fake_customer_id\"\n\n nock('https://www.googleapis.com')\n ",
"end": 21465,
"score": 0.5212814211845398,
"start": 21465,
"tag": "USERNAME",
"value": ""
},
{
"context": "s an OrgUnit', (done) ->\n patch_body = {name: 'UpdatedName'}\n body =\n kind: 'admin#directory#orgUnit",
"end": 27520,
"score": 0.9185932874679565,
"start": 27509,
"tag": "NAME",
"value": "UpdatedName"
},
{
"context": " kind: 'admin#directory#orgUnit'\n name: 'UpdatedName'\n orgUnitPath: '/UpdatedName'\n parentOr",
"end": 27596,
"score": 0.9190936088562012,
"start": 27585,
"tag": "NAME",
"value": "UpdatedName"
},
{
"context": "ial response', (done) ->\n patch_body = {name: 'UpdatedName'}\n body =\n name: 'UpdatedName'\n orgU",
"end": 28063,
"score": 0.8745288848876953,
"start": 28052,
"tag": "NAME",
"value": "UpdatedName"
},
{
"context": "y = {name: 'UpdatedName'}\n body =\n name: 'UpdatedName'\n orgUnitPath: '/UpdatedName'\n nock('http",
"end": 28101,
"score": 0.9219957590103149,
"start": 28090,
"tag": "NAME",
"value": "UpdatedName"
},
{
"context": "ith no patch_body', (done) ->\n body = { name: 'UpdateThisName' }\n nock('https://www.googleapis.com:443').per",
"end": 28568,
"score": 0.7903615832328796,
"start": 28554,
"tag": "PASSWORD",
"value": "UpdateThisName"
},
{
"context": "groups: [{\n id: 'abcd1234'\n email: 'group1@domain.org',\n name: 'Group1',\n description: 't",
"end": 30928,
"score": 0.999627411365509,
"start": 30911,
"tag": "EMAIL",
"value": "group1@domain.org"
},
{
"context": "rectory#group'\n id: 'abcd1234'\n email: 'group1@domain.org'\n name: 'Group1'\n description: 'the fir",
"end": 32474,
"score": 0.9998612999916077,
"start": 32457,
"tag": "EMAIL",
"value": "group1@domain.org"
},
{
"context": "id'\n body =\n id: 'abcd1234'\n email: 'newgroup@domain.org'\n description: 'new test group'\n properti",
"end": 33388,
"score": 0.9999173283576965,
"start": 33369,
"tag": "EMAIL",
"value": "newgroup@domain.org"
},
{
"context": ": 'new test group'\n properties =\n email: 'newgroup@domain.org'\n description: 'new test group'\n nock('ht",
"end": 33476,
"score": 0.9999176859855652,
"start": 33457,
"tag": "EMAIL",
"value": "newgroup@domain.org"
},
{
"context": " resp_body =\n id: 'abcd1234'\n email: 'group1@domain.org'\n name: 'Updated group'\n description: '",
"end": 35526,
"score": 0.9999068379402161,
"start": 35509,
"tag": "EMAIL",
"value": "group1@domain.org"
}
] | test/google.coffee | Clever/node-google-admin-sdk | 11 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
# There are 3 large test suites in this file:
# describe 'UserProvisioning'
# describe 'OrgUnitProvisioning'
# describe 'GroupProvisioning'
before ->
nock.disableNetConnect()
beforeEach ->
nock.cleanAll()
describe 'Retry', ->
before ->
@retry_count = 5
@up = new google_apis.UserProvisioning
token:
access: 'fake access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: @retry_count, randomize: true}
# The following 2 test verifies that @up.get is indeed retrying for @retry_count times.
# Including the initial request, there are retry_count + 1 total requests.
it "retries for `retry_count` times but nocked for `(retry_count + 1)` times", (done) ->
# Nock out all requests with failure
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count + 1).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err, 'FAIL'
done()
it 'retries for retry_count times and nocked for retry_count times', (done) ->
# Nock out all but last request with failure, so that on the (retry_count + 1)th request,
# it attempts to make a real http request.
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err.name, 'NetConnectNotAllowedError'
assert.equal err.message, 'Nock: Not allow net connect for "www.googleapis.com:443"'
done()
describe 'oauth2_request', ->
it 'does not deadlock with request_refresh_token if no refresh token', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(400, 'no refresh from google')
request_nock = nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234')
.reply(401, 'go request token refresh')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, dontcare) ->
refresh_nock.done()
request_nock.done()
assert.equal err, 'no refresh from google'
done()
it 'does not deadlock with request_refresh_token if genuinely invalid credentials', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(200, 'okay, here you go')
request_nock = nock('https://www.googleapis.com:443')
.get('/admin/directory/v1/users/1234').reply(401, 'go request token refresh')
.get('/admin/directory/v1/users/1234').reply(401, 'nope, genuinely invalid credentials')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, resp, body) ->
refresh_nock.done()
request_nock.done()
assert.equal resp.statusCode, 401
assert.equal body, 'nope, genuinely invalid credentials'
done()
describe 'UserProvisioning', ()->
before ->
@up = new google_apis.UserProvisioning
token:
access: 'fake access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'requires domain, client_id, client_secret upon construction', (done) ->
assert.throws () ->
new google_apis.UserProvisioning()
, Error
done()
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@up.get 12345, (err, data) ->
assert.equal err.toString(), 'Error: UserProvisioning::get requires (String userkey, [callback])'
cb_wf()
(cb_wf) =>
@up.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::insert expected (Object body, [callback])"
cb_wf()
(cb_wf) =>
@up.list 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::list requires (Object params, [callback])"
cb_wf()
(cb_wf) =>
@up.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::patch expected (String userkey, [Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@up.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::delete expected (String userkey, [callback])"
cb_wf()
], done
## GET ##
it 'can get user by id', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: 'george@domain.org'
name: { givenName: 'George', familyName: 'Washington', fullName: 'George Washington' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-02-20T21:29:18.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{address: "george@domain.org", primary: true}]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/1234567890')
.reply(200, body)
@up.get '1234567890', (err, data) ->
assert.ifError err
assert.deepEqual data, body
done()
it '404s when making get with bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/12345')
.reply(404, body)
@up.get '12345', (err, data) ->
assert.deepEqual err, body
done()
## LIST ##
it 'gets partial response for field argument', (done) ->
body =
users: [
{ name: { givenName: "George", familyName: "Washington", fullName: "George Washington" } }
{ name: { givenName: "Lhamo", familyName: "Dondrub", fullName: "Lhamo Dondrub" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=users%2Fname%2C%20nextPageToken')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name, nextPageToken'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets users that match a query', (done) ->
user =
kind: 'admin#directory#user'
id: '987654321'
primaryEmail: 'betsyross@domain.org'
name: { givenName: 'Betsy', familyName: 'Ross', fullName: 'Betsy Ross' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-25T17:01:23.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: 'betsyross@domain.org', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
body =
kind: 'admin#directory#users'
users: [user]
nextPageToken: 'next_page'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=1&query=email%3Abetsy*')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 1, query: 'email:betsy*'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets paging info even when not explicitly requested', (done) ->
body =
users: [
{ name: { givenName: "George", familyName: "Washington", fullName: "George Washington" } }
{ name: { givenName: "Lhamo", familyName: "Dondrub", fullName: "Lhamo Dondrub" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=nextPageToken%2Cusers%2Fname')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name'}, (err, data) ->
assert.deepEqual data, body
done()
## INSERT ##
it 'creates a user', (done) ->
post_body =
name: {familyName: "Gandhi", givenName: "Mahatma"}
password: "supersecurepassword12345"
primaryEmail: "mgandhi@domain.org"
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "mgandhi@domain.org"
name: { givenName: "Mahatma", familyName: "Gandhi" }
isAdmin: false
isDelegatedAdmin: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: false
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, (err, data) ->
assert.deepEqual data, resp_body
done()
## INSERT, and FAIL ##
it 'sends a "Domain User Limit" when their domain has its max number of users', (done) ->
# Lets pretend the domain is already at its user limit when we try to create this user
post_body =
name: {familyName: "Gandhi", givenName: "Mahatma"}
password: "supersecurepassword12345"
primaryEmail: "mgandhi@domain.org"
error =
error:
errors: [ { domain: 'global', reason: 'DomainUserLimitExceeded', message: 'Domain user limit exceeded.' } ]
code: 412
message: 'Domain user limit exceeded.'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(412, error)
@up.insert post_body, (err, data) ->
assert.deepEqual error, err
done()
it 'creates a user and returns a partial response', (done) ->
post_body =
name: {familyName: "Gandhi", givenName: "Mahatma"}
password: "supersecurepassword12345"
primaryEmail: "mgandhi@domain.org"
resp_body =
id: "1234567890"
primaryEmail: "mgandhi@domain.org"
name: { givenName: "Mahatma", familyName: "Gandhi" }
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, 'name,primaryEmail,id', (err, data) ->
assert.deepEqual data, resp_body
done()
it 'returns an error when trying to create a user without a required field', (done) ->
post_body =
name: {familyName: "Gandhi", givenName: "Mahatma"}
password: "supersecurepassword12345"
@up.insert post_body, (err, data) ->
assert.equal(err.toString(), "Error: UserProvisioning::insert requires 'primaryEmail'")
done()
## PATCH ##
it 'updates a user', (done) ->
req_body = {name: {familyName: 'Thatcher', givenName: 'Margaret'}}
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "mthatcher@domain.org"
name: { givenName: "Margaret", familyName: "Thatcher" }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{ address: "mthatcher@domain.org", primary: true }]
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/1234567890', req_body)
.reply(200, resp_body)
@up.patch '1234567890', req_body, (err, data) ->
assert.deepEqual resp_body, data
done()
it '404s when updating with a bad userkey', (done) ->
req_body = {}
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/12345', req_body)
.reply(404, body)
@up.patch '12345', req_body, (err, data) ->
assert.deepEqual err, body
done()
it 'can correctly call patch with userkey, body, cb', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: 'newemail@domain.org'
name: {givenName: 'Benjamin', familyName: 'Newlastname', fullName: 'Benjamin Newlastname' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-26T03:39:52.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: 'newemail@domain.org', type: 'custom', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
patch_body =
name:
familyName: 'Newlastname'
primaryEmail: 'newemail@domain.org'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890', patch_body)
.reply(200, body)
@up.patch '1234567890', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'can correctly call patch with userkey, fields, cb', (done) ->
body =
primaryEmail: 'newemail@domain.org'
name:
givenName: 'George'
familyName: 'Newlastname'
fullName: 'George Newlastname'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890?fields=name%2CprimaryEmail')
.reply(200, body)
@up.patch '1234567890', 'name,primaryEmail', (err, data) ->
assert.deepEqual data, body
done()
## DELETE ##
it 'deletes a user', (done) ->
body = {204: "Operation success"}
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/1234567890')
.reply(204, body)
@up.delete '1234567890', (err, data) ->
assert.deepEqual data, body
done()
it '404s when deleting a user with a bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/12345')
.reply(404, body)
@up.delete '12345', (err, data) ->
assert.deepEqual err, body
done()
describe 'OrgUnitProvisioning', ()->
ou_not_found =
error:
errors: []
code: 404,
message: "Org unit not found"
beforeEach ->
@ou = new google_apis.OrgUnitProvisioning
token:
access: 'access_token'
@ou.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@ou.get 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::get expected (String customer_id, String org_unit_path, [, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::insert expected (String customer_id, Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.list 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::list expected (String customer_id[, Object params, callback])"
cb_wf()
(cb_wf) =>
@ou.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::patch expected (String customer_id, String org_unit_path, [Object patch_body, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::delete expected (String customer_id, String org_unit_path[, callback])"
cb_wf()
], done
it 'can get an OrgUnit', (done) ->
body =
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', (err, data) ->
assert.deepEqual data, body
done()
## get_children
it 'get_children makes a request to the right endpoint', (done) ->
ou_path = "OrgUnitName"
customer_id = "customer_123"
mock_endpoint = nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits?orgUnitPath=#{ou_path}&type=children")
.reply(200, {body: "OK"})
@ou.get_children customer_id, ou_path, (err, data) ->
assert.ifError err
assert.deepEqual data, {body: "OK"}
assert mock_endpoint.isDone()
done()
it 'can get an OrgUnit filtered by fields', (done) ->
body =
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad?fields=name%2Cdescription')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', 'name,description', (err, data) ->
assert.deepEqual data, body
done()
it 'can list all org units for a customer', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: ''
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'Vanilla'
description: ''
orgUnitPath: '/Vanilla'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'ChocolateChipCookieDough'
description: ''
orgUnitPath: '/ChocolateChipCookieDough'
parentOrgUnitPath: '/'
blockInheritance: false
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits')
.reply(200, body)
@ou.list 'fake_customer_id', (err, data) ->
assert.deepEqual data, body
done()
it 'can list an org unit by params', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit1', description: '', orgUnitPath: '/ParentOU/OrgUnit1', parentOrgUnitPath: '/ParentOU', blockInheritance: false },
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit2', description: '', orgUnitPath: '/ParentOU/OrgUnit2', parentOrgUnitPath: '/ParentOU', blockInheritance: false }
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits?orgUnitPath=ParentOU')
.reply(200, body)
@ou.list 'fake_customer_id', {orgUnitPath: 'ParentOU'}, (err, data) ->
assert.deepEqual data, body
done()
it 'returns 400 with bad customer_id', (done) ->
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/asdfasdf/orgunits')
.reply(400, error)
@ou.list 'asdfasdf', (err, data) ->
assert.deepEqual err, error
done()
it 'uses cache for OU lookup', (done) ->
org_unit = ['Students']
first_ou =
kind: 'admin#directory#orgUnit'
name: 'Students'
orgUnitPath: '/Students'
orgUnitId: 'ou_id1'
parentOrgUnitPath: '/'
second_ou =
kind: 'admin#directory#orgUnit'
name: 'Schoolname'
orgUnitPath: '/Students/SchoolName'
orgUnitId: 'ou_id2'
parentOrgUnitPath: '/Students'
cache = {}
cache[first_ou.orgUnitPath] = first_ou
cache[second_ou.orgUnitPath] = second_ou
@ou.findOrCreate 'abcdef', org_unit, cache, (err, parent, returned_cache) ->
# this test is successful if it hits the cache and doesn't trigger nock.disableNetConnect()
assert.ifError err
assert.deepEqual returned_cache, cache
assert.equal parent, '/Students'
done()
it 'findOrCreate properly memoizes calls to get and insert', (done) ->
org_unit = ['TestOU']
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: org_unit[0]
orgUnitPath: "/#{org_unit[0]}"
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
customer_id = "fake_customer_id"
nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits/#{org_unit[0]}")
.times(3)
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post("/admin/directory/v1/customer/#{customer_id}/orgunits", properties)
.reply(200, body)
expected_cache = {}
expected_cache[body.orgUnitPath] = body
# this test is successful if the nock is hit only once, and doesn't trigger nock.disableNetConnect()
# on subsequent requests
async.each [0..100], (i, cb_e) =>
@ou.findOrCreate customer_id, org_unit, {}, (err, parent, returned_cache) ->
assert.ifError err
assert.deepEqual returned_cache, expected_cache
assert.equal parent, '/TestOU'
cb_e()
, done
## INSERT ##
it 'creates an orgunit', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOU'
orgUnitPath: '/TestOU'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an orgunit if it already exists', (done) ->
properties =
name: 'TestOUAlreadyExists'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUAlreadyExists'
orgUnitPath: '/TestOUAlreadyExists'
orgUnitId: 'ou_id_already_exists'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUAlreadyExists')
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUAlreadyExists'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUAlreadyExists': body}
assert.equal parent, '/TestOUAlreadyExists'
done()
it 'creates an orgunit if not found', (done) ->
properties =
name: 'TestOUCreate'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUCreate'
orgUnitPath: '/TestOUCreate'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUCreate')
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUCreate'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUCreate': body}
assert.equal parent, '/TestOUCreate'
insert_nock.done()
done()
it 'creates an orgunit with fields args for partial response', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
fields = 'name, orgUnitPath'
body =
name: 'TestOU'
orgUnitPath: '/TestOU'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits?fields=name%2C%20orgUnitPath', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'fails to create an orgunit when invalid customer_id is given', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/badId/orgunits', properties)
.reply(400, error)
@ou.insert 'badId', properties, (err, data) ->
assert.deepEqual err, error
done()
it 'fails to create an orgunit when required properties are not given', (done) ->
properties =
name: 'TestOU4'
error =
error:
errors: [ { domain: 'global', reason: 'invalid', message: 'Invalid Parent Orgunit Id' } ]
code: 400
message: 'Invalid Parent Orgunit Id'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(400, error)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'deletes an orgunit', (done) ->
body = { 204: 'Operation success' }
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/DeleteThis')
.reply(204, body)
@ou.delete 'fake_customer_id', 'DeleteThis', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to delete a nonexistant an orgunit', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Org unit not found' } ]
code: 404
message: 'Org unit not found'
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/doesnotexist')
.reply(404, error)
@ou.delete 'fake_customer_id', 'doesnotexist', (err, data) ->
assert.deepEqual err, error
done()
## PATCH ##
it 'updates an OrgUnit', (done) ->
patch_body = {name: 'UpdatedName'}
body =
kind: 'admin#directory#orgUnit'
name: 'UpdatedName'
orgUnitPath: '/UpdatedName'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'updates an OrgUnit and returns a partial response', (done) ->
patch_body = {name: 'UpdatedName'}
body =
name: 'UpdatedName'
orgUnitPath: '/UpdatedName'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name%2CorgUnitPath', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, 'name,orgUnitPath', (err, data) ->
assert.deepEqual data, body
done()
it 'can call update with no patch_body', (done) ->
body = { name: 'UpdateThisName' }
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name')
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual data, body
done()
it 'update returns an error when called with an invalid customer_id', (done) ->
error =
errors: [ { domain: 'global', reason: 'authError', message: 'Invalid Credentials', locationType: 'header', location: 'Authorization' } ]
code: 401
message: 'Invalid Credentials'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/bad_id/orgunits/UpdateThisName?fields=name')
.reply(401, error)
@ou.patch 'bad_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual err, error
done()
describe 'GroupProvisioning', ()->
before ->
@gp = new google_apis.GroupProvisioning
token:
access: 'fake_access_token'
@gp.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@gp.get 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::get expected (String group_key[, callback])"
cb_wf()
(cb_wf) =>
@gp.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::insert expected (Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.list 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list expected (Object params[, callback])"
cb_wf()
(cb_wf) =>
@gp.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, callback])"
cb_wf()
], done
## LIST ##
it 'lists groups for a domain', (done) ->
body =
kind: 'admin#directory#groups'
groups: [{
id: 'abcd1234'
email: 'group1@domain.org',
name: 'Group1',
description: 'the first group'
}]
nextPageToken: 'next_page'
params =
domain: 'domain.org'
maxResults: 1
fields: 'groups(description,email,id,name),kind,nextPageToken'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=domain.org&maxResults=1&fields=groups(description%2Cemail%2Cid%2Cname)%2Ckind%2CnextPageToken')
.reply(200, body)
@gp.list params, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when an invalid param is given', (done) ->
params =
domain: 'domain.org'
maxResults: 1
unknown_field: true
@gp.list params, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list invalid param 'unknown_field'"
done()
it 'returns 404 for a valid parameter that doesn not exist', (done) ->
params =
domain: 'badexample.com'
maxResults: 1
error =
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: badexample.com' } ]
code: 404
message: 'Resource Not Found: badexample.com'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=badexample.com&maxResults=1')
.reply(404, error)
@gp.list params, (err, data) ->
assert.deepEqual err, error
done()
## GET ##
it 'can get group by group_key', (done) ->
body =
kind: 'admin#directory#group'
id: 'abcd1234'
email: 'group1@domain.org'
name: 'Group1'
description: 'the first group'
adminCreated: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/groups/abcd1234')
.reply(200, body)
@gp.get 'abcd1234', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to get a group by invalid group_key', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups/badkey')
.reply(404, error)
@gp.get 'badkey', (err, data) ->
assert.deepEqual err, error
done()
## INSERT ##
it 'can insert a group', (done) ->
fields = 'description,email,id'
body =
id: 'abcd1234'
email: 'newgroup@domain.org'
description: 'new test group'
properties =
email: 'newgroup@domain.org'
description: 'new test group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups?fields=description%2Cemail%2Cid', properties)
.reply(200, body)
@gp.insert properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when trying to insert a group without required properties', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'required', message: 'Missing required field: email' } ]
code: 400
message: 'Missing required field: email'
properties =
description: 'no email for this group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups', properties)
.reply(400, error)
@gp.insert properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'can delete a group', (done) ->
nock('https://www.googleapis.com:443').persist() .delete('/admin/directory/v1/groups/abcd1234')
.reply(204, "")
@gp.delete 'abcd1234', (err, data) ->
assert.deepEqual data, { 204: 'Operation success'}
done()
it 'delete returns an error when a nonstring group_key is given', (done) ->
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), 'Error: GroupProvisioning::delete expected (String group_key[, callback])'
done()
it 'returns an error when a nonexistant group_key is given', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.delete('/admin/directory/v1/groups/asdf1234asdf')
.reply(404, error)
@gp.delete 'asdf1234asdf', (err, data) ->
assert.deepEqual err, error
done()
it 'updates a group', (done) ->
req_body =
name: 'Updated group'
description: 'new description'
resp_body =
id: 'abcd1234'
email: 'group1@domain.org'
name: 'Updated group'
description: 'new description'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/abcd1234?fields=id%2Cname%2Cdescription%2Cemail', req_body)
.reply(200, resp_body)
@gp.patch 'abcd1234', req_body, 'id,name,description,email', (err, data) ->
assert.deepEqual data, resp_body
done()
it '404s when updating with a bad group_key', (done) ->
req_body = {name: 'Updated group'}
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404,
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/12345', req_body)
.reply(404, error)
@gp.patch '12345', req_body, (err, data) ->
assert.deepEqual err, error
done()
| 160753 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
# There are 3 large test suites in this file:
# describe 'UserProvisioning'
# describe 'OrgUnitProvisioning'
# describe 'GroupProvisioning'
before ->
nock.disableNetConnect()
beforeEach ->
nock.cleanAll()
describe 'Retry', ->
before ->
@retry_count = 5
@up = new google_apis.UserProvisioning
token:
access: 'fake access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: @retry_count, randomize: true}
# The following 2 test verifies that @up.get is indeed retrying for @retry_count times.
# Including the initial request, there are retry_count + 1 total requests.
it "retries for `retry_count` times but nocked for `(retry_count + 1)` times", (done) ->
# Nock out all requests with failure
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count + 1).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err, 'FAIL'
done()
it 'retries for retry_count times and nocked for retry_count times', (done) ->
# Nock out all but last request with failure, so that on the (retry_count + 1)th request,
# it attempts to make a real http request.
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err.name, 'NetConnectNotAllowedError'
assert.equal err.message, 'Nock: Not allow net connect for "www.googleapis.com:443"'
done()
describe 'oauth2_request', ->
it 'does not deadlock with request_refresh_token if no refresh token', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(400, 'no refresh from google')
request_nock = nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234')
.reply(401, 'go request token refresh')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, dontcare) ->
refresh_nock.done()
request_nock.done()
assert.equal err, 'no refresh from google'
done()
it 'does not deadlock with request_refresh_token if genuinely invalid credentials', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(200, 'okay, here you go')
request_nock = nock('https://www.googleapis.com:443')
.get('/admin/directory/v1/users/1234').reply(401, 'go request token refresh')
.get('/admin/directory/v1/users/1234').reply(401, 'nope, genuinely invalid credentials')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, resp, body) ->
refresh_nock.done()
request_nock.done()
assert.equal resp.statusCode, 401
assert.equal body, 'nope, genuinely invalid credentials'
done()
describe 'UserProvisioning', ()->
before ->
@up = new google_apis.UserProvisioning
token:
access: '<KEY> access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'requires domain, client_id, client_secret upon construction', (done) ->
assert.throws () ->
new google_apis.UserProvisioning()
, Error
done()
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@up.get 12345, (err, data) ->
assert.equal err.toString(), 'Error: UserProvisioning::get requires (String userkey, [callback])'
cb_wf()
(cb_wf) =>
@up.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::insert expected (Object body, [callback])"
cb_wf()
(cb_wf) =>
@up.list 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::list requires (Object params, [callback])"
cb_wf()
(cb_wf) =>
@up.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::patch expected (String userkey, [Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@up.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::delete expected (String userkey, [callback])"
cb_wf()
], done
## GET ##
it 'can get user by id', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: '<EMAIL>'
name: { givenName: '<NAME>', familyName: '<NAME>', fullName: '<NAME>' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-02-20T21:29:18.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{address: "<EMAIL>", primary: true}]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/1234567890')
.reply(200, body)
@up.get '1234567890', (err, data) ->
assert.ifError err
assert.deepEqual data, body
done()
it '404s when making get with bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/12345')
.reply(404, body)
@up.get '12345', (err, data) ->
assert.deepEqual err, body
done()
## LIST ##
it 'gets partial response for field argument', (done) ->
body =
users: [
{ name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" } }
{ name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=users%2Fname%2C%20nextPageToken')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name, nextPageToken'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets users that match a query', (done) ->
user =
kind: 'admin#directory#user'
id: '987654321'
primaryEmail: '<EMAIL>'
name: { givenName: '<NAME>', familyName: '<NAME>', fullName: '<NAME>' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-25T17:01:23.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: '<EMAIL>', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
body =
kind: 'admin#directory#users'
users: [user]
nextPageToken: 'next_page'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=1&query=email%3Abetsy*')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 1, query: 'email:betsy*'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets paging info even when not explicitly requested', (done) ->
body =
users: [
{ name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" } }
{ name: { givenName: "<NAME>", familyName: "<NAME>", fullName: "<NAME>" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=nextPageToken%2Cusers%2Fname')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name'}, (err, data) ->
assert.deepEqual data, body
done()
## INSERT ##
it 'creates a user', (done) ->
post_body =
name: {familyName: "<NAME>", givenName: "<NAME>"}
password: "<PASSWORD>"
primaryEmail: "<EMAIL>"
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>" }
isAdmin: false
isDelegatedAdmin: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: false
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, (err, data) ->
assert.deepEqual data, resp_body
done()
## INSERT, and FAIL ##
it 'sends a "Domain User Limit" when their domain has its max number of users', (done) ->
# Lets pretend the domain is already at its user limit when we try to create this user
post_body =
name: {familyName: "<NAME>", givenName: "<NAME>"}
password: "<PASSWORD>"
primaryEmail: "<EMAIL>"
error =
error:
errors: [ { domain: 'global', reason: 'DomainUserLimitExceeded', message: 'Domain user limit exceeded.' } ]
code: 412
message: 'Domain user limit exceeded.'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(412, error)
@up.insert post_body, (err, data) ->
assert.deepEqual error, err
done()
it 'creates a user and returns a partial response', (done) ->
post_body =
name: {familyName: "<NAME>", givenName: "<NAME>"}
password: "<PASSWORD>"
primaryEmail: "<EMAIL>"
resp_body =
id: "1234567890"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>" }
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, 'name,primaryEmail,id', (err, data) ->
assert.deepEqual data, resp_body
done()
it 'returns an error when trying to create a user without a required field', (done) ->
post_body =
name: {familyName: "<NAME>", givenName: "<NAME>"}
password: "<PASSWORD>"
@up.insert post_body, (err, data) ->
assert.equal(err.toString(), "Error: UserProvisioning::insert requires 'primaryEmail'")
done()
## PATCH ##
it 'updates a user', (done) ->
req_body = {name: {familyName: '<NAME>', givenName: '<NAME>'}}
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "<EMAIL>"
name: { givenName: "<NAME>", familyName: "<NAME>" }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{ address: "<EMAIL>", primary: true }]
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/1234567890', req_body)
.reply(200, resp_body)
@up.patch '1234567890', req_body, (err, data) ->
assert.deepEqual resp_body, data
done()
it '404s when updating with a bad userkey', (done) ->
req_body = {}
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/12345', req_body)
.reply(404, body)
@up.patch '12345', req_body, (err, data) ->
assert.deepEqual err, body
done()
it 'can correctly call patch with userkey, body, cb', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: '<EMAIL>'
name: {givenName: '<NAME>', familyName: '<NAME>', fullName: '<NAME>' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-26T03:39:52.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: '<EMAIL>', type: 'custom', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
patch_body =
name:
familyName: '<NAME>'
primaryEmail: '<EMAIL>'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890', patch_body)
.reply(200, body)
@up.patch '1234567890', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'can correctly call patch with userkey, fields, cb', (done) ->
body =
primaryEmail: '<EMAIL>'
name:
givenName: '<NAME>'
familyName: '<NAME>'
fullName: '<NAME>'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890?fields=name%2CprimaryEmail')
.reply(200, body)
@up.patch '1234567890', 'name,primaryEmail', (err, data) ->
assert.deepEqual data, body
done()
## DELETE ##
it 'deletes a user', (done) ->
body = {204: "Operation success"}
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/1234567890')
.reply(204, body)
@up.delete '1234567890', (err, data) ->
assert.deepEqual data, body
done()
it '404s when deleting a user with a bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/12345')
.reply(404, body)
@up.delete '12345', (err, data) ->
assert.deepEqual err, body
done()
describe 'OrgUnitProvisioning', ()->
ou_not_found =
error:
errors: []
code: 404,
message: "Org unit not found"
beforeEach ->
@ou = new google_apis.OrgUnitProvisioning
token:
access: 'access_token'
@ou.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@ou.get 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::get expected (String customer_id, String org_unit_path, [, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::insert expected (String customer_id, Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.list 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::list expected (String customer_id[, Object params, callback])"
cb_wf()
(cb_wf) =>
@ou.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::patch expected (String customer_id, String org_unit_path, [Object patch_body, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::delete expected (String customer_id, String org_unit_path[, callback])"
cb_wf()
], done
it 'can get an OrgUnit', (done) ->
body =
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', (err, data) ->
assert.deepEqual data, body
done()
## get_children
it 'get_children makes a request to the right endpoint', (done) ->
ou_path = "OrgUnitName"
customer_id = "customer_123"
mock_endpoint = nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits?orgUnitPath=#{ou_path}&type=children")
.reply(200, {body: "OK"})
@ou.get_children customer_id, ou_path, (err, data) ->
assert.ifError err
assert.deepEqual data, {body: "OK"}
assert mock_endpoint.isDone()
done()
it 'can get an OrgUnit filtered by fields', (done) ->
body =
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad?fields=name%2Cdescription')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', 'name,description', (err, data) ->
assert.deepEqual data, body
done()
it 'can list all org units for a customer', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: ''
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'Vanilla'
description: ''
orgUnitPath: '/Vanilla'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'ChocolateChipCookieDough'
description: ''
orgUnitPath: '/ChocolateChipCookieDough'
parentOrgUnitPath: '/'
blockInheritance: false
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits')
.reply(200, body)
@ou.list 'fake_customer_id', (err, data) ->
assert.deepEqual data, body
done()
it 'can list an org unit by params', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit1', description: '', orgUnitPath: '/ParentOU/OrgUnit1', parentOrgUnitPath: '/ParentOU', blockInheritance: false },
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit2', description: '', orgUnitPath: '/ParentOU/OrgUnit2', parentOrgUnitPath: '/ParentOU', blockInheritance: false }
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits?orgUnitPath=ParentOU')
.reply(200, body)
@ou.list 'fake_customer_id', {orgUnitPath: 'ParentOU'}, (err, data) ->
assert.deepEqual data, body
done()
it 'returns 400 with bad customer_id', (done) ->
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/asdfasdf/orgunits')
.reply(400, error)
@ou.list 'asdfasdf', (err, data) ->
assert.deepEqual err, error
done()
it 'uses cache for OU lookup', (done) ->
org_unit = ['Students']
first_ou =
kind: 'admin#directory#orgUnit'
name: 'Students'
orgUnitPath: '/Students'
orgUnitId: 'ou_id1'
parentOrgUnitPath: '/'
second_ou =
kind: 'admin#directory#orgUnit'
name: '<NAME>name'
orgUnitPath: '/Students/SchoolName'
orgUnitId: 'ou_id2'
parentOrgUnitPath: '/Students'
cache = {}
cache[first_ou.orgUnitPath] = first_ou
cache[second_ou.orgUnitPath] = second_ou
@ou.findOrCreate 'abcdef', org_unit, cache, (err, parent, returned_cache) ->
# this test is successful if it hits the cache and doesn't trigger nock.disableNetConnect()
assert.ifError err
assert.deepEqual returned_cache, cache
assert.equal parent, '/Students'
done()
it 'findOrCreate properly memoizes calls to get and insert', (done) ->
org_unit = ['TestOU']
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: org_unit[0]
orgUnitPath: "/#{org_unit[0]}"
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
customer_id = "fake_customer_id"
nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits/#{org_unit[0]}")
.times(3)
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post("/admin/directory/v1/customer/#{customer_id}/orgunits", properties)
.reply(200, body)
expected_cache = {}
expected_cache[body.orgUnitPath] = body
# this test is successful if the nock is hit only once, and doesn't trigger nock.disableNetConnect()
# on subsequent requests
async.each [0..100], (i, cb_e) =>
@ou.findOrCreate customer_id, org_unit, {}, (err, parent, returned_cache) ->
assert.ifError err
assert.deepEqual returned_cache, expected_cache
assert.equal parent, '/TestOU'
cb_e()
, done
## INSERT ##
it 'creates an orgunit', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOU'
orgUnitPath: '/TestOU'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an orgunit if it already exists', (done) ->
properties =
name: 'TestOUAlreadyExists'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUAlreadyExists'
orgUnitPath: '/TestOUAlreadyExists'
orgUnitId: 'ou_id_already_exists'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUAlreadyExists')
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUAlreadyExists'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUAlreadyExists': body}
assert.equal parent, '/TestOUAlreadyExists'
done()
it 'creates an orgunit if not found', (done) ->
properties =
name: 'TestOUCreate'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUCreate'
orgUnitPath: '/TestOUCreate'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUCreate')
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUCreate'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUCreate': body}
assert.equal parent, '/TestOUCreate'
insert_nock.done()
done()
it 'creates an orgunit with fields args for partial response', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
fields = 'name, orgUnitPath'
body =
name: 'TestOU'
orgUnitPath: '/TestOU'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits?fields=name%2C%20orgUnitPath', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'fails to create an orgunit when invalid customer_id is given', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/badId/orgunits', properties)
.reply(400, error)
@ou.insert 'badId', properties, (err, data) ->
assert.deepEqual err, error
done()
it 'fails to create an orgunit when required properties are not given', (done) ->
properties =
name: 'TestOU4'
error =
error:
errors: [ { domain: 'global', reason: 'invalid', message: 'Invalid Parent Orgunit Id' } ]
code: 400
message: 'Invalid Parent Orgunit Id'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(400, error)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'deletes an orgunit', (done) ->
body = { 204: 'Operation success' }
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/DeleteThis')
.reply(204, body)
@ou.delete 'fake_customer_id', 'DeleteThis', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to delete a nonexistant an orgunit', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Org unit not found' } ]
code: 404
message: 'Org unit not found'
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/doesnotexist')
.reply(404, error)
@ou.delete 'fake_customer_id', 'doesnotexist', (err, data) ->
assert.deepEqual err, error
done()
## PATCH ##
it 'updates an OrgUnit', (done) ->
patch_body = {name: '<NAME>'}
body =
kind: 'admin#directory#orgUnit'
name: '<NAME>'
orgUnitPath: '/UpdatedName'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'updates an OrgUnit and returns a partial response', (done) ->
patch_body = {name: '<NAME>'}
body =
name: '<NAME>'
orgUnitPath: '/UpdatedName'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name%2CorgUnitPath', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, 'name,orgUnitPath', (err, data) ->
assert.deepEqual data, body
done()
it 'can call update with no patch_body', (done) ->
body = { name: '<PASSWORD>' }
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name')
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual data, body
done()
it 'update returns an error when called with an invalid customer_id', (done) ->
error =
errors: [ { domain: 'global', reason: 'authError', message: 'Invalid Credentials', locationType: 'header', location: 'Authorization' } ]
code: 401
message: 'Invalid Credentials'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/bad_id/orgunits/UpdateThisName?fields=name')
.reply(401, error)
@ou.patch 'bad_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual err, error
done()
describe 'GroupProvisioning', ()->
before ->
@gp = new google_apis.GroupProvisioning
token:
access: 'fake_access_token'
@gp.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@gp.get 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::get expected (String group_key[, callback])"
cb_wf()
(cb_wf) =>
@gp.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::insert expected (Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.list 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list expected (Object params[, callback])"
cb_wf()
(cb_wf) =>
@gp.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, callback])"
cb_wf()
], done
## LIST ##
it 'lists groups for a domain', (done) ->
body =
kind: 'admin#directory#groups'
groups: [{
id: 'abcd1234'
email: '<EMAIL>',
name: 'Group1',
description: 'the first group'
}]
nextPageToken: 'next_page'
params =
domain: 'domain.org'
maxResults: 1
fields: 'groups(description,email,id,name),kind,nextPageToken'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=domain.org&maxResults=1&fields=groups(description%2Cemail%2Cid%2Cname)%2Ckind%2CnextPageToken')
.reply(200, body)
@gp.list params, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when an invalid param is given', (done) ->
params =
domain: 'domain.org'
maxResults: 1
unknown_field: true
@gp.list params, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list invalid param 'unknown_field'"
done()
it 'returns 404 for a valid parameter that doesn not exist', (done) ->
params =
domain: 'badexample.com'
maxResults: 1
error =
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: badexample.com' } ]
code: 404
message: 'Resource Not Found: badexample.com'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=badexample.com&maxResults=1')
.reply(404, error)
@gp.list params, (err, data) ->
assert.deepEqual err, error
done()
## GET ##
it 'can get group by group_key', (done) ->
body =
kind: 'admin#directory#group'
id: 'abcd1234'
email: '<EMAIL>'
name: 'Group1'
description: 'the first group'
adminCreated: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/groups/abcd1234')
.reply(200, body)
@gp.get 'abcd1234', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to get a group by invalid group_key', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups/badkey')
.reply(404, error)
@gp.get 'badkey', (err, data) ->
assert.deepEqual err, error
done()
## INSERT ##
it 'can insert a group', (done) ->
fields = 'description,email,id'
body =
id: 'abcd1234'
email: '<EMAIL>'
description: 'new test group'
properties =
email: '<EMAIL>'
description: 'new test group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups?fields=description%2Cemail%2Cid', properties)
.reply(200, body)
@gp.insert properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when trying to insert a group without required properties', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'required', message: 'Missing required field: email' } ]
code: 400
message: 'Missing required field: email'
properties =
description: 'no email for this group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups', properties)
.reply(400, error)
@gp.insert properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'can delete a group', (done) ->
nock('https://www.googleapis.com:443').persist() .delete('/admin/directory/v1/groups/abcd1234')
.reply(204, "")
@gp.delete 'abcd1234', (err, data) ->
assert.deepEqual data, { 204: 'Operation success'}
done()
it 'delete returns an error when a nonstring group_key is given', (done) ->
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), 'Error: GroupProvisioning::delete expected (String group_key[, callback])'
done()
it 'returns an error when a nonexistant group_key is given', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.delete('/admin/directory/v1/groups/asdf1234asdf')
.reply(404, error)
@gp.delete 'asdf1234asdf', (err, data) ->
assert.deepEqual err, error
done()
it 'updates a group', (done) ->
req_body =
name: 'Updated group'
description: 'new description'
resp_body =
id: 'abcd1234'
email: '<EMAIL>'
name: 'Updated group'
description: 'new description'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/abcd1234?fields=id%2Cname%2Cdescription%2Cemail', req_body)
.reply(200, resp_body)
@gp.patch 'abcd1234', req_body, 'id,name,description,email', (err, data) ->
assert.deepEqual data, resp_body
done()
it '404s when updating with a bad group_key', (done) ->
req_body = {name: 'Updated group'}
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404,
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/12345', req_body)
.reply(404, error)
@gp.patch '12345', req_body, (err, data) ->
assert.deepEqual err, error
done()
| true | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
google_apis = require "#{__dirname}/../"
nock = require 'nock'
util = require 'util'
# There are 3 large test suites in this file:
# describe 'UserProvisioning'
# describe 'OrgUnitProvisioning'
# describe 'GroupProvisioning'
before ->
nock.disableNetConnect()
beforeEach ->
nock.cleanAll()
describe 'Retry', ->
before ->
@retry_count = 5
@up = new google_apis.UserProvisioning
token:
access: 'fake access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: @retry_count, randomize: true}
# The following 2 test verifies that @up.get is indeed retrying for @retry_count times.
# Including the initial request, there are retry_count + 1 total requests.
it "retries for `retry_count` times but nocked for `(retry_count + 1)` times", (done) ->
# Nock out all requests with failure
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count + 1).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err, 'FAIL'
done()
it 'retries for retry_count times and nocked for retry_count times', (done) ->
# Nock out all but last request with failure, so that on the (retry_count + 1)th request,
# it attempts to make a real http request.
nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234567890')
.times(@retry_count).reply(500, 'FAIL')
@up.get '1234567890', (err, data) ->
assert.equal err.name, 'NetConnectNotAllowedError'
assert.equal err.message, 'Nock: Not allow net connect for "www.googleapis.com:443"'
done()
describe 'oauth2_request', ->
it 'does not deadlock with request_refresh_token if no refresh token', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(400, 'no refresh from google')
request_nock = nock('https://www.googleapis.com:443').get('/admin/directory/v1/users/1234')
.reply(401, 'go request token refresh')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, dontcare) ->
refresh_nock.done()
request_nock.done()
assert.equal err, 'no refresh from google'
done()
it 'does not deadlock with request_refresh_token if genuinely invalid credentials', (done) ->
gsdk = new google_apis.AdminSDK
token:
refresh: 'sometoken'
access: 'someaccess'
client:
id: 'someid'
secret: 'somesecret'
refresh_nock = nock('https://accounts.google.com:443')
.filteringRequestBody(() -> return '*')
.post('/o/oauth2/token', '*')
.reply(200, 'okay, here you go')
request_nock = nock('https://www.googleapis.com:443')
.get('/admin/directory/v1/users/1234').reply(401, 'go request token refresh')
.get('/admin/directory/v1/users/1234').reply(401, 'nope, genuinely invalid credentials')
opts =
json: true
uri: "https://www.googleapis.com/admin/directory/v1/users/1234"
gsdk.oauth2_request opts, (err, resp, body) ->
refresh_nock.done()
request_nock.done()
assert.equal resp.statusCode, 401
assert.equal body, 'nope, genuinely invalid credentials'
done()
describe 'UserProvisioning', ()->
before ->
@up = new google_apis.UserProvisioning
token:
access: 'PI:KEY:<KEY>END_PI access token'
@up.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'requires domain, client_id, client_secret upon construction', (done) ->
assert.throws () ->
new google_apis.UserProvisioning()
, Error
done()
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@up.get 12345, (err, data) ->
assert.equal err.toString(), 'Error: UserProvisioning::get requires (String userkey, [callback])'
cb_wf()
(cb_wf) =>
@up.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::insert expected (Object body, [callback])"
cb_wf()
(cb_wf) =>
@up.list 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::list requires (Object params, [callback])"
cb_wf()
(cb_wf) =>
@up.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::patch expected (String userkey, [Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@up.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: UserProvisioning::delete expected (String userkey, [callback])"
cb_wf()
], done
## GET ##
it 'can get user by id', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: 'PI:EMAIL:<EMAIL>END_PI'
name: { givenName: 'PI:NAME:<NAME>END_PI', familyName: 'PI:NAME:<NAME>END_PI', fullName: 'PI:NAME:<NAME>END_PI' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-02-20T21:29:18.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{address: "PI:EMAIL:<EMAIL>END_PI", primary: true}]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/1234567890')
.reply(200, body)
@up.get '1234567890', (err, data) ->
assert.ifError err
assert.deepEqual data, body
done()
it '404s when making get with bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users/12345')
.reply(404, body)
@up.get '12345', (err, data) ->
assert.deepEqual err, body
done()
## LIST ##
it 'gets partial response for field argument', (done) ->
body =
users: [
{ name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" } }
{ name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=users%2Fname%2C%20nextPageToken')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name, nextPageToken'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets users that match a query', (done) ->
user =
kind: 'admin#directory#user'
id: '987654321'
primaryEmail: 'PI:EMAIL:<EMAIL>END_PI'
name: { givenName: 'PI:NAME:<NAME>END_PI', familyName: 'PI:NAME:<NAME>END_PI', fullName: 'PI:NAME:<NAME>END_PI' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-25T17:01:23.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: 'PI:EMAIL:<EMAIL>END_PI', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
body =
kind: 'admin#directory#users'
users: [user]
nextPageToken: 'next_page'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=1&query=email%3Abetsy*')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 1, query: 'email:betsy*'}, (err, data) ->
assert.deepEqual data, body
done()
it 'gets paging info even when not explicitly requested', (done) ->
body =
users: [
{ name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" } }
{ name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI", fullName: "PI:NAME:<NAME>END_PI" } }
]
nextPageToken: "next_page"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/users?domain=domain.org&maxResults=2&fields=nextPageToken%2Cusers%2Fname')
.reply(200, body)
@up.list {domain: 'domain.org', maxResults: 2, fields: 'users/name'}, (err, data) ->
assert.deepEqual data, body
done()
## INSERT ##
it 'creates a user', (done) ->
post_body =
name: {familyName: "PI:NAME:<NAME>END_PI", givenName: "PI:NAME:<NAME>END_PI"}
password: "PI:PASSWORD:<PASSWORD>END_PI"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI" }
isAdmin: false
isDelegatedAdmin: false
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: false
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, (err, data) ->
assert.deepEqual data, resp_body
done()
## INSERT, and FAIL ##
it 'sends a "Domain User Limit" when their domain has its max number of users', (done) ->
# Lets pretend the domain is already at its user limit when we try to create this user
post_body =
name: {familyName: "PI:NAME:<NAME>END_PI", givenName: "PI:NAME:<NAME>END_PI"}
password: "PI:PASSWORD:<PASSWORD>END_PI"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
error =
error:
errors: [ { domain: 'global', reason: 'DomainUserLimitExceeded', message: 'Domain user limit exceeded.' } ]
code: 412
message: 'Domain user limit exceeded.'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(412, error)
@up.insert post_body, (err, data) ->
assert.deepEqual error, err
done()
it 'creates a user and returns a partial response', (done) ->
post_body =
name: {familyName: "PI:NAME:<NAME>END_PI", givenName: "PI:NAME:<NAME>END_PI"}
password: "PI:PASSWORD:<PASSWORD>END_PI"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
resp_body =
id: "1234567890"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI" }
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/users', post_body)
.reply(200, resp_body)
@up.insert post_body, 'name,primaryEmail,id', (err, data) ->
assert.deepEqual data, resp_body
done()
it 'returns an error when trying to create a user without a required field', (done) ->
post_body =
name: {familyName: "PI:NAME:<NAME>END_PI", givenName: "PI:NAME:<NAME>END_PI"}
password: "PI:PASSWORD:<PASSWORD>END_PI"
@up.insert post_body, (err, data) ->
assert.equal(err.toString(), "Error: UserProvisioning::insert requires 'primaryEmail'")
done()
## PATCH ##
it 'updates a user', (done) ->
req_body = {name: {familyName: 'PI:NAME:<NAME>END_PI', givenName: 'PI:NAME:<NAME>END_PI'}}
resp_body =
kind: "admin#directory#user"
id: "1234567890"
primaryEmail: "PI:EMAIL:<EMAIL>END_PI"
name: { givenName: "PI:NAME:<NAME>END_PI", familyName: "PI:NAME:<NAME>END_PI" }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: "1970-01-01T00:00:00.000Z"
creationTime: "2013-06-25T19:41:26.000Z"
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [{ address: "PI:EMAIL:<EMAIL>END_PI", primary: true }]
customerId: "fake_customer_id"
orgUnitPath: "/"
isMailboxSetup: true
includeInGlobalAddressList: true
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/1234567890', req_body)
.reply(200, resp_body)
@up.patch '1234567890', req_body, (err, data) ->
assert.deepEqual resp_body, data
done()
it '404s when updating with a bad userkey', (done) ->
req_body = {}
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().patch('/admin/directory/v1/users/12345', req_body)
.reply(404, body)
@up.patch '12345', req_body, (err, data) ->
assert.deepEqual err, body
done()
it 'can correctly call patch with userkey, body, cb', (done) ->
body =
kind: 'admin#directory#user'
id: '1234567890'
primaryEmail: 'PI:EMAIL:<EMAIL>END_PI'
name: {givenName: 'PI:NAME:<NAME>END_PI', familyName: 'PI:NAME:<NAME>END_PI', fullName: 'PI:NAME:<NAME>END_PI' }
isAdmin: false
isDelegatedAdmin: false
lastLoginTime: '1970-01-01T00:00:00.000Z'
creationTime: '2013-06-26T03:39:52.000Z'
agreedToTerms: true
suspended: false
changePasswordAtNextLogin: false
ipWhitelisted: false
emails: [ { address: 'PI:EMAIL:<EMAIL>END_PI', type: 'custom', primary: true } ]
customerId: 'fake_customer_id'
orgUnitPath: '/'
isMailboxSetup: true
includeInGlobalAddressList: true
patch_body =
name:
familyName: 'PI:NAME:<NAME>END_PI'
primaryEmail: 'PI:EMAIL:<EMAIL>END_PI'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890', patch_body)
.reply(200, body)
@up.patch '1234567890', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'can correctly call patch with userkey, fields, cb', (done) ->
body =
primaryEmail: 'PI:EMAIL:<EMAIL>END_PI'
name:
givenName: 'PI:NAME:<NAME>END_PI'
familyName: 'PI:NAME:<NAME>END_PI'
fullName: 'PI:NAME:<NAME>END_PI'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/users/1234567890?fields=name%2CprimaryEmail')
.reply(200, body)
@up.patch '1234567890', 'name,primaryEmail', (err, data) ->
assert.deepEqual data, body
done()
## DELETE ##
it 'deletes a user', (done) ->
body = {204: "Operation success"}
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/1234567890')
.reply(204, body)
@up.delete '1234567890', (err, data) ->
assert.deepEqual data, body
done()
it '404s when deleting a user with a bad userkey', (done) ->
body =
error:
errors: [{ domain: "global", reason: "notFound", message: "Resource Not Found: userKey" }]
code: 404
message: "Resource Not Found: userKey"
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/users/12345')
.reply(404, body)
@up.delete '12345', (err, data) ->
assert.deepEqual err, body
done()
describe 'OrgUnitProvisioning', ()->
ou_not_found =
error:
errors: []
code: 404,
message: "Org unit not found"
beforeEach ->
@ou = new google_apis.OrgUnitProvisioning
token:
access: 'access_token'
@ou.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@ou.get 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::get expected (String customer_id, String org_unit_path, [, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::insert expected (String customer_id, Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.list 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::list expected (String customer_id[, Object params, callback])"
cb_wf()
(cb_wf) =>
@ou.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::patch expected (String customer_id, String org_unit_path, [Object patch_body, String fields, callback])"
cb_wf()
(cb_wf) =>
@ou.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: OrgUnit::delete expected (String customer_id, String org_unit_path[, callback])"
cb_wf()
], done
it 'can get an OrgUnit', (done) ->
body =
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', (err, data) ->
assert.deepEqual data, body
done()
## get_children
it 'get_children makes a request to the right endpoint', (done) ->
ou_path = "OrgUnitName"
customer_id = "customer_123"
mock_endpoint = nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits?orgUnitPath=#{ou_path}&type=children")
.reply(200, {body: "OK"})
@ou.get_children customer_id, ou_path, (err, data) ->
assert.ifError err
assert.deepEqual data, {body: "OK"}
assert mock_endpoint.isDone()
done()
it 'can get an OrgUnit filtered by fields', (done) ->
body =
name: 'RockyRoad'
description: 'For people who like Rocky Road ice cream'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/RockyRoad?fields=name%2Cdescription')
.reply(200, body)
@ou.get 'fake_customer_id', 'RockyRoad', 'name,description', (err, data) ->
assert.deepEqual data, body
done()
it 'can list all org units for a customer', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
kind: 'admin#directory#orgUnit'
name: 'RockyRoad'
description: ''
orgUnitPath: '/RockyRoad'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'Vanilla'
description: ''
orgUnitPath: '/Vanilla'
parentOrgUnitPath: '/'
blockInheritance: false
,
kind: 'admin#directory#orgUnit'
name: 'ChocolateChipCookieDough'
description: ''
orgUnitPath: '/ChocolateChipCookieDough'
parentOrgUnitPath: '/'
blockInheritance: false
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits')
.reply(200, body)
@ou.list 'fake_customer_id', (err, data) ->
assert.deepEqual data, body
done()
it 'can list an org unit by params', (done) ->
body =
kind: 'admin#directory#orgUnits',
organizationUnits: [
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit1', description: '', orgUnitPath: '/ParentOU/OrgUnit1', parentOrgUnitPath: '/ParentOU', blockInheritance: false },
{ kind: 'admin#directory#orgUnit', name: 'OrgUnit2', description: '', orgUnitPath: '/ParentOU/OrgUnit2', parentOrgUnitPath: '/ParentOU', blockInheritance: false }
]
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits?orgUnitPath=ParentOU')
.reply(200, body)
@ou.list 'fake_customer_id', {orgUnitPath: 'ParentOU'}, (err, data) ->
assert.deepEqual data, body
done()
it 'returns 400 with bad customer_id', (done) ->
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/asdfasdf/orgunits')
.reply(400, error)
@ou.list 'asdfasdf', (err, data) ->
assert.deepEqual err, error
done()
it 'uses cache for OU lookup', (done) ->
org_unit = ['Students']
first_ou =
kind: 'admin#directory#orgUnit'
name: 'Students'
orgUnitPath: '/Students'
orgUnitId: 'ou_id1'
parentOrgUnitPath: '/'
second_ou =
kind: 'admin#directory#orgUnit'
name: 'PI:NAME:<NAME>END_PIname'
orgUnitPath: '/Students/SchoolName'
orgUnitId: 'ou_id2'
parentOrgUnitPath: '/Students'
cache = {}
cache[first_ou.orgUnitPath] = first_ou
cache[second_ou.orgUnitPath] = second_ou
@ou.findOrCreate 'abcdef', org_unit, cache, (err, parent, returned_cache) ->
# this test is successful if it hits the cache and doesn't trigger nock.disableNetConnect()
assert.ifError err
assert.deepEqual returned_cache, cache
assert.equal parent, '/Students'
done()
it 'findOrCreate properly memoizes calls to get and insert', (done) ->
org_unit = ['TestOU']
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: org_unit[0]
orgUnitPath: "/#{org_unit[0]}"
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
customer_id = "fake_customer_id"
nock('https://www.googleapis.com')
.get("/admin/directory/v1/customer/#{customer_id}/orgunits/#{org_unit[0]}")
.times(3)
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post("/admin/directory/v1/customer/#{customer_id}/orgunits", properties)
.reply(200, body)
expected_cache = {}
expected_cache[body.orgUnitPath] = body
# this test is successful if the nock is hit only once, and doesn't trigger nock.disableNetConnect()
# on subsequent requests
async.each [0..100], (i, cb_e) =>
@ou.findOrCreate customer_id, org_unit, {}, (err, parent, returned_cache) ->
assert.ifError err
assert.deepEqual returned_cache, expected_cache
assert.equal parent, '/TestOU'
cb_e()
, done
## INSERT ##
it 'creates an orgunit', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOU'
orgUnitPath: '/TestOU'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an orgunit if it already exists', (done) ->
properties =
name: 'TestOUAlreadyExists'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUAlreadyExists'
orgUnitPath: '/TestOUAlreadyExists'
orgUnitId: 'ou_id_already_exists'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUAlreadyExists')
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUAlreadyExists'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUAlreadyExists': body}
assert.equal parent, '/TestOUAlreadyExists'
done()
it 'creates an orgunit if not found', (done) ->
properties =
name: 'TestOUCreate'
parentOrgUnitPath: '/'
body =
kind: 'admin#directory#orgUnit'
name: 'TestOUCreate'
orgUnitPath: '/TestOUCreate'
orgUnitId: 'ou_id'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOUCreate')
.reply(404, ou_not_found)
insert_nock = nock('https://www.googleapis.com:443')
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(200, body)
@ou.findOrCreate 'fake_customer_id', ['TestOUCreate'], (err, parent, cache) ->
assert.ifError err
assert.deepEqual cache, {'/TestOUCreate': body}
assert.equal parent, '/TestOUCreate'
insert_nock.done()
done()
it 'creates an orgunit with fields args for partial response', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
fields = 'name, orgUnitPath'
body =
name: 'TestOU'
orgUnitPath: '/TestOU'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits?fields=name%2C%20orgUnitPath', properties)
.reply(200, body)
@ou.insert 'fake_customer_id', properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'fails to create an orgunit when invalid customer_id is given', (done) ->
properties =
name: 'TestOU'
parentOrgUnitPath: '/'
error =
error:
errors: [{ domain: "global", reason: "badRequest", message: "Bad Request" }]
code: 400
message: "Bad Request"
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/badId/orgunits', properties)
.reply(400, error)
@ou.insert 'badId', properties, (err, data) ->
assert.deepEqual err, error
done()
it 'fails to create an orgunit when required properties are not given', (done) ->
properties =
name: 'TestOU4'
error =
error:
errors: [ { domain: 'global', reason: 'invalid', message: 'Invalid Parent Orgunit Id' } ]
code: 400
message: 'Invalid Parent Orgunit Id'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/customer/fake_customer_id/orgunits/TestOU')
.reply(404, ou_not_found)
nock('https://www.googleapis.com:443').persist()
.post('/admin/directory/v1/customer/fake_customer_id/orgunits', properties)
.reply(400, error)
@ou.insert 'fake_customer_id', properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'deletes an orgunit', (done) ->
body = { 204: 'Operation success' }
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/DeleteThis')
.reply(204, body)
@ou.delete 'fake_customer_id', 'DeleteThis', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to delete a nonexistant an orgunit', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Org unit not found' } ]
code: 404
message: 'Org unit not found'
nock('https://www.googleapis.com:443').persist().delete('/admin/directory/v1/customer/fake_customer_id/orgunits/doesnotexist')
.reply(404, error)
@ou.delete 'fake_customer_id', 'doesnotexist', (err, data) ->
assert.deepEqual err, error
done()
## PATCH ##
it 'updates an OrgUnit', (done) ->
patch_body = {name: 'PI:NAME:<NAME>END_PI'}
body =
kind: 'admin#directory#orgUnit'
name: 'PI:NAME:<NAME>END_PI'
orgUnitPath: '/UpdatedName'
parentOrgUnitPath: '/'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, (err, data) ->
assert.deepEqual data, body
done()
it 'updates an OrgUnit and returns a partial response', (done) ->
patch_body = {name: 'PI:NAME:<NAME>END_PI'}
body =
name: 'PI:NAME:<NAME>END_PI'
orgUnitPath: '/UpdatedName'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name%2CorgUnitPath', patch_body)
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', patch_body, 'name,orgUnitPath', (err, data) ->
assert.deepEqual data, body
done()
it 'can call update with no patch_body', (done) ->
body = { name: 'PI:PASSWORD:<PASSWORD>END_PI' }
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/fake_customer_id/orgunits/UpdateThisName?fields=name')
.reply(200, body)
@ou.patch 'fake_customer_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual data, body
done()
it 'update returns an error when called with an invalid customer_id', (done) ->
error =
errors: [ { domain: 'global', reason: 'authError', message: 'Invalid Credentials', locationType: 'header', location: 'Authorization' } ]
code: 401
message: 'Invalid Credentials'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/customer/bad_id/orgunits/UpdateThisName?fields=name')
.reply(401, error)
@ou.patch 'bad_id', 'UpdateThisName', 'name', (err, data) ->
assert.deepEqual err, error
done()
describe 'GroupProvisioning', ()->
before ->
@gp = new google_apis.GroupProvisioning
token:
access: 'fake_access_token'
@gp.retry_options = {minTimeout: 100, maxTimeout: 200, retries: 2, randomize: true}
it 'returns an error when an argument of wrong type is given', (done) ->
async.waterfall [
(cb_wf) =>
@gp.get 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::get expected (String group_key[, callback])"
cb_wf()
(cb_wf) =>
@gp.insert 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::insert expected (Object properties[, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.list 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list expected (Object params[, callback])"
cb_wf()
(cb_wf) =>
@gp.patch 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, Object body, String fields, callback])"
cb_wf()
(cb_wf) =>
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::delete expected (String group_key[, callback])"
cb_wf()
], done
## LIST ##
it 'lists groups for a domain', (done) ->
body =
kind: 'admin#directory#groups'
groups: [{
id: 'abcd1234'
email: 'PI:EMAIL:<EMAIL>END_PI',
name: 'Group1',
description: 'the first group'
}]
nextPageToken: 'next_page'
params =
domain: 'domain.org'
maxResults: 1
fields: 'groups(description,email,id,name),kind,nextPageToken'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=domain.org&maxResults=1&fields=groups(description%2Cemail%2Cid%2Cname)%2Ckind%2CnextPageToken')
.reply(200, body)
@gp.list params, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when an invalid param is given', (done) ->
params =
domain: 'domain.org'
maxResults: 1
unknown_field: true
@gp.list params, (err, data) ->
assert.equal err.toString(), "Error: GroupProvisioning::list invalid param 'unknown_field'"
done()
it 'returns 404 for a valid parameter that doesn not exist', (done) ->
params =
domain: 'badexample.com'
maxResults: 1
error =
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: badexample.com' } ]
code: 404
message: 'Resource Not Found: badexample.com'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups?domain=badexample.com&maxResults=1')
.reply(404, error)
@gp.list params, (err, data) ->
assert.deepEqual err, error
done()
## GET ##
it 'can get group by group_key', (done) ->
body =
kind: 'admin#directory#group'
id: 'abcd1234'
email: 'PI:EMAIL:<EMAIL>END_PI'
name: 'Group1'
description: 'the first group'
adminCreated: true
nock('https://www.googleapis.com:443').persist().get('/admin/directory/v1/groups/abcd1234')
.reply(200, body)
@gp.get 'abcd1234', (err, data) ->
assert.deepEqual data, body
done()
it '404s when trying to get a group by invalid group_key', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.get('/admin/directory/v1/groups/badkey')
.reply(404, error)
@gp.get 'badkey', (err, data) ->
assert.deepEqual err, error
done()
## INSERT ##
it 'can insert a group', (done) ->
fields = 'description,email,id'
body =
id: 'abcd1234'
email: 'PI:EMAIL:<EMAIL>END_PI'
description: 'new test group'
properties =
email: 'PI:EMAIL:<EMAIL>END_PI'
description: 'new test group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups?fields=description%2Cemail%2Cid', properties)
.reply(200, body)
@gp.insert properties, fields, (err, data) ->
assert.deepEqual data, body
done()
it 'returns an error when trying to insert a group without required properties', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'required', message: 'Missing required field: email' } ]
code: 400
message: 'Missing required field: email'
properties =
description: 'no email for this group'
nock('https://www.googleapis.com:443').persist().post('/admin/directory/v1/groups', properties)
.reply(400, error)
@gp.insert properties, (err, data) ->
assert.deepEqual err, error
done()
## DELETE ##
it 'can delete a group', (done) ->
nock('https://www.googleapis.com:443').persist() .delete('/admin/directory/v1/groups/abcd1234')
.reply(204, "")
@gp.delete 'abcd1234', (err, data) ->
assert.deepEqual data, { 204: 'Operation success'}
done()
it 'delete returns an error when a nonstring group_key is given', (done) ->
@gp.delete 12345, (err, data) ->
assert.equal err.toString(), 'Error: GroupProvisioning::delete expected (String group_key[, callback])'
done()
it 'returns an error when a nonexistant group_key is given', (done) ->
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.delete('/admin/directory/v1/groups/asdf1234asdf')
.reply(404, error)
@gp.delete 'asdf1234asdf', (err, data) ->
assert.deepEqual err, error
done()
it 'updates a group', (done) ->
req_body =
name: 'Updated group'
description: 'new description'
resp_body =
id: 'abcd1234'
email: 'PI:EMAIL:<EMAIL>END_PI'
name: 'Updated group'
description: 'new description'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/abcd1234?fields=id%2Cname%2Cdescription%2Cemail', req_body)
.reply(200, resp_body)
@gp.patch 'abcd1234', req_body, 'id,name,description,email', (err, data) ->
assert.deepEqual data, resp_body
done()
it '404s when updating with a bad group_key', (done) ->
req_body = {name: 'Updated group'}
error =
error:
errors: [ { domain: 'global', reason: 'notFound', message: 'Resource Not Found: groupKey' } ]
code: 404,
message: 'Resource Not Found: groupKey'
nock('https://www.googleapis.com:443').persist()
.patch('/admin/directory/v1/groups/12345', req_body)
.reply(404, error)
@gp.patch '12345', req_body, (err, data) ->
assert.deepEqual err, error
done()
|
[
{
"context": "i.nal.usda.gov/ndb/nutrients/?format=json&api_key=DEMO_KEY&nutrients=205&nutrients=204&nutrients=208&nut",
"end": 413,
"score": 0.5719553232192993,
"start": 409,
"tag": "KEY",
"value": "DEMO"
}
] | app/assets/javascripts/recipes.coffee | Leodip95/Recipely | 0 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
autocomplete = ->
bank_code = undefined
$("#ingredient").autocomplete
source: (request, response) ->
$.ajax
url: "https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=DEMO_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269"
dataType: "json"
data: name: request.term
success: (data) ->
response $.map(data, (item) ->
{
label: item.name
code: item.code
}
)
minLength: 1
select: (event, ui) ->
bank_code = ui.item.code
| 219407 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
autocomplete = ->
bank_code = undefined
$("#ingredient").autocomplete
source: (request, response) ->
$.ajax
url: "https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=<KEY>_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269"
dataType: "json"
data: name: request.term
success: (data) ->
response $.map(data, (item) ->
{
label: item.name
code: item.code
}
)
minLength: 1
select: (event, ui) ->
bank_code = ui.item.code
| true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
autocomplete = ->
bank_code = undefined
$("#ingredient").autocomplete
source: (request, response) ->
$.ajax
url: "https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=PI:KEY:<KEY>END_PI_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269"
dataType: "json"
data: name: request.term
success: (data) ->
response $.map(data, (item) ->
{
label: item.name
code: item.code
}
)
minLength: 1
select: (event, ui) ->
bank_code = ui.item.code
|
[
{
"context": "umes = [\n {\n id: 1\n lastName: \"Roberts\"\n firstName: \"Dread\"\n state: \"NY\"\n ",
"end": 290,
"score": 0.9997889399528503,
"start": 283,
"tag": "NAME",
"value": "Roberts"
},
{
"context": "1\n lastName: \"Roberts\"\n firstName: \"Dread\"\n state: \"NY\"\n },\n {\n id:",
"end": 317,
"score": 0.999748945236206,
"start": 312,
"tag": "NAME",
"value": "Dread"
},
{
"context": " },\n {\n id: 2\n lastName: \"Coyote\"\n firstName: \"Wile E\"\n state: \"NY\"\n",
"end": 395,
"score": 0.9998247027397156,
"start": 389,
"tag": "NAME",
"value": "Coyote"
},
{
"context": " 2\n lastName: \"Coyote\"\n firstName: \"Wile E\"\n state: \"NY\"\n }\n {\n id: ",
"end": 423,
"score": 0.9997706413269043,
"start": 417,
"tag": "NAME",
"value": "Wile E"
},
{
"context": "\n }\n {\n id: 3\n lastName: \"Sam\"\n firstName: \"Yosemite\"\n state: \"NY",
"end": 497,
"score": 0.9998206496238708,
"start": 494,
"tag": "NAME",
"value": "Sam"
},
{
"context": "id: 3\n lastName: \"Sam\"\n firstName: \"Yosemite\"\n state: \"NY\"\n }\n ]\n server = n",
"end": 527,
"score": 0.9997775554656982,
"start": 519,
"tag": "NAME",
"value": "Yosemite"
},
{
"context": "expect(find('.resume_list a').text()).to.include \"Roberts\"\n expect(find('.resume_list a').text()).to.i",
"end": 1879,
"score": 0.9996122121810913,
"start": 1872,
"tag": "NAME",
"value": "Roberts"
},
{
"context": "expect(find('.resume_list a').text()).to.include \"Coyote\"\n expect(find('.resume_list a').text()).to.i",
"end": 1943,
"score": 0.8510994911193848,
"start": 1937,
"tag": "NAME",
"value": "Coyote"
},
{
"context": "expect(find('.resume_list a').text()).to.include \"Sam\"\n\n it 'should clear the search when clicking res",
"end": 2004,
"score": 0.9997890591621399,
"start": 2001,
"tag": "NAME",
"value": "Sam"
},
{
"context": "expect(find('.resume_list a').text()).to.include \"Roberts\"\n click('button:contains(\"Reset\")').then ->\n ",
"end": 2225,
"score": 0.9994601011276245,
"start": 2218,
"tag": "NAME",
"value": "Roberts"
},
{
"context": "ct(find('.resume_list a').text()).not.to.include \"Roberts\"\n\n\n",
"end": 2390,
"score": 0.9995676279067993,
"start": 2383,
"tag": "NAME",
"value": "Roberts"
}
] | ember/tests/integration/resumes-test.coffee | kjayma/rezoome | 0 | `import Ember from 'ember'`
`import startApp from '../helpers/start-app'`
`import Pretender from 'pretender'`
App = undefined
server = undefined
describe 'Integration - Resumes Page', ->
beforeEach ->
App = startApp()
resumes = [
{
id: 1
lastName: "Roberts"
firstName: "Dread"
state: "NY"
},
{
id: 2
lastName: "Coyote"
firstName: "Wile E"
state: "NY"
}
{
id: 3
lastName: "Sam"
firstName: "Yosemite"
state: "NY"
}
]
server = new Pretender ->
@get '/api/v1/resumes', (request) ->
if request.queryParams.state == 'NY'
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: resumes}]
else
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: {}}]
@get '/api/v1/resumes/:id', (request) ->
resume = resumes.find ((resume) ->
if resume.id == parseInt(request.params.id, 10)
return resume
return
)
[
200
{ 'Content-Type': 'application/json' }
JSON.stringify(resume: resume)
]
return
afterEach ->
Ember.run(App, 'destroy')
return
it 'Should allow navigation to the resumes page', ->
visit('/').then ->
click('a:contains("Job Search")').then ->
expect(find('h4').text()).to.include "Candidates"
it 'Should require at least one parameter', ->
this.timeout(9000)
visit('/').then ->
click('a:contains("Job Search")').then ->
click('a:contains("Search Now")').then ->
expect(find('.alert.alert-warning').text()).to.match /at least one/
it 'Should list all resumes', ->
this.timeout(9000)
visit('/resumes?state=NY').then ->
expect(find('.resume_list a').text()).to.include "Roberts"
expect(find('.resume_list a').text()).to.include "Coyote"
expect(find('.resume_list a').text()).to.include "Sam"
it 'should clear the search when clicking reset', ->
this.timeout(9000)
visit('/resumes?state=NY')
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).to.include "Roberts"
click('button:contains("Reset")').then ->
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).not.to.include "Roberts"
| 32677 | `import Ember from 'ember'`
`import startApp from '../helpers/start-app'`
`import Pretender from 'pretender'`
App = undefined
server = undefined
describe 'Integration - Resumes Page', ->
beforeEach ->
App = startApp()
resumes = [
{
id: 1
lastName: "<NAME>"
firstName: "<NAME>"
state: "NY"
},
{
id: 2
lastName: "<NAME>"
firstName: "<NAME>"
state: "NY"
}
{
id: 3
lastName: "<NAME>"
firstName: "<NAME>"
state: "NY"
}
]
server = new Pretender ->
@get '/api/v1/resumes', (request) ->
if request.queryParams.state == 'NY'
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: resumes}]
else
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: {}}]
@get '/api/v1/resumes/:id', (request) ->
resume = resumes.find ((resume) ->
if resume.id == parseInt(request.params.id, 10)
return resume
return
)
[
200
{ 'Content-Type': 'application/json' }
JSON.stringify(resume: resume)
]
return
afterEach ->
Ember.run(App, 'destroy')
return
it 'Should allow navigation to the resumes page', ->
visit('/').then ->
click('a:contains("Job Search")').then ->
expect(find('h4').text()).to.include "Candidates"
it 'Should require at least one parameter', ->
this.timeout(9000)
visit('/').then ->
click('a:contains("Job Search")').then ->
click('a:contains("Search Now")').then ->
expect(find('.alert.alert-warning').text()).to.match /at least one/
it 'Should list all resumes', ->
this.timeout(9000)
visit('/resumes?state=NY').then ->
expect(find('.resume_list a').text()).to.include "<NAME>"
expect(find('.resume_list a').text()).to.include "<NAME>"
expect(find('.resume_list a').text()).to.include "<NAME>"
it 'should clear the search when clicking reset', ->
this.timeout(9000)
visit('/resumes?state=NY')
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).to.include "<NAME>"
click('button:contains("Reset")').then ->
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).not.to.include "<NAME>"
| true | `import Ember from 'ember'`
`import startApp from '../helpers/start-app'`
`import Pretender from 'pretender'`
App = undefined
server = undefined
describe 'Integration - Resumes Page', ->
beforeEach ->
App = startApp()
resumes = [
{
id: 1
lastName: "PI:NAME:<NAME>END_PI"
firstName: "PI:NAME:<NAME>END_PI"
state: "NY"
},
{
id: 2
lastName: "PI:NAME:<NAME>END_PI"
firstName: "PI:NAME:<NAME>END_PI"
state: "NY"
}
{
id: 3
lastName: "PI:NAME:<NAME>END_PI"
firstName: "PI:NAME:<NAME>END_PI"
state: "NY"
}
]
server = new Pretender ->
@get '/api/v1/resumes', (request) ->
if request.queryParams.state == 'NY'
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: resumes}]
else
[200, {"Content-Type": "application/json"}, JSON.stringify {resumes: {}}]
@get '/api/v1/resumes/:id', (request) ->
resume = resumes.find ((resume) ->
if resume.id == parseInt(request.params.id, 10)
return resume
return
)
[
200
{ 'Content-Type': 'application/json' }
JSON.stringify(resume: resume)
]
return
afterEach ->
Ember.run(App, 'destroy')
return
it 'Should allow navigation to the resumes page', ->
visit('/').then ->
click('a:contains("Job Search")').then ->
expect(find('h4').text()).to.include "Candidates"
it 'Should require at least one parameter', ->
this.timeout(9000)
visit('/').then ->
click('a:contains("Job Search")').then ->
click('a:contains("Search Now")').then ->
expect(find('.alert.alert-warning').text()).to.match /at least one/
it 'Should list all resumes', ->
this.timeout(9000)
visit('/resumes?state=NY').then ->
expect(find('.resume_list a').text()).to.include "PI:NAME:<NAME>END_PI"
expect(find('.resume_list a').text()).to.include "PI:NAME:<NAME>END_PI"
expect(find('.resume_list a').text()).to.include "PI:NAME:<NAME>END_PI"
it 'should clear the search when clicking reset', ->
this.timeout(9000)
visit('/resumes?state=NY')
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).to.include "PI:NAME:<NAME>END_PI"
click('button:contains("Reset")').then ->
click('a:contains("Search Now")').then ->
expect(find('.resume_list a').text()).not.to.include "PI:NAME:<NAME>END_PI"
|
[
{
"context": "b://localhost/basic-bot\"\nexports.sessionSecret = \"i am robot! a robot!\"\n\nexports.isPI = false\n\nchild = exec \"uname -m\", (",
"end": 249,
"score": 0.9873479008674622,
"start": 230,
"tag": "PASSWORD",
"value": "i am robot! a robot"
}
] | config.coffee | hcwiley/basic-bot | 1 |
exec = require("child_process").exec
exports.loggerFormat = "dev"
exports.useErrorHandler = true
exports.enableEmailLogin = true
exports.mongodb = process.env.MONGO_DB || "mongodb://localhost/basic-bot"
exports.sessionSecret = "i am robot! a robot!"
exports.isPI = false
child = exec "uname -m", (error, stdout, stderr) ->
# if the system is an arm chip we are going to assume its a pi
console.log stdout.match 'arm'
if stdout.match 'arm'
console.log 'its a PI!'
exports.isPI = true
#TODO: change these pins to your pins!
exports.motors =
a:
enable1: 24
enable2: 18
b:
enable1: 22
enable2: 17
| 2649 |
exec = require("child_process").exec
exports.loggerFormat = "dev"
exports.useErrorHandler = true
exports.enableEmailLogin = true
exports.mongodb = process.env.MONGO_DB || "mongodb://localhost/basic-bot"
exports.sessionSecret = "<PASSWORD>!"
exports.isPI = false
child = exec "uname -m", (error, stdout, stderr) ->
# if the system is an arm chip we are going to assume its a pi
console.log stdout.match 'arm'
if stdout.match 'arm'
console.log 'its a PI!'
exports.isPI = true
#TODO: change these pins to your pins!
exports.motors =
a:
enable1: 24
enable2: 18
b:
enable1: 22
enable2: 17
| true |
exec = require("child_process").exec
exports.loggerFormat = "dev"
exports.useErrorHandler = true
exports.enableEmailLogin = true
exports.mongodb = process.env.MONGO_DB || "mongodb://localhost/basic-bot"
exports.sessionSecret = "PI:PASSWORD:<PASSWORD>END_PI!"
exports.isPI = false
child = exec "uname -m", (error, stdout, stderr) ->
# if the system is an arm chip we are going to assume its a pi
console.log stdout.match 'arm'
if stdout.match 'arm'
console.log 'its a PI!'
exports.isPI = true
#TODO: change these pins to your pins!
exports.motors =
a:
enable1: 24
enable2: 18
b:
enable1: 22
enable2: 17
|
[
{
"context": "@encryption.encrypt({ uuid, token })\n key = new ObjectId().toString()\n @keys.insert { key, encryptedSec",
"end": 317,
"score": 0.7413864135742188,
"start": 309,
"tag": "KEY",
"value": "ObjectId"
},
{
"context": "encrypt({ uuid, token })\n key = new ObjectId().toString()\n @keys.insert { key, encryptedSecret, metada",
"end": 328,
"score": 0.8906522989273071,
"start": 320,
"tag": "KEY",
"value": "toString"
}
] | src/services/meshblu-otp-service.coffee | octoblu/meshblu-otp-service | 0 | Encryption = require './encryption'
{ObjectId} = require 'mongojs'
class MeshbluOtpService
constructor: ({ privateKey, @keys }) ->
@encryption = new Encryption { privateKey }
generate: ({ uuid, token, metadata }, callback) =>
encryptedSecret = @encryption.encrypt({ uuid, token })
key = new ObjectId().toString()
@keys.insert { key, encryptedSecret, metadata }, (error) =>
return callback @_createError 500, error.message if error?
callback null, { key }
exchange: ({ key }, callback) =>
@retrieve { key }, (error, response) =>
return callback error if error
{ uuid, token, metadata } = response
@expire { key }, (error) =>
return callback error if error?
callback null, { uuid, token, metadata }
retrieve: ({ key }, callback) =>
@keys.findOne { key }, (error, result) =>
return callback @_createError 502, error.message if error?
return callback @_createError 404, 'Missing record' unless result?
{metadata, encryptedSecret} = result
{uuid, token} = @encryption.decrypt(encryptedSecret)
callback null, { metadata, uuid, token }
expire: ({ key }, callback) =>
@keys.remove {key}, (error) =>
return callback @_createError 502, error.message if error?
callback null
_createError: (code, message) =>
error = new Error message
error.code = code if code?
return error
module.exports = MeshbluOtpService
| 199515 | Encryption = require './encryption'
{ObjectId} = require 'mongojs'
class MeshbluOtpService
constructor: ({ privateKey, @keys }) ->
@encryption = new Encryption { privateKey }
generate: ({ uuid, token, metadata }, callback) =>
encryptedSecret = @encryption.encrypt({ uuid, token })
key = new <KEY>().<KEY>()
@keys.insert { key, encryptedSecret, metadata }, (error) =>
return callback @_createError 500, error.message if error?
callback null, { key }
exchange: ({ key }, callback) =>
@retrieve { key }, (error, response) =>
return callback error if error
{ uuid, token, metadata } = response
@expire { key }, (error) =>
return callback error if error?
callback null, { uuid, token, metadata }
retrieve: ({ key }, callback) =>
@keys.findOne { key }, (error, result) =>
return callback @_createError 502, error.message if error?
return callback @_createError 404, 'Missing record' unless result?
{metadata, encryptedSecret} = result
{uuid, token} = @encryption.decrypt(encryptedSecret)
callback null, { metadata, uuid, token }
expire: ({ key }, callback) =>
@keys.remove {key}, (error) =>
return callback @_createError 502, error.message if error?
callback null
_createError: (code, message) =>
error = new Error message
error.code = code if code?
return error
module.exports = MeshbluOtpService
| true | Encryption = require './encryption'
{ObjectId} = require 'mongojs'
class MeshbluOtpService
constructor: ({ privateKey, @keys }) ->
@encryption = new Encryption { privateKey }
generate: ({ uuid, token, metadata }, callback) =>
encryptedSecret = @encryption.encrypt({ uuid, token })
key = new PI:KEY:<KEY>END_PI().PI:KEY:<KEY>END_PI()
@keys.insert { key, encryptedSecret, metadata }, (error) =>
return callback @_createError 500, error.message if error?
callback null, { key }
exchange: ({ key }, callback) =>
@retrieve { key }, (error, response) =>
return callback error if error
{ uuid, token, metadata } = response
@expire { key }, (error) =>
return callback error if error?
callback null, { uuid, token, metadata }
retrieve: ({ key }, callback) =>
@keys.findOne { key }, (error, result) =>
return callback @_createError 502, error.message if error?
return callback @_createError 404, 'Missing record' unless result?
{metadata, encryptedSecret} = result
{uuid, token} = @encryption.decrypt(encryptedSecret)
callback null, { metadata, uuid, token }
expire: ({ key }, callback) =>
@keys.remove {key}, (error) =>
return callback @_createError 502, error.message if error?
callback null
_createError: (code, message) =>
error = new Error message
error.code = code if code?
return error
module.exports = MeshbluOtpService
|
[
{
"context": "ect getModel #{stringify model_id.name}\"\n\n key: model_id.name\n isChecked: _isChecked\n predict: predict\n ",
"end": 1318,
"score": 0.9534705281257629,
"start": 1305,
"tag": "KEY",
"value": "model_id.name"
}
] | src/ext/components/grid-output.coffee | Tapad/h2o-flow | 0 | H2O.GridOutput = (_, _go, _grid) ->
_modelViews = signal []
_hasModels = _grid.model_ids.length > 0
_errorViews = signal []
_hasErrors = _grid.failure_details.length > 0
_checkAllModels = signal no
_checkedModelCount = signal 0
_canCompareModels = lift _checkedModelCount, (count) -> count > 1
_hasSelectedModels = lift _checkedModelCount, (count) -> count > 0
_isCheckingAll = no
react _checkAllModels, (checkAll) ->
_isCheckingAll = yes
views = _modelViews()
for view in views
view.isChecked checkAll
_checkedModelCount if checkAll then views.length else 0
_isCheckingAll = no
return
createModelView = (model_id) ->
_isChecked = signal no
react _isChecked, ->
return if _isCheckingAll
checkedViews = (view for view in _modelViews() when view.isChecked())
_checkedModelCount checkedViews.length
predict = ->
_.insertAndExecuteCell 'cs', "predict model: #{stringify model_id.name}"
cloneModel = ->
return alert 'Not implemented'
_.insertAndExecuteCell 'cs', "cloneModel #{stringify model_id.name}"
view = ->
_.insertAndExecuteCell 'cs', "getModel #{stringify model_id.name}"
inspect = ->
_.insertAndExecuteCell 'cs', "inspect getModel #{stringify model_id.name}"
key: model_id.name
isChecked: _isChecked
predict: predict
clone: cloneModel
inspect: inspect
view: view
buildModel = ->
_.insertAndExecuteCell 'cs', 'buildModel'
collectSelectedKeys = ->
for view in _modelViews() when view.isChecked()
view.key
compareModels = ->
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify collectSelectedKeys()}"
predictUsingModels = ->
_.insertAndExecuteCell 'cs', "predict models: #{stringify collectSelectedKeys()}"
deleteModels = ->
_.confirm 'Are you sure you want to delete these models?', { acceptCaption: 'Delete Models', declineCaption: 'Cancel' }, (accept) ->
if accept
_.insertAndExecuteCell 'cs', "deleteModels #{stringify collectSelectedKeys()}"
inspect = ->
summary = _.inspect 'summary', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'summary', #{summary.metadata.origin}"
inspectHistory = ->
history = _.inspect 'scoring_history', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'scoring_history', #{history.metadata.origin}"
inspectAll = ->
allKeys = (view.key for view in _modelViews())
#TODO use table origin
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify allKeys}"
initialize = (grid) ->
_modelViews map grid.model_ids, createModelView
errorViews = for i in [0 ... grid.failure_details.length]
title: "Error #{i + 1}"
detail: grid.failure_details[i]
params: "Parameters: [ #{ grid.failed_raw_params[i].join ', ' } ]"
stacktrace: grid.failure_stack_traces[i]
_errorViews errorViews
defer _go
initialize _grid
modelViews: _modelViews
hasModels: _hasModels
errorViews: _errorViews
hasErrors: _hasErrors
buildModel: buildModel
compareModels: compareModels
predictUsingModels: predictUsingModels
deleteModels: deleteModels
checkedModelCount: _checkedModelCount
canCompareModels: _canCompareModels
hasSelectedModels: _hasSelectedModels
checkAllModels: _checkAllModels
inspect: inspect
inspectHistory: inspectHistory
inspectAll: inspectAll
template: 'flow-grid-output'
| 137897 | H2O.GridOutput = (_, _go, _grid) ->
_modelViews = signal []
_hasModels = _grid.model_ids.length > 0
_errorViews = signal []
_hasErrors = _grid.failure_details.length > 0
_checkAllModels = signal no
_checkedModelCount = signal 0
_canCompareModels = lift _checkedModelCount, (count) -> count > 1
_hasSelectedModels = lift _checkedModelCount, (count) -> count > 0
_isCheckingAll = no
react _checkAllModels, (checkAll) ->
_isCheckingAll = yes
views = _modelViews()
for view in views
view.isChecked checkAll
_checkedModelCount if checkAll then views.length else 0
_isCheckingAll = no
return
createModelView = (model_id) ->
_isChecked = signal no
react _isChecked, ->
return if _isCheckingAll
checkedViews = (view for view in _modelViews() when view.isChecked())
_checkedModelCount checkedViews.length
predict = ->
_.insertAndExecuteCell 'cs', "predict model: #{stringify model_id.name}"
cloneModel = ->
return alert 'Not implemented'
_.insertAndExecuteCell 'cs', "cloneModel #{stringify model_id.name}"
view = ->
_.insertAndExecuteCell 'cs', "getModel #{stringify model_id.name}"
inspect = ->
_.insertAndExecuteCell 'cs', "inspect getModel #{stringify model_id.name}"
key: <KEY>
isChecked: _isChecked
predict: predict
clone: cloneModel
inspect: inspect
view: view
buildModel = ->
_.insertAndExecuteCell 'cs', 'buildModel'
collectSelectedKeys = ->
for view in _modelViews() when view.isChecked()
view.key
compareModels = ->
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify collectSelectedKeys()}"
predictUsingModels = ->
_.insertAndExecuteCell 'cs', "predict models: #{stringify collectSelectedKeys()}"
deleteModels = ->
_.confirm 'Are you sure you want to delete these models?', { acceptCaption: 'Delete Models', declineCaption: 'Cancel' }, (accept) ->
if accept
_.insertAndExecuteCell 'cs', "deleteModels #{stringify collectSelectedKeys()}"
inspect = ->
summary = _.inspect 'summary', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'summary', #{summary.metadata.origin}"
inspectHistory = ->
history = _.inspect 'scoring_history', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'scoring_history', #{history.metadata.origin}"
inspectAll = ->
allKeys = (view.key for view in _modelViews())
#TODO use table origin
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify allKeys}"
initialize = (grid) ->
_modelViews map grid.model_ids, createModelView
errorViews = for i in [0 ... grid.failure_details.length]
title: "Error #{i + 1}"
detail: grid.failure_details[i]
params: "Parameters: [ #{ grid.failed_raw_params[i].join ', ' } ]"
stacktrace: grid.failure_stack_traces[i]
_errorViews errorViews
defer _go
initialize _grid
modelViews: _modelViews
hasModels: _hasModels
errorViews: _errorViews
hasErrors: _hasErrors
buildModel: buildModel
compareModels: compareModels
predictUsingModels: predictUsingModels
deleteModels: deleteModels
checkedModelCount: _checkedModelCount
canCompareModels: _canCompareModels
hasSelectedModels: _hasSelectedModels
checkAllModels: _checkAllModels
inspect: inspect
inspectHistory: inspectHistory
inspectAll: inspectAll
template: 'flow-grid-output'
| true | H2O.GridOutput = (_, _go, _grid) ->
_modelViews = signal []
_hasModels = _grid.model_ids.length > 0
_errorViews = signal []
_hasErrors = _grid.failure_details.length > 0
_checkAllModels = signal no
_checkedModelCount = signal 0
_canCompareModels = lift _checkedModelCount, (count) -> count > 1
_hasSelectedModels = lift _checkedModelCount, (count) -> count > 0
_isCheckingAll = no
react _checkAllModels, (checkAll) ->
_isCheckingAll = yes
views = _modelViews()
for view in views
view.isChecked checkAll
_checkedModelCount if checkAll then views.length else 0
_isCheckingAll = no
return
createModelView = (model_id) ->
_isChecked = signal no
react _isChecked, ->
return if _isCheckingAll
checkedViews = (view for view in _modelViews() when view.isChecked())
_checkedModelCount checkedViews.length
predict = ->
_.insertAndExecuteCell 'cs', "predict model: #{stringify model_id.name}"
cloneModel = ->
return alert 'Not implemented'
_.insertAndExecuteCell 'cs', "cloneModel #{stringify model_id.name}"
view = ->
_.insertAndExecuteCell 'cs', "getModel #{stringify model_id.name}"
inspect = ->
_.insertAndExecuteCell 'cs', "inspect getModel #{stringify model_id.name}"
key: PI:KEY:<KEY>END_PI
isChecked: _isChecked
predict: predict
clone: cloneModel
inspect: inspect
view: view
buildModel = ->
_.insertAndExecuteCell 'cs', 'buildModel'
collectSelectedKeys = ->
for view in _modelViews() when view.isChecked()
view.key
compareModels = ->
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify collectSelectedKeys()}"
predictUsingModels = ->
_.insertAndExecuteCell 'cs', "predict models: #{stringify collectSelectedKeys()}"
deleteModels = ->
_.confirm 'Are you sure you want to delete these models?', { acceptCaption: 'Delete Models', declineCaption: 'Cancel' }, (accept) ->
if accept
_.insertAndExecuteCell 'cs', "deleteModels #{stringify collectSelectedKeys()}"
inspect = ->
summary = _.inspect 'summary', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'summary', #{summary.metadata.origin}"
inspectHistory = ->
history = _.inspect 'scoring_history', _grid
_.insertAndExecuteCell 'cs', "grid inspect 'scoring_history', #{history.metadata.origin}"
inspectAll = ->
allKeys = (view.key for view in _modelViews())
#TODO use table origin
_.insertAndExecuteCell 'cs', "inspect getModels #{stringify allKeys}"
initialize = (grid) ->
_modelViews map grid.model_ids, createModelView
errorViews = for i in [0 ... grid.failure_details.length]
title: "Error #{i + 1}"
detail: grid.failure_details[i]
params: "Parameters: [ #{ grid.failed_raw_params[i].join ', ' } ]"
stacktrace: grid.failure_stack_traces[i]
_errorViews errorViews
defer _go
initialize _grid
modelViews: _modelViews
hasModels: _hasModels
errorViews: _errorViews
hasErrors: _hasErrors
buildModel: buildModel
compareModels: compareModels
predictUsingModels: predictUsingModels
deleteModels: deleteModels
checkedModelCount: _checkedModelCount
canCompareModels: _canCompareModels
hasSelectedModels: _hasSelectedModels
checkAllModels: _checkAllModels
inspect: inspect
inspectHistory: inspectHistory
inspectAll: inspectAll
template: 'flow-grid-output'
|
[
{
"context": "dMail\n from: 'Spynotify <notify@spynotify.com>'\n to: '@gm",
"end": 4643,
"score": 0.9926804304122925,
"start": 4637,
"tag": "EMAIL",
"value": "notify"
},
{
"context": " from: 'Spynotify <notify@spynotify.com>'\n to: '@gmail.com' # pu",
"end": 4657,
"score": 0.6472835540771484,
"start": 4646,
"tag": "EMAIL",
"value": "ynotify.com"
},
{
"context": "tify@spynotify.com>'\n to: '@gmail.com' # put email here\n subje",
"end": 4701,
"score": 0.9476162195205688,
"start": 4690,
"tag": "USERNAME",
"value": "'@gmail.com"
}
] | spynotify/lib/elements_watcher.coffee | wearen1/sandbox | 0 | _ = require 'lodash'
fs = require 'fs'
# Spooky = require 'spooky'
request = require 'request'
Promise = require 'bluebird'
log = require './log'
promise_while = require './promise_while'
db = require dir 'db'
jade = Promise.promisifyAll require 'jade'
moment = require 'moment'
nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport()
Browser = require 'zombie'
browser = new Browser()
getElementContent = (elementId, img_version, url, selector, client)->
log.debug client
new Promise (resolve, reject)->
spooky = new Spooky
child:
"ssl-protocol": "tlsv1"
"ignore-ssl-errors": true
"web-security": "no"
casper:
pageSettings:
userAgent: client.ua
headers:
'Accept-Language': client.al
logLevel: 'info'
verbose: true
options:
clientScripts: [dir 'public/bower_components/jquery/dist/jquery.min.js']
, (err)->
if err
log.error e
else
spooky.start url
spooky.then [
selector: selector
elementId: elementId
img_version: img_version
, ->
element = @evaluate (selector)->
if $(selector)
result =
html: $(selector).html()
rect: $(selector)[0].getBoundingClientRect()
else
null
,
selector: selector
if element
@capture "./public/img/elements/#{ elementId }-#{ img_version }.png", element.rect
@emit "content", element.html
else
@emit 'content', ''
]
spooky.run()
spooky.on 'error', (e, stack)->
log.error e
log.trace stack
reject()
spooky.on 'content', (content)->
result =
url: url
elementId: elementId
selector: selector
client: client
html: content
img: dir "public/img/elements/#{ elementId }-#{ img_version }.png"
resolve result
spooky.on 'console', (line)->
log.trace line
spooky.on 'log', (log)->
if log.space is 'remote'
log.info log.message.replace(/\-.*/, '')
promise_while ->
Promise.resolve true
.delay 1e4
, ->
new Promise (resolve, reject)->
promise_arr = []
curDate = new Date
db.models.Spy.findAll
where:
next_check_at:
$lte: curDate
type: config.spy.spyTypes.indexOf 'webelement'
.then (spies)->
spies_j = _.map spies, (spy)->spy.toJSON()
Promise.map spies, (spy)->
spy.getElements()
.then (elements)->
elements = _.map elements, (elem)->elem.toJSON()
spy.elements = elements
spy = spy.toJSON()
spy.elements = elements
spy
,
concurrency: 1
.then (spies)->
Promise.map spies, (spy)->
Promise.map spy.elements, (element)->
log.trace spy
getElementContent element.id, element.img_version, spy.url, element.selector, spy.client
.then (content)->
unless element.latest_version
element.latest_version =
html: content.html
db.models.Element.update
latest_version: element.latest_version
,
where:
id: element.id
else
if element.latest_version.html isnt content.html
db.models.Element.findOne element.id
.then (element)->
element.img_version += 1
element.latest_version =
html: content.html
element.save()
.then ->
element.createEvent
spyId: spy.id
type: if content.html.length then 'modified' else 'deleted'
.then ->
log.trace spy
element = element.toJSON()
moment.locale 'ru'
fn = jade.compileFile dir 'views/email.jade'
html = fn
spy: spy
moment: moment
type: if content.html.length then 'modified' else 'deleted'
element: element
transporter.sendMail
from: 'Spynotify <notify@spynotify.com>'
to: '@gmail.com' # put email here
subject: 'Изменение страницы'
html: html
attachments: [
{
cid: 'logo'
filename: 'logo.png'
path: dir 'public/img/logo-full.png'
}, {
cid: 'left'
filename: 'left.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 2 }.png"
}, {
cid: 'right'
filename: 'right.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 1 }.png"
}, {
cid: 'arrow'
filename: 'arrow.png'
path: dir "public/img/arrow.png"
}
]
.then ->
updateData = {}
updateData.last_checked = new Date
updateData.next_check_at = new Date(Date.now() + spy.check_interval)
db.models.Spy.update updateData,
where:
id: spy.id
,
concurrency: 1
,
concurrency: 3
.then ->
resolve()
| 130752 | _ = require 'lodash'
fs = require 'fs'
# Spooky = require 'spooky'
request = require 'request'
Promise = require 'bluebird'
log = require './log'
promise_while = require './promise_while'
db = require dir 'db'
jade = Promise.promisifyAll require 'jade'
moment = require 'moment'
nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport()
Browser = require 'zombie'
browser = new Browser()
getElementContent = (elementId, img_version, url, selector, client)->
log.debug client
new Promise (resolve, reject)->
spooky = new Spooky
child:
"ssl-protocol": "tlsv1"
"ignore-ssl-errors": true
"web-security": "no"
casper:
pageSettings:
userAgent: client.ua
headers:
'Accept-Language': client.al
logLevel: 'info'
verbose: true
options:
clientScripts: [dir 'public/bower_components/jquery/dist/jquery.min.js']
, (err)->
if err
log.error e
else
spooky.start url
spooky.then [
selector: selector
elementId: elementId
img_version: img_version
, ->
element = @evaluate (selector)->
if $(selector)
result =
html: $(selector).html()
rect: $(selector)[0].getBoundingClientRect()
else
null
,
selector: selector
if element
@capture "./public/img/elements/#{ elementId }-#{ img_version }.png", element.rect
@emit "content", element.html
else
@emit 'content', ''
]
spooky.run()
spooky.on 'error', (e, stack)->
log.error e
log.trace stack
reject()
spooky.on 'content', (content)->
result =
url: url
elementId: elementId
selector: selector
client: client
html: content
img: dir "public/img/elements/#{ elementId }-#{ img_version }.png"
resolve result
spooky.on 'console', (line)->
log.trace line
spooky.on 'log', (log)->
if log.space is 'remote'
log.info log.message.replace(/\-.*/, '')
promise_while ->
Promise.resolve true
.delay 1e4
, ->
new Promise (resolve, reject)->
promise_arr = []
curDate = new Date
db.models.Spy.findAll
where:
next_check_at:
$lte: curDate
type: config.spy.spyTypes.indexOf 'webelement'
.then (spies)->
spies_j = _.map spies, (spy)->spy.toJSON()
Promise.map spies, (spy)->
spy.getElements()
.then (elements)->
elements = _.map elements, (elem)->elem.toJSON()
spy.elements = elements
spy = spy.toJSON()
spy.elements = elements
spy
,
concurrency: 1
.then (spies)->
Promise.map spies, (spy)->
Promise.map spy.elements, (element)->
log.trace spy
getElementContent element.id, element.img_version, spy.url, element.selector, spy.client
.then (content)->
unless element.latest_version
element.latest_version =
html: content.html
db.models.Element.update
latest_version: element.latest_version
,
where:
id: element.id
else
if element.latest_version.html isnt content.html
db.models.Element.findOne element.id
.then (element)->
element.img_version += 1
element.latest_version =
html: content.html
element.save()
.then ->
element.createEvent
spyId: spy.id
type: if content.html.length then 'modified' else 'deleted'
.then ->
log.trace spy
element = element.toJSON()
moment.locale 'ru'
fn = jade.compileFile dir 'views/email.jade'
html = fn
spy: spy
moment: moment
type: if content.html.length then 'modified' else 'deleted'
element: element
transporter.sendMail
from: 'Spynotify <<EMAIL>@sp<EMAIL>>'
to: '@gmail.com' # put email here
subject: 'Изменение страницы'
html: html
attachments: [
{
cid: 'logo'
filename: 'logo.png'
path: dir 'public/img/logo-full.png'
}, {
cid: 'left'
filename: 'left.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 2 }.png"
}, {
cid: 'right'
filename: 'right.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 1 }.png"
}, {
cid: 'arrow'
filename: 'arrow.png'
path: dir "public/img/arrow.png"
}
]
.then ->
updateData = {}
updateData.last_checked = new Date
updateData.next_check_at = new Date(Date.now() + spy.check_interval)
db.models.Spy.update updateData,
where:
id: spy.id
,
concurrency: 1
,
concurrency: 3
.then ->
resolve()
| true | _ = require 'lodash'
fs = require 'fs'
# Spooky = require 'spooky'
request = require 'request'
Promise = require 'bluebird'
log = require './log'
promise_while = require './promise_while'
db = require dir 'db'
jade = Promise.promisifyAll require 'jade'
moment = require 'moment'
nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport()
Browser = require 'zombie'
browser = new Browser()
getElementContent = (elementId, img_version, url, selector, client)->
log.debug client
new Promise (resolve, reject)->
spooky = new Spooky
child:
"ssl-protocol": "tlsv1"
"ignore-ssl-errors": true
"web-security": "no"
casper:
pageSettings:
userAgent: client.ua
headers:
'Accept-Language': client.al
logLevel: 'info'
verbose: true
options:
clientScripts: [dir 'public/bower_components/jquery/dist/jquery.min.js']
, (err)->
if err
log.error e
else
spooky.start url
spooky.then [
selector: selector
elementId: elementId
img_version: img_version
, ->
element = @evaluate (selector)->
if $(selector)
result =
html: $(selector).html()
rect: $(selector)[0].getBoundingClientRect()
else
null
,
selector: selector
if element
@capture "./public/img/elements/#{ elementId }-#{ img_version }.png", element.rect
@emit "content", element.html
else
@emit 'content', ''
]
spooky.run()
spooky.on 'error', (e, stack)->
log.error e
log.trace stack
reject()
spooky.on 'content', (content)->
result =
url: url
elementId: elementId
selector: selector
client: client
html: content
img: dir "public/img/elements/#{ elementId }-#{ img_version }.png"
resolve result
spooky.on 'console', (line)->
log.trace line
spooky.on 'log', (log)->
if log.space is 'remote'
log.info log.message.replace(/\-.*/, '')
promise_while ->
Promise.resolve true
.delay 1e4
, ->
new Promise (resolve, reject)->
promise_arr = []
curDate = new Date
db.models.Spy.findAll
where:
next_check_at:
$lte: curDate
type: config.spy.spyTypes.indexOf 'webelement'
.then (spies)->
spies_j = _.map spies, (spy)->spy.toJSON()
Promise.map spies, (spy)->
spy.getElements()
.then (elements)->
elements = _.map elements, (elem)->elem.toJSON()
spy.elements = elements
spy = spy.toJSON()
spy.elements = elements
spy
,
concurrency: 1
.then (spies)->
Promise.map spies, (spy)->
Promise.map spy.elements, (element)->
log.trace spy
getElementContent element.id, element.img_version, spy.url, element.selector, spy.client
.then (content)->
unless element.latest_version
element.latest_version =
html: content.html
db.models.Element.update
latest_version: element.latest_version
,
where:
id: element.id
else
if element.latest_version.html isnt content.html
db.models.Element.findOne element.id
.then (element)->
element.img_version += 1
element.latest_version =
html: content.html
element.save()
.then ->
element.createEvent
spyId: spy.id
type: if content.html.length then 'modified' else 'deleted'
.then ->
log.trace spy
element = element.toJSON()
moment.locale 'ru'
fn = jade.compileFile dir 'views/email.jade'
html = fn
spy: spy
moment: moment
type: if content.html.length then 'modified' else 'deleted'
element: element
transporter.sendMail
from: 'Spynotify <PI:EMAIL:<EMAIL>END_PI@spPI:EMAIL:<EMAIL>END_PI>'
to: '@gmail.com' # put email here
subject: 'Изменение страницы'
html: html
attachments: [
{
cid: 'logo'
filename: 'logo.png'
path: dir 'public/img/logo-full.png'
}, {
cid: 'left'
filename: 'left.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 2 }.png"
}, {
cid: 'right'
filename: 'right.png'
path: dir "public/img/elements/#{ element.id }-#{ element.img_version - 1 }.png"
}, {
cid: 'arrow'
filename: 'arrow.png'
path: dir "public/img/arrow.png"
}
]
.then ->
updateData = {}
updateData.last_checked = new Date
updateData.next_check_at = new Date(Date.now() + spy.check_interval)
db.models.Spy.update updateData,
where:
id: spy.id
,
concurrency: 1
,
concurrency: 3
.then ->
resolve()
|
[
{
"context": "overview Tests for no-class-assign rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 77,
"score": 0.9998576641082764,
"start": 63,
"tag": "NAME",
"value": "Toru Nagashima"
},
{
"context": " ,\n messageId: 'class'\n data: name: 'A'\n type: 'Identifier'\n line: 3\n col",
"end": 2010,
"score": 0.8825145959854126,
"start": 2009,
"tag": "NAME",
"value": "A"
}
] | src/tests/rules/no-class-assign.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-class-assign rule.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-class-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-class-assign', rule,
valid: [
'''
class A
foo A
'''
'''
A = class A
foo A
'''
'''
class A
b: (A) -> A = 0
'''
# ignores non class.
'''
x = 0
x = 1
'''
'''
x = ->
x = 1
'''
'foo = (x) -> x = 1'
'''
try
catch x
x = 1
'''
]
invalid: [
code: '''
class A
A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{A} = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{b: A = 0} = {}
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = 0
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
A = 0
A = 1
'''
errors: [
messageId: 'class'
data: name: 'A'
type: 'Identifier'
line: 2
column: 1
,
messageId: 'class'
data: name: 'A'
type: 'Identifier'
line: 3
column: 1
]
,
code: '''
class A
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'ClassDeclaration']
]
| 201546 | ###*
# @fileoverview Tests for no-class-assign rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-class-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-class-assign', rule,
valid: [
'''
class A
foo A
'''
'''
A = class A
foo A
'''
'''
class A
b: (A) -> A = 0
'''
# ignores non class.
'''
x = 0
x = 1
'''
'''
x = ->
x = 1
'''
'foo = (x) -> x = 1'
'''
try
catch x
x = 1
'''
]
invalid: [
code: '''
class A
A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{A} = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{b: A = 0} = {}
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = 0
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
A = 0
A = 1
'''
errors: [
messageId: 'class'
data: name: 'A'
type: 'Identifier'
line: 2
column: 1
,
messageId: 'class'
data: name: '<NAME>'
type: 'Identifier'
line: 3
column: 1
]
,
code: '''
class A
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'ClassDeclaration']
]
| true | ###*
# @fileoverview Tests for no-class-assign rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-class-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-class-assign', rule,
valid: [
'''
class A
foo A
'''
'''
A = class A
foo A
'''
'''
class A
b: (A) -> A = 0
'''
# ignores non class.
'''
x = 0
x = 1
'''
'''
x = ->
x = 1
'''
'foo = (x) -> x = 1'
'''
try
catch x
x = 1
'''
]
invalid: [
code: '''
class A
A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{A} = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
{b: A = 0} = {}
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = 0
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
A = class A
b: -> A = 0
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'Identifier']
,
code: '''
class A
A = 0
A = 1
'''
errors: [
messageId: 'class'
data: name: 'A'
type: 'Identifier'
line: 2
column: 1
,
messageId: 'class'
data: name: 'PI:NAME:<NAME>END_PI'
type: 'Identifier'
line: 3
column: 1
]
,
code: '''
class A
class A
'''
errors: [messageId: 'class', data: {name: 'A'}, type: 'ClassDeclaration']
]
|
[
{
"context": "\r\n models.user.create {\r\n email: 'tom'\r\n password: '123'\r\n show_name:",
"end": 252,
"score": 0.747060239315033,
"start": 249,
"tag": "USERNAME",
"value": "tom"
},
{
"context": "e {\r\n email: 'tom'\r\n password: '123'\r\n show_name: 'Tom'\r\n role: 'ad",
"end": 279,
"score": 0.9992563128471375,
"start": 276,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "\n password: '123'\r\n show_name: 'Tom'\r\n role: 'admin'\r\n }, (err, user)",
"end": 307,
"score": 0.998695433139801,
"start": 304,
"tag": "NAME",
"value": "Tom"
}
] | db.coffee | Lifeng-Liang/NodeBlog | 0 | orm = require('orm')
config = require('./config')
module.exports = (app) ->
init_db = (models) ->
models.user.count (err, count) ->
if err
throw err
if count <= 0
models.user.create {
email: 'tom'
password: '123'
show_name: 'Tom'
role: 'admin'
}, (err, user) ->
if err
throw err
fs = require('fs')
fs.readFile './README.md', 'utf-8', (err, data) ->
models.article.create [
{
title: 'welcome'
alias: 'about'
summary: 'welome to the real world!'
content: data
format: 'markdown'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
{
title: 'Hello'
summary: 'Hello from the blog.'
content: '<p>hello, is there anyone there?</p>'
format: 'html'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
], (err, articles) ->
if err
throw err
console.log articles
app.use orm.express(config.dbConnString, define: (db, models, next) ->
models.user = db.define('users',
email: String
password: String
show_name: String
role: [
'admin'
'user'
]
created_on: Date
updated_on: Date
session_id: String)
models.article = db.define('articles',
title: String
alias: String
content: String
summary: String
summary_is_empty: Boolean
recommend: Boolean
format: [
'html'
'markdown'
]
writer: String
reference: String
views_count: type: 'integer'
comments_count: type: 'integer'
created_on: Date
user_id: type: 'integer'
category_id: type: 'integer')
models.comment = db.define('comments',
writer: String
content: String
saved_on: Date
user_id: type: 'integer'
article_title: String
article_id: type: 'integer')
# Initialize database
db.sync (err) ->
if err
throw err
init_db models
next()
)
| 71303 | orm = require('orm')
config = require('./config')
module.exports = (app) ->
init_db = (models) ->
models.user.count (err, count) ->
if err
throw err
if count <= 0
models.user.create {
email: 'tom'
password: '<PASSWORD>'
show_name: '<NAME>'
role: 'admin'
}, (err, user) ->
if err
throw err
fs = require('fs')
fs.readFile './README.md', 'utf-8', (err, data) ->
models.article.create [
{
title: 'welcome'
alias: 'about'
summary: 'welome to the real world!'
content: data
format: 'markdown'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
{
title: 'Hello'
summary: 'Hello from the blog.'
content: '<p>hello, is there anyone there?</p>'
format: 'html'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
], (err, articles) ->
if err
throw err
console.log articles
app.use orm.express(config.dbConnString, define: (db, models, next) ->
models.user = db.define('users',
email: String
password: String
show_name: String
role: [
'admin'
'user'
]
created_on: Date
updated_on: Date
session_id: String)
models.article = db.define('articles',
title: String
alias: String
content: String
summary: String
summary_is_empty: Boolean
recommend: Boolean
format: [
'html'
'markdown'
]
writer: String
reference: String
views_count: type: 'integer'
comments_count: type: 'integer'
created_on: Date
user_id: type: 'integer'
category_id: type: 'integer')
models.comment = db.define('comments',
writer: String
content: String
saved_on: Date
user_id: type: 'integer'
article_title: String
article_id: type: 'integer')
# Initialize database
db.sync (err) ->
if err
throw err
init_db models
next()
)
| true | orm = require('orm')
config = require('./config')
module.exports = (app) ->
init_db = (models) ->
models.user.count (err, count) ->
if err
throw err
if count <= 0
models.user.create {
email: 'tom'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
show_name: 'PI:NAME:<NAME>END_PI'
role: 'admin'
}, (err, user) ->
if err
throw err
fs = require('fs')
fs.readFile './README.md', 'utf-8', (err, data) ->
models.article.create [
{
title: 'welcome'
alias: 'about'
summary: 'welome to the real world!'
content: data
format: 'markdown'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
{
title: 'Hello'
summary: 'Hello from the blog.'
content: '<p>hello, is there anyone there?</p>'
format: 'html'
views_count: 0
comments_count: 0
user_id: user.id
category_id: 1
created_on: new Date
}
], (err, articles) ->
if err
throw err
console.log articles
app.use orm.express(config.dbConnString, define: (db, models, next) ->
models.user = db.define('users',
email: String
password: String
show_name: String
role: [
'admin'
'user'
]
created_on: Date
updated_on: Date
session_id: String)
models.article = db.define('articles',
title: String
alias: String
content: String
summary: String
summary_is_empty: Boolean
recommend: Boolean
format: [
'html'
'markdown'
]
writer: String
reference: String
views_count: type: 'integer'
comments_count: type: 'integer'
created_on: Date
user_id: type: 'integer'
category_id: type: 'integer')
models.comment = db.define('comments',
writer: String
content: String
saved_on: Date
user_id: type: 'integer'
article_title: String
article_id: type: 'integer')
# Initialize database
db.sync (err) ->
if err
throw err
init_db models
next()
)
|
[
{
"context": "age\": 21,\n# \"eyeColor\": \"green\",\n# \"name\": \"Antonia Sutton\",\n# \"gender\": \"female\",\n# \"email\": \"antonia",
"end": 515,
"score": 0.9998596906661987,
"start": 501,
"tag": "NAME",
"value": "Antonia Sutton"
},
{
"context": " Sutton\",\n# \"gender\": \"female\",\n# \"email\": \"antoniasutton@digifad.com\",\n# \"phone\": \"+1 (904) 529-3234\"\n# },\n# {\n# ",
"end": 583,
"score": 0.999933123588562,
"start": 558,
"tag": "EMAIL",
"value": "antoniasutton@digifad.com"
},
{
"context": "age\": 29,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Mays Pate\",\n# \"gender\": \"male\",\n# \"email\": \"mayspate@",
"end": 696,
"score": 0.9998536705970764,
"start": 687,
"tag": "NAME",
"value": "Mays Pate"
},
{
"context": "Mays Pate\",\n# \"gender\": \"male\",\n# \"email\": \"mayspate@digifad.com\",\n# \"phone\": \"+1 (916) 485-2063\"\n# },\n# {\n# ",
"end": 757,
"score": 0.9999324083328247,
"start": 737,
"tag": "EMAIL",
"value": "mayspate@digifad.com"
},
{
"context": "\"age\": 32,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Ruthie Dean\",\n# \"gender\": \"female\",\n# \"email\": \"ruthied",
"end": 871,
"score": 0.9998569488525391,
"start": 860,
"tag": "NAME",
"value": "Ruthie Dean"
},
{
"context": "ie Dean\",\n# \"gender\": \"female\",\n# \"email\": \"ruthiedean@digifad.com\",\n# \"phone\": \"+1 (986) 584-3180\"\n# },\n# {\n# ",
"end": 936,
"score": 0.9999332427978516,
"start": 914,
"tag": "EMAIL",
"value": "ruthiedean@digifad.com"
},
{
"context": "age\": 39,\n# \"eyeColor\": \"green\",\n# \"name\": \"Julia Douglas\",\n# \"gender\": \"female\",\n# \"email\": \"juliado",
"end": 1053,
"score": 0.9998190402984619,
"start": 1040,
"tag": "NAME",
"value": "Julia Douglas"
},
{
"context": "Douglas\",\n# \"gender\": \"female\",\n# \"email\": \"juliadouglas@digifad.com\",\n# \"phone\": \"+1 (883) 417-3313\"\n# },\n# {\n# ",
"end": 1120,
"score": 0.9999328851699829,
"start": 1096,
"tag": "EMAIL",
"value": "juliadouglas@digifad.com"
},
{
"context": "\"age\": 28,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Theresa Stein\",\n# \"gender\": \"female\",\n# \"email\": \"theresa",
"end": 1236,
"score": 0.9998502731323242,
"start": 1223,
"tag": "NAME",
"value": "Theresa Stein"
},
{
"context": "a Stein\",\n# \"gender\": \"female\",\n# \"email\": \"theresastein@digifad.com\",\n# \"phone\": \"+1 (832) 589-2369\"\n# },\n# {\n# ",
"end": 1303,
"score": 0.9999294281005859,
"start": 1279,
"tag": "EMAIL",
"value": "theresastein@digifad.com"
},
{
"context": "\"age\": 36,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Rosanne Poole\",\n# \"gender\": \"female\",\n# \"email\": \"rosanne",
"end": 1419,
"score": 0.9998606443405151,
"start": 1406,
"tag": "NAME",
"value": "Rosanne Poole"
},
{
"context": "e Poole\",\n# \"gender\": \"female\",\n# \"email\": \"rosannepoole@digifad.com\",\n# \"phone\": \"+1 (864) 579-2495\"\n# },\n# {\n# ",
"end": 1486,
"score": 0.999923586845398,
"start": 1462,
"tag": "EMAIL",
"value": "rosannepoole@digifad.com"
},
{
"context": "\"age\": 30,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Hope Velez\",\n# \"gender\": \"female\",\n# \"email\": \"hopevel",
"end": 1599,
"score": 0.999828577041626,
"start": 1589,
"tag": "NAME",
"value": "Hope Velez"
},
{
"context": "e Velez\",\n# \"gender\": \"female\",\n# \"email\": \"hopevelez@digifad.com\",\n# \"phone\": \"+1 (866) 416-2480\"\n# },\n# {\n# ",
"end": 1663,
"score": 0.999930739402771,
"start": 1642,
"tag": "EMAIL",
"value": "hopevelez@digifad.com"
},
{
"context": "age\": 32,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Daniels Brady\",\n# \"gender\": \"male\",\n# \"email\": \"danielsbr",
"end": 1780,
"score": 0.9998366236686707,
"start": 1767,
"tag": "NAME",
"value": "Daniels Brady"
},
{
"context": "els Brady\",\n# \"gender\": \"male\",\n# \"email\": \"danielsbrady@digifad.com\",\n# \"phone\": \"+1 (938) 574-2423\"\n# },\n# {\n# ",
"end": 1845,
"score": 0.9999299049377441,
"start": 1821,
"tag": "EMAIL",
"value": "danielsbrady@digifad.com"
},
{
"context": "age\": 30,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Carey Hughes\",\n# \"gender\": \"female\",\n# \"email\": \"careyhu",
"end": 1961,
"score": 0.999853789806366,
"start": 1949,
"tag": "NAME",
"value": "Carey Hughes"
},
{
"context": " Hughes\",\n# \"gender\": \"female\",\n# \"email\": \"careyhughes@digifad.com\",\n# \"phone\": \"+1 (810) 504-3850\"\n# },\n# {\n# ",
"end": 2027,
"score": 0.9999241828918457,
"start": 2004,
"tag": "EMAIL",
"value": "careyhughes@digifad.com"
},
{
"context": "age\": 32,\n# \"eyeColor\": \"green\",\n# \"name\": \"Camacho Carter\",\n# \"gender\": \"male\",\n# \"email\": \"camachoca",
"end": 2145,
"score": 0.9998253583908081,
"start": 2131,
"tag": "NAME",
"value": "Camacho Carter"
},
{
"context": "ho Carter\",\n# \"gender\": \"male\",\n# \"email\": \"camachocarter@digifad.com\",\n# \"phone\": \"+1 (988) 450-2162\"\n# },\n# {\n# ",
"end": 2211,
"score": 0.999901294708252,
"start": 2186,
"tag": "EMAIL",
"value": "camachocarter@digifad.com"
},
{
"context": "age\": 28,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Margery Rowland\",\n# \"gender\": \"female\",\n# \"email\": \"margery",
"end": 2330,
"score": 0.9998788833618164,
"start": 2315,
"tag": "NAME",
"value": "Margery Rowland"
},
{
"context": "Rowland\",\n# \"gender\": \"female\",\n# \"email\": \"margeryrowland@digifad.com\",\n# \"phone\": \"+1 (970) 480-2628\"\n# },\n# {\n# ",
"end": 2399,
"score": 0.9999256730079651,
"start": 2373,
"tag": "EMAIL",
"value": "margeryrowland@digifad.com"
},
{
"context": "age\": 33,\n# \"eyeColor\": \"green\",\n# \"name\": \"Rosa Holcomb\",\n# \"gender\": \"female\",\n# \"email\": \"rosahol",
"end": 2515,
"score": 0.9998705387115479,
"start": 2503,
"tag": "NAME",
"value": "Rosa Holcomb"
},
{
"context": "Holcomb\",\n# \"gender\": \"female\",\n# \"email\": \"rosaholcomb@digifad.com\",\n# \"phone\": \"+1 (897) 561-2638\"\n# },\n# {\n# ",
"end": 2581,
"score": 0.9999229311943054,
"start": 2558,
"tag": "EMAIL",
"value": "rosaholcomb@digifad.com"
},
{
"context": "age\": 21,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Hawkins Leonard\",\n# \"gender\": \"male\",\n# \"email\": \"hawkinsle",
"end": 2700,
"score": 0.9998664855957031,
"start": 2685,
"tag": "NAME",
"value": "Hawkins Leonard"
},
{
"context": "s Leonard\",\n# \"gender\": \"male\",\n# \"email\": \"hawkinsleonard@digifad.com\",\n# \"phone\": \"+1 (960) 585-3899\"\n# },\n# {\n# ",
"end": 2767,
"score": 0.9999300241470337,
"start": 2741,
"tag": "EMAIL",
"value": "hawkinsleonard@digifad.com"
},
{
"context": "\"age\": 25,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Robert Whitney\",\n# \"gender\": \"female\",\n# \"email\": \"robertw",
"end": 2884,
"score": 0.9998542666435242,
"start": 2870,
"tag": "NAME",
"value": "Robert Whitney"
},
{
"context": "Whitney\",\n# \"gender\": \"female\",\n# \"email\": \"robertwhitney@digifad.com\",\n# \"phone\": \"+1 (920) 483-2584\"\n# },\n# {\n# ",
"end": 2952,
"score": 0.999920666217804,
"start": 2927,
"tag": "EMAIL",
"value": "robertwhitney@digifad.com"
},
{
"context": "\"age\": 32,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Conner Cantrell\",\n# \"gender\": \"male\",\n# \"email\": \"connercan",
"end": 3070,
"score": 0.9998564720153809,
"start": 3055,
"tag": "NAME",
"value": "Conner Cantrell"
},
{
"context": " Cantrell\",\n# \"gender\": \"male\",\n# \"email\": \"connercantrell@digifad.com\",\n# \"phone\": \"+1 (803) 431-2452\"\n# },\n# {\n# ",
"end": 3137,
"score": 0.9999123215675354,
"start": 3111,
"tag": "EMAIL",
"value": "connercantrell@digifad.com"
},
{
"context": "age\": 32,\n# \"eyeColor\": \"green\",\n# \"name\": \"Gretchen Graves\",\n# \"gender\": \"female\",\n# \"email\": \"gretche",
"end": 3256,
"score": 0.9998546838760376,
"start": 3241,
"tag": "NAME",
"value": "Gretchen Graves"
},
{
"context": " Graves\",\n# \"gender\": \"female\",\n# \"email\": \"gretchengraves@digifad.com\",\n# \"phone\": \"+1 (886) 577-3465\"\n# },\n# {\n# ",
"end": 3325,
"score": 0.9999346137046814,
"start": 3299,
"tag": "EMAIL",
"value": "gretchengraves@digifad.com"
},
{
"context": "age\": 25,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Blankenship Shepherd\",\n# \"gender\": \"male\",\n# \"email\": \"blankensh",
"end": 3449,
"score": 0.9998604655265808,
"start": 3429,
"tag": "NAME",
"value": "Blankenship Shepherd"
},
{
"context": " Shepherd\",\n# \"gender\": \"male\",\n# \"email\": \"blankenshipshepherd@digifad.com\",\n# \"phone\": \"+1 (845) 402-3387\"\n# },\n# {\n# ",
"end": 3521,
"score": 0.9999341368675232,
"start": 3490,
"tag": "EMAIL",
"value": "blankenshipshepherd@digifad.com"
},
{
"context": "\"age\": 36,\n# \"eyeColor\": \"blue\",\n# \"name\": \"Lowery Rodriguez\",\n# \"gender\": \"male\",\n# \"email\": \"loweryrod",
"end": 3640,
"score": 0.9998318552970886,
"start": 3624,
"tag": "NAME",
"value": "Lowery Rodriguez"
},
{
"context": "Rodriguez\",\n# \"gender\": \"male\",\n# \"email\": \"loweryrodriguez@digifad.com\",\n# \"phone\": \"+1 (966) 547-3710\"\n# },\n# {\n# ",
"end": 3708,
"score": 0.9999350905418396,
"start": 3681,
"tag": "EMAIL",
"value": "loweryrodriguez@digifad.com"
},
{
"context": "age\": 26,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Goff Goodman\",\n# \"gender\": \"male\",\n# \"email\": \"goffgoodm",
"end": 3824,
"score": 0.9997800588607788,
"start": 3812,
"tag": "NAME",
"value": "Goff Goodman"
},
{
"context": "f Goodman\",\n# \"gender\": \"male\",\n# \"email\": \"goffgoodman@digifad.com\",\n# \"phone\": \"+1 (997) 549-2049\"\n# },\n# {\n# ",
"end": 3888,
"score": 0.9999338388442993,
"start": 3865,
"tag": "EMAIL",
"value": "goffgoodman@digifad.com"
},
{
"context": "age\": 21,\n# \"eyeColor\": \"brown\",\n# \"name\": \"Simon Giles\",\n# \"gender\": \"male\",\n# \"email\": \"simongile",
"end": 4003,
"score": 0.9998061060905457,
"start": 3992,
"tag": "NAME",
"value": "Simon Giles"
},
{
"context": "mon Giles\",\n# \"gender\": \"male\",\n# \"email\": \"simongiles@digifad.com\",\n# \"phone\": \"+1 (847) 533-2955\"\n# }\n#]\n#\n#It",
"end": 4066,
"score": 0.9999330043792725,
"start": 4044,
"tag": "EMAIL",
"value": "simongiles@digifad.com"
}
] | test/init-data.coffee | tungv/mongo-authorize | 1 | #config = require 'config'
#
#mongoose = require 'mongoose'
#try
# mongoose.connection.close()
# mongoose.connect config.mongo.connection
#catch ex
# console.error ex
#
#
#mongoose.models = {}
#
#itemSchema = mongoose.Schema {
# age: Number,
# eyeColor: String,
# name: String,
# gender: String,
# email: String,
# phone: String
#}
#
#mongoose.model 'item', itemSchema
#
#ItemModel = mongoose.model 'item', itemSchema
#
#items = [
# {
# "age": 21,
# "eyeColor": "green",
# "name": "Antonia Sutton",
# "gender": "female",
# "email": "antoniasutton@digifad.com",
# "phone": "+1 (904) 529-3234"
# },
# {
# "age": 29,
# "eyeColor": "brown",
# "name": "Mays Pate",
# "gender": "male",
# "email": "mayspate@digifad.com",
# "phone": "+1 (916) 485-2063"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "Ruthie Dean",
# "gender": "female",
# "email": "ruthiedean@digifad.com",
# "phone": "+1 (986) 584-3180"
# },
# {
# "age": 39,
# "eyeColor": "green",
# "name": "Julia Douglas",
# "gender": "female",
# "email": "juliadouglas@digifad.com",
# "phone": "+1 (883) 417-3313"
# },
# {
# "age": 28,
# "eyeColor": "blue",
# "name": "Theresa Stein",
# "gender": "female",
# "email": "theresastein@digifad.com",
# "phone": "+1 (832) 589-2369"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "Rosanne Poole",
# "gender": "female",
# "email": "rosannepoole@digifad.com",
# "phone": "+1 (864) 579-2495"
# },
# {
# "age": 30,
# "eyeColor": "blue",
# "name": "Hope Velez",
# "gender": "female",
# "email": "hopevelez@digifad.com",
# "phone": "+1 (866) 416-2480"
# },
# {
# "age": 32,
# "eyeColor": "brown",
# "name": "Daniels Brady",
# "gender": "male",
# "email": "danielsbrady@digifad.com",
# "phone": "+1 (938) 574-2423"
# },
# {
# "age": 30,
# "eyeColor": "brown",
# "name": "Carey Hughes",
# "gender": "female",
# "email": "careyhughes@digifad.com",
# "phone": "+1 (810) 504-3850"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "Camacho Carter",
# "gender": "male",
# "email": "camachocarter@digifad.com",
# "phone": "+1 (988) 450-2162"
# },
# {
# "age": 28,
# "eyeColor": "brown",
# "name": "Margery Rowland",
# "gender": "female",
# "email": "margeryrowland@digifad.com",
# "phone": "+1 (970) 480-2628"
# },
# {
# "age": 33,
# "eyeColor": "green",
# "name": "Rosa Holcomb",
# "gender": "female",
# "email": "rosaholcomb@digifad.com",
# "phone": "+1 (897) 561-2638"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "Hawkins Leonard",
# "gender": "male",
# "email": "hawkinsleonard@digifad.com",
# "phone": "+1 (960) 585-3899"
# },
# {
# "age": 25,
# "eyeColor": "blue",
# "name": "Robert Whitney",
# "gender": "female",
# "email": "robertwhitney@digifad.com",
# "phone": "+1 (920) 483-2584"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "Conner Cantrell",
# "gender": "male",
# "email": "connercantrell@digifad.com",
# "phone": "+1 (803) 431-2452"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "Gretchen Graves",
# "gender": "female",
# "email": "gretchengraves@digifad.com",
# "phone": "+1 (886) 577-3465"
# },
# {
# "age": 25,
# "eyeColor": "brown",
# "name": "Blankenship Shepherd",
# "gender": "male",
# "email": "blankenshipshepherd@digifad.com",
# "phone": "+1 (845) 402-3387"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "Lowery Rodriguez",
# "gender": "male",
# "email": "loweryrodriguez@digifad.com",
# "phone": "+1 (966) 547-3710"
# },
# {
# "age": 26,
# "eyeColor": "brown",
# "name": "Goff Goodman",
# "gender": "male",
# "email": "goffgoodman@digifad.com",
# "phone": "+1 (997) 549-2049"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "Simon Giles",
# "gender": "male",
# "email": "simongiles@digifad.com",
# "phone": "+1 (847) 533-2955"
# }
#]
#
#ItemModel.remove ()->
# for item in items
# doc = new ItemModel item
# doc.save() | 112206 | #config = require 'config'
#
#mongoose = require 'mongoose'
#try
# mongoose.connection.close()
# mongoose.connect config.mongo.connection
#catch ex
# console.error ex
#
#
#mongoose.models = {}
#
#itemSchema = mongoose.Schema {
# age: Number,
# eyeColor: String,
# name: String,
# gender: String,
# email: String,
# phone: String
#}
#
#mongoose.model 'item', itemSchema
#
#ItemModel = mongoose.model 'item', itemSchema
#
#items = [
# {
# "age": 21,
# "eyeColor": "green",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (904) 529-3234"
# },
# {
# "age": 29,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (916) 485-2063"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (986) 584-3180"
# },
# {
# "age": 39,
# "eyeColor": "green",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (883) 417-3313"
# },
# {
# "age": 28,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (832) 589-2369"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (864) 579-2495"
# },
# {
# "age": 30,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (866) 416-2480"
# },
# {
# "age": 32,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (938) 574-2423"
# },
# {
# "age": 30,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (810) 504-3850"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (988) 450-2162"
# },
# {
# "age": 28,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (970) 480-2628"
# },
# {
# "age": 33,
# "eyeColor": "green",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (897) 561-2638"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (960) 585-3899"
# },
# {
# "age": 25,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (920) 483-2584"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (803) 431-2452"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "<NAME>",
# "gender": "female",
# "email": "<EMAIL>",
# "phone": "+1 (886) 577-3465"
# },
# {
# "age": 25,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (845) 402-3387"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (966) 547-3710"
# },
# {
# "age": 26,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (997) 549-2049"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "<NAME>",
# "gender": "male",
# "email": "<EMAIL>",
# "phone": "+1 (847) 533-2955"
# }
#]
#
#ItemModel.remove ()->
# for item in items
# doc = new ItemModel item
# doc.save() | true | #config = require 'config'
#
#mongoose = require 'mongoose'
#try
# mongoose.connection.close()
# mongoose.connect config.mongo.connection
#catch ex
# console.error ex
#
#
#mongoose.models = {}
#
#itemSchema = mongoose.Schema {
# age: Number,
# eyeColor: String,
# name: String,
# gender: String,
# email: String,
# phone: String
#}
#
#mongoose.model 'item', itemSchema
#
#ItemModel = mongoose.model 'item', itemSchema
#
#items = [
# {
# "age": 21,
# "eyeColor": "green",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (904) 529-3234"
# },
# {
# "age": 29,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (916) 485-2063"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (986) 584-3180"
# },
# {
# "age": 39,
# "eyeColor": "green",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (883) 417-3313"
# },
# {
# "age": 28,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (832) 589-2369"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (864) 579-2495"
# },
# {
# "age": 30,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (866) 416-2480"
# },
# {
# "age": 32,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (938) 574-2423"
# },
# {
# "age": 30,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (810) 504-3850"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (988) 450-2162"
# },
# {
# "age": 28,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (970) 480-2628"
# },
# {
# "age": 33,
# "eyeColor": "green",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (897) 561-2638"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (960) 585-3899"
# },
# {
# "age": 25,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (920) 483-2584"
# },
# {
# "age": 32,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (803) 431-2452"
# },
# {
# "age": 32,
# "eyeColor": "green",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "female",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (886) 577-3465"
# },
# {
# "age": 25,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (845) 402-3387"
# },
# {
# "age": 36,
# "eyeColor": "blue",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (966) 547-3710"
# },
# {
# "age": 26,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (997) 549-2049"
# },
# {
# "age": 21,
# "eyeColor": "brown",
# "name": "PI:NAME:<NAME>END_PI",
# "gender": "male",
# "email": "PI:EMAIL:<EMAIL>END_PI",
# "phone": "+1 (847) 533-2955"
# }
#]
#
#ItemModel.remove ()->
# for item in items
# doc = new ItemModel item
# doc.save() |
[
{
"context": "quire('./../lib/gisty')\n\ngist = new Gisty login: 'login', password: 'password'\n\ngist.starred (error, gist",
"end": 122,
"score": 0.992490828037262,
"start": 117,
"tag": "USERNAME",
"value": "login"
},
{
"context": "ty')\n\ngist = new Gisty login: 'login', password: 'password'\n\ngist.starred (error, gists) ->\n throw new Erro",
"end": 144,
"score": 0.9993002414703369,
"start": 136,
"tag": "PASSWORD",
"value": "password"
}
] | examples/plain-auth.coffee | meritt/node-gisty | 6 | ###
Retrieve starred gist with plain authenticate
###
Gisty = require('./../lib/gisty')
gist = new Gisty login: 'login', password: 'password'
gist.starred (error, gists) ->
throw new Error error if error
console.log gists | 146260 | ###
Retrieve starred gist with plain authenticate
###
Gisty = require('./../lib/gisty')
gist = new Gisty login: 'login', password: '<PASSWORD>'
gist.starred (error, gists) ->
throw new Error error if error
console.log gists | true | ###
Retrieve starred gist with plain authenticate
###
Gisty = require('./../lib/gisty')
gist = new Gisty login: 'login', password: 'PI:PASSWORD:<PASSWORD>END_PI'
gist.starred (error, gists) ->
throw new Error error if error
console.log gists |
[
{
"context": "//www.example.com/'\n\n\nCUSTOMERS =\n 1:\n user: 'Alfred'\n gender: 'male'\n age: 24\n 2:\n user: 'G",
"end": 289,
"score": 0.9997753500938416,
"start": 283,
"tag": "NAME",
"value": "Alfred"
},
{
"context": "d'\n gender: 'male'\n age: 24\n 2:\n user: 'George'\n gender: 'male'\n age: 42\n 3:\n user: 'C",
"end": 344,
"score": 0.998241662979126,
"start": 338,
"tag": "NAME",
"value": "George"
},
{
"context": "e'\n gender: 'male'\n age: 42\n 3:\n user: 'Cynthia'\n gender: 'female'\n age: 28\n\n\napp = express",
"end": 400,
"score": 0.9994816184043884,
"start": 393,
"tag": "NAME",
"value": "Cynthia"
},
{
"context": "(done) ->\n api('test-post').post {'user': 'Mickael', 'age': 42, 'gender': 'male'}, (err, ret) ->\n ",
"end": 7061,
"score": 0.778045654296875,
"start": 7054,
"tag": "USERNAME",
"value": "Mickael"
},
{
"context": "\n assert.equal ret['parsed-body'].user, 'Mickael'\n assert.equal ret['parsed-body'].age, 4",
"end": 7241,
"score": 0.7395787239074707,
"start": 7234,
"tag": "USERNAME",
"value": "Mickael"
},
{
"context": "qual 'object', typeof ret\n assert.equal 'Alfred', ret[1].user\n do done\n\n describe 'Pass",
"end": 9450,
"score": 0.8424696326255798,
"start": 9444,
"tag": "NAME",
"value": "Alfred"
}
] | node_modules/gitlab/node_modules/slumber/tests/test.coffee | rudolfoborges/gitlab_dashboard | 1 | #!/usr/bin/env coffee
querystring = require 'querystring'
url = require 'url'
assert = require 'assert'
express = require 'express'
connect = require 'connect'
freeport = require 'freeport'
slumber = require '..'
base_url = 'http://www.example.com/'
CUSTOMERS =
1:
user: 'Alfred'
gender: 'male'
age: 24
2:
user: 'George'
gender: 'male'
age: 42
3:
user: 'Cynthia'
gender: 'female'
age: 28
app = express()
app.use connect.urlencoded()
app.use connect.json()
app.get '/', (req, res) ->
res.end 'Hello World !'
app.get '/test-headers', (req, res) ->
res.json 'headers': req.headers
app.get '/customers', (req, res) ->
url_parts = url.parse req.url
query = querystring.parse url_parts.query
ret = []
for customer_id, customer of CUSTOMERS
ok = true
for filter_key, filter_value of query
if customer[filter_key] != filter_value
ok = false
break
if ok
ret.push customer_id
res.json ret
app.post '/test-post', (req, res) ->
res.json 'parsed-body': req.body
app.put '/test-put', (req, res) ->
res.json 'parsed-body': req.body
app.delete '/test-delete', (req, res) ->
res.json 'test ok'
app.patch '/test-patch', (req, res) ->
res.json 'parsed-body': req.body
app.get '/customers-yml', (req, res) ->
yamljs = require 'yamljs'
res.end yamljs.stringify CUSTOMERS
app.get '/customers-yml-with-header', (req, res) ->
yamljs = require 'yamljs'
res.header 'Content-Type', 'text/yaml'
res.end yamljs.stringify CUSTOMERS
app.get '/customers/:id', (req, res) ->
res.json CUSTOMERS[parseInt req.params.id]
describe 'Routing', ->
api = slumber.API base_url, {}
describe '#base_url', ->
it 'should retrieve a string with base_url of api', ->
assert.equal api.base_url, base_url
describe 'one child', ->
it 'should retrieve a string with base_url of api with 1 child', ->
assert.equal api('customers').base_url, "#{base_url}customers/"
describe 'two children', ->
it 'should retrieve a string with base_url of api with 2 children', ->
assert.equal api('customers')(42).base_url, "#{base_url}customers/42/"
describe 'Serializer', ->
describe 'serializer', ->
api = slumber.API base_url, {}
it 'should be an object', ->
assert.equal 'object', typeof api.serializer
describe '#serializers', ->
it 'should return an array of available serializers', ->
assert.equal 'object', typeof api.serializer.serializers
describe '#get_serializer()', ->
it 'should return the default serializer', ->
serializer = api.serializer.get_serializer()
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#get_by_name', ->
it 'should return the best serializer depending on name', ->
assert.equal 'yaml', api.serializer.get_serializer('yaml').key
describe '#get_by_content_type', ->
it 'should return the best serializer depending on content-type', ->
mapping =
'text/yaml': 'yaml'
'application/json': 'json'
'application/x-javascript': 'json'
'text/javascript': 'json'
'text/x-javascript': 'json'
'text/x-json': 'json'
'dontexists': null
for k, v of mapping
if v is null
assert.throws (-> api.serializer.get_serializer(null, k)), /there is no available serializer for content-type/
else
assert.equal v, api.serializer.get_serializer(null, k).key
describe 'YamlSerializer', ->
api = slumber.API base_url, {'format': 'yaml'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'yaml', serializer.key
describe '#loads', ->
it 'should loads jyaml encoded string and return a javascript object', ->
ret = serializer.loads 'a: 42\nb:\n - 43\n - 45\n'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads 'a: 42\nb:\n - 43\n -\n')
describe '#dumps', ->
it 'should dumps a javascript object to a yaml encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, 'a: 42\nb:\n - 43\n - 45\n'
describe 'JsonSerializer', ->
api = slumber.API base_url, {'format': 'json'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#loads', ->
it 'should loads json encoded string and return a javascript object', ->
ret = serializer.loads '{"a": 42, "b": [43, 45]}'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads '{"a": 42, "b": [43, 45]')
describe '#dumps', ->
it 'should dumps a javascript object to a json encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, '{"a":42,"b":[43,45]}'
describe 'UnknownSerializer', ->
describe '#constructor', ->
it 'should be an empty Serializer', ->
api = slumber.API base_url, {'format': 'dontexists'}
serializer = api.serializer.get_serializer()
# should raise ?
assert.equal undefined, serializer
describe 'Local Express', ->
api = null
port = null
describe 'Authenticated', ->
before (done) ->
freeport (err, _port) ->
port = _port
app.listen port, ->
do done
it 'should send connection detail', (done) ->
api = slumber.API "http://localhost:#{port}/", {auth: ['admin', 'secure']}, ->
api('test-headers').get (err, ret) ->
assert.equal err, null
assert.equal ret.headers.authorization, 'Basic YWRtaW46c2VjdXJl'
do done
describe 'Anonymous', ->
before (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
do done
describe 'Connection', ->
it 'should connect to express and return a string Hello World', (done) ->
api.get (err, ret) ->
assert.equal err, null
assert.equal ret, 'Hello World !'
do done
it 'should return an array (from json) of customers', (done) ->
api('customers').get (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret.length, 3
do done
it 'should post data', (done) ->
api('test-post').post {'user': 'Mickael', 'age': 42, 'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].user, 'Mickael'
assert.equal ret['parsed-body'].age, 42
assert.equal ret['parsed-body'].gender, 'male'
do done
it 'should put data', (done) ->
api('test-put').put {'test': 42, 'test2': 'toto'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 42
assert.equal ret['parsed-body'].test2, 'toto'
do done
it 'should patch data', (done) ->
api('test-patch').patch {'test': 43, 'test2': 'titi'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 43
assert.equal ret['parsed-body'].test2, 'titi'
do done
it 'should delete data', (done) ->
api('test-delete').delete (err, ret) ->
assert.equal err, null
assert.equal ret, true
do done
it 'should return customer object (from json) with id = 1', (done) ->
api('customers')(1).get (err, ret) ->
assert.equal ret.user, CUSTOMERS[1].user
assert.equal ret.age, CUSTOMERS[1].age
assert.equal ret.gender, CUSTOMERS[1].gender
do done
it 'should return an array (from json) of customers for gender=male', (done) ->
api('customers').get {'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should return an array (from json) of customers for gender=male explicitely defining args', (done) ->
api('customers').get {'__args': {'gender': 'male'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should not detect yaml content-type and return an object', (done) ->
api('customers-yml').get (err, ret) ->
assert.equal null, err
assert.equal 'string', typeof ret
do done
it 'should detect yaml content-type and return an object', (done) ->
api('customers-yml-with-header').get (err, ret) ->
assert.equal null, err
assert.equal 'object', typeof ret
assert.equal 'Alfred', ret[1].user
do done
describe 'Passing headers', ->
headers =
"X-AAA": 42
"X-BBB": "test"
headers_override =
"X-AAA": 43
"X-CCC": "hello"
it 'should pass headers when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: headers}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally and override them when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {headers: headers_override}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '43'
assert.equal ret.headers['x-bbb'], 'test'
assert.equal ret.headers['x-ccc'], 'hello'
do done
it 'should have a default user-agent', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
defaultVersion = require('../package.json').version
targetVersion = "node-slumber/#{defaultVersion}"
assert.equal ret.headers['user-agent'], targetVersion
do done
it 'should override user-agent globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'user-agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent globally using capitalize', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'User-Agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: {'User-Agent': 'test'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
describe 'Rare cases', ->
api = null
describe 'Non existing remote host', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an handled error', (done) ->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get (err, ret) ->
assert.equal ret, null
assert.equal err.code, 'ENOTFOUND'
assert.equal err.errno, 'ENOTFOUND'
do done
describe 'Call method without callback', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an exception', ->
assert.throws (->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get()
), Error
| 67986 | #!/usr/bin/env coffee
querystring = require 'querystring'
url = require 'url'
assert = require 'assert'
express = require 'express'
connect = require 'connect'
freeport = require 'freeport'
slumber = require '..'
base_url = 'http://www.example.com/'
CUSTOMERS =
1:
user: '<NAME>'
gender: 'male'
age: 24
2:
user: '<NAME>'
gender: 'male'
age: 42
3:
user: '<NAME>'
gender: 'female'
age: 28
app = express()
app.use connect.urlencoded()
app.use connect.json()
app.get '/', (req, res) ->
res.end 'Hello World !'
app.get '/test-headers', (req, res) ->
res.json 'headers': req.headers
app.get '/customers', (req, res) ->
url_parts = url.parse req.url
query = querystring.parse url_parts.query
ret = []
for customer_id, customer of CUSTOMERS
ok = true
for filter_key, filter_value of query
if customer[filter_key] != filter_value
ok = false
break
if ok
ret.push customer_id
res.json ret
app.post '/test-post', (req, res) ->
res.json 'parsed-body': req.body
app.put '/test-put', (req, res) ->
res.json 'parsed-body': req.body
app.delete '/test-delete', (req, res) ->
res.json 'test ok'
app.patch '/test-patch', (req, res) ->
res.json 'parsed-body': req.body
app.get '/customers-yml', (req, res) ->
yamljs = require 'yamljs'
res.end yamljs.stringify CUSTOMERS
app.get '/customers-yml-with-header', (req, res) ->
yamljs = require 'yamljs'
res.header 'Content-Type', 'text/yaml'
res.end yamljs.stringify CUSTOMERS
app.get '/customers/:id', (req, res) ->
res.json CUSTOMERS[parseInt req.params.id]
describe 'Routing', ->
api = slumber.API base_url, {}
describe '#base_url', ->
it 'should retrieve a string with base_url of api', ->
assert.equal api.base_url, base_url
describe 'one child', ->
it 'should retrieve a string with base_url of api with 1 child', ->
assert.equal api('customers').base_url, "#{base_url}customers/"
describe 'two children', ->
it 'should retrieve a string with base_url of api with 2 children', ->
assert.equal api('customers')(42).base_url, "#{base_url}customers/42/"
describe 'Serializer', ->
describe 'serializer', ->
api = slumber.API base_url, {}
it 'should be an object', ->
assert.equal 'object', typeof api.serializer
describe '#serializers', ->
it 'should return an array of available serializers', ->
assert.equal 'object', typeof api.serializer.serializers
describe '#get_serializer()', ->
it 'should return the default serializer', ->
serializer = api.serializer.get_serializer()
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#get_by_name', ->
it 'should return the best serializer depending on name', ->
assert.equal 'yaml', api.serializer.get_serializer('yaml').key
describe '#get_by_content_type', ->
it 'should return the best serializer depending on content-type', ->
mapping =
'text/yaml': 'yaml'
'application/json': 'json'
'application/x-javascript': 'json'
'text/javascript': 'json'
'text/x-javascript': 'json'
'text/x-json': 'json'
'dontexists': null
for k, v of mapping
if v is null
assert.throws (-> api.serializer.get_serializer(null, k)), /there is no available serializer for content-type/
else
assert.equal v, api.serializer.get_serializer(null, k).key
describe 'YamlSerializer', ->
api = slumber.API base_url, {'format': 'yaml'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'yaml', serializer.key
describe '#loads', ->
it 'should loads jyaml encoded string and return a javascript object', ->
ret = serializer.loads 'a: 42\nb:\n - 43\n - 45\n'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads 'a: 42\nb:\n - 43\n -\n')
describe '#dumps', ->
it 'should dumps a javascript object to a yaml encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, 'a: 42\nb:\n - 43\n - 45\n'
describe 'JsonSerializer', ->
api = slumber.API base_url, {'format': 'json'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#loads', ->
it 'should loads json encoded string and return a javascript object', ->
ret = serializer.loads '{"a": 42, "b": [43, 45]}'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads '{"a": 42, "b": [43, 45]')
describe '#dumps', ->
it 'should dumps a javascript object to a json encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, '{"a":42,"b":[43,45]}'
describe 'UnknownSerializer', ->
describe '#constructor', ->
it 'should be an empty Serializer', ->
api = slumber.API base_url, {'format': 'dontexists'}
serializer = api.serializer.get_serializer()
# should raise ?
assert.equal undefined, serializer
describe 'Local Express', ->
api = null
port = null
describe 'Authenticated', ->
before (done) ->
freeport (err, _port) ->
port = _port
app.listen port, ->
do done
it 'should send connection detail', (done) ->
api = slumber.API "http://localhost:#{port}/", {auth: ['admin', 'secure']}, ->
api('test-headers').get (err, ret) ->
assert.equal err, null
assert.equal ret.headers.authorization, 'Basic YWRtaW46c2VjdXJl'
do done
describe 'Anonymous', ->
before (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
do done
describe 'Connection', ->
it 'should connect to express and return a string Hello World', (done) ->
api.get (err, ret) ->
assert.equal err, null
assert.equal ret, 'Hello World !'
do done
it 'should return an array (from json) of customers', (done) ->
api('customers').get (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret.length, 3
do done
it 'should post data', (done) ->
api('test-post').post {'user': 'Mickael', 'age': 42, 'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].user, 'Mickael'
assert.equal ret['parsed-body'].age, 42
assert.equal ret['parsed-body'].gender, 'male'
do done
it 'should put data', (done) ->
api('test-put').put {'test': 42, 'test2': 'toto'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 42
assert.equal ret['parsed-body'].test2, 'toto'
do done
it 'should patch data', (done) ->
api('test-patch').patch {'test': 43, 'test2': 'titi'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 43
assert.equal ret['parsed-body'].test2, 'titi'
do done
it 'should delete data', (done) ->
api('test-delete').delete (err, ret) ->
assert.equal err, null
assert.equal ret, true
do done
it 'should return customer object (from json) with id = 1', (done) ->
api('customers')(1).get (err, ret) ->
assert.equal ret.user, CUSTOMERS[1].user
assert.equal ret.age, CUSTOMERS[1].age
assert.equal ret.gender, CUSTOMERS[1].gender
do done
it 'should return an array (from json) of customers for gender=male', (done) ->
api('customers').get {'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should return an array (from json) of customers for gender=male explicitely defining args', (done) ->
api('customers').get {'__args': {'gender': 'male'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should not detect yaml content-type and return an object', (done) ->
api('customers-yml').get (err, ret) ->
assert.equal null, err
assert.equal 'string', typeof ret
do done
it 'should detect yaml content-type and return an object', (done) ->
api('customers-yml-with-header').get (err, ret) ->
assert.equal null, err
assert.equal 'object', typeof ret
assert.equal '<NAME>', ret[1].user
do done
describe 'Passing headers', ->
headers =
"X-AAA": 42
"X-BBB": "test"
headers_override =
"X-AAA": 43
"X-CCC": "hello"
it 'should pass headers when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: headers}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally and override them when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {headers: headers_override}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '43'
assert.equal ret.headers['x-bbb'], 'test'
assert.equal ret.headers['x-ccc'], 'hello'
do done
it 'should have a default user-agent', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
defaultVersion = require('../package.json').version
targetVersion = "node-slumber/#{defaultVersion}"
assert.equal ret.headers['user-agent'], targetVersion
do done
it 'should override user-agent globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'user-agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent globally using capitalize', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'User-Agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: {'User-Agent': 'test'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
describe 'Rare cases', ->
api = null
describe 'Non existing remote host', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an handled error', (done) ->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get (err, ret) ->
assert.equal ret, null
assert.equal err.code, 'ENOTFOUND'
assert.equal err.errno, 'ENOTFOUND'
do done
describe 'Call method without callback', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an exception', ->
assert.throws (->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get()
), Error
| true | #!/usr/bin/env coffee
querystring = require 'querystring'
url = require 'url'
assert = require 'assert'
express = require 'express'
connect = require 'connect'
freeport = require 'freeport'
slumber = require '..'
base_url = 'http://www.example.com/'
CUSTOMERS =
1:
user: 'PI:NAME:<NAME>END_PI'
gender: 'male'
age: 24
2:
user: 'PI:NAME:<NAME>END_PI'
gender: 'male'
age: 42
3:
user: 'PI:NAME:<NAME>END_PI'
gender: 'female'
age: 28
app = express()
app.use connect.urlencoded()
app.use connect.json()
app.get '/', (req, res) ->
res.end 'Hello World !'
app.get '/test-headers', (req, res) ->
res.json 'headers': req.headers
app.get '/customers', (req, res) ->
url_parts = url.parse req.url
query = querystring.parse url_parts.query
ret = []
for customer_id, customer of CUSTOMERS
ok = true
for filter_key, filter_value of query
if customer[filter_key] != filter_value
ok = false
break
if ok
ret.push customer_id
res.json ret
app.post '/test-post', (req, res) ->
res.json 'parsed-body': req.body
app.put '/test-put', (req, res) ->
res.json 'parsed-body': req.body
app.delete '/test-delete', (req, res) ->
res.json 'test ok'
app.patch '/test-patch', (req, res) ->
res.json 'parsed-body': req.body
app.get '/customers-yml', (req, res) ->
yamljs = require 'yamljs'
res.end yamljs.stringify CUSTOMERS
app.get '/customers-yml-with-header', (req, res) ->
yamljs = require 'yamljs'
res.header 'Content-Type', 'text/yaml'
res.end yamljs.stringify CUSTOMERS
app.get '/customers/:id', (req, res) ->
res.json CUSTOMERS[parseInt req.params.id]
describe 'Routing', ->
api = slumber.API base_url, {}
describe '#base_url', ->
it 'should retrieve a string with base_url of api', ->
assert.equal api.base_url, base_url
describe 'one child', ->
it 'should retrieve a string with base_url of api with 1 child', ->
assert.equal api('customers').base_url, "#{base_url}customers/"
describe 'two children', ->
it 'should retrieve a string with base_url of api with 2 children', ->
assert.equal api('customers')(42).base_url, "#{base_url}customers/42/"
describe 'Serializer', ->
describe 'serializer', ->
api = slumber.API base_url, {}
it 'should be an object', ->
assert.equal 'object', typeof api.serializer
describe '#serializers', ->
it 'should return an array of available serializers', ->
assert.equal 'object', typeof api.serializer.serializers
describe '#get_serializer()', ->
it 'should return the default serializer', ->
serializer = api.serializer.get_serializer()
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#get_by_name', ->
it 'should return the best serializer depending on name', ->
assert.equal 'yaml', api.serializer.get_serializer('yaml').key
describe '#get_by_content_type', ->
it 'should return the best serializer depending on content-type', ->
mapping =
'text/yaml': 'yaml'
'application/json': 'json'
'application/x-javascript': 'json'
'text/javascript': 'json'
'text/x-javascript': 'json'
'text/x-json': 'json'
'dontexists': null
for k, v of mapping
if v is null
assert.throws (-> api.serializer.get_serializer(null, k)), /there is no available serializer for content-type/
else
assert.equal v, api.serializer.get_serializer(null, k).key
describe 'YamlSerializer', ->
api = slumber.API base_url, {'format': 'yaml'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'yaml', serializer.key
describe '#loads', ->
it 'should loads jyaml encoded string and return a javascript object', ->
ret = serializer.loads 'a: 42\nb:\n - 43\n - 45\n'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads 'a: 42\nb:\n - 43\n -\n')
describe '#dumps', ->
it 'should dumps a javascript object to a yaml encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, 'a: 42\nb:\n - 43\n - 45\n'
describe 'JsonSerializer', ->
api = slumber.API base_url, {'format': 'json'}
serializer = api.serializer.get_serializer()
describe '#constructor', ->
it 'should be a valid Serializer', ->
assert.equal 'object', typeof serializer
assert.equal 'json', serializer.key
describe '#loads', ->
it 'should loads json encoded string and return a javascript object', ->
ret = serializer.loads '{"a": 42, "b": [43, 45]}'
assert.equal 'object', typeof ret
assert.equal ret.a, 42
assert.equal ret.b.length, 2
describe '#loads#error', ->
it 'should raise an exception', ->
assert.throws (-> serializer.loads '{"a": 42, "b": [43, 45]')
describe '#dumps', ->
it 'should dumps a javascript object to a json encoded string', ->
ret = serializer.dumps {a: 42, b: [43, 45]}
assert.equal 'string', typeof ret
assert.equal ret, '{"a":42,"b":[43,45]}'
describe 'UnknownSerializer', ->
describe '#constructor', ->
it 'should be an empty Serializer', ->
api = slumber.API base_url, {'format': 'dontexists'}
serializer = api.serializer.get_serializer()
# should raise ?
assert.equal undefined, serializer
describe 'Local Express', ->
api = null
port = null
describe 'Authenticated', ->
before (done) ->
freeport (err, _port) ->
port = _port
app.listen port, ->
do done
it 'should send connection detail', (done) ->
api = slumber.API "http://localhost:#{port}/", {auth: ['admin', 'secure']}, ->
api('test-headers').get (err, ret) ->
assert.equal err, null
assert.equal ret.headers.authorization, 'Basic YWRtaW46c2VjdXJl'
do done
describe 'Anonymous', ->
before (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
do done
describe 'Connection', ->
it 'should connect to express and return a string Hello World', (done) ->
api.get (err, ret) ->
assert.equal err, null
assert.equal ret, 'Hello World !'
do done
it 'should return an array (from json) of customers', (done) ->
api('customers').get (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret.length, 3
do done
it 'should post data', (done) ->
api('test-post').post {'user': 'Mickael', 'age': 42, 'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].user, 'Mickael'
assert.equal ret['parsed-body'].age, 42
assert.equal ret['parsed-body'].gender, 'male'
do done
it 'should put data', (done) ->
api('test-put').put {'test': 42, 'test2': 'toto'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 42
assert.equal ret['parsed-body'].test2, 'toto'
do done
it 'should patch data', (done) ->
api('test-patch').patch {'test': 43, 'test2': 'titi'}, (err, ret) ->
assert.equal err, null
assert.equal 'object', typeof ret
assert.equal ret['parsed-body'].test, 43
assert.equal ret['parsed-body'].test2, 'titi'
do done
it 'should delete data', (done) ->
api('test-delete').delete (err, ret) ->
assert.equal err, null
assert.equal ret, true
do done
it 'should return customer object (from json) with id = 1', (done) ->
api('customers')(1).get (err, ret) ->
assert.equal ret.user, CUSTOMERS[1].user
assert.equal ret.age, CUSTOMERS[1].age
assert.equal ret.gender, CUSTOMERS[1].gender
do done
it 'should return an array (from json) of customers for gender=male', (done) ->
api('customers').get {'gender': 'male'}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should return an array (from json) of customers for gender=male explicitely defining args', (done) ->
api('customers').get {'__args': {'gender': 'male'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.length, 2
do done
it 'should not detect yaml content-type and return an object', (done) ->
api('customers-yml').get (err, ret) ->
assert.equal null, err
assert.equal 'string', typeof ret
do done
it 'should detect yaml content-type and return an object', (done) ->
api('customers-yml-with-header').get (err, ret) ->
assert.equal null, err
assert.equal 'object', typeof ret
assert.equal 'PI:NAME:<NAME>END_PI', ret[1].user
do done
describe 'Passing headers', ->
headers =
"X-AAA": 42
"X-BBB": "test"
headers_override =
"X-AAA": 43
"X-CCC": "hello"
it 'should pass headers when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: headers}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '42'
assert.equal ret.headers['x-bbb'], 'test'
do done
it 'should pass headers globally and override them when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: headers}, ->
api('test-headers').get {headers: headers_override}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['x-aaa'], '43'
assert.equal ret.headers['x-bbb'], 'test'
assert.equal ret.headers['x-ccc'], 'hello'
do done
it 'should have a default user-agent', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
defaultVersion = require('../package.json').version
targetVersion = "node-slumber/#{defaultVersion}"
assert.equal ret.headers['user-agent'], targetVersion
do done
it 'should override user-agent globally', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'user-agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent globally using capitalize', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {headers: {'User-Agent': 'test'}}, ->
api('test-headers').get {}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
it 'should override user-agent when calling method', (done) ->
freeport (err, port) ->
app.listen port, ->
api = slumber.API "http://localhost:#{port}/", {}, ->
api('test-headers').get {headers: {'User-Agent': 'test'}}, (err, ret) ->
assert.equal err, null
assert.equal ret.headers['user-agent'], 'test'
do done
describe 'Rare cases', ->
api = null
describe 'Non existing remote host', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an handled error', (done) ->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get (err, ret) ->
assert.equal ret, null
assert.equal err.code, 'ENOTFOUND'
assert.equal err.errno, 'ENOTFOUND'
do done
describe 'Call method without callback', ->
api = slumber.API 'http://alskdjgalskdjgalskdjgalskdjgalskdgj.com', {}
it 'should raise an exception', ->
assert.throws (->
api('lkasdjglaksdjglkasdjglkasdjglkasdg').get()
), Error
|
[
{
"context": "onize\" module\n#\n# Nodize CMS\n# https://github.com/hypee/nodize\n#\n# Copyright 2012-2013, Hypee\n# http://hy",
"end": 71,
"score": 0.9994471669197083,
"start": 66,
"tag": "USERNAME",
"value": "hypee"
},
{
"context": "//github.com/hypee/nodize\n#\n# Copyright 2012-2013, Hypee\n# http://hypee.com\n#\n# Licensed under the MIT lic",
"end": 109,
"score": 0.9835984110832214,
"start": 104,
"tag": "NAME",
"value": "Hypee"
}
] | modules/ionize/module_ionize.coffee | nodize/nodizecms | 32 | # Nodize core "ionize" module
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012-2013, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
_moduleName = "ionize"
#**********************************
#* LOADING VIEWS, HELPERS, CONTROLLERS
#**
fs = require 'fs'
#path = require 'path'
includeFolders = []
includeFolders.push "./modules/#{_moduleName}/views/"
includeFolders.push "./modules/#{_moduleName}/controllers/"
includeFolders.push "./modules/#{_moduleName}/helpers/"
for includeFolder in includeFolders
if fs.existsSync includeFolder
files = fs.readdirSync includeFolder
@include includeFolder+file for file in files
#**********************************
#* HELPERS FOR JADE ENGINE
#**
jade_support = require __applicationPath+"/modules/ionize/libs/jade_helpers_filters"
jade_support.createFilters( @helpers )
#**********************************
#* CATCH ALL & PAGES DISPLAY MANAGEMENT
#**
# Managing all other cases
@all '*': (req, res) =>
@catch_all( req, res )
@catch_all = ( req, res ) =>
name = req.params[0]
#
# We don't intercept request for zappa.js client libs
#
if name in ["/zappa/zappa.js", "/zappa/Zappa.js", "/zappa/Zappa-simple.js", "/zappa/jquery.js" ] or name.indexOf("/zappa/socket/") is 0
#console.log "passthru ->", name
req.next()
return
#
# Looking for a matching page in Ionize database (if no extension is specified)
#
ext = getExt(name)
if ext == ""
name=name.replace( "/", "" )
@ionize_displayPage( req, res, @helpers, name )
else
#
# Extracting lang from URI
#
segments = name.split('/')
#
# Redirect to / path for resources if lang is specified
# (/en/css/styles.css is redirected to /css/styles.css)
#
if segments[1] in Static_langs?
lang = segments[1]
#
# Remove lang segment
#
segments.splice( 1, 1 )
name = segments.join("/")
#
# Do the redirection
#
res.redirect( name )
else
res.send("you are requesting #{req.params[0]} (file extension:#{ext})", 404)
#
# Error management
#
nodizeErrorHandler = (err, req, res, next) ->
res.send( 500, "Nodize error <hr/>"+err )
console.log "Nodize error \r\n", err.stack
@configure
development: => @use nodizeErrorHandler
production: => @use 'errorHandler'
#**********************************
#* GENERIC FUNCTIONS
#**
# Return file extension
# @param {string} file name
# @return {string} file extension, without the .
getExt = (filename) ->
ext = filename.split('.').pop();
if ext == filename
''
else
ext
#**********************************
#* LANGS
#**
#
# Load translation from settings folder
# TODO: auto load existing files
#
nconf = require 'nconf'
nconf.add( 'lang_en', {type: 'file', file:'settings/langs/lang_en.json' } )
nconf.add( 'lang_fr', {type: 'file', file:'settings/langs/lang_fr.json' } )
global.ion_lang = {}
ion_lang['en'] = nconf.get "en"
ion_lang['fr'] = nconf.get "fr"
#
# Monkey patching Date, to allow returning date in MySQL format
#
Date::_toMysql = ->
if isNaN( this.getDate() )
strDate = ''
else
strDate = this.getFullYear()+'-'
# Month starts at 0, we add 1 for human display
strDate += '0' if parseInt(this.getMonth())<=8
strDate += this.getMonth()+1+'-'
strDate += '0' if this.getDate()<=9
strDate += this.getDate()+' '
strDate += '0' if this.getHours()<=9
strDate += this.getHours()+':'
strDate += '0' if this.getMinutes()<=9
strDate += this.getMinutes()+':00'
return strDate
#
# Monkey patching String, to emulate "Date" fields when using SQLite
#
String::_toMysql = ->
myDate = new Date()
if isNaN( myDate.getDate(this) )
strDate = ''
else
date = myDate.getDate( this )
return ""
strDate = date.getFullYear()+'-'
strDate += '0' if date.getMonth()<=9
strDate += date.getMonth()+1+'-'
strDate += '0' if date.getDate()<=9
strDate += date.getDate()+' '
strDate += '0' if date.getHours()<=9
strDate += date.getHours()+':'
strDate += '0' if date.getMinutes()<=9
strDate += date.getMinutes()+':00'
return strDate
String::getDate = ->
return ""
String::getMonth = ->
return ""
#**********************************
#* DATABASE MODELS
#*
#**
#
# Connecting to the database & creating models
#
nodize_db = require __applicationPath+"/modules/ionize/libs/nodize_db"
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
| 126484 | # Nodize core "ionize" module
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012-2013, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
_moduleName = "ionize"
#**********************************
#* LOADING VIEWS, HELPERS, CONTROLLERS
#**
fs = require 'fs'
#path = require 'path'
includeFolders = []
includeFolders.push "./modules/#{_moduleName}/views/"
includeFolders.push "./modules/#{_moduleName}/controllers/"
includeFolders.push "./modules/#{_moduleName}/helpers/"
for includeFolder in includeFolders
if fs.existsSync includeFolder
files = fs.readdirSync includeFolder
@include includeFolder+file for file in files
#**********************************
#* HELPERS FOR JADE ENGINE
#**
jade_support = require __applicationPath+"/modules/ionize/libs/jade_helpers_filters"
jade_support.createFilters( @helpers )
#**********************************
#* CATCH ALL & PAGES DISPLAY MANAGEMENT
#**
# Managing all other cases
@all '*': (req, res) =>
@catch_all( req, res )
@catch_all = ( req, res ) =>
name = req.params[0]
#
# We don't intercept request for zappa.js client libs
#
if name in ["/zappa/zappa.js", "/zappa/Zappa.js", "/zappa/Zappa-simple.js", "/zappa/jquery.js" ] or name.indexOf("/zappa/socket/") is 0
#console.log "passthru ->", name
req.next()
return
#
# Looking for a matching page in Ionize database (if no extension is specified)
#
ext = getExt(name)
if ext == ""
name=name.replace( "/", "" )
@ionize_displayPage( req, res, @helpers, name )
else
#
# Extracting lang from URI
#
segments = name.split('/')
#
# Redirect to / path for resources if lang is specified
# (/en/css/styles.css is redirected to /css/styles.css)
#
if segments[1] in Static_langs?
lang = segments[1]
#
# Remove lang segment
#
segments.splice( 1, 1 )
name = segments.join("/")
#
# Do the redirection
#
res.redirect( name )
else
res.send("you are requesting #{req.params[0]} (file extension:#{ext})", 404)
#
# Error management
#
nodizeErrorHandler = (err, req, res, next) ->
res.send( 500, "Nodize error <hr/>"+err )
console.log "Nodize error \r\n", err.stack
@configure
development: => @use nodizeErrorHandler
production: => @use 'errorHandler'
#**********************************
#* GENERIC FUNCTIONS
#**
# Return file extension
# @param {string} file name
# @return {string} file extension, without the .
getExt = (filename) ->
ext = filename.split('.').pop();
if ext == filename
''
else
ext
#**********************************
#* LANGS
#**
#
# Load translation from settings folder
# TODO: auto load existing files
#
nconf = require 'nconf'
nconf.add( 'lang_en', {type: 'file', file:'settings/langs/lang_en.json' } )
nconf.add( 'lang_fr', {type: 'file', file:'settings/langs/lang_fr.json' } )
global.ion_lang = {}
ion_lang['en'] = nconf.get "en"
ion_lang['fr'] = nconf.get "fr"
#
# Monkey patching Date, to allow returning date in MySQL format
#
Date::_toMysql = ->
if isNaN( this.getDate() )
strDate = ''
else
strDate = this.getFullYear()+'-'
# Month starts at 0, we add 1 for human display
strDate += '0' if parseInt(this.getMonth())<=8
strDate += this.getMonth()+1+'-'
strDate += '0' if this.getDate()<=9
strDate += this.getDate()+' '
strDate += '0' if this.getHours()<=9
strDate += this.getHours()+':'
strDate += '0' if this.getMinutes()<=9
strDate += this.getMinutes()+':00'
return strDate
#
# Monkey patching String, to emulate "Date" fields when using SQLite
#
String::_toMysql = ->
myDate = new Date()
if isNaN( myDate.getDate(this) )
strDate = ''
else
date = myDate.getDate( this )
return ""
strDate = date.getFullYear()+'-'
strDate += '0' if date.getMonth()<=9
strDate += date.getMonth()+1+'-'
strDate += '0' if date.getDate()<=9
strDate += date.getDate()+' '
strDate += '0' if date.getHours()<=9
strDate += date.getHours()+':'
strDate += '0' if date.getMinutes()<=9
strDate += date.getMinutes()+':00'
return strDate
String::getDate = ->
return ""
String::getMonth = ->
return ""
#**********************************
#* DATABASE MODELS
#*
#**
#
# Connecting to the database & creating models
#
nodize_db = require __applicationPath+"/modules/ionize/libs/nodize_db"
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
| true | # Nodize core "ionize" module
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012-2013, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
_moduleName = "ionize"
#**********************************
#* LOADING VIEWS, HELPERS, CONTROLLERS
#**
fs = require 'fs'
#path = require 'path'
includeFolders = []
includeFolders.push "./modules/#{_moduleName}/views/"
includeFolders.push "./modules/#{_moduleName}/controllers/"
includeFolders.push "./modules/#{_moduleName}/helpers/"
for includeFolder in includeFolders
if fs.existsSync includeFolder
files = fs.readdirSync includeFolder
@include includeFolder+file for file in files
#**********************************
#* HELPERS FOR JADE ENGINE
#**
jade_support = require __applicationPath+"/modules/ionize/libs/jade_helpers_filters"
jade_support.createFilters( @helpers )
#**********************************
#* CATCH ALL & PAGES DISPLAY MANAGEMENT
#**
# Managing all other cases
@all '*': (req, res) =>
@catch_all( req, res )
@catch_all = ( req, res ) =>
name = req.params[0]
#
# We don't intercept request for zappa.js client libs
#
if name in ["/zappa/zappa.js", "/zappa/Zappa.js", "/zappa/Zappa-simple.js", "/zappa/jquery.js" ] or name.indexOf("/zappa/socket/") is 0
#console.log "passthru ->", name
req.next()
return
#
# Looking for a matching page in Ionize database (if no extension is specified)
#
ext = getExt(name)
if ext == ""
name=name.replace( "/", "" )
@ionize_displayPage( req, res, @helpers, name )
else
#
# Extracting lang from URI
#
segments = name.split('/')
#
# Redirect to / path for resources if lang is specified
# (/en/css/styles.css is redirected to /css/styles.css)
#
if segments[1] in Static_langs?
lang = segments[1]
#
# Remove lang segment
#
segments.splice( 1, 1 )
name = segments.join("/")
#
# Do the redirection
#
res.redirect( name )
else
res.send("you are requesting #{req.params[0]} (file extension:#{ext})", 404)
#
# Error management
#
nodizeErrorHandler = (err, req, res, next) ->
res.send( 500, "Nodize error <hr/>"+err )
console.log "Nodize error \r\n", err.stack
@configure
development: => @use nodizeErrorHandler
production: => @use 'errorHandler'
#**********************************
#* GENERIC FUNCTIONS
#**
# Return file extension
# @param {string} file name
# @return {string} file extension, without the .
getExt = (filename) ->
ext = filename.split('.').pop();
if ext == filename
''
else
ext
#**********************************
#* LANGS
#**
#
# Load translation from settings folder
# TODO: auto load existing files
#
nconf = require 'nconf'
nconf.add( 'lang_en', {type: 'file', file:'settings/langs/lang_en.json' } )
nconf.add( 'lang_fr', {type: 'file', file:'settings/langs/lang_fr.json' } )
global.ion_lang = {}
ion_lang['en'] = nconf.get "en"
ion_lang['fr'] = nconf.get "fr"
#
# Monkey patching Date, to allow returning date in MySQL format
#
Date::_toMysql = ->
if isNaN( this.getDate() )
strDate = ''
else
strDate = this.getFullYear()+'-'
# Month starts at 0, we add 1 for human display
strDate += '0' if parseInt(this.getMonth())<=8
strDate += this.getMonth()+1+'-'
strDate += '0' if this.getDate()<=9
strDate += this.getDate()+' '
strDate += '0' if this.getHours()<=9
strDate += this.getHours()+':'
strDate += '0' if this.getMinutes()<=9
strDate += this.getMinutes()+':00'
return strDate
#
# Monkey patching String, to emulate "Date" fields when using SQLite
#
String::_toMysql = ->
myDate = new Date()
if isNaN( myDate.getDate(this) )
strDate = ''
else
date = myDate.getDate( this )
return ""
strDate = date.getFullYear()+'-'
strDate += '0' if date.getMonth()<=9
strDate += date.getMonth()+1+'-'
strDate += '0' if date.getDate()<=9
strDate += date.getDate()+' '
strDate += '0' if date.getHours()<=9
strDate += date.getHours()+':'
strDate += '0' if date.getMinutes()<=9
strDate += date.getMinutes()+':00'
return strDate
String::getDate = ->
return ""
String::getMonth = ->
return ""
#**********************************
#* DATABASE MODELS
#*
#**
#
# Connecting to the database & creating models
#
nodize_db = require __applicationPath+"/modules/ionize/libs/nodize_db"
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
|
[
{
"context": "ken\"\n input: [\n token: \"test token one\"\n starts: 32\n ends:",
"end": 2001,
"score": 0.7201690673828125,
"start": 1987,
"tag": "KEY",
"value": "test token one"
},
{
"context": "\n input: [\n token: \"test token one\"\n starts: 32\n ",
"end": 2502,
"score": 0.7602076530456543,
"start": 2492,
"tag": "KEY",
"value": "test token"
},
{
"context": " parsesExpression: [\n token: \"test token one\"\n starts: 32\n e",
"end": 2803,
"score": 0.6983166337013245,
"start": 2793,
"tag": "KEY",
"value": "test token"
}
] | src/coffee/expression/parse/call.spec.coffee | jameswilddev/influx7 | 1 | describe "expression", -> describe "parse", -> describe "call", ->
rewire = require "rewire"
describe "imports", ->
expressionParseCall = rewire "./call"
it "expressionParse", -> (expect expressionParseCall.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseArgumentList", -> (expect expressionParseCall.__get__ "expressionParseArgumentList").toBe require "./argumentList"
describe "on calling", ->
expressionParseCall = rewire "./call"
run = (config) -> describe config.description, ->
result = inputCopy = undefined
beforeEach ->
expressionParseCall.__set__ "expressionParse", (expr, declarations) ->
if config.parsesExpression
(expect expr).toEqual config.parsesExpression
(expect declarations).toEqual "test declarations"
"test parsed lambda expression"
else fail "unexpected call to parseExpression"
expressionParseCall.__set__ "expressionParseArgumentList", (token, declarations) ->
if config.parsesArgumentList
(expect token).toEqual config.parsesArgumentList
(expect declarations).toEqual "test declarations"
"test parsed argument list"
else fail "unexpected call to expressionParseArgumentList"
inputCopy = JSON.parse JSON.stringify config.input
result = expressionParseCall config.input, "test declarations"
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "returns the expected output", -> (expect result).toEqual config.output
run
description: "nothing"
input: []
output: null
run
description: "one token"
input: [
token: "test token one"
starts: 32
ends: 65
]
output: null
run
description: "one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
]
output: null
run
description: "one token followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by one token"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
]
output: null
run
description: "two tokens"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
output: null
run
description: "two sets of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "("
starts: 70
ends: 89
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by two tokens"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "one token followed by one set of parentheses followed by one token"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "two tokens followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one set of parentheses followed by one token followed by one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one token followed by one set of parentheses followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114 | 141431 | describe "expression", -> describe "parse", -> describe "call", ->
rewire = require "rewire"
describe "imports", ->
expressionParseCall = rewire "./call"
it "expressionParse", -> (expect expressionParseCall.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseArgumentList", -> (expect expressionParseCall.__get__ "expressionParseArgumentList").toBe require "./argumentList"
describe "on calling", ->
expressionParseCall = rewire "./call"
run = (config) -> describe config.description, ->
result = inputCopy = undefined
beforeEach ->
expressionParseCall.__set__ "expressionParse", (expr, declarations) ->
if config.parsesExpression
(expect expr).toEqual config.parsesExpression
(expect declarations).toEqual "test declarations"
"test parsed lambda expression"
else fail "unexpected call to parseExpression"
expressionParseCall.__set__ "expressionParseArgumentList", (token, declarations) ->
if config.parsesArgumentList
(expect token).toEqual config.parsesArgumentList
(expect declarations).toEqual "test declarations"
"test parsed argument list"
else fail "unexpected call to expressionParseArgumentList"
inputCopy = JSON.parse JSON.stringify config.input
result = expressionParseCall config.input, "test declarations"
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "returns the expected output", -> (expect result).toEqual config.output
run
description: "nothing"
input: []
output: null
run
description: "one token"
input: [
token: "<KEY>"
starts: 32
ends: 65
]
output: null
run
description: "one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
]
output: null
run
description: "one token followed by one set of parentheses"
input: [
token: "<KEY> one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
]
parsesExpression: [
token: "<KEY> one"
starts: 32
ends: 65
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by one token"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
]
output: null
run
description: "two tokens"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
output: null
run
description: "two sets of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "("
starts: 70
ends: 89
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by two tokens"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "one token followed by one set of parentheses followed by one token"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "two tokens followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one set of parentheses followed by one token followed by one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one token followed by one set of parentheses followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114 | true | describe "expression", -> describe "parse", -> describe "call", ->
rewire = require "rewire"
describe "imports", ->
expressionParseCall = rewire "./call"
it "expressionParse", -> (expect expressionParseCall.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseArgumentList", -> (expect expressionParseCall.__get__ "expressionParseArgumentList").toBe require "./argumentList"
describe "on calling", ->
expressionParseCall = rewire "./call"
run = (config) -> describe config.description, ->
result = inputCopy = undefined
beforeEach ->
expressionParseCall.__set__ "expressionParse", (expr, declarations) ->
if config.parsesExpression
(expect expr).toEqual config.parsesExpression
(expect declarations).toEqual "test declarations"
"test parsed lambda expression"
else fail "unexpected call to parseExpression"
expressionParseCall.__set__ "expressionParseArgumentList", (token, declarations) ->
if config.parsesArgumentList
(expect token).toEqual config.parsesArgumentList
(expect declarations).toEqual "test declarations"
"test parsed argument list"
else fail "unexpected call to expressionParseArgumentList"
inputCopy = JSON.parse JSON.stringify config.input
result = expressionParseCall config.input, "test declarations"
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "returns the expected output", -> (expect result).toEqual config.output
run
description: "nothing"
input: []
output: null
run
description: "one token"
input: [
token: "PI:KEY:<KEY>END_PI"
starts: 32
ends: 65
]
output: null
run
description: "one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
]
output: null
run
description: "one token followed by one set of parentheses"
input: [
token: "PI:KEY:<KEY>END_PI one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
]
parsesExpression: [
token: "PI:KEY:<KEY>END_PI one"
starts: 32
ends: 65
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by one token"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
]
output: null
run
description: "two tokens"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
output: null
run
description: "two sets of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "("
starts: 70
ends: 89
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 70
ends: 89
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 70
ends: 89
run
description: "one set of parentheses followed by two tokens"
input: [
token: "("
starts: 32
ends: 65
children: "test children"
,
token: "test token one"
starts: 70
ends: 89
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "one token followed by one set of parentheses followed by one token"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children"
,
token: "test token two"
starts: 96
ends: 114
]
output: null
run
description: "two tokens followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "test token two"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one set of parentheses followed by one token followed by one set of parentheses"
input: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "("
starts: 32
ends: 65
children: "test children a"
,
token: "test token one"
starts: 70
ends: 89
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114
run
description: "one token followed by one set of parentheses followed by one set of parentheses"
input: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
,
token: "("
starts: 96
ends: 114
children: "test children b"
]
parsesExpression: [
token: "test token one"
starts: 32
ends: 65
,
token: "("
starts: 70
ends: 89
children: "test children a"
]
parsesArgumentList:
token: "("
starts: 96
ends: 114
children: "test children b"
output:
callLambda: "test parsed lambda expression"
with: "test parsed argument list"
starts: 96
ends: 114 |
[
{
"context": "{\n name: \"UNO\"\n serviceKeys: [\n \"uno\"\n \"uno-mobile\"\n \"global-m2m\"\n ",
"end": 1186,
"score": 0.7619909644126892,
"start": 1183,
"tag": "KEY",
"value": "uno"
},
{
"context": "\"UNO\"\n serviceKeys: [\n \"uno\"\n \"uno-mobile\"\n \"global-m2m\"\n \"uno-virtual\"\n ",
"end": 1207,
"score": 0.9582746624946594,
"start": 1197,
"tag": "KEY",
"value": "uno-mobile"
},
{
"context": "ys: [\n \"uno\"\n \"uno-mobile\"\n \"global-m2m\"\n \"uno-virtual\"\n ]\n }\n {\n ",
"end": 1228,
"score": 0.9651257395744324,
"start": 1218,
"tag": "KEY",
"value": "global-m2m"
},
{
"context": " \"uno-mobile\"\n \"global-m2m\"\n \"uno-virtual\"\n ]\n }\n {\n name: \"Cloud\"\n ",
"end": 1242,
"score": 0.5616123676300049,
"start": 1242,
"tag": "KEY",
"value": ""
},
{
"context": " name: \"Cloud\"\n serviceKeys: [\n \"cloudn\"\n \"bhec\"\n ]\n }\n {\n name: \"",
"end": 1328,
"score": 0.9951112270355225,
"start": 1322,
"tag": "KEY",
"value": "cloudn"
},
{
"context": "d\"\n serviceKeys: [\n \"cloudn\"\n \"bhec\"\n ]\n }\n {\n name: \"Voice\"\n se",
"end": 1343,
"score": 0.9954944252967834,
"start": 1339,
"tag": "KEY",
"value": "bhec"
},
{
"context": " name: \"Voice\"\n serviceKeys: [\n \"ucaas\"\n \"sip-trunking\"\n \"050plusbiz\"\n ",
"end": 1420,
"score": 0.998891294002533,
"start": 1415,
"tag": "KEY",
"value": "ucaas"
},
{
"context": "ce\"\n serviceKeys: [\n \"ucaas\"\n \"sip-trunking\"\n \"050plusbiz\"\n \"ip-voice\"\n ",
"end": 1443,
"score": 0.9988266229629517,
"start": 1431,
"tag": "KEY",
"value": "sip-trunking"
},
{
"context": "[\n \"ucaas\"\n \"sip-trunking\"\n \"050plusbiz\"\n \"ip-voice\"\n \"smart-pbx\"\n \"",
"end": 1464,
"score": 0.998543918132782,
"start": 1454,
"tag": "KEY",
"value": "050plusbiz"
},
{
"context": " \"sip-trunking\"\n \"050plusbiz\"\n \"ip-voice\"\n \"smart-pbx\"\n \"accs\"\n ]\n }",
"end": 1483,
"score": 0.937222957611084,
"start": 1475,
"tag": "KEY",
"value": "ip-voice"
},
{
"context": "\n \"050plusbiz\"\n \"ip-voice\"\n \"smart-pbx\"\n \"accs\"\n ]\n }\n {\n name: \"",
"end": 1503,
"score": 0.9955507516860962,
"start": 1494,
"tag": "KEY",
"value": "smart-pbx"
},
{
"context": "\"\n \"ip-voice\"\n \"smart-pbx\"\n \"accs\"\n ]\n }\n {\n name: \"App\"\n serv",
"end": 1518,
"score": 0.9310423135757446,
"start": 1514,
"tag": "KEY",
"value": "accs"
},
{
"context": "{\n name: \"App\"\n serviceKeys: [\n \"bizmail\"\n \"bdp-e\"\n \"mss\"\n \"gmone\"\n ",
"end": 1595,
"score": 0.9987955689430237,
"start": 1588,
"tag": "KEY",
"value": "bizmail"
},
{
"context": "\"\n serviceKeys: [\n \"bizmail\"\n \"bdp-e\"\n \"mss\"\n \"gmone\"\n ]\n }]\n",
"end": 1611,
"score": 0.998856246471405,
"start": 1606,
"tag": "KEY",
"value": "bdp-e"
},
{
"context": "eys: [\n \"bizmail\"\n \"bdp-e\"\n \"mss\"\n \"gmone\"\n ]\n }]\n",
"end": 1625,
"score": 0.9930734038352966,
"start": 1622,
"tag": "KEY",
"value": "mss"
},
{
"context": " \"bizmail\"\n \"bdp-e\"\n \"mss\"\n \"gmone\"\n ]\n }]\n",
"end": 1641,
"score": 0.997111439704895,
"start": 1636,
"tag": "KEY",
"value": "gmone"
}
] | ClientApp/app/scripts/services/services/service_category_constant.coffee | nttcom/apigw-sample-app | 1 | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceCategoryConstant
# @description
# # serviceCategoryConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceCategoryConstant',
[{
name: "UNO"
serviceKeys: [
"uno"
"uno-mobile"
"global-m2m"
"uno-virtual"
]
}
{
name: "Cloud"
serviceKeys: [
"cloudn"
"bhec"
]
}
{
name: "Voice"
serviceKeys: [
"ucaas"
"sip-trunking"
"050plusbiz"
"ip-voice"
"smart-pbx"
"accs"
]
}
{
name: "App"
serviceKeys: [
"bizmail"
"bdp-e"
"mss"
"gmone"
]
}]
| 892 | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceCategoryConstant
# @description
# # serviceCategoryConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceCategoryConstant',
[{
name: "UNO"
serviceKeys: [
"<KEY>"
"<KEY>"
"<KEY>"
"uno<KEY>-virtual"
]
}
{
name: "Cloud"
serviceKeys: [
"<KEY>"
"<KEY>"
]
}
{
name: "Voice"
serviceKeys: [
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
]
}
{
name: "App"
serviceKeys: [
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
]
}]
| true | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceCategoryConstant
# @description
# # serviceCategoryConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceCategoryConstant',
[{
name: "UNO"
serviceKeys: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"unoPI:KEY:<KEY>END_PI-virtual"
]
}
{
name: "Cloud"
serviceKeys: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
}
{
name: "Voice"
serviceKeys: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
}
{
name: "App"
serviceKeys: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
}]
|
[
{
"context": "tInfo.firstName + ' ' + accountInfo.lastName + '\\'S SHOWS'\n\t\t\t$scope.loadMore()\n]",
"end": 1173,
"score": 0.9204910397529602,
"start": 1166,
"tag": "NAME",
"value": "S SHOWS"
}
] | src/controllers/AccountDetailController.coffee | waltzcode/showroom-shopify | 0 | angular.module 'showroomControllers'
.controller 'AccountDetailController', [
'$scope', '$rootScope', 'showService', 'userService', '$log', '$routeParams', 'videoService'
($scope, $rootScope, showService, userService, $log, $routeParams, videoService) ->
# display setting
$rootScope.removeHeader = false
$rootScope.removeBrand = false
$rootScope.removeNav = false
$rootScope.removeFooter = false
$scope.header = 'Account Show'
$scope.currentPage = 0
$scope.hasMore = true
$scope.videos = []
$scope.loadMore = ->
showService.getShowByUser accountId: $routeParams.accountId, pageNumber: $scope.currentPage++
.then (response) ->
if response.data.code == 1000
$scope.videos = $scope.videos.concat videoService.parseVideo response:response.data
$scope.hasMore = false if $scope.videos.length >= response.data.payload.totalItem
else
$log.error response.data.message
userService.getAccountProfile accountId: $routeParams.accountId
.then (response) ->
if response.data.code == 1000
accountInfo = response.data.payload.accountInfo
$scope.header = accountInfo.firstName + ' ' + accountInfo.lastName + '\'S SHOWS'
$scope.loadMore()
] | 188174 | angular.module 'showroomControllers'
.controller 'AccountDetailController', [
'$scope', '$rootScope', 'showService', 'userService', '$log', '$routeParams', 'videoService'
($scope, $rootScope, showService, userService, $log, $routeParams, videoService) ->
# display setting
$rootScope.removeHeader = false
$rootScope.removeBrand = false
$rootScope.removeNav = false
$rootScope.removeFooter = false
$scope.header = 'Account Show'
$scope.currentPage = 0
$scope.hasMore = true
$scope.videos = []
$scope.loadMore = ->
showService.getShowByUser accountId: $routeParams.accountId, pageNumber: $scope.currentPage++
.then (response) ->
if response.data.code == 1000
$scope.videos = $scope.videos.concat videoService.parseVideo response:response.data
$scope.hasMore = false if $scope.videos.length >= response.data.payload.totalItem
else
$log.error response.data.message
userService.getAccountProfile accountId: $routeParams.accountId
.then (response) ->
if response.data.code == 1000
accountInfo = response.data.payload.accountInfo
$scope.header = accountInfo.firstName + ' ' + accountInfo.lastName + '\'<NAME>'
$scope.loadMore()
] | true | angular.module 'showroomControllers'
.controller 'AccountDetailController', [
'$scope', '$rootScope', 'showService', 'userService', '$log', '$routeParams', 'videoService'
($scope, $rootScope, showService, userService, $log, $routeParams, videoService) ->
# display setting
$rootScope.removeHeader = false
$rootScope.removeBrand = false
$rootScope.removeNav = false
$rootScope.removeFooter = false
$scope.header = 'Account Show'
$scope.currentPage = 0
$scope.hasMore = true
$scope.videos = []
$scope.loadMore = ->
showService.getShowByUser accountId: $routeParams.accountId, pageNumber: $scope.currentPage++
.then (response) ->
if response.data.code == 1000
$scope.videos = $scope.videos.concat videoService.parseVideo response:response.data
$scope.hasMore = false if $scope.videos.length >= response.data.payload.totalItem
else
$log.error response.data.message
userService.getAccountProfile accountId: $routeParams.accountId
.then (response) ->
if response.data.code == 1000
accountInfo = response.data.payload.accountInfo
$scope.header = accountInfo.firstName + ' ' + accountInfo.lastName + '\'PI:NAME:<NAME>END_PI'
$scope.loadMore()
] |
[
{
"context": "\n #\n # options = \n # user_text: 'Hello world'\n #\n # *OR*\n #\n # options =\n # ",
"end": 277,
"score": 0.9191247820854187,
"start": 266,
"tag": "NAME",
"value": "Hello world"
}
] | src/node-wit.coffee | jsgoecke/node-wit | 1 | class Wit
constructor: (access_token, uri) ->
@fs = require 'fs'
@request = require 'request'
@access_token = access_token
@uri = uri || 'https://api.wit.ai'
##
# Analyze text or audio messages
#
# options =
# user_text: 'Hello world'
#
# *OR*
#
# options =
# audio_file: './audio_sample/helloWorld.wav'
#
# analyze options, (err, res, body) ->
# console.log JSON.parse body
analyze: (options, callback) ->
request_options =
headers:
Authorization: "Bearer #{@access_token}"
if options.audio_file
request_options.method = 'POST'
request_options.uri = @uri + '/speech'
request_options.headers['Content-Type'] = options.content_type || 'audio/wav;rate=8000'
@fs.readFile options.audio_file, (err, data) =>
request_options.body = data
@request request_options, callback
else
request_options.method = 'GET'
request_options.uri = @uri + "/message?q=#{encodeURIComponent(options.user_text)}"
@request request_options, callback
module.exports = Wit | 224759 | class Wit
constructor: (access_token, uri) ->
@fs = require 'fs'
@request = require 'request'
@access_token = access_token
@uri = uri || 'https://api.wit.ai'
##
# Analyze text or audio messages
#
# options =
# user_text: '<NAME>'
#
# *OR*
#
# options =
# audio_file: './audio_sample/helloWorld.wav'
#
# analyze options, (err, res, body) ->
# console.log JSON.parse body
analyze: (options, callback) ->
request_options =
headers:
Authorization: "Bearer #{@access_token}"
if options.audio_file
request_options.method = 'POST'
request_options.uri = @uri + '/speech'
request_options.headers['Content-Type'] = options.content_type || 'audio/wav;rate=8000'
@fs.readFile options.audio_file, (err, data) =>
request_options.body = data
@request request_options, callback
else
request_options.method = 'GET'
request_options.uri = @uri + "/message?q=#{encodeURIComponent(options.user_text)}"
@request request_options, callback
module.exports = Wit | true | class Wit
constructor: (access_token, uri) ->
@fs = require 'fs'
@request = require 'request'
@access_token = access_token
@uri = uri || 'https://api.wit.ai'
##
# Analyze text or audio messages
#
# options =
# user_text: 'PI:NAME:<NAME>END_PI'
#
# *OR*
#
# options =
# audio_file: './audio_sample/helloWorld.wav'
#
# analyze options, (err, res, body) ->
# console.log JSON.parse body
analyze: (options, callback) ->
request_options =
headers:
Authorization: "Bearer #{@access_token}"
if options.audio_file
request_options.method = 'POST'
request_options.uri = @uri + '/speech'
request_options.headers['Content-Type'] = options.content_type || 'audio/wav;rate=8000'
@fs.readFile options.audio_file, (err, data) =>
request_options.body = data
@request request_options, callback
else
request_options.method = 'GET'
request_options.uri = @uri + "/message?q=#{encodeURIComponent(options.user_text)}"
@request request_options, callback
module.exports = Wit |
[
{
"context": ".inDir DEST\n .withOptions\n realname: 'Alex Gorbatchev'\n githubUrl: 'https://github.com/alexgorba",
"end": 378,
"score": 0.9998796582221985,
"start": 363,
"tag": "NAME",
"value": "Alex Gorbatchev"
},
{
"context": "orbatchev'\n githubUrl: 'https://github.com/alexgorbatchev'\n .withPrompt\n githubUser: 'alexgorba",
"end": 433,
"score": 0.9996706247329712,
"start": 419,
"tag": "USERNAME",
"value": "alexgorbatchev"
},
{
"context": "orbatchev'\n .withPrompt\n githubUser: 'alexgorbatchev'\n generatorName: GENERATOR_NAME\n .on ",
"end": 488,
"score": 0.99961918592453,
"start": 474,
"tag": "USERNAME",
"value": "alexgorbatchev"
}
] | test/app.spec.coffee | octoblu/generator-nanocyte-component | 0 | path = require 'path'
fs = require 'fs'
{exec} = require 'child_process'
helpers = require('yeoman-generator').test
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "generator-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'Alex Gorbatchev'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompt
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
helpers.assertFile '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
| 58133 | path = require 'path'
fs = require 'fs'
{exec} = require 'child_process'
helpers = require('yeoman-generator').test
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "generator-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: '<NAME>'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompt
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
helpers.assertFile '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
| true | path = require 'path'
fs = require 'fs'
{exec} = require 'child_process'
helpers = require('yeoman-generator').test
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "generator-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'PI:NAME:<NAME>END_PI'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompt
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
helpers.assertFile '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
|
[
{
"context": " BIND_CONFLICT: \"绑定账号已存在\"\n PASSWORD_TOO_SIMPLE: \"密码过于简单\"\n LOGIN_VERIFY_FAILED: '登录失败,邮箱,手机号或密码错误'\n ACCO",
"end": 449,
"score": 0.9321833848953247,
"start": 443,
"tag": "PASSWORD",
"value": "密码过于简单"
}
] | talk-account/server/initializers/locales/zh.coffee | ikingye/talk-os | 3,084 | module.exports =
NOT_FOUND: 'Not Found'
OBJECT_MISSING: (msg = '') -> "对象不存在 #{msg}"
PARAMS_INVALID: (msg = '') -> "错误的参数 #{msg}"
PARAMS_MISSING: (msg = '') -> "缺少参数 #{msg}"
RATE_LIMIT_EXCEEDED: "请求过于频繁"
REQUEST_FAILED: '请求失败'
VERIFY_FAILED: '验证失败'
ACCESS_FAILED: '无权限访问'
RESEND_TOO_OFTEN: '发送过于频繁'
INVALID_SOURCE: (source) -> "错误的来源 #{source}"
LOGIN_FAILED: "登录失败:%s"
BIND_CONFLICT: "绑定账号已存在"
PASSWORD_TOO_SIMPLE: "密码过于简单"
LOGIN_VERIFY_FAILED: '登录失败,邮箱,手机号或密码错误'
ACCOUNT_EXISTS: '账号已存在'
INVALID_ACTION: '错误的 action 参数'
ACCOUNT_NOT_EXIST: '账号不存在'
SEND_SMS_ERROR: '发送短信失败'
NO_PASSWORD: "账号尚未设置密码,请通过找回密码登录"
| 102346 | module.exports =
NOT_FOUND: 'Not Found'
OBJECT_MISSING: (msg = '') -> "对象不存在 #{msg}"
PARAMS_INVALID: (msg = '') -> "错误的参数 #{msg}"
PARAMS_MISSING: (msg = '') -> "缺少参数 #{msg}"
RATE_LIMIT_EXCEEDED: "请求过于频繁"
REQUEST_FAILED: '请求失败'
VERIFY_FAILED: '验证失败'
ACCESS_FAILED: '无权限访问'
RESEND_TOO_OFTEN: '发送过于频繁'
INVALID_SOURCE: (source) -> "错误的来源 #{source}"
LOGIN_FAILED: "登录失败:%s"
BIND_CONFLICT: "绑定账号已存在"
PASSWORD_TOO_SIMPLE: "<PASSWORD>"
LOGIN_VERIFY_FAILED: '登录失败,邮箱,手机号或密码错误'
ACCOUNT_EXISTS: '账号已存在'
INVALID_ACTION: '错误的 action 参数'
ACCOUNT_NOT_EXIST: '账号不存在'
SEND_SMS_ERROR: '发送短信失败'
NO_PASSWORD: "账号尚未设置密码,请通过找回密码登录"
| true | module.exports =
NOT_FOUND: 'Not Found'
OBJECT_MISSING: (msg = '') -> "对象不存在 #{msg}"
PARAMS_INVALID: (msg = '') -> "错误的参数 #{msg}"
PARAMS_MISSING: (msg = '') -> "缺少参数 #{msg}"
RATE_LIMIT_EXCEEDED: "请求过于频繁"
REQUEST_FAILED: '请求失败'
VERIFY_FAILED: '验证失败'
ACCESS_FAILED: '无权限访问'
RESEND_TOO_OFTEN: '发送过于频繁'
INVALID_SOURCE: (source) -> "错误的来源 #{source}"
LOGIN_FAILED: "登录失败:%s"
BIND_CONFLICT: "绑定账号已存在"
PASSWORD_TOO_SIMPLE: "PI:PASSWORD:<PASSWORD>END_PI"
LOGIN_VERIFY_FAILED: '登录失败,邮箱,手机号或密码错误'
ACCOUNT_EXISTS: '账号已存在'
INVALID_ACTION: '错误的 action 参数'
ACCOUNT_NOT_EXIST: '账号不存在'
SEND_SMS_ERROR: '发送短信失败'
NO_PASSWORD: "账号尚未设置密码,请通过找回密码登录"
|
[
{
"context": " jid: config.thing\n password: config.password\n host: config.host\n port: c",
"end": 772,
"score": 0.999139130115509,
"start": 757,
"tag": "PASSWORD",
"value": "config.password"
},
{
"context": " jid: config.owner\n password: config.password\n host: config.host\n ",
"end": 1160,
"score": 0.9991598129272461,
"start": 1145,
"tag": "PASSWORD",
"value": "config.password"
},
{
"context": "2'/>\n <str name='KEY' value='4857402340298342'/>\n </register>\n <",
"end": 3462,
"score": 0.9996922016143799,
"start": 3446,
"tag": "KEY",
"value": "4857402340298342"
},
{
"context": "2'/>\n <str name='KEY' value='4857402340298342'/>\n </mine>\n </iq",
"end": 4505,
"score": 0.9996283650398254,
"start": 4489,
"tag": "KEY",
"value": "4857402340298342"
}
] | test/003-remove.coffee | TNO-IoT/testing-xep-0347 | 0 | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# This set test the removal function
#
ltx = require('node-xmpp-core').ltx
Client = require 'node-xmpp-client'
bunyan = require 'bunyan'
shortId = require 'shortid'
assert = require 'assert'
chai = require 'chai'
Q = require 'q'
config = require './helpers/config'
log = bunyan.createLogger
name: '003-remove'
level: 'trace'
# global config
thingConn = undefined
ownerConn = undefined
chai.should()
assert = chai.assert
describe 'Delayed notificatons: ', ->
this.timeout 10000
before () ->
defer = Q.defer()
log.trace 'Connecting to XMPP server'
thingConn = new Client
jid: config.thing
password: config.password
host: config.host
port: config.port
reconnect: false
thingConn.once 'online', () ->
log.trace 'Thing is now online.'
thingConn.send '<presence/>'
thingConn.once 'stanza', (stanza) ->
ownerConn = new Client
jid: config.owner
password: config.password
host: config.host
port: config.port
reconnect: false
ownerConn.once 'online', () ->
log.trace 'Owner is now online.'
defer.resolve()
thingConn.on 'error', (err) ->
log.warn err
defer.reject()
return defer.promise
after () ->
defer = Q.defer()
log.trace 'Unsubscribing from presence!'
thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>"
ready = () ->
thingConn.end()
defer.resolve()
setTimeout ready, 100
ownerConn.end()
return defer.promise
describe 'subscribes to the presence of the registry', ->
it '', (done) ->
log.trace 'Sending presence subscription'
message = "<presence type='subscribe'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'presence'
stanza.attrs.type.should.equal 'subscribe'
stanza.attrs.from.should.equal config.registry
answer = "<presence type='subscribed'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ answer }"
thingConn.send answer
done()
describe 'registers the thing in the registry', ->
it 'and receives a confirmation', (done) ->
log.trace 'Sending register message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
done()
describe 'the thing is claimed by the owner', ->
it 'and the owner sends a claim message', (done) ->
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.thing
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.attrs.from.should.equal config.registry
stanza.attrs.type.should.equal 'set'
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.owner
thingConn.send "<iq type='result'
to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
describe 'owner removes the thing from the registry', ->
it 'by sending the remove message and receives a confirmation', (done) ->
log.trace 'Sending remove message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<remove xmlns='urn:xmpp:iot:discovery' jid='#{ config.thing }'/>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'set'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'removed'
thingConn.send "<iq type='result' to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
| 48047 | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# This set test the removal function
#
ltx = require('node-xmpp-core').ltx
Client = require 'node-xmpp-client'
bunyan = require 'bunyan'
shortId = require 'shortid'
assert = require 'assert'
chai = require 'chai'
Q = require 'q'
config = require './helpers/config'
log = bunyan.createLogger
name: '003-remove'
level: 'trace'
# global config
thingConn = undefined
ownerConn = undefined
chai.should()
assert = chai.assert
describe 'Delayed notificatons: ', ->
this.timeout 10000
before () ->
defer = Q.defer()
log.trace 'Connecting to XMPP server'
thingConn = new Client
jid: config.thing
password: <PASSWORD>
host: config.host
port: config.port
reconnect: false
thingConn.once 'online', () ->
log.trace 'Thing is now online.'
thingConn.send '<presence/>'
thingConn.once 'stanza', (stanza) ->
ownerConn = new Client
jid: config.owner
password: <PASSWORD>
host: config.host
port: config.port
reconnect: false
ownerConn.once 'online', () ->
log.trace 'Owner is now online.'
defer.resolve()
thingConn.on 'error', (err) ->
log.warn err
defer.reject()
return defer.promise
after () ->
defer = Q.defer()
log.trace 'Unsubscribing from presence!'
thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>"
ready = () ->
thingConn.end()
defer.resolve()
setTimeout ready, 100
ownerConn.end()
return defer.promise
describe 'subscribes to the presence of the registry', ->
it '', (done) ->
log.trace 'Sending presence subscription'
message = "<presence type='subscribe'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'presence'
stanza.attrs.type.should.equal 'subscribe'
stanza.attrs.from.should.equal config.registry
answer = "<presence type='subscribed'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ answer }"
thingConn.send answer
done()
describe 'registers the thing in the registry', ->
it 'and receives a confirmation', (done) ->
log.trace 'Sending register message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
done()
describe 'the thing is claimed by the owner', ->
it 'and the owner sends a claim message', (done) ->
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.thing
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.attrs.from.should.equal config.registry
stanza.attrs.type.should.equal 'set'
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.owner
thingConn.send "<iq type='result'
to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
describe 'owner removes the thing from the registry', ->
it 'by sending the remove message and receives a confirmation', (done) ->
log.trace 'Sending remove message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<remove xmlns='urn:xmpp:iot:discovery' jid='#{ config.thing }'/>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'set'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'removed'
thingConn.send "<iq type='result' to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
| true | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# This set test the removal function
#
ltx = require('node-xmpp-core').ltx
Client = require 'node-xmpp-client'
bunyan = require 'bunyan'
shortId = require 'shortid'
assert = require 'assert'
chai = require 'chai'
Q = require 'q'
config = require './helpers/config'
log = bunyan.createLogger
name: '003-remove'
level: 'trace'
# global config
thingConn = undefined
ownerConn = undefined
chai.should()
assert = chai.assert
describe 'Delayed notificatons: ', ->
this.timeout 10000
before () ->
defer = Q.defer()
log.trace 'Connecting to XMPP server'
thingConn = new Client
jid: config.thing
password: PI:PASSWORD:<PASSWORD>END_PI
host: config.host
port: config.port
reconnect: false
thingConn.once 'online', () ->
log.trace 'Thing is now online.'
thingConn.send '<presence/>'
thingConn.once 'stanza', (stanza) ->
ownerConn = new Client
jid: config.owner
password: PI:PASSWORD:<PASSWORD>END_PI
host: config.host
port: config.port
reconnect: false
ownerConn.once 'online', () ->
log.trace 'Owner is now online.'
defer.resolve()
thingConn.on 'error', (err) ->
log.warn err
defer.reject()
return defer.promise
after () ->
defer = Q.defer()
log.trace 'Unsubscribing from presence!'
thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>"
ready = () ->
thingConn.end()
defer.resolve()
setTimeout ready, 100
ownerConn.end()
return defer.promise
describe 'subscribes to the presence of the registry', ->
it '', (done) ->
log.trace 'Sending presence subscription'
message = "<presence type='subscribe'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'presence'
stanza.attrs.type.should.equal 'subscribe'
stanza.attrs.from.should.equal config.registry
answer = "<presence type='subscribed'
to='#{ config.registry }'
id='#{ shortId.generate() }'/>"
log.info "Sending message: #{ answer }"
thingConn.send answer
done()
describe 'registers the thing in the registry', ->
it 'and receives a confirmation', (done) ->
log.trace 'Sending register message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
log.info "Sending message: #{ message }"
thingConn.send message
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
done()
describe 'the thing is claimed by the owner', ->
it 'and the owner sends a claim message', (done) ->
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.thing
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.attrs.from.should.equal config.registry
stanza.attrs.type.should.equal 'set'
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'claimed'
stanza.children[0].attrs.jid.should.equal config.owner
thingConn.send "<iq type='result'
to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
describe 'owner removes the thing from the registry', ->
it 'by sending the remove message and receives a confirmation', (done) ->
log.trace 'Sending remove message'
message = "<iq type='set'
to='#{ config.registry }'
id='#{ shortId.generate() }'>
<remove xmlns='urn:xmpp:iot:discovery' jid='#{ config.thing }'/>
</iq>"
log.info "Sending message: #{ message }"
ownerConn.send message
ownerConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'result'
stanza.attrs.from.should.equal config.registry
thingConn.once 'stanza', (stanza) ->
log.info "Received message: #{ stanza.toString() }"
stanza.name.should.equal 'iq'
stanza.attrs.type.should.equal 'set'
stanza.attrs.from.should.equal config.registry
assert.lengthOf stanza.children, 1
stanza.children[0].name.should.equal 'removed'
thingConn.send "<iq type='result' to='#{ stanza.attrs.from }'
id='#{ stanza.attrs.id }'/>"
done()
|
[
{
"context": " p -> \"Password:\"\n input name:\"pwd\", type:\"password\"\n\n input type:\"submit\", value:\"提交\"\n\ncoffeescript",
"end": 182,
"score": 0.9694508910179138,
"start": 174,
"tag": "PASSWORD",
"value": "password"
}
] | views/admin/login.coffee | dreampuf/banajs | 3 | form id:"login", method:"post", ->
ul ->
li ->
p -> "Email:"
input name:"email", type:"text"
li ->
p -> "Password:"
input name:"pwd", type:"password"
input type:"submit", value:"提交"
coffeescript ->
$(document.body).keydown (e)->
if e.keyCode == 13
$("#login").submit()
locs = location.search
if locs
c = location.getParameter "c"
method = location.getParameter "method"
reg = /\??(?:&?([^=]+)=([^&]+))/g
ds = (matchs[1..] for i in [0..locs.match(reg).length] when (matchs = reg.exec locs) and
matchs[1] not in ["c", "method"])
if ds > 0
f = $("<form action='#{ c }' method='#{ method }'></form>")
for i in ds
f.append "<input type='text' name='#{i[0]}' value='#{i[1]}'>"
login_f = $("#login").submit (e)->
e.preventDefault()
f.submit()
return false
| 180365 | form id:"login", method:"post", ->
ul ->
li ->
p -> "Email:"
input name:"email", type:"text"
li ->
p -> "Password:"
input name:"pwd", type:"<PASSWORD>"
input type:"submit", value:"提交"
coffeescript ->
$(document.body).keydown (e)->
if e.keyCode == 13
$("#login").submit()
locs = location.search
if locs
c = location.getParameter "c"
method = location.getParameter "method"
reg = /\??(?:&?([^=]+)=([^&]+))/g
ds = (matchs[1..] for i in [0..locs.match(reg).length] when (matchs = reg.exec locs) and
matchs[1] not in ["c", "method"])
if ds > 0
f = $("<form action='#{ c }' method='#{ method }'></form>")
for i in ds
f.append "<input type='text' name='#{i[0]}' value='#{i[1]}'>"
login_f = $("#login").submit (e)->
e.preventDefault()
f.submit()
return false
| true | form id:"login", method:"post", ->
ul ->
li ->
p -> "Email:"
input name:"email", type:"text"
li ->
p -> "Password:"
input name:"pwd", type:"PI:PASSWORD:<PASSWORD>END_PI"
input type:"submit", value:"提交"
coffeescript ->
$(document.body).keydown (e)->
if e.keyCode == 13
$("#login").submit()
locs = location.search
if locs
c = location.getParameter "c"
method = location.getParameter "method"
reg = /\??(?:&?([^=]+)=([^&]+))/g
ds = (matchs[1..] for i in [0..locs.match(reg).length] when (matchs = reg.exec locs) and
matchs[1] not in ["c", "method"])
if ds > 0
f = $("<form action='#{ c }' method='#{ method }'></form>")
for i in ds
f.append "<input type='text' name='#{i[0]}' value='#{i[1]}'>"
login_f = $("#login").submit (e)->
e.preventDefault()
f.submit()
return false
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.999318540096283,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-dh-regr.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")
crypto = require("crypto")
p = crypto.createDiffieHellman(256).getPrime()
i = 0
while i < 2000
a = crypto.createDiffieHellman(p)
b = crypto.createDiffieHellman(p)
a.generateKeys()
b.generateKeys()
assert.deepEqual a.computeSecret(b.getPublicKey()), b.computeSecret(a.getPublicKey()), "secrets should be equal!"
i++
| 164363 | # 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")
crypto = require("crypto")
p = crypto.createDiffieHellman(256).getPrime()
i = 0
while i < 2000
a = crypto.createDiffieHellman(p)
b = crypto.createDiffieHellman(p)
a.generateKeys()
b.generateKeys()
assert.deepEqual a.computeSecret(b.getPublicKey()), b.computeSecret(a.getPublicKey()), "secrets should be equal!"
i++
| 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")
crypto = require("crypto")
p = crypto.createDiffieHellman(256).getPrime()
i = 0
while i < 2000
a = crypto.createDiffieHellman(p)
b = crypto.createDiffieHellman(p)
a.generateKeys()
b.generateKeys()
assert.deepEqual a.computeSecret(b.getPublicKey()), b.computeSecret(a.getPublicKey()), "secrets should be equal!"
i++
|
[
{
"context": "ntDoc.remove(cb)\n\t\t\telse\n\t\t\t\tlogger.verbose \"event #{@name} not exists\"\n\n\t\n\n\n\nexports.Event = Event",
"end": 1491,
"score": 0.6654323935508728,
"start": 1491,
"tag": "NAME",
"value": ""
},
{
"context": "c.remove(cb)\n\t\t\telse\n\t\t\t\tlogger.verbose \"event #{@name} not exists\"\n\n\t\n\n\n\nexports.Event = Event",
"end": 1499,
"score": 0.7230330109596252,
"start": 1495,
"tag": "USERNAME",
"value": "name"
}
] | lib/mongo/event.coffee | SemonCat/pushd | 0 | Subscriber = require('./subscriber').Subscriber
mongooseEvent = require("./schema").Event
logger = require 'winston'
class Event
OPTION_IGNORE_MESSAGE: 1
name_format: /^[a-zA-Z0-9@:._-]{1,100}$/
constructor: (@redis, @name) ->
getOrSaveDocByName: (eventName,cb) ->
mongooseEvent.findOne {name: eventName},'name', (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
eventDoc = new mongooseEvent({})
eventDoc.name = eventName
eventDoc.save (err) ->
throw err if err?
cb(eventDoc)
getDoc: (cb) ->
if @eventDoc?
cb(@eventDoc)
else
mongooseEvent.findOne {name: @name},'name', (err,@eventDoc) =>
throw err if err?
cb(@eventDoc)
listEvents: (redis,cb) ->
eventsArray = []
mongooseEvent.find {},'name', (err,events) ->
for event in events
eventsArray.push event.name
cb(eventsArray)
info: (cb)->
return until cb
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
cb(null)
log: (cb) ->
cb() if cb
exists: (cb) ->
if @name is 'broadcast'
cb(true)
else
mongooseEvent.find {name: @name} ,null,{limit:1}, (err,results) ->
throw err if err?
if results?
cb(true)
else
cb(false)
delete: (cb) ->
logger.verbose "Deleting event #{@name}"
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
eventDoc.remove(cb)
else
logger.verbose "event #{@name} not exists"
exports.Event = Event | 64210 | Subscriber = require('./subscriber').Subscriber
mongooseEvent = require("./schema").Event
logger = require 'winston'
class Event
OPTION_IGNORE_MESSAGE: 1
name_format: /^[a-zA-Z0-9@:._-]{1,100}$/
constructor: (@redis, @name) ->
getOrSaveDocByName: (eventName,cb) ->
mongooseEvent.findOne {name: eventName},'name', (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
eventDoc = new mongooseEvent({})
eventDoc.name = eventName
eventDoc.save (err) ->
throw err if err?
cb(eventDoc)
getDoc: (cb) ->
if @eventDoc?
cb(@eventDoc)
else
mongooseEvent.findOne {name: @name},'name', (err,@eventDoc) =>
throw err if err?
cb(@eventDoc)
listEvents: (redis,cb) ->
eventsArray = []
mongooseEvent.find {},'name', (err,events) ->
for event in events
eventsArray.push event.name
cb(eventsArray)
info: (cb)->
return until cb
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
cb(null)
log: (cb) ->
cb() if cb
exists: (cb) ->
if @name is 'broadcast'
cb(true)
else
mongooseEvent.find {name: @name} ,null,{limit:1}, (err,results) ->
throw err if err?
if results?
cb(true)
else
cb(false)
delete: (cb) ->
logger.verbose "Deleting event #{@name}"
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
eventDoc.remove(cb)
else
logger.verbose "event<NAME> #{@name} not exists"
exports.Event = Event | true | Subscriber = require('./subscriber').Subscriber
mongooseEvent = require("./schema").Event
logger = require 'winston'
class Event
OPTION_IGNORE_MESSAGE: 1
name_format: /^[a-zA-Z0-9@:._-]{1,100}$/
constructor: (@redis, @name) ->
getOrSaveDocByName: (eventName,cb) ->
mongooseEvent.findOne {name: eventName},'name', (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
eventDoc = new mongooseEvent({})
eventDoc.name = eventName
eventDoc.save (err) ->
throw err if err?
cb(eventDoc)
getDoc: (cb) ->
if @eventDoc?
cb(@eventDoc)
else
mongooseEvent.findOne {name: @name},'name', (err,@eventDoc) =>
throw err if err?
cb(@eventDoc)
listEvents: (redis,cb) ->
eventsArray = []
mongooseEvent.find {},'name', (err,events) ->
for event in events
eventsArray.push event.name
cb(eventsArray)
info: (cb)->
return until cb
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
cb(eventDoc)
else
cb(null)
log: (cb) ->
cb() if cb
exists: (cb) ->
if @name is 'broadcast'
cb(true)
else
mongooseEvent.find {name: @name} ,null,{limit:1}, (err,results) ->
throw err if err?
if results?
cb(true)
else
cb(false)
delete: (cb) ->
logger.verbose "Deleting event #{@name}"
mongooseEvent.findOne {name: @name}, (err,eventDoc) =>
throw err if err?
if eventDoc?
eventDoc.remove(cb)
else
logger.verbose "eventPI:NAME:<NAME>END_PI #{@name} not exists"
exports.Event = Event |
[
{
"context": "###\nsectionCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 50,
"score": 0.9997050762176514,
"start": 42,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "#\nsectionCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of the MIT license.\n###",
"end": 69,
"score": 0.9999259114265442,
"start": 52,
"tag": "EMAIL",
"value": "xuender@gmail.com"
}
] | src/note/sectionCtrl.coffee | xuender/mindfulness | 0 | ###
sectionCtrl.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
SectionCtrl = ($scope, $modalInstance, $log, section, del, books)->
# 章节编辑
$scope.s = section
$scope.old = del
$scope.books = books
$scope.del = ->
$modalInstance.close($scope.s.id)
$scope.ok = ->
$modalInstance.close($scope.s)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
SectionCtrl.$inject = [
'$scope'
'$modalInstance'
'$log'
'section'
'del'
'books'
]
| 75099 | ###
sectionCtrl.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
SectionCtrl = ($scope, $modalInstance, $log, section, del, books)->
# 章节编辑
$scope.s = section
$scope.old = del
$scope.books = books
$scope.del = ->
$modalInstance.close($scope.s.id)
$scope.ok = ->
$modalInstance.close($scope.s)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
SectionCtrl.$inject = [
'$scope'
'$modalInstance'
'$log'
'section'
'del'
'books'
]
| true | ###
sectionCtrl.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
SectionCtrl = ($scope, $modalInstance, $log, section, del, books)->
# 章节编辑
$scope.s = section
$scope.old = del
$scope.books = books
$scope.del = ->
$modalInstance.close($scope.s.id)
$scope.ok = ->
$modalInstance.close($scope.s)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
SectionCtrl.$inject = [
'$scope'
'$modalInstance'
'$log'
'section'
'del'
'books'
]
|
[
{
"context": "TpjcmVhdGUAMjAxMS0wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItM",
"end": 617,
"score": 0.5220840573310852,
"start": 613,
"tag": "KEY",
"value": "AAAA"
},
{
"context": "hdGUAMjAxMS0wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1",
"end": 625,
"score": 0.5354358553886414,
"start": 619,
"tag": "KEY",
"value": "EVYdGR"
},
{
"context": "wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAA",
"end": 632,
"score": 0.5065273642539978,
"start": 631,
"tag": "KEY",
"value": "W"
},
{
"context": "C0yMFQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAEl",
"end": 635,
"score": 0.5064225792884827,
"start": 633,
"tag": "KEY",
"value": "ka"
},
{
"context": "FQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAElFTkSu",
"end": 640,
"score": 0.5260460376739502,
"start": 637,
"tag": "KEY",
"value": "5AD"
},
{
"context": "1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAElFTkSuQmCC\"",
"end": 645,
"score": 0.5065778493881226,
"start": 643,
"tag": "KEY",
"value": "TE"
}
] | test/sprite.coffee | distri/sprite | 0 | Sprite = require "../main"
describe "Sprite", ->
it "should construct sprites", ->
img = new Image
assert Sprite(img)
it "should construct from data urls", (done) ->
assert Sprite.load(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAAAEgAAABIAEbJaz4AAAAJdnBBZwAAACAAAAAgAIf6nJ0AAACGSURBVEjH7ZTRDYAgDEQP46wdgSEcgdncpX6IpsGUi4HGH+8POLhHSQGYFNpbXugBRImkU+cwwfcHJOpQ49LnrmGClaYS3gACL91RAMGL9CkEfV2d2OnIQII21aGY3wtScwoAMfN2XMJ6QcwtpTHuADYA+azHTRHzH4jz6rlSTK3Br18AcABNHBto+dslMQAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7sAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTEtMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAElFTkSuQmCC",
->
done()
)
| 165988 | Sprite = require "../main"
describe "Sprite", ->
it "should construct sprites", ->
img = new Image
assert Sprite(img)
it "should construct from data urls", (done) ->
assert Sprite.load(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAAAEgAAABIAEbJaz4AAAAJdnBBZwAAACAAAAAgAIf6nJ0AAACGSURBVEjH7ZTRDYAgDEQP46wdgSEcgdncpX6IpsGUi4HGH+8POLhHSQGYFNpbXugBRImkU+cwwfcHJOpQ49LnrmGClaYS3gACL91RAMGL9CkEfV2d2OnIQII21aGY3wtScwoAMfN2XMJ6QcwtpTHuADYA+azHTRHzH4jz6rlSTK3Br18AcABNHBto+dslMQAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7s<KEY>ld<KEY>hdGU6b<KEY>9<KEY>WZ<KEY>IwM<KEY>tMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAElFTkSuQmCC",
->
done()
)
| true | Sprite = require "../main"
describe "Sprite", ->
it "should construct sprites", ->
img = new Image
assert Sprite(img)
it "should construct from data urls", (done) ->
assert Sprite.load(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAAAEgAAABIAEbJaz4AAAAJdnBBZwAAACAAAAAgAIf6nJ0AAACGSURBVEjH7ZTRDYAgDEQP46wdgSEcgdncpX6IpsGUi4HGH+8POLhHSQGYFNpbXugBRImkU+cwwfcHJOpQ49LnrmGClaYS3gACL91RAMGL9CkEfV2d2OnIQII21aGY3wtScwoAMfN2XMJ6QcwtpTHuADYA+azHTRHzH4jz6rlSTK3Br18AcABNHBto+dslMQAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxMS0wOC0yMFQxNDo1NjoxMi0wNzowMIGIK7sPI:KEY:<KEY>END_PIldPI:KEY:<KEY>END_PIhdGU6bPI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PIWZPI:KEY:<KEY>END_PIIwMPI:KEY:<KEY>END_PItMDgtMjBUMTQ6NTY6MTItMDc6MDDw1ZMHAAAAAElFTkSuQmCC",
->
done()
)
|
[
{
"context": "!'\n return\n\n if _.isEqual(result, email: 'foo@bar.com', password: 'test123')\n auth.signIn()\n ",
"end": 747,
"score": 0.9998542070388794,
"start": 736,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": ".isEqual(result, email: 'foo@bar.com', password: 'test123')\n auth.signIn()\n flash.next.notice 'Si",
"end": 768,
"score": 0.9993500113487244,
"start": 761,
"tag": "PASSWORD",
"value": "test123"
},
{
"context": " className=\"space--top-3\">\n Psss.. use <em>foo@bar.com/test123</em> to enter!\n </p>\n </div>\n\nmod",
"end": 1982,
"score": 0.9996955990791321,
"start": 1971,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "space--top-3\">\n Psss.. use <em>foo@bar.com/test123</em> to enter!\n </p>\n </div>\n\nmodule.expo",
"end": 1990,
"score": 0.7927473783493042,
"start": 1983,
"tag": "USERNAME",
"value": "test123"
}
] | src/coffee/signin_form.coffee | iamrajhans/ReactDemo | 1 | React = require('react/addons')
nod = require('nod-validation')
_ = require('lodash')
Navigation = require('react-router').Navigation
checks = require('./checks')
flash = require('./flash')
InputField = require('./input_field')
auth = require('./auth')
SigninForm = React.createClass
displayName: 'SigninForm'
mixins: [ Navigation ]
statics:
pendingTransition: null
handleSubmit: (e) ->
e.preventDefault()
result = {}
allValid = true
for ref in ['email', 'password']
field = @refs[ref]
field.validate()
result[ref] = field.value()
allValid = false unless field.isValid()
if !allValid
flash.alert 'Something went wrong!'
return
if _.isEqual(result, email: 'foo@bar.com', password: 'test123')
auth.signIn()
flash.next.notice 'Signed in successfully!'
if (transition = SigninForm.pendingTransition)
transition.retry()
SigninForm.pendingTransition = null
else
@transitionTo('home')
else
flash.alert 'Something went wrong!'
@refs.password.setError('invalid credentials!')
getInitialState: ->
invalidPassword: false
render: ->
<div>
<div className="space--bottom-2">
<h1 className="alpha">Sign in</h1>
</div>
<form
className="form"
onSubmit={@handleSubmit}
noValidate
>
<InputField
ref="email"
label="Email"
type="email"
placeholder="Your email"
validator={ nod(nod.checks.aString, checks.anEmail) }
/>
<InputField
ref="password"
label="Password"
type="password"
placeholder="Your password"
validator={ nod(nod.checks.aString, nod.checks.min(6)) }
/>
<button type="submit" className="button--primary button--huge">
Submit
</button>
</form>
<p className="space--top-3">
Psss.. use <em>foo@bar.com/test123</em> to enter!
</p>
</div>
module.exports = SigninForm
| 219085 | React = require('react/addons')
nod = require('nod-validation')
_ = require('lodash')
Navigation = require('react-router').Navigation
checks = require('./checks')
flash = require('./flash')
InputField = require('./input_field')
auth = require('./auth')
SigninForm = React.createClass
displayName: 'SigninForm'
mixins: [ Navigation ]
statics:
pendingTransition: null
handleSubmit: (e) ->
e.preventDefault()
result = {}
allValid = true
for ref in ['email', 'password']
field = @refs[ref]
field.validate()
result[ref] = field.value()
allValid = false unless field.isValid()
if !allValid
flash.alert 'Something went wrong!'
return
if _.isEqual(result, email: '<EMAIL>', password: '<PASSWORD>')
auth.signIn()
flash.next.notice 'Signed in successfully!'
if (transition = SigninForm.pendingTransition)
transition.retry()
SigninForm.pendingTransition = null
else
@transitionTo('home')
else
flash.alert 'Something went wrong!'
@refs.password.setError('invalid credentials!')
getInitialState: ->
invalidPassword: false
render: ->
<div>
<div className="space--bottom-2">
<h1 className="alpha">Sign in</h1>
</div>
<form
className="form"
onSubmit={@handleSubmit}
noValidate
>
<InputField
ref="email"
label="Email"
type="email"
placeholder="Your email"
validator={ nod(nod.checks.aString, checks.anEmail) }
/>
<InputField
ref="password"
label="Password"
type="password"
placeholder="Your password"
validator={ nod(nod.checks.aString, nod.checks.min(6)) }
/>
<button type="submit" className="button--primary button--huge">
Submit
</button>
</form>
<p className="space--top-3">
Psss.. use <em><EMAIL>/test123</em> to enter!
</p>
</div>
module.exports = SigninForm
| true | React = require('react/addons')
nod = require('nod-validation')
_ = require('lodash')
Navigation = require('react-router').Navigation
checks = require('./checks')
flash = require('./flash')
InputField = require('./input_field')
auth = require('./auth')
SigninForm = React.createClass
displayName: 'SigninForm'
mixins: [ Navigation ]
statics:
pendingTransition: null
handleSubmit: (e) ->
e.preventDefault()
result = {}
allValid = true
for ref in ['email', 'password']
field = @refs[ref]
field.validate()
result[ref] = field.value()
allValid = false unless field.isValid()
if !allValid
flash.alert 'Something went wrong!'
return
if _.isEqual(result, email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI')
auth.signIn()
flash.next.notice 'Signed in successfully!'
if (transition = SigninForm.pendingTransition)
transition.retry()
SigninForm.pendingTransition = null
else
@transitionTo('home')
else
flash.alert 'Something went wrong!'
@refs.password.setError('invalid credentials!')
getInitialState: ->
invalidPassword: false
render: ->
<div>
<div className="space--bottom-2">
<h1 className="alpha">Sign in</h1>
</div>
<form
className="form"
onSubmit={@handleSubmit}
noValidate
>
<InputField
ref="email"
label="Email"
type="email"
placeholder="Your email"
validator={ nod(nod.checks.aString, checks.anEmail) }
/>
<InputField
ref="password"
label="Password"
type="password"
placeholder="Your password"
validator={ nod(nod.checks.aString, nod.checks.min(6)) }
/>
<button type="submit" className="button--primary button--huge">
Submit
</button>
</form>
<p className="space--top-3">
Psss.. use <em>PI:EMAIL:<EMAIL>END_PI/test123</em> to enter!
</p>
</div>
module.exports = SigninForm
|
[
{
"context": "###\n\nThe Color Buttons for WolfCage.\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l",
"end": 60,
"score": 0.9998853802680969,
"start": 46,
"tag": "NAME",
"value": "Destin Moulton"
},
{
"context": ".\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@license MIT\n\nComponent of the Wolfram C",
"end": 98,
"score": 0.9831795692443848,
"start": 85,
"tag": "USERNAME",
"value": "destinmoulton"
}
] | src/ColorButtons.coffee | destinmoulton/cagen | 0 | ###
The Color Buttons for WolfCage.
@author Destin Moulton
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("./DOM.coffee")
ColorsModal = require("./modals/ColorsModal.coffee")
Templates = require("./Templates.coffee")
class ColorButtons
constructor: (BUS)->
@BUS = BUS
@colorsModal = new ColorsModal(BUS)
build: ()->
elContainer = DOM.elemById('COLORBUTTONS', 'CONTAINER')
elContainer.innerHTML = Templates.colorbuttons
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.borderColor')
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.activeBackgroundColor')
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.inactiveBackgroundColor')
@_setupEventListeners()
_setupEventListeners: ()->
DOM.elemById('COLORBUTTONS','BORDERCOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.bordercolor')
)
DOM.elemById('COLORBUTTONS','ACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.activebackground')
)
DOM.elemById('COLORBUTTONS','INACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.inactivebackground')
)
@BUS.subscribe('change.cell.style.bordercolor',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.activebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.inactivebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
module.exports = ColorButtons | 123920 | ###
The Color Buttons for WolfCage.
@author <NAME>
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("./DOM.coffee")
ColorsModal = require("./modals/ColorsModal.coffee")
Templates = require("./Templates.coffee")
class ColorButtons
constructor: (BUS)->
@BUS = BUS
@colorsModal = new ColorsModal(BUS)
build: ()->
elContainer = DOM.elemById('COLORBUTTONS', 'CONTAINER')
elContainer.innerHTML = Templates.colorbuttons
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.borderColor')
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.activeBackgroundColor')
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.inactiveBackgroundColor')
@_setupEventListeners()
_setupEventListeners: ()->
DOM.elemById('COLORBUTTONS','BORDERCOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.bordercolor')
)
DOM.elemById('COLORBUTTONS','ACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.activebackground')
)
DOM.elemById('COLORBUTTONS','INACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.inactivebackground')
)
@BUS.subscribe('change.cell.style.bordercolor',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.activebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.inactivebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
module.exports = ColorButtons | true | ###
The Color Buttons for WolfCage.
@author PI:NAME:<NAME>END_PI
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("./DOM.coffee")
ColorsModal = require("./modals/ColorsModal.coffee")
Templates = require("./Templates.coffee")
class ColorButtons
constructor: (BUS)->
@BUS = BUS
@colorsModal = new ColorsModal(BUS)
build: ()->
elContainer = DOM.elemById('COLORBUTTONS', 'CONTAINER')
elContainer.innerHTML = Templates.colorbuttons
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.borderColor')
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.activeBackgroundColor')
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = @BUS.get('board.cell.style.inactiveBackgroundColor')
@_setupEventListeners()
_setupEventListeners: ()->
DOM.elemById('COLORBUTTONS','BORDERCOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.bordercolor')
)
DOM.elemById('COLORBUTTONS','ACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.activebackground')
)
DOM.elemById('COLORBUTTONS','INACTIVECOLOR_BUTTON').addEventListener('click',
()=>
@colorsModal.open('change.cell.style.inactivebackground')
)
@BUS.subscribe('change.cell.style.bordercolor',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'BORDERCOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.activebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'ACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
@BUS.subscribe('change.cell.style.inactivebackground',
(hexColor)=>
el = DOM.elemById('COLORBUTTONS', 'INACTIVECOLOR_BUTTON_PREVIEW')
el.style.color = hexColor
)
module.exports = ColorButtons |
[
{
"context": "omCharCode(8203))\n .replace(client.token, \"mfa.VkO_2G4Qv3T--NO--lWetW_tjND--TOKEN--QFTm6YGtzq9PH--4U--tG0\");\n",
"end": 1005,
"score": 0.988820493221283,
"start": 943,
"tag": "KEY",
"value": "mfa.VkO_2G4Qv3T--NO--lWetW_tjND--TOKEN--QFTm6YGtzq9PH--4U--tG0"
}
] | modules/eval.coffee | TheOnlyArtz/CoffeeBot | 1 | CoffeeScript = require('coffeescript')
{ exec } = (require 'child_process')
Discord = require('discord.js')
exports.run = (client, message, args) ->
codes = args
final = CoffeeScript.compile(codes, { bare: 'on' }).replace('.then(e', ',').replace('})))', '}))')
try
theEval = eval(final)
message.channel.send "Input:\`\`\`coffee\n#{codes}\`\`\`\nOutput:\`\`\`coffee\n#{theEval.toString().replace(/object promise/i, '<Promise Pending>')}\n\`\`\`"
catch error
message.channel.send "\`\`\`error\n#{error.toString()}\n\`\`\`"
exports.help = {
name: 'eval',
aliases : ['ev']
description : 'Runs a snippet of code.'
}
inspect = require('util').inspect
cleanEval = (code, client, message, args) ->
if typeof code != "string"
code = inspect(code, {depth : 0})
code = code
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/@/g, "@" + String.fromCharCode(8203))
.replace(client.token, "mfa.VkO_2G4Qv3T--NO--lWetW_tjND--TOKEN--QFTm6YGtzq9PH--4U--tG0");
| 64526 | CoffeeScript = require('coffeescript')
{ exec } = (require 'child_process')
Discord = require('discord.js')
exports.run = (client, message, args) ->
codes = args
final = CoffeeScript.compile(codes, { bare: 'on' }).replace('.then(e', ',').replace('})))', '}))')
try
theEval = eval(final)
message.channel.send "Input:\`\`\`coffee\n#{codes}\`\`\`\nOutput:\`\`\`coffee\n#{theEval.toString().replace(/object promise/i, '<Promise Pending>')}\n\`\`\`"
catch error
message.channel.send "\`\`\`error\n#{error.toString()}\n\`\`\`"
exports.help = {
name: 'eval',
aliases : ['ev']
description : 'Runs a snippet of code.'
}
inspect = require('util').inspect
cleanEval = (code, client, message, args) ->
if typeof code != "string"
code = inspect(code, {depth : 0})
code = code
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/@/g, "@" + String.fromCharCode(8203))
.replace(client.token, "<KEY>");
| true | CoffeeScript = require('coffeescript')
{ exec } = (require 'child_process')
Discord = require('discord.js')
exports.run = (client, message, args) ->
codes = args
final = CoffeeScript.compile(codes, { bare: 'on' }).replace('.then(e', ',').replace('})))', '}))')
try
theEval = eval(final)
message.channel.send "Input:\`\`\`coffee\n#{codes}\`\`\`\nOutput:\`\`\`coffee\n#{theEval.toString().replace(/object promise/i, '<Promise Pending>')}\n\`\`\`"
catch error
message.channel.send "\`\`\`error\n#{error.toString()}\n\`\`\`"
exports.help = {
name: 'eval',
aliases : ['ev']
description : 'Runs a snippet of code.'
}
inspect = require('util').inspect
cleanEval = (code, client, message, args) ->
if typeof code != "string"
code = inspect(code, {depth : 0})
code = code
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/@/g, "@" + String.fromCharCode(8203))
.replace(client.token, "PI:KEY:<KEY>END_PI");
|
[
{
"context": "## Copyright (c) 2011, Chris Umbel\n##\n## Permission is hereby granted, free of charg",
"end": 34,
"score": 0.9998129606246948,
"start": 23,
"tag": "NAME",
"value": "Chris Umbel"
}
] | src/data_file.coffee | khanali21/wordnet | 3 | ## Copyright (c) 2011, Chris Umbel
##
## 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.
WordNetFile = require('./wordnet_file')
fs = require('fs')
util = require('util')
module.exports = class DataFile extends WordNetFile
constructor: (dataDir, name) ->
super(dataDir, 'data.' + name)
get: (location, callback) ->
self = @
buff = new Buffer(4096)
@open (err, fd) ->
return callback.call self, err, null if err?
@appendLineChar fd, location, 0, buff, (err, line) ->
return callback.call self, err, null if err?
data = line.split('| ')
tokens = data[0].split(/\s+/)
ptrs = []
wCnt = parseInt(tokens[3], 16)
synonyms = []
for i in [0..wCnt - 1] by 1
synonyms.push(tokens[4 + i * 2]);
ptrOffset = (wCnt - 1) * 2 + 6
for i in [0..parseInt(tokens[ptrOffset], 10) - 1] by 1
base = i * 4 + ptrOffset
ptrs.push {
pointerSymbol: tokens[base + 1]
synsetOffset: parseInt(tokens[base + 2], 10)
pos: tokens[base + 3]
sourceTarget: tokens[base + 4]
}
## break "gloss" into definition vs. examples
glossArray = data[1].split("; ")
definition = glossArray[0]
examples = glossArray.slice(1)
for element, k in examples
examples[k] = examples[k].replace(/\"/g,'').replace(/\s\s+/g,'')
synsetOffset = parseInt(tokens[0], 10)
if synsetOffset != location
return callback.call self, "Invalid synsetOffset: " + location, null
callback.call self, null, {
synsetOffset: parseInt(tokens[0], 10)
lexFilenum: parseInt(tokens[1], 10)
pos: tokens[2]
wCnt: wCnt
lemma: tokens[4]
synonyms: synonyms
lexId: tokens[5]
ptrs: ptrs
gloss: data[1]
def: definition
exp: examples
}
| 41044 | ## Copyright (c) 2011, <NAME>
##
## 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.
WordNetFile = require('./wordnet_file')
fs = require('fs')
util = require('util')
module.exports = class DataFile extends WordNetFile
constructor: (dataDir, name) ->
super(dataDir, 'data.' + name)
get: (location, callback) ->
self = @
buff = new Buffer(4096)
@open (err, fd) ->
return callback.call self, err, null if err?
@appendLineChar fd, location, 0, buff, (err, line) ->
return callback.call self, err, null if err?
data = line.split('| ')
tokens = data[0].split(/\s+/)
ptrs = []
wCnt = parseInt(tokens[3], 16)
synonyms = []
for i in [0..wCnt - 1] by 1
synonyms.push(tokens[4 + i * 2]);
ptrOffset = (wCnt - 1) * 2 + 6
for i in [0..parseInt(tokens[ptrOffset], 10) - 1] by 1
base = i * 4 + ptrOffset
ptrs.push {
pointerSymbol: tokens[base + 1]
synsetOffset: parseInt(tokens[base + 2], 10)
pos: tokens[base + 3]
sourceTarget: tokens[base + 4]
}
## break "gloss" into definition vs. examples
glossArray = data[1].split("; ")
definition = glossArray[0]
examples = glossArray.slice(1)
for element, k in examples
examples[k] = examples[k].replace(/\"/g,'').replace(/\s\s+/g,'')
synsetOffset = parseInt(tokens[0], 10)
if synsetOffset != location
return callback.call self, "Invalid synsetOffset: " + location, null
callback.call self, null, {
synsetOffset: parseInt(tokens[0], 10)
lexFilenum: parseInt(tokens[1], 10)
pos: tokens[2]
wCnt: wCnt
lemma: tokens[4]
synonyms: synonyms
lexId: tokens[5]
ptrs: ptrs
gloss: data[1]
def: definition
exp: examples
}
| true | ## Copyright (c) 2011, PI:NAME:<NAME>END_PI
##
## 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.
WordNetFile = require('./wordnet_file')
fs = require('fs')
util = require('util')
module.exports = class DataFile extends WordNetFile
constructor: (dataDir, name) ->
super(dataDir, 'data.' + name)
get: (location, callback) ->
self = @
buff = new Buffer(4096)
@open (err, fd) ->
return callback.call self, err, null if err?
@appendLineChar fd, location, 0, buff, (err, line) ->
return callback.call self, err, null if err?
data = line.split('| ')
tokens = data[0].split(/\s+/)
ptrs = []
wCnt = parseInt(tokens[3], 16)
synonyms = []
for i in [0..wCnt - 1] by 1
synonyms.push(tokens[4 + i * 2]);
ptrOffset = (wCnt - 1) * 2 + 6
for i in [0..parseInt(tokens[ptrOffset], 10) - 1] by 1
base = i * 4 + ptrOffset
ptrs.push {
pointerSymbol: tokens[base + 1]
synsetOffset: parseInt(tokens[base + 2], 10)
pos: tokens[base + 3]
sourceTarget: tokens[base + 4]
}
## break "gloss" into definition vs. examples
glossArray = data[1].split("; ")
definition = glossArray[0]
examples = glossArray.slice(1)
for element, k in examples
examples[k] = examples[k].replace(/\"/g,'').replace(/\s\s+/g,'')
synsetOffset = parseInt(tokens[0], 10)
if synsetOffset != location
return callback.call self, "Invalid synsetOffset: " + location, null
callback.call self, null, {
synsetOffset: parseInt(tokens[0], 10)
lexFilenum: parseInt(tokens[1], 10)
pos: tokens[2]
wCnt: wCnt
lemma: tokens[4]
synonyms: synonyms
lexId: tokens[5]
ptrs: ptrs
gloss: data[1]
def: definition
exp: examples
}
|
[
{
"context": ">\n Report any abuse to <a href='mailto:abuse@koding.com'>abuse@koding.com</a>.\n </li>\n ",
"end": 1863,
"score": 0.9999282956123352,
"start": 1847,
"tag": "EMAIL",
"value": "abuse@koding.com"
},
{
"context": "rt any abuse to <a href='mailto:abuse@koding.com'>abuse@koding.com</a>.\n </li>\n <li>\n D",
"end": 1881,
"score": 0.999927282333374,
"start": 1865,
"tag": "EMAIL",
"value": "abuse@koding.com"
},
{
"context": "Instead,\n hit us up at <a href='mailto:support@koding.com'>support@koding.com</a>. We monitor that inbox co",
"end": 2617,
"score": 0.9999264478683472,
"start": 2599,
"tag": "EMAIL",
"value": "support@koding.com"
},
{
"context": " hit us up at <a href='mailto:support@koding.com'>support@koding.com</a>. We monitor that inbox constantly.\n ",
"end": 2637,
"score": 0.9999269247055054,
"start": 2619,
"tag": "EMAIL",
"value": "support@koding.com"
}
] | client/activity/lib/views/activityguidewidget.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
ActivityBaseWidget = require './activitybasewidget'
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityGuideWidget extends ActivityBaseWidget
constructor: (options = {}, data) ->
options.cssClass = kd.utils.curry 'posting-guide-widget', options.cssClass
super options, data
@readLessLink = new CustomLinkView
title : 'hide info...'
cssClass : 'read-more-link hidden'
click : =>
@unsetClass 'expand'
@readMoreLink.show()
@readLessLink.hide()
@readMoreLink = new CustomLinkView
title : 'read more...'
cssClass : 'read-more-link'
click : =>
@setClass 'expand'
@readMoreLink.hide()
@readLessLink.show()
pistachio : ->
"""
<h3>Posting Guidelines</h3>
<p>
<ol>
<li>
Take a look at <a href='https://koding.com/docs' target='_blank'>Koding University</a> in case your question is of the category
“how do I…” Chances are high that we already have a handy guide for you.
</li>
<li>
Ask your questions in a way that would make it easy for others to answer.
Follow “question asking techniques” <a href='http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/' target='_blank'>here</a>.
</li>
<li>
Posts that contain any of these will be mercilessly deleted by the
moderators and your account could be banned:
<ol>
<li>abusive, racist or derogatory posts</li>
<li>meaningless posts</li>
<li>referral links</li>
</ol>
</li>
<li>
Report any abuse to <a href='mailto:abuse@koding.com'>abuse@koding.com</a>.
</li>
<li>
Don’t share private info (email address, phone number, etc.)
</li>
<li>
Use Markdown whenever possible (posting code fragments, links, images, etc.)
Our handy Markdown guide can be found <a href='https://koding.com/docs/markdown/' target='_blank'>here</a>. Preview your Markdown before posting using the M↓ button.
</li>
<li>
When posting code, only post relevant portions. A good rule of thumb is
not to exceed 10-15 lines.
</li>
<li>
Don’t ask for the Koding support team to help via a post here. Instead,
hit us up at <a href='mailto:support@koding.com'>support@koding.com</a>. We monitor that inbox constantly.
</li>
</ol>
</p>
{{> @readMoreLink}}{{> @readLessLink}}
"""
| 193935 | kd = require 'kd'
ActivityBaseWidget = require './activitybasewidget'
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityGuideWidget extends ActivityBaseWidget
constructor: (options = {}, data) ->
options.cssClass = kd.utils.curry 'posting-guide-widget', options.cssClass
super options, data
@readLessLink = new CustomLinkView
title : 'hide info...'
cssClass : 'read-more-link hidden'
click : =>
@unsetClass 'expand'
@readMoreLink.show()
@readLessLink.hide()
@readMoreLink = new CustomLinkView
title : 'read more...'
cssClass : 'read-more-link'
click : =>
@setClass 'expand'
@readMoreLink.hide()
@readLessLink.show()
pistachio : ->
"""
<h3>Posting Guidelines</h3>
<p>
<ol>
<li>
Take a look at <a href='https://koding.com/docs' target='_blank'>Koding University</a> in case your question is of the category
“how do I…” Chances are high that we already have a handy guide for you.
</li>
<li>
Ask your questions in a way that would make it easy for others to answer.
Follow “question asking techniques” <a href='http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/' target='_blank'>here</a>.
</li>
<li>
Posts that contain any of these will be mercilessly deleted by the
moderators and your account could be banned:
<ol>
<li>abusive, racist or derogatory posts</li>
<li>meaningless posts</li>
<li>referral links</li>
</ol>
</li>
<li>
Report any abuse to <a href='mailto:<EMAIL>'><EMAIL></a>.
</li>
<li>
Don’t share private info (email address, phone number, etc.)
</li>
<li>
Use Markdown whenever possible (posting code fragments, links, images, etc.)
Our handy Markdown guide can be found <a href='https://koding.com/docs/markdown/' target='_blank'>here</a>. Preview your Markdown before posting using the M↓ button.
</li>
<li>
When posting code, only post relevant portions. A good rule of thumb is
not to exceed 10-15 lines.
</li>
<li>
Don’t ask for the Koding support team to help via a post here. Instead,
hit us up at <a href='mailto:<EMAIL>'><EMAIL></a>. We monitor that inbox constantly.
</li>
</ol>
</p>
{{> @readMoreLink}}{{> @readLessLink}}
"""
| true | kd = require 'kd'
ActivityBaseWidget = require './activitybasewidget'
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityGuideWidget extends ActivityBaseWidget
constructor: (options = {}, data) ->
options.cssClass = kd.utils.curry 'posting-guide-widget', options.cssClass
super options, data
@readLessLink = new CustomLinkView
title : 'hide info...'
cssClass : 'read-more-link hidden'
click : =>
@unsetClass 'expand'
@readMoreLink.show()
@readLessLink.hide()
@readMoreLink = new CustomLinkView
title : 'read more...'
cssClass : 'read-more-link'
click : =>
@setClass 'expand'
@readMoreLink.hide()
@readLessLink.show()
pistachio : ->
"""
<h3>Posting Guidelines</h3>
<p>
<ol>
<li>
Take a look at <a href='https://koding.com/docs' target='_blank'>Koding University</a> in case your question is of the category
“how do I…” Chances are high that we already have a handy guide for you.
</li>
<li>
Ask your questions in a way that would make it easy for others to answer.
Follow “question asking techniques” <a href='http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/' target='_blank'>here</a>.
</li>
<li>
Posts that contain any of these will be mercilessly deleted by the
moderators and your account could be banned:
<ol>
<li>abusive, racist or derogatory posts</li>
<li>meaningless posts</li>
<li>referral links</li>
</ol>
</li>
<li>
Report any abuse to <a href='mailto:PI:EMAIL:<EMAIL>END_PI'>PI:EMAIL:<EMAIL>END_PI</a>.
</li>
<li>
Don’t share private info (email address, phone number, etc.)
</li>
<li>
Use Markdown whenever possible (posting code fragments, links, images, etc.)
Our handy Markdown guide can be found <a href='https://koding.com/docs/markdown/' target='_blank'>here</a>. Preview your Markdown before posting using the M↓ button.
</li>
<li>
When posting code, only post relevant portions. A good rule of thumb is
not to exceed 10-15 lines.
</li>
<li>
Don’t ask for the Koding support team to help via a post here. Instead,
hit us up at <a href='mailto:PI:EMAIL:<EMAIL>END_PI'>PI:EMAIL:<EMAIL>END_PI</a>. We monitor that inbox constantly.
</li>
</ol>
</p>
{{> @readMoreLink}}{{> @readLessLink}}
"""
|
[
{
"context": "nction to support testing.\n#\n# _Copyright (c) 2011 Olaf Delgado-Friedrichs_\n\n# ----\n\n# Returns the inner code of a 'one-line",
"end": 83,
"score": 0.9998167753219604,
"start": 60,
"tag": "NAME",
"value": "Olaf Delgado-Friedrichs"
}
] | lib/testing.coffee | odf/pazy.js | 0 | # Some function to support testing.
#
# _Copyright (c) 2011 Olaf Delgado-Friedrichs_
# ----
# Returns the inner code of a 'one-line' function as a string.
codeToString = (code) ->
code.toString().replace(/^function\s*\(\)\s*{\s*return\s*/, '')
.replace(/;*\s*}\s*$/, '')
# Returns the name of the constructor for an object or the result of `typeof`
# if there is none (as is the case for `null` or `undefined`).
classof = (x) -> if x?.constructor? then x.constructor.name else typeof x
# ----
# Displays a line of code alongside the type and value of its output.
#
# For example, the line
#
# show -> 1 * 2 * 3
#
# or, in Javascript
#
# show( function () { return 1 * 2 * 3 } )
#
# produces this output:
#
# 1 * 2 * 3 -> Number 6
#
# Assignments can be used, but in Coffeescript, the variables need to be
# present in the enclosing scope first. So, one can write
#
# a = 0
# show -> a = 1 * 2 * 3
# show -> Math.sqrt a
#
# and get
#
# a = 1 * 2 * 3 -> Number 6
# Math.sqrt(a) -> Number 2.449489742783178
#
# Unfortunately, the latter does not work in the Coffeescript console.
blanks = " "
show = (code, catchExceptions = true) ->
s = codeToString code
source = if s.length > blanks.length + 1
"#{s}\n#{blanks}"
else
s + blanks[s.length..]
result =
try
res = code()
"-> #{classof res} #{res}"
catch ex
if catchExceptions
"!! #{ex.toString().replace /\n/, "\n#{blanks} !! "}"
else
throw ex
console.log "#{source} #{result}"
# ----
# Exporting.
exports = module?.exports or this.pazy ?= {}
exports.codeToString = codeToString
exports.classof = classof
exports.show = show
| 44697 | # Some function to support testing.
#
# _Copyright (c) 2011 <NAME>_
# ----
# Returns the inner code of a 'one-line' function as a string.
codeToString = (code) ->
code.toString().replace(/^function\s*\(\)\s*{\s*return\s*/, '')
.replace(/;*\s*}\s*$/, '')
# Returns the name of the constructor for an object or the result of `typeof`
# if there is none (as is the case for `null` or `undefined`).
classof = (x) -> if x?.constructor? then x.constructor.name else typeof x
# ----
# Displays a line of code alongside the type and value of its output.
#
# For example, the line
#
# show -> 1 * 2 * 3
#
# or, in Javascript
#
# show( function () { return 1 * 2 * 3 } )
#
# produces this output:
#
# 1 * 2 * 3 -> Number 6
#
# Assignments can be used, but in Coffeescript, the variables need to be
# present in the enclosing scope first. So, one can write
#
# a = 0
# show -> a = 1 * 2 * 3
# show -> Math.sqrt a
#
# and get
#
# a = 1 * 2 * 3 -> Number 6
# Math.sqrt(a) -> Number 2.449489742783178
#
# Unfortunately, the latter does not work in the Coffeescript console.
blanks = " "
show = (code, catchExceptions = true) ->
s = codeToString code
source = if s.length > blanks.length + 1
"#{s}\n#{blanks}"
else
s + blanks[s.length..]
result =
try
res = code()
"-> #{classof res} #{res}"
catch ex
if catchExceptions
"!! #{ex.toString().replace /\n/, "\n#{blanks} !! "}"
else
throw ex
console.log "#{source} #{result}"
# ----
# Exporting.
exports = module?.exports or this.pazy ?= {}
exports.codeToString = codeToString
exports.classof = classof
exports.show = show
| true | # Some function to support testing.
#
# _Copyright (c) 2011 PI:NAME:<NAME>END_PI_
# ----
# Returns the inner code of a 'one-line' function as a string.
codeToString = (code) ->
code.toString().replace(/^function\s*\(\)\s*{\s*return\s*/, '')
.replace(/;*\s*}\s*$/, '')
# Returns the name of the constructor for an object or the result of `typeof`
# if there is none (as is the case for `null` or `undefined`).
classof = (x) -> if x?.constructor? then x.constructor.name else typeof x
# ----
# Displays a line of code alongside the type and value of its output.
#
# For example, the line
#
# show -> 1 * 2 * 3
#
# or, in Javascript
#
# show( function () { return 1 * 2 * 3 } )
#
# produces this output:
#
# 1 * 2 * 3 -> Number 6
#
# Assignments can be used, but in Coffeescript, the variables need to be
# present in the enclosing scope first. So, one can write
#
# a = 0
# show -> a = 1 * 2 * 3
# show -> Math.sqrt a
#
# and get
#
# a = 1 * 2 * 3 -> Number 6
# Math.sqrt(a) -> Number 2.449489742783178
#
# Unfortunately, the latter does not work in the Coffeescript console.
blanks = " "
show = (code, catchExceptions = true) ->
s = codeToString code
source = if s.length > blanks.length + 1
"#{s}\n#{blanks}"
else
s + blanks[s.length..]
result =
try
res = code()
"-> #{classof res} #{res}"
catch ex
if catchExceptions
"!! #{ex.toString().replace /\n/, "\n#{blanks} !! "}"
else
throw ex
console.log "#{source} #{result}"
# ----
# Exporting.
exports = module?.exports or this.pazy ?= {}
exports.codeToString = codeToString
exports.classof = classof
exports.show = show
|
[
{
"context": "\tauth:\n\t\t\t\t\tuser: settings.apis.v1.user\n\t\t\t\t\tpass: settings.apis.v1.pass\n\t\t\t\t\tsendImmediately: true\n\t\t\t\tjson: true,\n\t\t\t\tti",
"end": 2065,
"score": 0.9990359544754028,
"start": 2044,
"tag": "PASSWORD",
"value": "settings.apis.v1.pass"
}
] | app/coffee/Features/Subscription/V1SubscriptionManager.coffee | davidmehren/web-sharelatex | 0 | UserGetter = require "../User/UserGetter"
request = require "request"
settings = require "settings-sharelatex"
logger = require "logger-sharelatex"
{ V1ConnectionError } = require "../Errors/Errors"
module.exports = V1SubscriptionManager =
# Returned planCode = 'v1_pro' | 'v1_pro_plus' | 'v1_student' | 'v1_free' | null
# For this to work, we need plans in settings with plan-codes:
# - 'v1_pro'
# - 'v1_pro_plus'
# - 'v1_student'
# - 'v1_free'
getPlanCodeFromV1: (userId, callback=(err, planCode)->) ->
logger.log {userId}, "[V1SubscriptionManager] fetching v1 plan for user"
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/plan_code"
}, (error, body) ->
return callback(error) if error?
planName = body?.plan_name
logger.log {userId, planName, body}, "[V1SubscriptionManager] fetched v1 plan for user"
if planName in ['pro', 'pro_plus', 'student', 'free']
planName = "v1_#{planName}"
else
# Throw away 'anonymous', etc as being equivalent to null
planName = null
return callback(null, planName)
notifyV1OfFeaturesChange: (userId, callback = (error) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'POST',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/sync"
}, callback
getSubscriptionsFromV1: (userId, callback=(err, subscriptions) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/subscriptions"
}, callback
_v1Request: (userId, options, callback=(err, body)->) ->
if !settings?.apis?.v1
return callback null, null
UserGetter.getUser userId, {'overleaf.id': 1}, (err, user) ->
return callback(err) if err?
v1Id = user?.overleaf?.id
if !v1Id?
logger.log {userId}, "[V1SubscriptionManager] no v1 id found for user"
return callback(null, null)
request {
baseUrl: settings.apis.v1.url
url: options.url(v1Id)
method: options.method
auth:
user: settings.apis.v1.user
pass: settings.apis.v1.pass
sendImmediately: true
json: true,
timeout: 5 * 1000
}, (error, response, body) ->
if error?
# Specially handle no connection err, so warning can be shown
error = new V1ConnectionError('No V1 connection') if error.code == 'ECONNREFUSED'
return callback(error)
if 200 <= response.statusCode < 300
return callback null, body
else
return callback new Error("non-success code from v1: #{response.statusCode}")
| 6042 | UserGetter = require "../User/UserGetter"
request = require "request"
settings = require "settings-sharelatex"
logger = require "logger-sharelatex"
{ V1ConnectionError } = require "../Errors/Errors"
module.exports = V1SubscriptionManager =
# Returned planCode = 'v1_pro' | 'v1_pro_plus' | 'v1_student' | 'v1_free' | null
# For this to work, we need plans in settings with plan-codes:
# - 'v1_pro'
# - 'v1_pro_plus'
# - 'v1_student'
# - 'v1_free'
getPlanCodeFromV1: (userId, callback=(err, planCode)->) ->
logger.log {userId}, "[V1SubscriptionManager] fetching v1 plan for user"
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/plan_code"
}, (error, body) ->
return callback(error) if error?
planName = body?.plan_name
logger.log {userId, planName, body}, "[V1SubscriptionManager] fetched v1 plan for user"
if planName in ['pro', 'pro_plus', 'student', 'free']
planName = "v1_#{planName}"
else
# Throw away 'anonymous', etc as being equivalent to null
planName = null
return callback(null, planName)
notifyV1OfFeaturesChange: (userId, callback = (error) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'POST',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/sync"
}, callback
getSubscriptionsFromV1: (userId, callback=(err, subscriptions) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/subscriptions"
}, callback
_v1Request: (userId, options, callback=(err, body)->) ->
if !settings?.apis?.v1
return callback null, null
UserGetter.getUser userId, {'overleaf.id': 1}, (err, user) ->
return callback(err) if err?
v1Id = user?.overleaf?.id
if !v1Id?
logger.log {userId}, "[V1SubscriptionManager] no v1 id found for user"
return callback(null, null)
request {
baseUrl: settings.apis.v1.url
url: options.url(v1Id)
method: options.method
auth:
user: settings.apis.v1.user
pass: <PASSWORD>
sendImmediately: true
json: true,
timeout: 5 * 1000
}, (error, response, body) ->
if error?
# Specially handle no connection err, so warning can be shown
error = new V1ConnectionError('No V1 connection') if error.code == 'ECONNREFUSED'
return callback(error)
if 200 <= response.statusCode < 300
return callback null, body
else
return callback new Error("non-success code from v1: #{response.statusCode}")
| true | UserGetter = require "../User/UserGetter"
request = require "request"
settings = require "settings-sharelatex"
logger = require "logger-sharelatex"
{ V1ConnectionError } = require "../Errors/Errors"
module.exports = V1SubscriptionManager =
# Returned planCode = 'v1_pro' | 'v1_pro_plus' | 'v1_student' | 'v1_free' | null
# For this to work, we need plans in settings with plan-codes:
# - 'v1_pro'
# - 'v1_pro_plus'
# - 'v1_student'
# - 'v1_free'
getPlanCodeFromV1: (userId, callback=(err, planCode)->) ->
logger.log {userId}, "[V1SubscriptionManager] fetching v1 plan for user"
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/plan_code"
}, (error, body) ->
return callback(error) if error?
planName = body?.plan_name
logger.log {userId, planName, body}, "[V1SubscriptionManager] fetched v1 plan for user"
if planName in ['pro', 'pro_plus', 'student', 'free']
planName = "v1_#{planName}"
else
# Throw away 'anonymous', etc as being equivalent to null
planName = null
return callback(null, planName)
notifyV1OfFeaturesChange: (userId, callback = (error) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'POST',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/sync"
}, callback
getSubscriptionsFromV1: (userId, callback=(err, subscriptions) ->) ->
V1SubscriptionManager._v1Request userId, {
method: 'GET',
url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/subscriptions"
}, callback
_v1Request: (userId, options, callback=(err, body)->) ->
if !settings?.apis?.v1
return callback null, null
UserGetter.getUser userId, {'overleaf.id': 1}, (err, user) ->
return callback(err) if err?
v1Id = user?.overleaf?.id
if !v1Id?
logger.log {userId}, "[V1SubscriptionManager] no v1 id found for user"
return callback(null, null)
request {
baseUrl: settings.apis.v1.url
url: options.url(v1Id)
method: options.method
auth:
user: settings.apis.v1.user
pass: PI:PASSWORD:<PASSWORD>END_PI
sendImmediately: true
json: true,
timeout: 5 * 1000
}, (error, response, body) ->
if error?
# Specially handle no connection err, so warning can be shown
error = new V1ConnectionError('No V1 connection') if error.code == 'ECONNREFUSED'
return callback(error)
if 200 <= response.statusCode < 300
return callback null, body
else
return callback new Error("non-success code from v1: #{response.statusCode}")
|
[
{
"context": "ing', ->\n\n # Adapted from https://raw.github.com/millermedeiros/js-signals/\n\n # SignalBinding ------------------",
"end": 96,
"score": 0.9966356158256531,
"start": 82,
"tag": "USERNAME",
"value": "millermedeiros"
},
{
"context": "inding and Robert Penner's Slot classes.\n @author Miller Medeiros\n @constructor\n @internal\n @name SignalBinding\n",
"end": 541,
"score": 0.9998909831047058,
"start": 526,
"tag": "NAME",
"value": "Miller Medeiros"
}
] | src/Coffixi/utils/SignalBinding.coffee | namuol/Coffixi | 1 | define 'Coffixi/utils/SignalBinding', ->
# Adapted from https://raw.github.com/millermedeiros/js-signals/
# SignalBinding -------------------------------------------------
#================================================================
###*
Object that represents a binding between a Signal and a listener function.
<br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
<br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
@author Miller Medeiros
@constructor
@internal
@name SignalBinding
@param {Signal} signal Reference to Signal object that listener is currently bound to.
@param {Function} listener Handler function bound to the signal.
@param {boolean} isOnce If binding should be executed just once.
@param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@param {Number} [priority] The priority level of the event listener. (default = 0).
###
class SignalBinding
constructor: (signal, listener, isOnce, listenerContext, priority) ->
###*
Handler function bound to the signal.
@type Function
@private
###
@_listener = listener
###*
If binding should be executed just once.
@type boolean
@private
###
@_isOnce = isOnce
###*
Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@memberOf SignalBinding.prototype
@name context
@type Object|undefined|null
###
@context = listenerContext
###*
Reference to Signal object that listener is currently bound to.
@type Signal
@private
###
@_signal = signal
###*
Listener priority
@type Number
@private
###
@_priority = priority or 0
###*
If binding is active and should be executed.
@type boolean
###
active: true
###*
Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
@type Array|null
###
params: null
###*
Call listener passing arbitrary parameters.
<p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
@param {Array} [paramsArr] Array of parameters that should be passed to the listener
@return {*} Value returned by the listener.
###
execute: (paramsArr) ->
handlerReturn = undefined
params = undefined
if @active and !!@_listener
params = (if @params then @params.concat(paramsArr) else paramsArr)
handlerReturn = @_listener.apply(@context, params)
@detach() if @_isOnce
handlerReturn
###*
Detach binding from signal.
- alias to: mySignal.remove(myBinding.getListener());
@return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
###
detach: ->
(if @isBound() then @_signal.remove(@_listener, @context) else null)
###*
@return {Boolean} `true` if binding is still bound to the signal and have a listener.
###
isBound: ->
!!@_signal and !!@_listener
###*
@return {boolean} If SignalBinding will only be executed once.
###
isOnce: ->
@_isOnce
###*
@return {Function} Handler function bound to the signal.
###
getListener: ->
@_listener
###*
@return {Signal} Signal that listener is currently bound to.
###
getSignal: ->
@_signal
###*
Delete instance properties
@private
###
_destroy: ->
delete @_signal
delete @_listener
delete @context
###*
@return {string} String representation of the object.
###
toString: ->
"[SignalBinding isOnce:" + @_isOnce + ", isBound:" + @isBound() + ", active:" + @active + "]"
return SignalBinding | 52197 | define 'Coffixi/utils/SignalBinding', ->
# Adapted from https://raw.github.com/millermedeiros/js-signals/
# SignalBinding -------------------------------------------------
#================================================================
###*
Object that represents a binding between a Signal and a listener function.
<br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
<br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
@author <NAME>
@constructor
@internal
@name SignalBinding
@param {Signal} signal Reference to Signal object that listener is currently bound to.
@param {Function} listener Handler function bound to the signal.
@param {boolean} isOnce If binding should be executed just once.
@param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@param {Number} [priority] The priority level of the event listener. (default = 0).
###
class SignalBinding
constructor: (signal, listener, isOnce, listenerContext, priority) ->
###*
Handler function bound to the signal.
@type Function
@private
###
@_listener = listener
###*
If binding should be executed just once.
@type boolean
@private
###
@_isOnce = isOnce
###*
Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@memberOf SignalBinding.prototype
@name context
@type Object|undefined|null
###
@context = listenerContext
###*
Reference to Signal object that listener is currently bound to.
@type Signal
@private
###
@_signal = signal
###*
Listener priority
@type Number
@private
###
@_priority = priority or 0
###*
If binding is active and should be executed.
@type boolean
###
active: true
###*
Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
@type Array|null
###
params: null
###*
Call listener passing arbitrary parameters.
<p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
@param {Array} [paramsArr] Array of parameters that should be passed to the listener
@return {*} Value returned by the listener.
###
execute: (paramsArr) ->
handlerReturn = undefined
params = undefined
if @active and !!@_listener
params = (if @params then @params.concat(paramsArr) else paramsArr)
handlerReturn = @_listener.apply(@context, params)
@detach() if @_isOnce
handlerReturn
###*
Detach binding from signal.
- alias to: mySignal.remove(myBinding.getListener());
@return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
###
detach: ->
(if @isBound() then @_signal.remove(@_listener, @context) else null)
###*
@return {Boolean} `true` if binding is still bound to the signal and have a listener.
###
isBound: ->
!!@_signal and !!@_listener
###*
@return {boolean} If SignalBinding will only be executed once.
###
isOnce: ->
@_isOnce
###*
@return {Function} Handler function bound to the signal.
###
getListener: ->
@_listener
###*
@return {Signal} Signal that listener is currently bound to.
###
getSignal: ->
@_signal
###*
Delete instance properties
@private
###
_destroy: ->
delete @_signal
delete @_listener
delete @context
###*
@return {string} String representation of the object.
###
toString: ->
"[SignalBinding isOnce:" + @_isOnce + ", isBound:" + @isBound() + ", active:" + @active + "]"
return SignalBinding | true | define 'Coffixi/utils/SignalBinding', ->
# Adapted from https://raw.github.com/millermedeiros/js-signals/
# SignalBinding -------------------------------------------------
#================================================================
###*
Object that represents a binding between a Signal and a listener function.
<br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
<br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
@author PI:NAME:<NAME>END_PI
@constructor
@internal
@name SignalBinding
@param {Signal} signal Reference to Signal object that listener is currently bound to.
@param {Function} listener Handler function bound to the signal.
@param {boolean} isOnce If binding should be executed just once.
@param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@param {Number} [priority] The priority level of the event listener. (default = 0).
###
class SignalBinding
constructor: (signal, listener, isOnce, listenerContext, priority) ->
###*
Handler function bound to the signal.
@type Function
@private
###
@_listener = listener
###*
If binding should be executed just once.
@type boolean
@private
###
@_isOnce = isOnce
###*
Context on which listener will be executed (object that should represent the `this` variable inside listener function).
@memberOf SignalBinding.prototype
@name context
@type Object|undefined|null
###
@context = listenerContext
###*
Reference to Signal object that listener is currently bound to.
@type Signal
@private
###
@_signal = signal
###*
Listener priority
@type Number
@private
###
@_priority = priority or 0
###*
If binding is active and should be executed.
@type boolean
###
active: true
###*
Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
@type Array|null
###
params: null
###*
Call listener passing arbitrary parameters.
<p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
@param {Array} [paramsArr] Array of parameters that should be passed to the listener
@return {*} Value returned by the listener.
###
execute: (paramsArr) ->
handlerReturn = undefined
params = undefined
if @active and !!@_listener
params = (if @params then @params.concat(paramsArr) else paramsArr)
handlerReturn = @_listener.apply(@context, params)
@detach() if @_isOnce
handlerReturn
###*
Detach binding from signal.
- alias to: mySignal.remove(myBinding.getListener());
@return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
###
detach: ->
(if @isBound() then @_signal.remove(@_listener, @context) else null)
###*
@return {Boolean} `true` if binding is still bound to the signal and have a listener.
###
isBound: ->
!!@_signal and !!@_listener
###*
@return {boolean} If SignalBinding will only be executed once.
###
isOnce: ->
@_isOnce
###*
@return {Function} Handler function bound to the signal.
###
getListener: ->
@_listener
###*
@return {Signal} Signal that listener is currently bound to.
###
getSignal: ->
@_signal
###*
Delete instance properties
@private
###
_destroy: ->
delete @_signal
delete @_listener
delete @context
###*
@return {string} String representation of the object.
###
toString: ->
"[SignalBinding isOnce:" + @_isOnce + ", isBound:" + @isBound() + ", active:" + @active + "]"
return SignalBinding |
[
{
"context": "# @project nanoScrollerJS\n# @url http://jamesflorentino.github.com/nanoScrollerJS/\n# @author James Flore",
"end": 57,
"score": 0.9828483462333679,
"start": 42,
"tag": "USERNAME",
"value": "jamesflorentino"
},
{
"context": "esflorentino.github.com/nanoScrollerJS/\n# @author James Florentino\n# @contributor Krister Kari\n\n(($, window, docume",
"end": 112,
"score": 0.9999008178710938,
"start": 96,
"tag": "NAME",
"value": "James Florentino"
},
{
"context": "lerJS/\n# @author James Florentino\n# @contributor Krister Kari\n\n(($, window, document) ->\n \"use strict\"\n\n # De",
"end": 141,
"score": 0.9998927116394043,
"start": 129,
"tag": "NAME",
"value": "Krister Kari"
}
] | coffeescripts/jquery.nanoscroller.coffee | prasadsambari/nanoScrollerJS | 1 | # @project nanoScrollerJS
# @url http://jamesflorentino.github.com/nanoScrollerJS/
# @author James Florentino
# @contributor Krister Kari
(($, window, document) ->
"use strict"
# Default settings
defaults =
###*
a classname for the pane element.
@property paneClass
@type String
@default 'pane'
###
paneClass: 'pane'
###*
a classname for the slider element.
@property sliderClass
@type String
@default 'slider'
###
sliderClass: 'slider'
###*
a classname for the content element.
@property contentClass
@type String
@default 'content'
###
contentClass: 'content'
###*
a setting to enable native scrolling in iOS devices.
@property iOSNativeScrolling
@type Boolean
@default false
###
iOSNativeScrolling: false
###*
a setting to prevent the rest of the page being
scrolled when user scrolls the `.content` element.
@property preventPageScrolling
@type Boolean
@default false
###
preventPageScrolling: false
###*
a setting to disable binding to the resize event.
@property disableResize
@type Boolean
@default false
###
disableResize: false
###*
a setting to make the scrollbar always visible.
@property alwaysVisible
@type Boolean
@default false
###
alwaysVisible: false
###*
a default timeout for the `flash()` method.
@property flashDelay
@type Number
@default 1500
###
flashDelay: 1500
###*
a minimum height for the `.slider` element.
@property sliderMinHeight
@type Number
@default 20
###
sliderMinHeight: 20
###*
a maximum height for the `.slider` element.
@property sliderMaxHeight
@type Number
@default null
###
sliderMaxHeight: null
# Constants
###*
@property SCROLLBAR
@type String
@static
@final
@private
###
SCROLLBAR = 'scrollbar'
###*
@property SCROLL
@type String
@static
@final
@private
###
SCROLL = 'scroll'
###*
@property MOUSEDOWN
@type String
@final
@private
###
MOUSEDOWN = 'mousedown'
###*
@property MOUSEMOVE
@type String
@static
@final
@private
###
MOUSEMOVE = 'mousemove'
###*
@property MOUSEWHEEL
@type String
@final
@private
###
MOUSEWHEEL = 'mousewheel'
###*
@property MOUSEUP
@type String
@static
@final
@private
###
MOUSEUP = 'mouseup'
###*
@property RESIZE
@type String
@final
@private
###
RESIZE = 'resize'
###*
@property DRAG
@type String
@static
@final
@private
###
DRAG = 'drag'
###*
@property UP
@type String
@static
@final
@private
###
UP = 'up'
###*
@property PANEDOWN
@type String
@static
@final
@private
###
PANEDOWN = 'panedown'
###*
@property DOMSCROLL
@type String
@static
@final
@private
###
DOMSCROLL = 'DOMMouseScroll'
###*
@property DOWN
@type String
@static
@final
@private
###
DOWN = 'down'
###*
@property WHEEL
@type String
@static
@final
@private
###
WHEEL = 'wheel'
###*
@property KEYDOWN
@type String
@static
@final
@private
###
KEYDOWN = 'keydown'
###*
@property KEYUP
@type String
@static
@final
@private
###
KEYUP = 'keyup'
###*
@property TOUCHMOVE
@type String
@static
@final
@private
###
TOUCHMOVE = 'touchmove'
###*
@property BROWSER_IS_IE7
@type Boolean
@static
@final
@private
###
BROWSER_IS_IE7 = window.navigator.appName is 'Microsoft Internet Explorer' and (/msie 7./i).test(window.navigator.appVersion) and window.ActiveXObject
###*
@property BROWSER_SCROLLBAR_WIDTH
@type Number
@static
@default null
@private
###
BROWSER_SCROLLBAR_WIDTH = null
###*
Returns browser's native scrollbar width
@method getBrowserScrollbarWidth
@return {Number} the scrollbar width in pixels
@static
@private
###
getBrowserScrollbarWidth = ->
outer = document.createElement 'div'
outerStyle = outer.style
outerStyle.position = 'absolute'
outerStyle.width = '100px'
outerStyle.height = '100px'
outerStyle.overflow = SCROLL
outerStyle.top = '-9999px'
document.body.appendChild outer
scrollbarWidth = outer.offsetWidth - outer.clientWidth
document.body.removeChild outer
scrollbarWidth
###*
@class NanoScroll
@param element {HTMLElement|Node} the main element
@param options {Object} nanoScroller's options
@constructor
###
class NanoScroll
constructor: (@el, @options) ->
BROWSER_SCROLLBAR_WIDTH or= do getBrowserScrollbarWidth
@$el = $ @el
@doc = $ document
@win = $ window
@$content = @$el.children(".#{options.contentClass}")
@$content.attr 'tabindex', 0
@content = @$content[0]
if @options.iOSNativeScrolling && @el.style.WebkitOverflowScrolling?
do @nativeScrolling
else
do @generate
do @createEvents
do @addEvents
do @reset
###*
Prevents the rest of the page being scrolled
when user scrolls the `.content` element.
@method preventScrolling
@param event {Event}
@param direction {String} Scroll direction (up or down)
@private
###
preventScrolling: (e, direction) ->
return unless @isActive
if e.type is DOMSCROLL # Gecko
if direction is DOWN and e.originalEvent.detail > 0 or direction is UP and e.originalEvent.detail < 0
do e.preventDefault
else if e.type is MOUSEWHEEL # WebKit, Trident and Presto
return if not e.originalEvent or not e.originalEvent.wheelDelta
if direction is DOWN and e.originalEvent.wheelDelta < 0 or direction is UP and e.originalEvent.wheelDelta > 0
do e.preventDefault
return
###*
Enable iOS native scrolling
####
nativeScrolling: ->
# simply enable container
@$content.css {WebkitOverflowScrolling: 'touch'}
@iOSNativeScrolling = true
# we are always active
@isActive = true
return
###*
Updates those nanoScroller properties that
are related to current scrollbar position.
@method updateScrollValues
@private
###
updateScrollValues: ->
content = @content
# Formula/ratio
# `scrollTop / maxScrollTop = sliderTop / maxSliderTop`
@maxScrollTop = content.scrollHeight - content.clientHeight
@contentScrollTop = content.scrollTop
if not @iOSNativeScrolling
@maxSliderTop = @paneHeight - @sliderHeight
# `sliderTop = scrollTop / maxScrollTop * maxSliderTop
@sliderTop = @contentScrollTop * @maxSliderTop / @maxScrollTop
return
###*
Creates event related methods
@method createEvents
@private
###
createEvents: ->
@events =
down: (e) =>
@isBeingDragged = true
@offsetY = e.pageY - @slider.offset().top
@pane.addClass 'active'
@doc
.bind(MOUSEMOVE, @events[DRAG])
.bind(MOUSEUP, @events[UP])
false
drag: (e) =>
@sliderY = e.pageY - @$el.offset().top - @offsetY
do @scroll
do @updateScrollValues
if @contentScrollTop >= @maxScrollTop
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@$el.trigger 'scrolltop'
false
up: (e) =>
@isBeingDragged = false
@pane.removeClass 'active'
@doc
.unbind(MOUSEMOVE, @events[DRAG])
.unbind(MOUSEUP, @events[UP])
false
resize: (e) =>
do @reset
return
panedown: (e) =>
@sliderY = (e.offsetY or e.originalEvent.layerY) - (@sliderHeight * 0.5)
do @scroll
@events.down e
false
scroll: (e) =>
# Don't operate if there is a dragging mechanism going on.
# This is invoked when a user presses and moves the slider or pane
return if @isBeingDragged
do @updateScrollValues
if not @iOSNativeScrolling
# update the slider position
@sliderY = @sliderTop
@slider.css top: @sliderTop
# the succeeding code should be ignored if @events.scroll() wasn't
# invoked by a DOM event. (refer to @reset)
return unless e?
# if it reaches the maximum and minimum scrolling point,
# we dispatch an event.
if @contentScrollTop >= @maxScrollTop
@preventScrolling(e, DOWN) if @options.preventPageScrolling
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@preventScrolling(e, UP) if @options.preventPageScrolling
@$el.trigger 'scrolltop'
return
wheel: (e) =>
return unless e?
@sliderY += -e.wheelDeltaY or -e.delta
do @scroll
false
return
###*
Adds event listeners with jQuery.
@method addEvents
@private
###
addEvents: ->
do @removeEvents
events = @events
if not @options.disableResize
@win
.bind RESIZE, events[RESIZE]
if not @iOSNativeScrolling
@slider
.bind MOUSEDOWN, events[DOWN]
@pane
.bind(MOUSEDOWN, events[PANEDOWN])
.bind("#{MOUSEWHEEL} #{DOMSCROLL}", events[WHEEL])
@$content
.bind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Removes event listeners with jQuery.
@method removeEvents
@private
###
removeEvents: ->
events = @events
@win
.unbind(RESIZE, events[RESIZE])
if not @iOSNativeScrolling
do @slider.unbind
do @pane.unbind
@$content
.unbind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Generates nanoScroller's scrollbar and elements for it.
@method generate
@chainable
@private
###
generate: ->
# For reference:
# http://msdn.microsoft.com/en-us/library/windows/desktop/bb787527(v=vs.85).aspx#parts_of_scroll_bar
options = @options
{paneClass, sliderClass, contentClass} = options
if not @$el.find("#{paneClass}").length and not @$el.find("#{sliderClass}").length
@$el.append """<div class="#{paneClass}"><div class="#{sliderClass}" /></div>"""
# pane is the name for the actual scrollbar.
@pane = @$el.children ".#{paneClass}"
# slider is the name for the scrollbox or thumb of the scrollbar gadget
@slider = @pane.find ".#{sliderClass}"
if BROWSER_SCROLLBAR_WIDTH
cssRule = if @$el.css('direction') is 'rtl' then left: -BROWSER_SCROLLBAR_WIDTH else right: -BROWSER_SCROLLBAR_WIDTH
@$el.addClass 'has-scrollbar'
@$content.css cssRule if cssRule?
this
###*
@method restore
@private
###
restore: ->
@stopped = false
do @pane.show
do @addEvents
return
###*
Resets nanoScroller's scrollbar.
@method reset
@chainable
@example
$(".nano").nanoScroller();
###
reset: ->
if @iOSNativeScrolling
@contentHeight = @content.scrollHeight
return
@generate().stop() if not @$el.find(".#{@options.paneClass}").length
do @restore if @stopped
content = @content
contentStyle = content.style
contentStyleOverflowY = contentStyle.overflowY
# try to detect IE7 and IE7 compatibility mode.
# this sniffing is done to fix a IE7 related bug.
@$content.css height: do @$content.height if BROWSER_IS_IE7
# set the scrollbar UI's height
# the target content
contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH
# set the pane's height.
paneHeight = do @pane.outerHeight
paneTop = parseInt @pane.css('top'), 10
paneBottom = parseInt @pane.css('bottom'), 10
paneOuterHeight = paneHeight + paneTop + paneBottom
# set the slider's height
sliderHeight = Math.round paneOuterHeight / contentHeight * paneOuterHeight
if sliderHeight < @options.sliderMinHeight
sliderHeight = @options.sliderMinHeight # set min height
else if @options.sliderMaxHeight? and sliderHeight > @options.sliderMaxHeight
sliderHeight = @options.sliderMaxHeight # set max height
sliderHeight += BROWSER_SCROLLBAR_WIDTH if contentStyleOverflowY is SCROLL and contentStyle.overflowX isnt SCROLL
# the maximum top value for the slider
@maxSliderTop = paneOuterHeight - sliderHeight
# set into properties for further use
@contentHeight = contentHeight
@paneHeight = paneHeight
@paneOuterHeight = paneOuterHeight
@sliderHeight = sliderHeight
# set the values to the gadget
@slider.height sliderHeight
# scroll sets the position of the @slider
do @events.scroll
do @pane.show
@isActive = true
if (content.scrollHeight is content.clientHeight) or (
@pane.outerHeight(true) >= content.scrollHeight and contentStyleOverflowY isnt SCROLL)
do @pane.hide
@isActive = false
else if @el.clientHeight is content.scrollHeight and contentStyleOverflowY is SCROLL
do @slider.hide
else
do @slider.show
# allow the pane element to stay visible
@pane.css
opacity: (if @options.alwaysVisible then 1 else '')
visibility: (if @options.alwaysVisible then 'visible' else '')
this
###*
@method scroll
@private
@example
$(".nano").nanoScroller({ scroll: 'top' });
###
scroll: ->
return unless @isActive
@sliderY = Math.max 0, @sliderY
@sliderY = Math.min @maxSliderTop, @sliderY
@$content.scrollTop (@paneHeight - @contentHeight + BROWSER_SCROLLBAR_WIDTH) * @sliderY / @maxSliderTop * -1
if not @iOSNativeScrolling
@slider.css top: @sliderY
this
###*
Scroll at the bottom with an offset value
@method scrollBottom
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollBottom: value });
###
scrollBottom: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(@contentHeight - @$content.height() - offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll at the top with an offset value
@method scrollTop
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollTop: value });
###
scrollTop: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(+offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll to an element
@method scrollTo
@param node {Node} A node to scroll to.
@chainable
@example
$(".nano").nanoScroller({ scrollTo: $('#a_node') });
###
scrollTo: (node) ->
return unless @isActive
do @reset
@scrollTop $(node).get(0).offsetTop
this
###*
To stop the operation.
This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.
@method stop
@chainable
@example
$(".nano").nanoScroller({ stop: true });
###
stop: ->
@stopped = true
do @removeEvents
do @pane.hide
this
###*
To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.
@method flash
@chainable
@example
$(".nano").nanoScroller({ flash: true });
###
flash: ->
return unless @isActive
do @reset
@pane.addClass 'flashed'
setTimeout =>
@pane.removeClass 'flashed'
return
, @options.flashDelay
this
$.fn.nanoScroller = (settings) ->
@each ->
if not scrollbar = @nanoscroller
options = $.extend {}, defaults, settings
@nanoscroller = scrollbar = new NanoScroll this, options
# scrollbar settings
if settings and typeof settings is "object"
$.extend scrollbar.options, settings # update scrollbar settings
return scrollbar.scrollBottom settings.scrollBottom if settings.scrollBottom
return scrollbar.scrollTop settings.scrollTop if settings.scrollTop
return scrollbar.scrollTo settings.scrollTo if settings.scrollTo
return scrollbar.scrollBottom 0 if settings.scroll is 'bottom'
return scrollbar.scrollTop 0 if settings.scroll is 'top'
return scrollbar.scrollTo settings.scroll if settings.scroll and settings.scroll instanceof $
return do scrollbar.stop if settings.stop
return do scrollbar.flash if settings.flash
do scrollbar.reset
return
)(jQuery, window, document)
| 52879 | # @project nanoScrollerJS
# @url http://jamesflorentino.github.com/nanoScrollerJS/
# @author <NAME>
# @contributor <NAME>
(($, window, document) ->
"use strict"
# Default settings
defaults =
###*
a classname for the pane element.
@property paneClass
@type String
@default 'pane'
###
paneClass: 'pane'
###*
a classname for the slider element.
@property sliderClass
@type String
@default 'slider'
###
sliderClass: 'slider'
###*
a classname for the content element.
@property contentClass
@type String
@default 'content'
###
contentClass: 'content'
###*
a setting to enable native scrolling in iOS devices.
@property iOSNativeScrolling
@type Boolean
@default false
###
iOSNativeScrolling: false
###*
a setting to prevent the rest of the page being
scrolled when user scrolls the `.content` element.
@property preventPageScrolling
@type Boolean
@default false
###
preventPageScrolling: false
###*
a setting to disable binding to the resize event.
@property disableResize
@type Boolean
@default false
###
disableResize: false
###*
a setting to make the scrollbar always visible.
@property alwaysVisible
@type Boolean
@default false
###
alwaysVisible: false
###*
a default timeout for the `flash()` method.
@property flashDelay
@type Number
@default 1500
###
flashDelay: 1500
###*
a minimum height for the `.slider` element.
@property sliderMinHeight
@type Number
@default 20
###
sliderMinHeight: 20
###*
a maximum height for the `.slider` element.
@property sliderMaxHeight
@type Number
@default null
###
sliderMaxHeight: null
# Constants
###*
@property SCROLLBAR
@type String
@static
@final
@private
###
SCROLLBAR = 'scrollbar'
###*
@property SCROLL
@type String
@static
@final
@private
###
SCROLL = 'scroll'
###*
@property MOUSEDOWN
@type String
@final
@private
###
MOUSEDOWN = 'mousedown'
###*
@property MOUSEMOVE
@type String
@static
@final
@private
###
MOUSEMOVE = 'mousemove'
###*
@property MOUSEWHEEL
@type String
@final
@private
###
MOUSEWHEEL = 'mousewheel'
###*
@property MOUSEUP
@type String
@static
@final
@private
###
MOUSEUP = 'mouseup'
###*
@property RESIZE
@type String
@final
@private
###
RESIZE = 'resize'
###*
@property DRAG
@type String
@static
@final
@private
###
DRAG = 'drag'
###*
@property UP
@type String
@static
@final
@private
###
UP = 'up'
###*
@property PANEDOWN
@type String
@static
@final
@private
###
PANEDOWN = 'panedown'
###*
@property DOMSCROLL
@type String
@static
@final
@private
###
DOMSCROLL = 'DOMMouseScroll'
###*
@property DOWN
@type String
@static
@final
@private
###
DOWN = 'down'
###*
@property WHEEL
@type String
@static
@final
@private
###
WHEEL = 'wheel'
###*
@property KEYDOWN
@type String
@static
@final
@private
###
KEYDOWN = 'keydown'
###*
@property KEYUP
@type String
@static
@final
@private
###
KEYUP = 'keyup'
###*
@property TOUCHMOVE
@type String
@static
@final
@private
###
TOUCHMOVE = 'touchmove'
###*
@property BROWSER_IS_IE7
@type Boolean
@static
@final
@private
###
BROWSER_IS_IE7 = window.navigator.appName is 'Microsoft Internet Explorer' and (/msie 7./i).test(window.navigator.appVersion) and window.ActiveXObject
###*
@property BROWSER_SCROLLBAR_WIDTH
@type Number
@static
@default null
@private
###
BROWSER_SCROLLBAR_WIDTH = null
###*
Returns browser's native scrollbar width
@method getBrowserScrollbarWidth
@return {Number} the scrollbar width in pixels
@static
@private
###
getBrowserScrollbarWidth = ->
outer = document.createElement 'div'
outerStyle = outer.style
outerStyle.position = 'absolute'
outerStyle.width = '100px'
outerStyle.height = '100px'
outerStyle.overflow = SCROLL
outerStyle.top = '-9999px'
document.body.appendChild outer
scrollbarWidth = outer.offsetWidth - outer.clientWidth
document.body.removeChild outer
scrollbarWidth
###*
@class NanoScroll
@param element {HTMLElement|Node} the main element
@param options {Object} nanoScroller's options
@constructor
###
class NanoScroll
constructor: (@el, @options) ->
BROWSER_SCROLLBAR_WIDTH or= do getBrowserScrollbarWidth
@$el = $ @el
@doc = $ document
@win = $ window
@$content = @$el.children(".#{options.contentClass}")
@$content.attr 'tabindex', 0
@content = @$content[0]
if @options.iOSNativeScrolling && @el.style.WebkitOverflowScrolling?
do @nativeScrolling
else
do @generate
do @createEvents
do @addEvents
do @reset
###*
Prevents the rest of the page being scrolled
when user scrolls the `.content` element.
@method preventScrolling
@param event {Event}
@param direction {String} Scroll direction (up or down)
@private
###
preventScrolling: (e, direction) ->
return unless @isActive
if e.type is DOMSCROLL # Gecko
if direction is DOWN and e.originalEvent.detail > 0 or direction is UP and e.originalEvent.detail < 0
do e.preventDefault
else if e.type is MOUSEWHEEL # WebKit, Trident and Presto
return if not e.originalEvent or not e.originalEvent.wheelDelta
if direction is DOWN and e.originalEvent.wheelDelta < 0 or direction is UP and e.originalEvent.wheelDelta > 0
do e.preventDefault
return
###*
Enable iOS native scrolling
####
nativeScrolling: ->
# simply enable container
@$content.css {WebkitOverflowScrolling: 'touch'}
@iOSNativeScrolling = true
# we are always active
@isActive = true
return
###*
Updates those nanoScroller properties that
are related to current scrollbar position.
@method updateScrollValues
@private
###
updateScrollValues: ->
content = @content
# Formula/ratio
# `scrollTop / maxScrollTop = sliderTop / maxSliderTop`
@maxScrollTop = content.scrollHeight - content.clientHeight
@contentScrollTop = content.scrollTop
if not @iOSNativeScrolling
@maxSliderTop = @paneHeight - @sliderHeight
# `sliderTop = scrollTop / maxScrollTop * maxSliderTop
@sliderTop = @contentScrollTop * @maxSliderTop / @maxScrollTop
return
###*
Creates event related methods
@method createEvents
@private
###
createEvents: ->
@events =
down: (e) =>
@isBeingDragged = true
@offsetY = e.pageY - @slider.offset().top
@pane.addClass 'active'
@doc
.bind(MOUSEMOVE, @events[DRAG])
.bind(MOUSEUP, @events[UP])
false
drag: (e) =>
@sliderY = e.pageY - @$el.offset().top - @offsetY
do @scroll
do @updateScrollValues
if @contentScrollTop >= @maxScrollTop
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@$el.trigger 'scrolltop'
false
up: (e) =>
@isBeingDragged = false
@pane.removeClass 'active'
@doc
.unbind(MOUSEMOVE, @events[DRAG])
.unbind(MOUSEUP, @events[UP])
false
resize: (e) =>
do @reset
return
panedown: (e) =>
@sliderY = (e.offsetY or e.originalEvent.layerY) - (@sliderHeight * 0.5)
do @scroll
@events.down e
false
scroll: (e) =>
# Don't operate if there is a dragging mechanism going on.
# This is invoked when a user presses and moves the slider or pane
return if @isBeingDragged
do @updateScrollValues
if not @iOSNativeScrolling
# update the slider position
@sliderY = @sliderTop
@slider.css top: @sliderTop
# the succeeding code should be ignored if @events.scroll() wasn't
# invoked by a DOM event. (refer to @reset)
return unless e?
# if it reaches the maximum and minimum scrolling point,
# we dispatch an event.
if @contentScrollTop >= @maxScrollTop
@preventScrolling(e, DOWN) if @options.preventPageScrolling
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@preventScrolling(e, UP) if @options.preventPageScrolling
@$el.trigger 'scrolltop'
return
wheel: (e) =>
return unless e?
@sliderY += -e.wheelDeltaY or -e.delta
do @scroll
false
return
###*
Adds event listeners with jQuery.
@method addEvents
@private
###
addEvents: ->
do @removeEvents
events = @events
if not @options.disableResize
@win
.bind RESIZE, events[RESIZE]
if not @iOSNativeScrolling
@slider
.bind MOUSEDOWN, events[DOWN]
@pane
.bind(MOUSEDOWN, events[PANEDOWN])
.bind("#{MOUSEWHEEL} #{DOMSCROLL}", events[WHEEL])
@$content
.bind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Removes event listeners with jQuery.
@method removeEvents
@private
###
removeEvents: ->
events = @events
@win
.unbind(RESIZE, events[RESIZE])
if not @iOSNativeScrolling
do @slider.unbind
do @pane.unbind
@$content
.unbind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Generates nanoScroller's scrollbar and elements for it.
@method generate
@chainable
@private
###
generate: ->
# For reference:
# http://msdn.microsoft.com/en-us/library/windows/desktop/bb787527(v=vs.85).aspx#parts_of_scroll_bar
options = @options
{paneClass, sliderClass, contentClass} = options
if not @$el.find("#{paneClass}").length and not @$el.find("#{sliderClass}").length
@$el.append """<div class="#{paneClass}"><div class="#{sliderClass}" /></div>"""
# pane is the name for the actual scrollbar.
@pane = @$el.children ".#{paneClass}"
# slider is the name for the scrollbox or thumb of the scrollbar gadget
@slider = @pane.find ".#{sliderClass}"
if BROWSER_SCROLLBAR_WIDTH
cssRule = if @$el.css('direction') is 'rtl' then left: -BROWSER_SCROLLBAR_WIDTH else right: -BROWSER_SCROLLBAR_WIDTH
@$el.addClass 'has-scrollbar'
@$content.css cssRule if cssRule?
this
###*
@method restore
@private
###
restore: ->
@stopped = false
do @pane.show
do @addEvents
return
###*
Resets nanoScroller's scrollbar.
@method reset
@chainable
@example
$(".nano").nanoScroller();
###
reset: ->
if @iOSNativeScrolling
@contentHeight = @content.scrollHeight
return
@generate().stop() if not @$el.find(".#{@options.paneClass}").length
do @restore if @stopped
content = @content
contentStyle = content.style
contentStyleOverflowY = contentStyle.overflowY
# try to detect IE7 and IE7 compatibility mode.
# this sniffing is done to fix a IE7 related bug.
@$content.css height: do @$content.height if BROWSER_IS_IE7
# set the scrollbar UI's height
# the target content
contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH
# set the pane's height.
paneHeight = do @pane.outerHeight
paneTop = parseInt @pane.css('top'), 10
paneBottom = parseInt @pane.css('bottom'), 10
paneOuterHeight = paneHeight + paneTop + paneBottom
# set the slider's height
sliderHeight = Math.round paneOuterHeight / contentHeight * paneOuterHeight
if sliderHeight < @options.sliderMinHeight
sliderHeight = @options.sliderMinHeight # set min height
else if @options.sliderMaxHeight? and sliderHeight > @options.sliderMaxHeight
sliderHeight = @options.sliderMaxHeight # set max height
sliderHeight += BROWSER_SCROLLBAR_WIDTH if contentStyleOverflowY is SCROLL and contentStyle.overflowX isnt SCROLL
# the maximum top value for the slider
@maxSliderTop = paneOuterHeight - sliderHeight
# set into properties for further use
@contentHeight = contentHeight
@paneHeight = paneHeight
@paneOuterHeight = paneOuterHeight
@sliderHeight = sliderHeight
# set the values to the gadget
@slider.height sliderHeight
# scroll sets the position of the @slider
do @events.scroll
do @pane.show
@isActive = true
if (content.scrollHeight is content.clientHeight) or (
@pane.outerHeight(true) >= content.scrollHeight and contentStyleOverflowY isnt SCROLL)
do @pane.hide
@isActive = false
else if @el.clientHeight is content.scrollHeight and contentStyleOverflowY is SCROLL
do @slider.hide
else
do @slider.show
# allow the pane element to stay visible
@pane.css
opacity: (if @options.alwaysVisible then 1 else '')
visibility: (if @options.alwaysVisible then 'visible' else '')
this
###*
@method scroll
@private
@example
$(".nano").nanoScroller({ scroll: 'top' });
###
scroll: ->
return unless @isActive
@sliderY = Math.max 0, @sliderY
@sliderY = Math.min @maxSliderTop, @sliderY
@$content.scrollTop (@paneHeight - @contentHeight + BROWSER_SCROLLBAR_WIDTH) * @sliderY / @maxSliderTop * -1
if not @iOSNativeScrolling
@slider.css top: @sliderY
this
###*
Scroll at the bottom with an offset value
@method scrollBottom
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollBottom: value });
###
scrollBottom: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(@contentHeight - @$content.height() - offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll at the top with an offset value
@method scrollTop
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollTop: value });
###
scrollTop: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(+offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll to an element
@method scrollTo
@param node {Node} A node to scroll to.
@chainable
@example
$(".nano").nanoScroller({ scrollTo: $('#a_node') });
###
scrollTo: (node) ->
return unless @isActive
do @reset
@scrollTop $(node).get(0).offsetTop
this
###*
To stop the operation.
This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.
@method stop
@chainable
@example
$(".nano").nanoScroller({ stop: true });
###
stop: ->
@stopped = true
do @removeEvents
do @pane.hide
this
###*
To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.
@method flash
@chainable
@example
$(".nano").nanoScroller({ flash: true });
###
flash: ->
return unless @isActive
do @reset
@pane.addClass 'flashed'
setTimeout =>
@pane.removeClass 'flashed'
return
, @options.flashDelay
this
$.fn.nanoScroller = (settings) ->
@each ->
if not scrollbar = @nanoscroller
options = $.extend {}, defaults, settings
@nanoscroller = scrollbar = new NanoScroll this, options
# scrollbar settings
if settings and typeof settings is "object"
$.extend scrollbar.options, settings # update scrollbar settings
return scrollbar.scrollBottom settings.scrollBottom if settings.scrollBottom
return scrollbar.scrollTop settings.scrollTop if settings.scrollTop
return scrollbar.scrollTo settings.scrollTo if settings.scrollTo
return scrollbar.scrollBottom 0 if settings.scroll is 'bottom'
return scrollbar.scrollTop 0 if settings.scroll is 'top'
return scrollbar.scrollTo settings.scroll if settings.scroll and settings.scroll instanceof $
return do scrollbar.stop if settings.stop
return do scrollbar.flash if settings.flash
do scrollbar.reset
return
)(jQuery, window, document)
| true | # @project nanoScrollerJS
# @url http://jamesflorentino.github.com/nanoScrollerJS/
# @author PI:NAME:<NAME>END_PI
# @contributor PI:NAME:<NAME>END_PI
(($, window, document) ->
"use strict"
# Default settings
defaults =
###*
a classname for the pane element.
@property paneClass
@type String
@default 'pane'
###
paneClass: 'pane'
###*
a classname for the slider element.
@property sliderClass
@type String
@default 'slider'
###
sliderClass: 'slider'
###*
a classname for the content element.
@property contentClass
@type String
@default 'content'
###
contentClass: 'content'
###*
a setting to enable native scrolling in iOS devices.
@property iOSNativeScrolling
@type Boolean
@default false
###
iOSNativeScrolling: false
###*
a setting to prevent the rest of the page being
scrolled when user scrolls the `.content` element.
@property preventPageScrolling
@type Boolean
@default false
###
preventPageScrolling: false
###*
a setting to disable binding to the resize event.
@property disableResize
@type Boolean
@default false
###
disableResize: false
###*
a setting to make the scrollbar always visible.
@property alwaysVisible
@type Boolean
@default false
###
alwaysVisible: false
###*
a default timeout for the `flash()` method.
@property flashDelay
@type Number
@default 1500
###
flashDelay: 1500
###*
a minimum height for the `.slider` element.
@property sliderMinHeight
@type Number
@default 20
###
sliderMinHeight: 20
###*
a maximum height for the `.slider` element.
@property sliderMaxHeight
@type Number
@default null
###
sliderMaxHeight: null
# Constants
###*
@property SCROLLBAR
@type String
@static
@final
@private
###
SCROLLBAR = 'scrollbar'
###*
@property SCROLL
@type String
@static
@final
@private
###
SCROLL = 'scroll'
###*
@property MOUSEDOWN
@type String
@final
@private
###
MOUSEDOWN = 'mousedown'
###*
@property MOUSEMOVE
@type String
@static
@final
@private
###
MOUSEMOVE = 'mousemove'
###*
@property MOUSEWHEEL
@type String
@final
@private
###
MOUSEWHEEL = 'mousewheel'
###*
@property MOUSEUP
@type String
@static
@final
@private
###
MOUSEUP = 'mouseup'
###*
@property RESIZE
@type String
@final
@private
###
RESIZE = 'resize'
###*
@property DRAG
@type String
@static
@final
@private
###
DRAG = 'drag'
###*
@property UP
@type String
@static
@final
@private
###
UP = 'up'
###*
@property PANEDOWN
@type String
@static
@final
@private
###
PANEDOWN = 'panedown'
###*
@property DOMSCROLL
@type String
@static
@final
@private
###
DOMSCROLL = 'DOMMouseScroll'
###*
@property DOWN
@type String
@static
@final
@private
###
DOWN = 'down'
###*
@property WHEEL
@type String
@static
@final
@private
###
WHEEL = 'wheel'
###*
@property KEYDOWN
@type String
@static
@final
@private
###
KEYDOWN = 'keydown'
###*
@property KEYUP
@type String
@static
@final
@private
###
KEYUP = 'keyup'
###*
@property TOUCHMOVE
@type String
@static
@final
@private
###
TOUCHMOVE = 'touchmove'
###*
@property BROWSER_IS_IE7
@type Boolean
@static
@final
@private
###
BROWSER_IS_IE7 = window.navigator.appName is 'Microsoft Internet Explorer' and (/msie 7./i).test(window.navigator.appVersion) and window.ActiveXObject
###*
@property BROWSER_SCROLLBAR_WIDTH
@type Number
@static
@default null
@private
###
BROWSER_SCROLLBAR_WIDTH = null
###*
Returns browser's native scrollbar width
@method getBrowserScrollbarWidth
@return {Number} the scrollbar width in pixels
@static
@private
###
getBrowserScrollbarWidth = ->
outer = document.createElement 'div'
outerStyle = outer.style
outerStyle.position = 'absolute'
outerStyle.width = '100px'
outerStyle.height = '100px'
outerStyle.overflow = SCROLL
outerStyle.top = '-9999px'
document.body.appendChild outer
scrollbarWidth = outer.offsetWidth - outer.clientWidth
document.body.removeChild outer
scrollbarWidth
###*
@class NanoScroll
@param element {HTMLElement|Node} the main element
@param options {Object} nanoScroller's options
@constructor
###
class NanoScroll
constructor: (@el, @options) ->
BROWSER_SCROLLBAR_WIDTH or= do getBrowserScrollbarWidth
@$el = $ @el
@doc = $ document
@win = $ window
@$content = @$el.children(".#{options.contentClass}")
@$content.attr 'tabindex', 0
@content = @$content[0]
if @options.iOSNativeScrolling && @el.style.WebkitOverflowScrolling?
do @nativeScrolling
else
do @generate
do @createEvents
do @addEvents
do @reset
###*
Prevents the rest of the page being scrolled
when user scrolls the `.content` element.
@method preventScrolling
@param event {Event}
@param direction {String} Scroll direction (up or down)
@private
###
preventScrolling: (e, direction) ->
return unless @isActive
if e.type is DOMSCROLL # Gecko
if direction is DOWN and e.originalEvent.detail > 0 or direction is UP and e.originalEvent.detail < 0
do e.preventDefault
else if e.type is MOUSEWHEEL # WebKit, Trident and Presto
return if not e.originalEvent or not e.originalEvent.wheelDelta
if direction is DOWN and e.originalEvent.wheelDelta < 0 or direction is UP and e.originalEvent.wheelDelta > 0
do e.preventDefault
return
###*
Enable iOS native scrolling
####
nativeScrolling: ->
# simply enable container
@$content.css {WebkitOverflowScrolling: 'touch'}
@iOSNativeScrolling = true
# we are always active
@isActive = true
return
###*
Updates those nanoScroller properties that
are related to current scrollbar position.
@method updateScrollValues
@private
###
updateScrollValues: ->
content = @content
# Formula/ratio
# `scrollTop / maxScrollTop = sliderTop / maxSliderTop`
@maxScrollTop = content.scrollHeight - content.clientHeight
@contentScrollTop = content.scrollTop
if not @iOSNativeScrolling
@maxSliderTop = @paneHeight - @sliderHeight
# `sliderTop = scrollTop / maxScrollTop * maxSliderTop
@sliderTop = @contentScrollTop * @maxSliderTop / @maxScrollTop
return
###*
Creates event related methods
@method createEvents
@private
###
createEvents: ->
@events =
down: (e) =>
@isBeingDragged = true
@offsetY = e.pageY - @slider.offset().top
@pane.addClass 'active'
@doc
.bind(MOUSEMOVE, @events[DRAG])
.bind(MOUSEUP, @events[UP])
false
drag: (e) =>
@sliderY = e.pageY - @$el.offset().top - @offsetY
do @scroll
do @updateScrollValues
if @contentScrollTop >= @maxScrollTop
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@$el.trigger 'scrolltop'
false
up: (e) =>
@isBeingDragged = false
@pane.removeClass 'active'
@doc
.unbind(MOUSEMOVE, @events[DRAG])
.unbind(MOUSEUP, @events[UP])
false
resize: (e) =>
do @reset
return
panedown: (e) =>
@sliderY = (e.offsetY or e.originalEvent.layerY) - (@sliderHeight * 0.5)
do @scroll
@events.down e
false
scroll: (e) =>
# Don't operate if there is a dragging mechanism going on.
# This is invoked when a user presses and moves the slider or pane
return if @isBeingDragged
do @updateScrollValues
if not @iOSNativeScrolling
# update the slider position
@sliderY = @sliderTop
@slider.css top: @sliderTop
# the succeeding code should be ignored if @events.scroll() wasn't
# invoked by a DOM event. (refer to @reset)
return unless e?
# if it reaches the maximum and minimum scrolling point,
# we dispatch an event.
if @contentScrollTop >= @maxScrollTop
@preventScrolling(e, DOWN) if @options.preventPageScrolling
@$el.trigger 'scrollend'
else if @contentScrollTop is 0
@preventScrolling(e, UP) if @options.preventPageScrolling
@$el.trigger 'scrolltop'
return
wheel: (e) =>
return unless e?
@sliderY += -e.wheelDeltaY or -e.delta
do @scroll
false
return
###*
Adds event listeners with jQuery.
@method addEvents
@private
###
addEvents: ->
do @removeEvents
events = @events
if not @options.disableResize
@win
.bind RESIZE, events[RESIZE]
if not @iOSNativeScrolling
@slider
.bind MOUSEDOWN, events[DOWN]
@pane
.bind(MOUSEDOWN, events[PANEDOWN])
.bind("#{MOUSEWHEEL} #{DOMSCROLL}", events[WHEEL])
@$content
.bind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Removes event listeners with jQuery.
@method removeEvents
@private
###
removeEvents: ->
events = @events
@win
.unbind(RESIZE, events[RESIZE])
if not @iOSNativeScrolling
do @slider.unbind
do @pane.unbind
@$content
.unbind("#{SCROLL} #{MOUSEWHEEL} #{DOMSCROLL} #{TOUCHMOVE}", events[SCROLL])
return
###*
Generates nanoScroller's scrollbar and elements for it.
@method generate
@chainable
@private
###
generate: ->
# For reference:
# http://msdn.microsoft.com/en-us/library/windows/desktop/bb787527(v=vs.85).aspx#parts_of_scroll_bar
options = @options
{paneClass, sliderClass, contentClass} = options
if not @$el.find("#{paneClass}").length and not @$el.find("#{sliderClass}").length
@$el.append """<div class="#{paneClass}"><div class="#{sliderClass}" /></div>"""
# pane is the name for the actual scrollbar.
@pane = @$el.children ".#{paneClass}"
# slider is the name for the scrollbox or thumb of the scrollbar gadget
@slider = @pane.find ".#{sliderClass}"
if BROWSER_SCROLLBAR_WIDTH
cssRule = if @$el.css('direction') is 'rtl' then left: -BROWSER_SCROLLBAR_WIDTH else right: -BROWSER_SCROLLBAR_WIDTH
@$el.addClass 'has-scrollbar'
@$content.css cssRule if cssRule?
this
###*
@method restore
@private
###
restore: ->
@stopped = false
do @pane.show
do @addEvents
return
###*
Resets nanoScroller's scrollbar.
@method reset
@chainable
@example
$(".nano").nanoScroller();
###
reset: ->
if @iOSNativeScrolling
@contentHeight = @content.scrollHeight
return
@generate().stop() if not @$el.find(".#{@options.paneClass}").length
do @restore if @stopped
content = @content
contentStyle = content.style
contentStyleOverflowY = contentStyle.overflowY
# try to detect IE7 and IE7 compatibility mode.
# this sniffing is done to fix a IE7 related bug.
@$content.css height: do @$content.height if BROWSER_IS_IE7
# set the scrollbar UI's height
# the target content
contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH
# set the pane's height.
paneHeight = do @pane.outerHeight
paneTop = parseInt @pane.css('top'), 10
paneBottom = parseInt @pane.css('bottom'), 10
paneOuterHeight = paneHeight + paneTop + paneBottom
# set the slider's height
sliderHeight = Math.round paneOuterHeight / contentHeight * paneOuterHeight
if sliderHeight < @options.sliderMinHeight
sliderHeight = @options.sliderMinHeight # set min height
else if @options.sliderMaxHeight? and sliderHeight > @options.sliderMaxHeight
sliderHeight = @options.sliderMaxHeight # set max height
sliderHeight += BROWSER_SCROLLBAR_WIDTH if contentStyleOverflowY is SCROLL and contentStyle.overflowX isnt SCROLL
# the maximum top value for the slider
@maxSliderTop = paneOuterHeight - sliderHeight
# set into properties for further use
@contentHeight = contentHeight
@paneHeight = paneHeight
@paneOuterHeight = paneOuterHeight
@sliderHeight = sliderHeight
# set the values to the gadget
@slider.height sliderHeight
# scroll sets the position of the @slider
do @events.scroll
do @pane.show
@isActive = true
if (content.scrollHeight is content.clientHeight) or (
@pane.outerHeight(true) >= content.scrollHeight and contentStyleOverflowY isnt SCROLL)
do @pane.hide
@isActive = false
else if @el.clientHeight is content.scrollHeight and contentStyleOverflowY is SCROLL
do @slider.hide
else
do @slider.show
# allow the pane element to stay visible
@pane.css
opacity: (if @options.alwaysVisible then 1 else '')
visibility: (if @options.alwaysVisible then 'visible' else '')
this
###*
@method scroll
@private
@example
$(".nano").nanoScroller({ scroll: 'top' });
###
scroll: ->
return unless @isActive
@sliderY = Math.max 0, @sliderY
@sliderY = Math.min @maxSliderTop, @sliderY
@$content.scrollTop (@paneHeight - @contentHeight + BROWSER_SCROLLBAR_WIDTH) * @sliderY / @maxSliderTop * -1
if not @iOSNativeScrolling
@slider.css top: @sliderY
this
###*
Scroll at the bottom with an offset value
@method scrollBottom
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollBottom: value });
###
scrollBottom: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(@contentHeight - @$content.height() - offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll at the top with an offset value
@method scrollTop
@param offsetY {Number}
@chainable
@example
$(".nano").nanoScroller({ scrollTop: value });
###
scrollTop: (offsetY) ->
return unless @isActive
do @reset
@$content.scrollTop(+offsetY).trigger(MOUSEWHEEL) # Update scrollbar position by triggering one of the scroll events
this
###*
Scroll to an element
@method scrollTo
@param node {Node} A node to scroll to.
@chainable
@example
$(".nano").nanoScroller({ scrollTo: $('#a_node') });
###
scrollTo: (node) ->
return unless @isActive
do @reset
@scrollTop $(node).get(0).offsetTop
this
###*
To stop the operation.
This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.
@method stop
@chainable
@example
$(".nano").nanoScroller({ stop: true });
###
stop: ->
@stopped = true
do @removeEvents
do @pane.hide
this
###*
To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.
@method flash
@chainable
@example
$(".nano").nanoScroller({ flash: true });
###
flash: ->
return unless @isActive
do @reset
@pane.addClass 'flashed'
setTimeout =>
@pane.removeClass 'flashed'
return
, @options.flashDelay
this
$.fn.nanoScroller = (settings) ->
@each ->
if not scrollbar = @nanoscroller
options = $.extend {}, defaults, settings
@nanoscroller = scrollbar = new NanoScroll this, options
# scrollbar settings
if settings and typeof settings is "object"
$.extend scrollbar.options, settings # update scrollbar settings
return scrollbar.scrollBottom settings.scrollBottom if settings.scrollBottom
return scrollbar.scrollTop settings.scrollTop if settings.scrollTop
return scrollbar.scrollTo settings.scrollTo if settings.scrollTo
return scrollbar.scrollBottom 0 if settings.scroll is 'bottom'
return scrollbar.scrollTop 0 if settings.scroll is 'top'
return scrollbar.scrollTo settings.scroll if settings.scroll and settings.scroll instanceof $
return do scrollbar.stop if settings.stop
return do scrollbar.flash if settings.flash
do scrollbar.reset
return
)(jQuery, window, document)
|
[
{
"context": "'}\n scope.services = [github]\n scope.key = 'github'\n\n ctrl()\n expect(scope.service).toBeDefine",
"end": 1008,
"score": 0.9856590628623962,
"start": 1002,
"tag": "KEY",
"value": "github"
}
] | test/unit/controllers/home_controller.coffee | rrampage/monitor | 114 | describe 'HomeCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
ctrl = $controller 'HomeCtrl', $scope: scope, services: []
it 'assigns demo apis', inject () ->
expect(scope.demos).toBeDefined()
expect(scope.demos.github).toBeDefined()
describe 'HomeDemoCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
scope.services = []
ctrl = -> $controller 'HomeDemoCtrl', $scope: scope
it 'creates demo service', inject (DemoService) ->
ctrl()
scope.demo = 'whatever'
spyOn(DemoService, 'create')
scope.createDemo()
expect(DemoService.create).toHaveBeenCalledWith('whatever', jasmine.any(Function))
it 'finds service for the demo', ->
ctrl()
expect(scope.service).not.toBeDefined()
github = {demo: 'github'}
scope.services = [github]
scope.key = 'github'
ctrl()
expect(scope.service).toBeDefined()
expect(scope.service).toBe(github)
| 203121 | describe 'HomeCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
ctrl = $controller 'HomeCtrl', $scope: scope, services: []
it 'assigns demo apis', inject () ->
expect(scope.demos).toBeDefined()
expect(scope.demos.github).toBeDefined()
describe 'HomeDemoCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
scope.services = []
ctrl = -> $controller 'HomeDemoCtrl', $scope: scope
it 'creates demo service', inject (DemoService) ->
ctrl()
scope.demo = 'whatever'
spyOn(DemoService, 'create')
scope.createDemo()
expect(DemoService.create).toHaveBeenCalledWith('whatever', jasmine.any(Function))
it 'finds service for the demo', ->
ctrl()
expect(scope.service).not.toBeDefined()
github = {demo: 'github'}
scope.services = [github]
scope.key = '<KEY>'
ctrl()
expect(scope.service).toBeDefined()
expect(scope.service).toBe(github)
| true | describe 'HomeCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
ctrl = $controller 'HomeCtrl', $scope: scope, services: []
it 'assigns demo apis', inject () ->
expect(scope.demos).toBeDefined()
expect(scope.demos.github).toBeDefined()
describe 'HomeDemoCtrl', ->
beforeEach module('slug.home')
[scope, ctrl] = []
beforeEach inject ($rootScope, $controller) ->
scope = $rootScope.$new()
scope.services = []
ctrl = -> $controller 'HomeDemoCtrl', $scope: scope
it 'creates demo service', inject (DemoService) ->
ctrl()
scope.demo = 'whatever'
spyOn(DemoService, 'create')
scope.createDemo()
expect(DemoService.create).toHaveBeenCalledWith('whatever', jasmine.any(Function))
it 'finds service for the demo', ->
ctrl()
expect(scope.service).not.toBeDefined()
github = {demo: 'github'}
scope.services = [github]
scope.key = 'PI:KEY:<KEY>END_PI'
ctrl()
expect(scope.service).toBeDefined()
expect(scope.service).toBe(github)
|
[
{
"context": "erms of the MIT license.\nCopyright 2012 - 2016 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nJID = require(\"nod",
"end": 109,
"score": 0.9998982548713684,
"start": 94,
"tag": "NAME",
"value": "Markus Kohlhase"
},
{
"context": "cense.\nCopyright 2012 - 2016 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nJID = require(\"node-xmpp-core\").JID\n\ngetDef",
"end": 134,
"score": 0.9999304413795471,
"start": 111,
"tag": "EMAIL",
"value": "mail@markus-kohlhase.de"
}
] | src/JOAPObjects.coffee | flosse/node-xmpp-joap | 0 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) Markus Kohlhase <mail@markus-kohlhase.de>
###
JID = require("node-xmpp-core").JID
getDefaultOpts = ->
attributes: {}
methods: {}
required: []
protected: []
creator: ->
timestamp: new Date()
description: new Description
definitions:
attributes: {}
methods: {}
class Class
constructor: (jid, opts={}) ->
@jid = new JID jid
{ @attributes, @methods, @timestamp, @description,
@definitions, @superclass, @creator, @required, @protected } = opts
@[k] ?= v for k,v of getDefaultOpts()
if not @creator?
@creator = ->
else if typeof(@creator) is "function"
#TODO: specify types
for c in [@creator, @creator.prototype]
for k,v of c
if typeof(v) isnt "function"
@attributes[k] ?= v
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: (c is @creator)
required: (k in @required)
writable: not (k in @protected)
else
@methods[k] ?= v
@definitions.methods[k] ?= new MethodDefinition
classMethod: (c is @creator)
for a in [@protected, @required]
for k in a
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: false
required: (k in @required)
writable: not (k in @protected)
if typeof(@superclass) is "string"
@superclass = new JID @superclass
class Description
constructor: (desc={}) ->
@[k]=v for k,v of desc when typeof(v) is "string"
class Definition
constructor: (opts={}) ->
{ @type, @description } = opts
@type ?= ""
@description ?= new Description
class AttributeDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @writable, @required, @classAttribute } = opts
@writable ?= true
@required ?= false
@classAttribute ?= false
class MethodDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @classMethod, @parameters } = opts
@classMethod ?= false
@parameters ?= {}
exports.Class = Class
exports.Description = Description
exports.AttributeDefinition = AttributeDefinition
exports.MethodDefinition = MethodDefinition
exports.ParameterDefinition = Definition
| 106071 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) <NAME> <<EMAIL>>
###
JID = require("node-xmpp-core").JID
getDefaultOpts = ->
attributes: {}
methods: {}
required: []
protected: []
creator: ->
timestamp: new Date()
description: new Description
definitions:
attributes: {}
methods: {}
class Class
constructor: (jid, opts={}) ->
@jid = new JID jid
{ @attributes, @methods, @timestamp, @description,
@definitions, @superclass, @creator, @required, @protected } = opts
@[k] ?= v for k,v of getDefaultOpts()
if not @creator?
@creator = ->
else if typeof(@creator) is "function"
#TODO: specify types
for c in [@creator, @creator.prototype]
for k,v of c
if typeof(v) isnt "function"
@attributes[k] ?= v
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: (c is @creator)
required: (k in @required)
writable: not (k in @protected)
else
@methods[k] ?= v
@definitions.methods[k] ?= new MethodDefinition
classMethod: (c is @creator)
for a in [@protected, @required]
for k in a
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: false
required: (k in @required)
writable: not (k in @protected)
if typeof(@superclass) is "string"
@superclass = new JID @superclass
class Description
constructor: (desc={}) ->
@[k]=v for k,v of desc when typeof(v) is "string"
class Definition
constructor: (opts={}) ->
{ @type, @description } = opts
@type ?= ""
@description ?= new Description
class AttributeDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @writable, @required, @classAttribute } = opts
@writable ?= true
@required ?= false
@classAttribute ?= false
class MethodDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @classMethod, @parameters } = opts
@classMethod ?= false
@parameters ?= {}
exports.Class = Class
exports.Description = Description
exports.AttributeDefinition = AttributeDefinition
exports.MethodDefinition = MethodDefinition
exports.ParameterDefinition = Definition
| true | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
JID = require("node-xmpp-core").JID
getDefaultOpts = ->
attributes: {}
methods: {}
required: []
protected: []
creator: ->
timestamp: new Date()
description: new Description
definitions:
attributes: {}
methods: {}
class Class
constructor: (jid, opts={}) ->
@jid = new JID jid
{ @attributes, @methods, @timestamp, @description,
@definitions, @superclass, @creator, @required, @protected } = opts
@[k] ?= v for k,v of getDefaultOpts()
if not @creator?
@creator = ->
else if typeof(@creator) is "function"
#TODO: specify types
for c in [@creator, @creator.prototype]
for k,v of c
if typeof(v) isnt "function"
@attributes[k] ?= v
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: (c is @creator)
required: (k in @required)
writable: not (k in @protected)
else
@methods[k] ?= v
@definitions.methods[k] ?= new MethodDefinition
classMethod: (c is @creator)
for a in [@protected, @required]
for k in a
@definitions.attributes[k] ?= new AttributeDefinition
classAttribute: false
required: (k in @required)
writable: not (k in @protected)
if typeof(@superclass) is "string"
@superclass = new JID @superclass
class Description
constructor: (desc={}) ->
@[k]=v for k,v of desc when typeof(v) is "string"
class Definition
constructor: (opts={}) ->
{ @type, @description } = opts
@type ?= ""
@description ?= new Description
class AttributeDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @writable, @required, @classAttribute } = opts
@writable ?= true
@required ?= false
@classAttribute ?= false
class MethodDefinition extends Definition
constructor: (opts={}) ->
super opts
{ @classMethod, @parameters } = opts
@classMethod ?= false
@parameters ?= {}
exports.Class = Class
exports.Description = Description
exports.AttributeDefinition = AttributeDefinition
exports.MethodDefinition = MethodDefinition
exports.ParameterDefinition = Definition
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n * For the full copyrig",
"end": 75,
"score": 0.9998899698257446,
"start": 61,
"tag": "NAME",
"value": "Marvin Frachet"
},
{
"context": " the Konsserto package.\n *\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 97,
"score": 0.9999351501464844,
"start": 77,
"tag": "EMAIL",
"value": "marvin@konsserto.com"
},
{
"context": "/Component/Stopwatch/Period')\n\n# Event\n#\n# @author Marvin Frachet <marvin@konsserto.com>\nclass Event\n\n\n # Class co",
"end": 438,
"score": 0.9998955726623535,
"start": 424,
"tag": "NAME",
"value": "Marvin Frachet"
},
{
"context": "tch/Period')\n\n# Event\n#\n# @author Marvin Frachet <marvin@konsserto.com>\nclass Event\n\n\n # Class constructor\n # @param {",
"end": 460,
"score": 0.9999358057975769,
"start": 440,
"tag": "EMAIL",
"value": "marvin@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Stopwatch/Event.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Marvin Frachet <marvin@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
###
# Event class in Stopwatch service #
This is the Event class documentation linked to the Stopwatch service
###
Period = use('@Konsserto/Component/Stopwatch/Period')
# Event
#
# @author Marvin Frachet <marvin@konsserto.com>
class Event
# Class constructor
# @param {String} name Name of the event
# @param {String category (optional) of the event
constructor: (@name, @category)->
@periods = []
@origin = new Date().getTime()
# Stop the event time setting the stop variable
stopEvent: ()->
@stop = new Date().getTime()
# Get the stop time of the current Event
# @return {Number} The stop variable (end of the event)
getStopTime: ()->
return @stop
# Get the name of the current Event
# @return {String} The event name
getName: ()->
return @name
# Get the origin time of the current Event
# @return {Number} The origin of the event (the starting time of the event)
getOrigin: ()->
return @origin
# Get the last time of the last period of the event
# @return {Number} The end time of the event
getEndTime: ()->
if @periods.length > 0
return @periods[@periods.length - 1].getEndTime()
return null
# Get the periods duration
# @return {Number} The duration of every periods of the event
getDurationPeriods: ()->
duration = 0
for p in @periods
duration += p.getDuration()
return duration / 1000
# Get the event duration
# @return {Number} The global duration from start to stop
getDuration: ()->
return (@stop - @origin) / 1000
# Get the category
# @return {String} The category of the event
getCategory: ()->
return @category
# Get the {Period} list of the event
# @return [Period] The periods of the event
getPeriods: ()->
return @periods
# Create a new period from the previous period end time (origin if no periods before
setPeriod: ()->
if @periods.length == 0
@periods.push(new Period(@origin))
else
@periods.push(new Period(@periods[@periods.length - 1].getEndTime()))
module.exports = Event | 184125 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
###
# Event class in Stopwatch service #
This is the Event class documentation linked to the Stopwatch service
###
Period = use('@Konsserto/Component/Stopwatch/Period')
# Event
#
# @author <NAME> <<EMAIL>>
class Event
# Class constructor
# @param {String} name Name of the event
# @param {String category (optional) of the event
constructor: (@name, @category)->
@periods = []
@origin = new Date().getTime()
# Stop the event time setting the stop variable
stopEvent: ()->
@stop = new Date().getTime()
# Get the stop time of the current Event
# @return {Number} The stop variable (end of the event)
getStopTime: ()->
return @stop
# Get the name of the current Event
# @return {String} The event name
getName: ()->
return @name
# Get the origin time of the current Event
# @return {Number} The origin of the event (the starting time of the event)
getOrigin: ()->
return @origin
# Get the last time of the last period of the event
# @return {Number} The end time of the event
getEndTime: ()->
if @periods.length > 0
return @periods[@periods.length - 1].getEndTime()
return null
# Get the periods duration
# @return {Number} The duration of every periods of the event
getDurationPeriods: ()->
duration = 0
for p in @periods
duration += p.getDuration()
return duration / 1000
# Get the event duration
# @return {Number} The global duration from start to stop
getDuration: ()->
return (@stop - @origin) / 1000
# Get the category
# @return {String} The category of the event
getCategory: ()->
return @category
# Get the {Period} list of the event
# @return [Period] The periods of the event
getPeriods: ()->
return @periods
# Create a new period from the previous period end time (origin if no periods before
setPeriod: ()->
if @periods.length == 0
@periods.push(new Period(@origin))
else
@periods.push(new Period(@periods[@periods.length - 1].getEndTime()))
module.exports = Event | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
###
# Event class in Stopwatch service #
This is the Event class documentation linked to the Stopwatch service
###
Period = use('@Konsserto/Component/Stopwatch/Period')
# Event
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
class Event
# Class constructor
# @param {String} name Name of the event
# @param {String category (optional) of the event
constructor: (@name, @category)->
@periods = []
@origin = new Date().getTime()
# Stop the event time setting the stop variable
stopEvent: ()->
@stop = new Date().getTime()
# Get the stop time of the current Event
# @return {Number} The stop variable (end of the event)
getStopTime: ()->
return @stop
# Get the name of the current Event
# @return {String} The event name
getName: ()->
return @name
# Get the origin time of the current Event
# @return {Number} The origin of the event (the starting time of the event)
getOrigin: ()->
return @origin
# Get the last time of the last period of the event
# @return {Number} The end time of the event
getEndTime: ()->
if @periods.length > 0
return @periods[@periods.length - 1].getEndTime()
return null
# Get the periods duration
# @return {Number} The duration of every periods of the event
getDurationPeriods: ()->
duration = 0
for p in @periods
duration += p.getDuration()
return duration / 1000
# Get the event duration
# @return {Number} The global duration from start to stop
getDuration: ()->
return (@stop - @origin) / 1000
# Get the category
# @return {String} The category of the event
getCategory: ()->
return @category
# Get the {Period} list of the event
# @return [Period] The periods of the event
getPeriods: ()->
return @periods
# Create a new period from the previous period end time (origin if no periods before
setPeriod: ()->
if @periods.length == 0
@periods.push(new Period(@origin))
else
@periods.push(new Period(@periods[@periods.length - 1].getEndTime()))
module.exports = Event |
[
{
"context": "lassniki:\n\t\tclientID: 1101943552\n\t\tclientPublic: 'CBAEFPKCEBABABABA'\n\t\tclientSecret: '55C1FD7EA97F4FBDB571E7A8'\n\t\tcal",
"end": 190,
"score": 0.9127596616744995,
"start": 173,
"tag": "KEY",
"value": "CBAEFPKCEBABABABA"
},
{
"context": "lientPublic: 'CBAEFPKCEBABABABA'\n\t\tclientSecret: '55C1FD7EA97F4FBDB571E7A8'\n\t\tcallbackURL: '/logged/ok'\n\n\tbaseUrl: 'http://p",
"end": 233,
"score": 0.9994651675224304,
"start": 209,
"tag": "KEY",
"value": "55C1FD7EA97F4FBDB571E7A8"
}
] | meta/socialConfig.coffee | winnlab/Optimeal | 0 | module.exports =
facebook:
clientID: 512705898864753
clientSecret: ''
callbackURL: ''
vk:
apiId: 4547249
odnoklassniki:
clientID: 1101943552
clientPublic: 'CBAEFPKCEBABABABA'
clientSecret: '55C1FD7EA97F4FBDB571E7A8'
callbackURL: '/logged/ok'
baseUrl: 'http://promo.365rozvag.com.ua/'
| 165578 | module.exports =
facebook:
clientID: 512705898864753
clientSecret: ''
callbackURL: ''
vk:
apiId: 4547249
odnoklassniki:
clientID: 1101943552
clientPublic: '<KEY>'
clientSecret: '<KEY>'
callbackURL: '/logged/ok'
baseUrl: 'http://promo.365rozvag.com.ua/'
| true | module.exports =
facebook:
clientID: 512705898864753
clientSecret: ''
callbackURL: ''
vk:
apiId: 4547249
odnoklassniki:
clientID: 1101943552
clientPublic: 'PI:KEY:<KEY>END_PI'
clientSecret: 'PI:KEY:<KEY>END_PI'
callbackURL: '/logged/ok'
baseUrl: 'http://promo.365rozvag.com.ua/'
|
[
{
"context": "on 1.0\n\npan events for Touchy.\n\n(c) 2015 Copyright Stardotstar.\nproject located at https://github.com/stardotsta",
"end": 89,
"score": 0.9198061227798462,
"start": 78,
"tag": "NAME",
"value": "Stardotstar"
},
{
"context": "tardotstar.\nproject located at https://github.com/stardotstar/Touchy.js.\nLicenced under the Apache license (see",
"end": 140,
"score": 0.9995042681694031,
"start": 129,
"tag": "USERNAME",
"value": "stardotstar"
}
] | touchy_panner.coffee | stardotstar/Touchy | 0 | ###
touchy_panner.js, version 1.0
pan events for Touchy.
(c) 2015 Copyright Stardotstar.
project located at https://github.com/stardotstar/Touchy.js.
Licenced under the Apache license (see LICENSE file)
###
((window) ->
# helper methods
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
noop = ->
TouchyPannerDefinition = (Touchy,$,EventEmitter,TweenMax) ->
class TouchyPanner
constructor: (elm,options) ->
@elm = $(elm).first()
@options = $.extend {}, _default_options, options
# console.log('Initialized TouchyPanner on', @elm ,@options)
@_configurePanner()
@_setupTouchyInstance()
@_configureOptions()
@_configureNav()
@_configureIndicator()
@value(@options.initial_index)
@_setupResize()
@emitEvent('init', [ @ ] )
@elm.css('opacity',1)
_default_options =
vertical: false
initial_index: 0
container_elm: '.options'
option_elm: '.option'
nav_elm: '.nav'
indicator: false
indicator_elm: '.indicator'
threshold: 20
velocityXThreshold: 1
deltaXThresholdPercent: .3
refreshOptions: ->
@_tl?.kill()
@_configureOptions()
@value(@options.initial_index)
_setupTouchyInstance: ->
@_touchy = new Touchy @elm
# cancel_on_scroll: false
@_touchy.on 'start', (event,t,pointer) =>
@_onStart(event,pointer)
# @emitEvent('panstart', [ event, @, @_value ] )
@_touchy.on 'move', (event,t,pointer) =>
@_onMove(event,pointer)
# @emitEvent('panmove', [ event, @, @_value ] )
@_touchy.on 'end', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
@_touchy.on 'cancel', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
_configurePanner: ->
@elm.addClass('panner')
@elm.addClass(if @options.vertical then 'panner_v' else 'panner_h')
@_options_elm = @elm.find(@options.container_elm)
@_options_elm.css
position: 'relative'
_configureOptions: ->
@_tl = new TimelineMax
paused: true
@_options = @_options_elm.find('.option')
@_options.css
position: 'absolute'
@_option_count = @_options.length
@_option_w = @_options_elm.width()
for option in @_options
@_addOptionPage(option)
true
_addOptionPage: (option) ->
id = $(option).data('id')
# offset = if @args.offset_class then $(option).find(@args.offset_class).position() else 0
offset = {
left: 0
}
# console.log('offset',id,offset)
@_tl.from option, .4,
x: @_option_w - offset.left
ease: Linear.easeNone
@_tl.fromTo option, .1,
{
opacity: 0
}
{
opacity: 1
ease: Power1.easeInOut
}
,"-=.25"
@_tl.add "option-#{id}"
@_tl.to option, .4,
x: -(@_option_w - offset.left)
ease: Linear.easeNone
@_tl.to option, .1,
opacity: 0
ease: Power1.easeInOut
,"-=.25"
_configureNav: ->
@_nav_elm = @elm.find(@options.nav_elm)
true
_configureIndicator: ->
return unless @options.indicator
@_indicator_elm = @elm.find(@options.indicator_elm)
@_indicator_elm.append("<span class='icon'>") for i in [1..@_option_count]
true
value: (val) ->
if val?
# console.log('setting,',val)
@_pageTo(val)
else
@_current_option
_pageTo: (id,instant) ->
@_current_option = id
data_id = @_options.eq(@_current_option).data('id')
# console.log('paging to',id)
if instant
@_tl.seek("option-#{data_id}")
else
@_tl.seek("option-#{data_id}")
@_updateNavState()
@_updateIndicatorState()
_onStart: (e, pointer) ->
# console.log('Touch started')
_onMove: (e, pointer) ->
direction = @_direction()
distance = @_distance()
return true if direction and not direction.match /^(left|right)$/
# console.log(distance)
if distance >= @options.threshold and not @_started
# console.log('Pan Started')
@_started = true
@emitEvent('panstart', [ @ ] )
else if @_started
duration = @_tl.totalDuration()
duration_ms = duration * 1000
duration_per_option = duration_ms / @_option_count
duration_per_pixel = duration_ms / (@_option_w * @_option_count)
# console.log(duration_ms,@_option_w,@_option_count)
data_id = @_options.eq(@_current_option).data('id')
current_time = @_tl.getLabelTime("option-#{data_id}")
time_change = Math.abs(distance * (duration_per_pixel / 2)) / 1000
# console.log(time_change)
if direction == "right"
time_change = current_time if current_time - time_change < 0
time = "option-#{data_id}-=#{time_change}"
else if direction == "left"
time_change = current_time if current_time + time_change > duration
time = "option-#{data_id}+=#{time_change}"
# console.log('seeking to',time)
@_tl.seek(time)
@emitEvent('panmove', [ e, @ ] )
_onEnd: (e,pointer) ->
if $(e.target).parent().is(@_nav_elm)
@_onNavEnd(e,pointer)
return
return unless @_started
direction = @_direction()
distance = @_distance()
current_elm = @_options.eq(@_current_option)
current_elm.removeClass('current')
if direction == "left"
next_ind = @_current_option + 1
else if direction == "right"
next_ind = @_current_option - 1
@_panTo(next_ind)
@_started = false
@emitEvent('panend', [ e, @ ] )
_onNavEnd: (e,pointer) ->
e.preventDefault()
elm = $(e.target)
if elm.hasClass('prev')
# console.log('go prev')
@_panTo @_current_option - 1
else if elm.hasClass('next')
# console.log('go next')
@_panTo @_current_option + 1
_direction: ->
if @_touchy.distance.x > 0
'right'
else if @_touchy.distance.x < 0
'left'
else
''
_distance: ->
Math.abs(@_touchy.distance.x)
_panTo: (id) ->
# dont allow paging past min and max
if not (id > -1 and id < @_option_count)
id = @_current_option
elm = @_options.eq(id)
elm.addClass('current')
data_id = elm.data('id')
# console.log('panning to',data_id)
@_tl.tweenTo "option-#{data_id}",
ease: Strong.easeOut,
onComplete: =>
# console.log('panchanged')
@emitEvent('panchanged', [ @ ] )
@_current_option = id
@_updateNavState()
@_updateIndicatorState()
_updateNavState: ->
if @_current_option == 0
@elm.addClass('first')
@elm.removeClass('last')
else if @_current_option == @_option_count - 1
@elm.addClass('last')
@elm.removeClass('first')
else
@elm.removeClass('first last')
_updateIndicatorState: ->
if @_indicator_elm and @_indicator_elm.length
@_indicator_elm.find('.icon')
.removeClass('active')
.eq(@_current_option)
.addClass('active')
_valueToPercent: (val) ->
((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100
_percentToValue: (pct) ->
((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value
_trimAlignValue: (val) ->
if val <= @options.min_value
return @options.min_value
if val >= @options.max_value
return @options.max_value
step = if @options.step > 0 then @options.step else 1
valModStep = (val - @options.min_value) % step
alignValue = val - valModStep
if Math.abs(valModStep) * 2 >= step
alignValue += if valModStep > 0 then step else -step
# Since JavaScript has problems with large floats, round
# the final value to 5 digits after the decimal point
return parseFloat(alignValue.toFixed(5))
_setupResize: ->
$(window).on 'resize', =>
@_resize()
@_resize()
_resize: ->
if @options.vertical
@_length = @elm.height()
@_offset = @elm.offset().top
else
@_length = @elm.width()
@_offset = @elm.offset().left
@_setOptionHeight()
_setOptionHeight: ->
if @elm.is(':visible')
@_option_h = 0
for option in @_options
oh = $(option).outerHeight()
if oh > @_option_h
@_option_h = oh
@_options_elm.css
minHeight: @_option_h
extend TouchyPanner.prototype, EventEmitter.prototype
return TouchyPanner
if typeof define == 'function' and define.amd
# amd
define([
'touchy',
'jquery',
'eventEmitter',
'gsap',
'jquery-transform'
], TouchyPannerDefinition)
else if typeof exports == 'object'
# commonjs
module.exports = TouchyPannerDefinition(
require('touchy'),
require('jquery'),
require('wolfy87-eventemitter'),
require('gsap'),
require('jquery-transform')
)
else
# global
window.TouchyPanner = TouchyPannerDefinition(
window.Touchy,
window.jQuery,
window.EventEmitter,
window.TweenMax
)
)(window) | 114079 | ###
touchy_panner.js, version 1.0
pan events for Touchy.
(c) 2015 Copyright <NAME>.
project located at https://github.com/stardotstar/Touchy.js.
Licenced under the Apache license (see LICENSE file)
###
((window) ->
# helper methods
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
noop = ->
TouchyPannerDefinition = (Touchy,$,EventEmitter,TweenMax) ->
class TouchyPanner
constructor: (elm,options) ->
@elm = $(elm).first()
@options = $.extend {}, _default_options, options
# console.log('Initialized TouchyPanner on', @elm ,@options)
@_configurePanner()
@_setupTouchyInstance()
@_configureOptions()
@_configureNav()
@_configureIndicator()
@value(@options.initial_index)
@_setupResize()
@emitEvent('init', [ @ ] )
@elm.css('opacity',1)
_default_options =
vertical: false
initial_index: 0
container_elm: '.options'
option_elm: '.option'
nav_elm: '.nav'
indicator: false
indicator_elm: '.indicator'
threshold: 20
velocityXThreshold: 1
deltaXThresholdPercent: .3
refreshOptions: ->
@_tl?.kill()
@_configureOptions()
@value(@options.initial_index)
_setupTouchyInstance: ->
@_touchy = new Touchy @elm
# cancel_on_scroll: false
@_touchy.on 'start', (event,t,pointer) =>
@_onStart(event,pointer)
# @emitEvent('panstart', [ event, @, @_value ] )
@_touchy.on 'move', (event,t,pointer) =>
@_onMove(event,pointer)
# @emitEvent('panmove', [ event, @, @_value ] )
@_touchy.on 'end', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
@_touchy.on 'cancel', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
_configurePanner: ->
@elm.addClass('panner')
@elm.addClass(if @options.vertical then 'panner_v' else 'panner_h')
@_options_elm = @elm.find(@options.container_elm)
@_options_elm.css
position: 'relative'
_configureOptions: ->
@_tl = new TimelineMax
paused: true
@_options = @_options_elm.find('.option')
@_options.css
position: 'absolute'
@_option_count = @_options.length
@_option_w = @_options_elm.width()
for option in @_options
@_addOptionPage(option)
true
_addOptionPage: (option) ->
id = $(option).data('id')
# offset = if @args.offset_class then $(option).find(@args.offset_class).position() else 0
offset = {
left: 0
}
# console.log('offset',id,offset)
@_tl.from option, .4,
x: @_option_w - offset.left
ease: Linear.easeNone
@_tl.fromTo option, .1,
{
opacity: 0
}
{
opacity: 1
ease: Power1.easeInOut
}
,"-=.25"
@_tl.add "option-#{id}"
@_tl.to option, .4,
x: -(@_option_w - offset.left)
ease: Linear.easeNone
@_tl.to option, .1,
opacity: 0
ease: Power1.easeInOut
,"-=.25"
_configureNav: ->
@_nav_elm = @elm.find(@options.nav_elm)
true
_configureIndicator: ->
return unless @options.indicator
@_indicator_elm = @elm.find(@options.indicator_elm)
@_indicator_elm.append("<span class='icon'>") for i in [1..@_option_count]
true
value: (val) ->
if val?
# console.log('setting,',val)
@_pageTo(val)
else
@_current_option
_pageTo: (id,instant) ->
@_current_option = id
data_id = @_options.eq(@_current_option).data('id')
# console.log('paging to',id)
if instant
@_tl.seek("option-#{data_id}")
else
@_tl.seek("option-#{data_id}")
@_updateNavState()
@_updateIndicatorState()
_onStart: (e, pointer) ->
# console.log('Touch started')
_onMove: (e, pointer) ->
direction = @_direction()
distance = @_distance()
return true if direction and not direction.match /^(left|right)$/
# console.log(distance)
if distance >= @options.threshold and not @_started
# console.log('Pan Started')
@_started = true
@emitEvent('panstart', [ @ ] )
else if @_started
duration = @_tl.totalDuration()
duration_ms = duration * 1000
duration_per_option = duration_ms / @_option_count
duration_per_pixel = duration_ms / (@_option_w * @_option_count)
# console.log(duration_ms,@_option_w,@_option_count)
data_id = @_options.eq(@_current_option).data('id')
current_time = @_tl.getLabelTime("option-#{data_id}")
time_change = Math.abs(distance * (duration_per_pixel / 2)) / 1000
# console.log(time_change)
if direction == "right"
time_change = current_time if current_time - time_change < 0
time = "option-#{data_id}-=#{time_change}"
else if direction == "left"
time_change = current_time if current_time + time_change > duration
time = "option-#{data_id}+=#{time_change}"
# console.log('seeking to',time)
@_tl.seek(time)
@emitEvent('panmove', [ e, @ ] )
_onEnd: (e,pointer) ->
if $(e.target).parent().is(@_nav_elm)
@_onNavEnd(e,pointer)
return
return unless @_started
direction = @_direction()
distance = @_distance()
current_elm = @_options.eq(@_current_option)
current_elm.removeClass('current')
if direction == "left"
next_ind = @_current_option + 1
else if direction == "right"
next_ind = @_current_option - 1
@_panTo(next_ind)
@_started = false
@emitEvent('panend', [ e, @ ] )
_onNavEnd: (e,pointer) ->
e.preventDefault()
elm = $(e.target)
if elm.hasClass('prev')
# console.log('go prev')
@_panTo @_current_option - 1
else if elm.hasClass('next')
# console.log('go next')
@_panTo @_current_option + 1
_direction: ->
if @_touchy.distance.x > 0
'right'
else if @_touchy.distance.x < 0
'left'
else
''
_distance: ->
Math.abs(@_touchy.distance.x)
_panTo: (id) ->
# dont allow paging past min and max
if not (id > -1 and id < @_option_count)
id = @_current_option
elm = @_options.eq(id)
elm.addClass('current')
data_id = elm.data('id')
# console.log('panning to',data_id)
@_tl.tweenTo "option-#{data_id}",
ease: Strong.easeOut,
onComplete: =>
# console.log('panchanged')
@emitEvent('panchanged', [ @ ] )
@_current_option = id
@_updateNavState()
@_updateIndicatorState()
_updateNavState: ->
if @_current_option == 0
@elm.addClass('first')
@elm.removeClass('last')
else if @_current_option == @_option_count - 1
@elm.addClass('last')
@elm.removeClass('first')
else
@elm.removeClass('first last')
_updateIndicatorState: ->
if @_indicator_elm and @_indicator_elm.length
@_indicator_elm.find('.icon')
.removeClass('active')
.eq(@_current_option)
.addClass('active')
_valueToPercent: (val) ->
((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100
_percentToValue: (pct) ->
((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value
_trimAlignValue: (val) ->
if val <= @options.min_value
return @options.min_value
if val >= @options.max_value
return @options.max_value
step = if @options.step > 0 then @options.step else 1
valModStep = (val - @options.min_value) % step
alignValue = val - valModStep
if Math.abs(valModStep) * 2 >= step
alignValue += if valModStep > 0 then step else -step
# Since JavaScript has problems with large floats, round
# the final value to 5 digits after the decimal point
return parseFloat(alignValue.toFixed(5))
_setupResize: ->
$(window).on 'resize', =>
@_resize()
@_resize()
_resize: ->
if @options.vertical
@_length = @elm.height()
@_offset = @elm.offset().top
else
@_length = @elm.width()
@_offset = @elm.offset().left
@_setOptionHeight()
_setOptionHeight: ->
if @elm.is(':visible')
@_option_h = 0
for option in @_options
oh = $(option).outerHeight()
if oh > @_option_h
@_option_h = oh
@_options_elm.css
minHeight: @_option_h
extend TouchyPanner.prototype, EventEmitter.prototype
return TouchyPanner
if typeof define == 'function' and define.amd
# amd
define([
'touchy',
'jquery',
'eventEmitter',
'gsap',
'jquery-transform'
], TouchyPannerDefinition)
else if typeof exports == 'object'
# commonjs
module.exports = TouchyPannerDefinition(
require('touchy'),
require('jquery'),
require('wolfy87-eventemitter'),
require('gsap'),
require('jquery-transform')
)
else
# global
window.TouchyPanner = TouchyPannerDefinition(
window.Touchy,
window.jQuery,
window.EventEmitter,
window.TweenMax
)
)(window) | true | ###
touchy_panner.js, version 1.0
pan events for Touchy.
(c) 2015 Copyright PI:NAME:<NAME>END_PI.
project located at https://github.com/stardotstar/Touchy.js.
Licenced under the Apache license (see LICENSE file)
###
((window) ->
# helper methods
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
noop = ->
TouchyPannerDefinition = (Touchy,$,EventEmitter,TweenMax) ->
class TouchyPanner
constructor: (elm,options) ->
@elm = $(elm).first()
@options = $.extend {}, _default_options, options
# console.log('Initialized TouchyPanner on', @elm ,@options)
@_configurePanner()
@_setupTouchyInstance()
@_configureOptions()
@_configureNav()
@_configureIndicator()
@value(@options.initial_index)
@_setupResize()
@emitEvent('init', [ @ ] )
@elm.css('opacity',1)
_default_options =
vertical: false
initial_index: 0
container_elm: '.options'
option_elm: '.option'
nav_elm: '.nav'
indicator: false
indicator_elm: '.indicator'
threshold: 20
velocityXThreshold: 1
deltaXThresholdPercent: .3
refreshOptions: ->
@_tl?.kill()
@_configureOptions()
@value(@options.initial_index)
_setupTouchyInstance: ->
@_touchy = new Touchy @elm
# cancel_on_scroll: false
@_touchy.on 'start', (event,t,pointer) =>
@_onStart(event,pointer)
# @emitEvent('panstart', [ event, @, @_value ] )
@_touchy.on 'move', (event,t,pointer) =>
@_onMove(event,pointer)
# @emitEvent('panmove', [ event, @, @_value ] )
@_touchy.on 'end', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
@_touchy.on 'cancel', (event,t,pointer) =>
@_onEnd(event,pointer)
# @emitEvent('panend', [ event, @, @_value ] )
_configurePanner: ->
@elm.addClass('panner')
@elm.addClass(if @options.vertical then 'panner_v' else 'panner_h')
@_options_elm = @elm.find(@options.container_elm)
@_options_elm.css
position: 'relative'
_configureOptions: ->
@_tl = new TimelineMax
paused: true
@_options = @_options_elm.find('.option')
@_options.css
position: 'absolute'
@_option_count = @_options.length
@_option_w = @_options_elm.width()
for option in @_options
@_addOptionPage(option)
true
_addOptionPage: (option) ->
id = $(option).data('id')
# offset = if @args.offset_class then $(option).find(@args.offset_class).position() else 0
offset = {
left: 0
}
# console.log('offset',id,offset)
@_tl.from option, .4,
x: @_option_w - offset.left
ease: Linear.easeNone
@_tl.fromTo option, .1,
{
opacity: 0
}
{
opacity: 1
ease: Power1.easeInOut
}
,"-=.25"
@_tl.add "option-#{id}"
@_tl.to option, .4,
x: -(@_option_w - offset.left)
ease: Linear.easeNone
@_tl.to option, .1,
opacity: 0
ease: Power1.easeInOut
,"-=.25"
_configureNav: ->
@_nav_elm = @elm.find(@options.nav_elm)
true
_configureIndicator: ->
return unless @options.indicator
@_indicator_elm = @elm.find(@options.indicator_elm)
@_indicator_elm.append("<span class='icon'>") for i in [1..@_option_count]
true
value: (val) ->
if val?
# console.log('setting,',val)
@_pageTo(val)
else
@_current_option
_pageTo: (id,instant) ->
@_current_option = id
data_id = @_options.eq(@_current_option).data('id')
# console.log('paging to',id)
if instant
@_tl.seek("option-#{data_id}")
else
@_tl.seek("option-#{data_id}")
@_updateNavState()
@_updateIndicatorState()
_onStart: (e, pointer) ->
# console.log('Touch started')
_onMove: (e, pointer) ->
direction = @_direction()
distance = @_distance()
return true if direction and not direction.match /^(left|right)$/
# console.log(distance)
if distance >= @options.threshold and not @_started
# console.log('Pan Started')
@_started = true
@emitEvent('panstart', [ @ ] )
else if @_started
duration = @_tl.totalDuration()
duration_ms = duration * 1000
duration_per_option = duration_ms / @_option_count
duration_per_pixel = duration_ms / (@_option_w * @_option_count)
# console.log(duration_ms,@_option_w,@_option_count)
data_id = @_options.eq(@_current_option).data('id')
current_time = @_tl.getLabelTime("option-#{data_id}")
time_change = Math.abs(distance * (duration_per_pixel / 2)) / 1000
# console.log(time_change)
if direction == "right"
time_change = current_time if current_time - time_change < 0
time = "option-#{data_id}-=#{time_change}"
else if direction == "left"
time_change = current_time if current_time + time_change > duration
time = "option-#{data_id}+=#{time_change}"
# console.log('seeking to',time)
@_tl.seek(time)
@emitEvent('panmove', [ e, @ ] )
_onEnd: (e,pointer) ->
if $(e.target).parent().is(@_nav_elm)
@_onNavEnd(e,pointer)
return
return unless @_started
direction = @_direction()
distance = @_distance()
current_elm = @_options.eq(@_current_option)
current_elm.removeClass('current')
if direction == "left"
next_ind = @_current_option + 1
else if direction == "right"
next_ind = @_current_option - 1
@_panTo(next_ind)
@_started = false
@emitEvent('panend', [ e, @ ] )
_onNavEnd: (e,pointer) ->
e.preventDefault()
elm = $(e.target)
if elm.hasClass('prev')
# console.log('go prev')
@_panTo @_current_option - 1
else if elm.hasClass('next')
# console.log('go next')
@_panTo @_current_option + 1
_direction: ->
if @_touchy.distance.x > 0
'right'
else if @_touchy.distance.x < 0
'left'
else
''
_distance: ->
Math.abs(@_touchy.distance.x)
_panTo: (id) ->
# dont allow paging past min and max
if not (id > -1 and id < @_option_count)
id = @_current_option
elm = @_options.eq(id)
elm.addClass('current')
data_id = elm.data('id')
# console.log('panning to',data_id)
@_tl.tweenTo "option-#{data_id}",
ease: Strong.easeOut,
onComplete: =>
# console.log('panchanged')
@emitEvent('panchanged', [ @ ] )
@_current_option = id
@_updateNavState()
@_updateIndicatorState()
_updateNavState: ->
if @_current_option == 0
@elm.addClass('first')
@elm.removeClass('last')
else if @_current_option == @_option_count - 1
@elm.addClass('last')
@elm.removeClass('first')
else
@elm.removeClass('first last')
_updateIndicatorState: ->
if @_indicator_elm and @_indicator_elm.length
@_indicator_elm.find('.icon')
.removeClass('active')
.eq(@_current_option)
.addClass('active')
_valueToPercent: (val) ->
((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100
_percentToValue: (pct) ->
((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value
_trimAlignValue: (val) ->
if val <= @options.min_value
return @options.min_value
if val >= @options.max_value
return @options.max_value
step = if @options.step > 0 then @options.step else 1
valModStep = (val - @options.min_value) % step
alignValue = val - valModStep
if Math.abs(valModStep) * 2 >= step
alignValue += if valModStep > 0 then step else -step
# Since JavaScript has problems with large floats, round
# the final value to 5 digits after the decimal point
return parseFloat(alignValue.toFixed(5))
_setupResize: ->
$(window).on 'resize', =>
@_resize()
@_resize()
_resize: ->
if @options.vertical
@_length = @elm.height()
@_offset = @elm.offset().top
else
@_length = @elm.width()
@_offset = @elm.offset().left
@_setOptionHeight()
_setOptionHeight: ->
if @elm.is(':visible')
@_option_h = 0
for option in @_options
oh = $(option).outerHeight()
if oh > @_option_h
@_option_h = oh
@_options_elm.css
minHeight: @_option_h
extend TouchyPanner.prototype, EventEmitter.prototype
return TouchyPanner
if typeof define == 'function' and define.amd
# amd
define([
'touchy',
'jquery',
'eventEmitter',
'gsap',
'jquery-transform'
], TouchyPannerDefinition)
else if typeof exports == 'object'
# commonjs
module.exports = TouchyPannerDefinition(
require('touchy'),
require('jquery'),
require('wolfy87-eventemitter'),
require('gsap'),
require('jquery-transform')
)
else
# global
window.TouchyPanner = TouchyPannerDefinition(
window.Touchy,
window.jQuery,
window.EventEmitter,
window.TweenMax
)
)(window) |
[
{
"context": "vice.whereOperator('or')\n # .where('name(en = \"Red\")')\n # .where('name(de = \"Rot\")')\n # .fetch",
"end": 4005,
"score": 0.8113642930984497,
"start": 4002,
"tag": "NAME",
"value": "Red"
},
{
"context": "here('name(en = \"Red\")')\n # .where('name(de = \"Rot\")')\n # .fetch()\n whereOperator: (operator = '",
"end": 4038,
"score": 0.5761952996253967,
"start": 4035,
"tag": "NAME",
"value": "Rot"
}
] | src/coffee/services/base.coffee | commercetools/sphere-node-sdk | 13 | debug = require('debug')('sphere-client')
_ = require 'underscore'
_.mixin require('underscore-mixins')
Promise = require 'bluebird'
Utils = require '../utils'
{HttpError, GraphQLError, SphereHttpError} = require '../errors'
# Private: RegExp to parse time period for last function.
REGEX_LAST = /^(\d+)([s|m|h|d|w])$/
# Abstract: Define a `BaseService` to provide basic methods to interact with the HTTP API.
#
# This class should **not be exposed** and **must be extended** when defining a new `*Service`.
#
# Examples
#
# class FooService extends BaseService
# @baseResourceEndpoint: '/foo'
class BaseService
# Internal: Base path for a API resource endpoint (to be overriden by specific service) ({String})
# constant
@baseResourceEndpoint: ''
# Internal: Indicates whether the current service supports keys or not
# constant
@supportsByKey: false
# Public: Construct a `*Service` object.
#
# options - An {Object} to configure the service
# :_rest - a {Rest} instance
# :_task - a {TaskQueue} instance
# :_stats - an {Object} to configure statistics
constructor: (options = {}) ->
{@_rest, @_task, @_stats} = options
@_setDefaults()
# Private: Reset default _currentEndpoint and _params used to build request endpoints
_setDefaults: ->
# Private: Current path for a API resource endpoint which can be modified by appending ids, queries, etc
@_currentEndpoint = @constructor.baseResourceEndpoint
# Private: Container that holds request parameters such `id`, `query`, etc
@_params =
encoded: ['where', 'expand', 'sort']
plain: ['perPage', 'page']
query:
where: []
operator: 'and'
sort: []
expand: []
@_fetchAll = false
# Public: Build the endpoint path by appending the given id
#
# id - {String} The resource specific id
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byId('123').fetch()
byId: (id) ->
if @_params.key
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/#{id}"
@_params.id = id
debug 'setting endpoint id: %j', @_currentEndpoint
this
# Public: Build the endpoint path by appending the given key query
#
# key - {String} The resource specific key
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.productTypes
# service.byKey('key').fetch()
byKey: (key) ->
if @_params.id
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/key=#{key}"
@_params.key = key
debug 'setting endpoint key: %j', @_currentEndpoint
this
# Public: Define a URI encoded [Predicate](http://dev.sphere.io/http-api.html#predicates)
# from the given string, used for quering and filtering a resource. Can be set multiple times.
#
# predicate - {String} A [Predicate](http://dev.sphere.io/http-api.html#predicates) string for the `where` query parameter.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').fetch()
where: (predicate) ->
# TODO: use query builder (for specific service) to faciliate build queries
# e.g.: `QueryBuilder.product.name('Foo', 'en')`
return this unless predicate
encodedPredicate = encodeURIComponent(predicate)
@_params.query.where.push encodedPredicate
debug 'setting predicate: %s', predicate
this
# Public: Define the logical operator to combine multiple {::where} query parameters.
#
# operator - {String} A logical operator (default `and`)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.whereOperator('or')
# .where('name(en = "Red")')
# .where('name(de = "Rot")')
# .fetch()
whereOperator: (operator = 'and') ->
@_params.query.operator = switch operator
when 'and', 'or' then operator
else 'and'
debug 'setting where operator: %s', operator
this
# Public: This is a convenient method to query for the latest changes.
#
# Please be aware that `last` is just another `where` clause and thus
# depends on the `operator` you choose.
#
# predicate - {String} Time period of format `numberX` where `X` is one of the follwing units:
# :s - seconds
# :m - minutes
# :h - hours
# :d - days
# :w - weeks
#
# Throws an {Error} if `period` cannot be parsed
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.last('10d').fetch()
last: (period) ->
throw new Error "Cannot parse period '#{period}'" unless REGEX_LAST.test(period)
matches = REGEX_LAST.exec(period)
amount = matches[1]
if amount is '0'
return this
before = Utils.getTime amount, matches[2]
now = new Date().getTime()
dateTime = new Date(now - before).toISOString()
@where("lastModifiedAt > \"#{dateTime}\"")
# Public: Define how the query should be sorted.
# It is possible to add several sort criteria, thereby the order is relevant.
#
# path - {String} Sort path to search for
# ascending - {Boolean} Whether the direction should be ascending or not, (default `asc`)
# :true - `asc`
# :false - `desc`
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.sort('name.en', true).fetch()
sort: (path, ascending = true) ->
direction = if ascending then 'asc' else 'desc'
@_params.query.sort.push encodeURIComponent("#{path} #{direction}")
debug 'setting sort: %s %s', path, direction
this
# Public: Define the page number to be requested from the complete query result (used for pagination as `offset`)
#
# page - {Number} The page number `>= 1` (default is 1)
#
# Throws an {Error} if `page` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.page(4).fetch()
page: (page) ->
throw new Error 'Page must be a number >= 1' if _.isNumber(page) and page < 1
@_params.query.page = page
debug 'setting page: %s', page
this
# Public: Define the number of results to return from a query (used for pagination as `limit`)
#
# perPage - {Number} How many results in a page, it must be `>= 0` (default is 100)
#
# Throws an {Error} if `perPage` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.perPage(50).fetch()
perPage: (perPage) ->
throw new Error 'PerPage (limit) must be a number >= 0' if _.isNumber(perPage) and perPage < 0
@_params.query.perPage = perPage
debug 'setting perPage: %s', perPage
this
# Public: A convenient method to fetch all pages
# recursively in chunks and return them all together once completed.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.all().fetch()
all: ->
@_fetchAll = true
this
# Public: Define an [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion)
# used for expanding [Reference](http://dev.sphere.io/http-api-types.html#reference)s of a resource.
#
# expansionPath - {String} An [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion) for the `expand` query parameter
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.expand('productType').fetch()
expand: (expansionPath) ->
return this unless expansionPath
encodedExpansionPath = encodeURIComponent(expansionPath)
@_params.query.expand.push encodedExpansionPath
debug 'setting expand: %s', expansionPath
this
# Public: Allow to pass a literal query string
#
# query - {String} The literal query string
# withEncodedParams - {Boolean} Whether the given query string has encoded params or not (default false)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byQueryString('where=slug(en = "my-slug")&limit=5&staged=true', false)
# .fetch()
byQueryString: (query, withEncodedParams = false) ->
parsed = _.parseQuery(query, false)
unless withEncodedParams
# when we rebuild the query string, we need to encode following parameters
_.each @_params.encoded, (param) =>
if parsed[param]
if _.contains @_params.encoded, param
parsed[param] = _.map _.flatten([parsed[param]]), (p) -> encodeURIComponent(p)
@_params.query[param] = parsed[param]
_.each @_params.plain, (param) =>
if parsed[param]
@_params.query[param] = parsed[param]
# API accepts limit parameter instead of perPage which we use here in SDK so this
# quick hash unifies both worlds
parsed.limit = parsed.perPage if parsed.perPage
delete parsed.perPage
@_params.query.perPage = Number(parsed.limit) if parsed.limit
@_params.queryString = _.stringifyQuery(parsed)
debug 'setting queryString: %s', query
this
# Private: Build a query string from (pre)defined params (can be overriden for custom params)
#
# Returns the built query string
_queryString: (params = @_params) ->
qs = if params.queryString
params.queryString
else
Utils.buildQueryString
where: params.query.where
whereOperator: params.query.operator
page: params.query.page
perPage: params.query.perPage
sort: params.query.sort
expand: params.query.expand
debug 'built query string: %s', qs
qs
# Public: Fetch resource defined by the `Service` with all chained query parameters.
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').sort('createdAt desc').fetch()
#
# client.products.fetch()
fetch: ->
_getEndpoint = =>
queryString = @_queryString()
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
endpoint
if not @_params.queryString and @_fetchAll is true
# we should provide a default sorting when fetching all results
@sort 'id' if _.isEmpty @_params.query.sort
@_paged(_getEndpoint())
else
@_get(_getEndpoint())
# Public: Process the resources for each `page` separately using the function `fn`.
# The function `fn` will then be called once per page and has to return a
# {Promise} that should be resolved when all elements of the page are processed.
#
# Batch processing allows to process a lot of resources in chunks.
# Using this approach you can balance between memory usage and parallelism.
#
# fn - {Function} The function called for each processing page (it must return a {Promise})
# options - {Object} To configure the processing
# :accumulate - {Boolean} Whether the results should be accumulated or not (default true)
#
# Throws an {Error} if `fn` is not a {Function}
#
# Returns a {Promise}, fulfilled with an {Array} of the results of each resolved
# page from the `fn`, or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# # Define your custom function, which returns a promise
# fn = (payload) ->
# new Promise (resolve, reject) ->
# # do something with the payload
# if # something unexpected happens
# reject 'BAD'
# else # good case
# resolve 'OK'
# service = client.products
# service.perPage(20).process(fn)
# .then (result) ->
# # here we get the total result, which is just an array of all pages accumulated
# # eg: ['OK', 'OK', 'OK'] if you have 41 to 60 products - the function fn is called three times
# .catch (error) ->
# # eg: 'BAD'
process: (fn, options = {}) ->
throw new Error 'Please provide a function to process the elements' unless _.isFunction fn
new Promise (resolve, reject) =>
options = _.defaults options,
accumulate: true # whether the results should be accumulated or not
endpoint = @constructor.baseResourceEndpoint
originalQuery = @_params.query
if originalQuery.perPage is 0
debug 'using batch size of 20 since 0 wont return any results'
originalQuery.perPage = 20
_processPage = (params, lastId, acc = []) =>
debug 'processing next page with id: %s', lastId
# set the query to the original query
# this is needed since the query is reset after each request
@_params.query = originalQuery
queryString = @_queryString params
if lastId
wherePredicate = encodeURIComponent("id > \"#{lastId}\"")
debug 'process where predicate: %j', wherePredicate
enhancedQueryString = [
"sort=#{encodeURIComponent("id asc")}",
queryString,
"withTotal=false"
# even if the enhanced query string already has a where query
# we can simply add another one, since the API combines
# "the individual predicates in a logical conjunction, just as if
# they had been specified in a single `where` query parameter and
# combined with `and`"
if wherePredicate then "where=#{wherePredicate}" else null,
].filter(Boolean).join('&')
debug 'enhanced query: %s', enhancedQueryString
@_get("#{endpoint}?#{enhancedQueryString}")
.then (payload) ->
fn(payload)
.then (result) ->
resultsSize = _.size(payload.body.results)
debug 'accumulating: size %s, offset %s, count %s', resultsSize, payload.body.offset, payload.body.count
accumulated = acc.concat(result or []) if options.accumulate
if resultsSize < (originalQuery.perPage or 20)
return resolve(accumulated or [])
last = _.last(payload.body.results)
newLastId = last && last.id
_processPage params, newLastId, accumulated
.catch (error) -> reject error
.done()
_processPage(@_params)
# Public: Save a new resource defined by the `Service` by passing the payload {Object}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.save
# name:
# en: 'Foo'
# slug:
# en: 'foo'
# productType:
# id: '123'
# typeId: 'product-type'
save: (body) ->
unless body
throw new Error "Body payload is required for creating a resource (endpoint: #{@constructor.baseResourceEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @constructor.baseResourceEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Alias of {::save}
create: -> @save.apply(@, arguments)
# Public: Update a resource defined by the `Service` by passing the payload {Object}
# with [UpdateAction](http://dev.sphere.io/http-api.html#partial-updates).
# The `id` of the resource must be provided with {::byId}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if resource `id` is missing
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').update
# version: 2
# actions: [
# {
# action: 'changeName'
# name:
# en: Bar
# }
# ]
update: (body) ->
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
unless body
throw new Error "Body payload is required for updating a resource (endpoint: #{@_currentEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Delete an existing resource defined by the `Service`
#
# version - {Number} The current version of the resource to delete
#
# Throws an {Error} if `version` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').delete(2)
delete: (version) ->
# TODO: automatically fetch the resource if no version is given?
# TODO: describe which endpoints support this?
unless version
throw new Error "Version is required for deleting a resource (endpoint: #{@_currentEndpoint})"
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
endpoint = "#{@_currentEndpoint}?version=#{version}"
@_delete(endpoint)
# Private: Return a {Promise} for a GET call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_get: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.GET endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a PAGED call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_paged: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
# fetch all results in chunks
@_rest.PAGED endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a POST call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
# payload - {Object} The body payload as JSON
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_save: (endpoint, payload) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
payload: payload
new Promise (resolve, reject) =>
@_rest.POST endpoint, payload, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a DELETE call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_delete: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.DELETE endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Wrap the HTTP response and decide whether to reject or resolve the promise
#
# resolve - {Function} The function called to `resolve` the {Promise}
# reject - {Function} The function called to `reject` the {Promise}
# originalRequest - {Object} The object containing information about the request, used when the request fails
# error - {Object} An error object when applicable (usually from `http.ClientRequest` object) otherwise `null`
# response - {Object} An `http.IncomingMessage` object containing all kind of information about the request / response
# body - {Object} A JSON object containing the HTTP API resource or error messages
_wrapResponse: (resolve, reject, originalRequest, error, response, body) ->
if @_stats.maskSensitiveHeaderData is true and response
response.req._header = Utils._censorHeaderStr(response.req._header)
response.request.headers = Utils._censorHeaderObj(
response.request.headers
)
response.headers = Utils._censorHeaderObj(response.headers)
responseJson =
if @_stats.includeHeaders and response
http:
request:
method: response.request.method
httpVersion: response.httpVersion
uri: response.request.uri
header: response.req._header
headers: response.request.headers
response:
headers: response.headers
else {}
options = _.deepClone(_.omit(@_rest._options, ['access_token']))
if options.config
options.config = _.omit(options.config, ['client_id', 'client_secret'])
if @_stats.maskSensitiveHeaderData is true
options.headers = Utils._censorHeaderObj(options.headers)
originalRequest.options = options
if error
if error instanceof Error
errorMessage = error.message
else
errorMessage = error
errorResp =
statusCode: response?.statusCode
message: errorMessage
originalRequest: originalRequest
errorResp.body = body if body
errorBody = _.extend(responseJson, errorResp)
reject new HttpError errorMessage, errorBody
else
# check for API deprecation headers
if response.headers?['X-DEPRECATION-NOTICE']
console.warn("Deprecation notice: #{response.headers['X-DEPRECATION-NOTICE']}")
# TODO: check other possible acceptable codes (304, ...)
if 200 <= response.statusCode < 300
return resolve _.extend responseJson,
statusCode: response.statusCode
body: body
else if response.statusCode is 404
endpoint = response.request.uri.path
# since the API doesn't return an error message for a resource not found
# we return a custom JSON error message
reject new SphereHttpError.NotFound "Endpoint '#{endpoint}' not found.",
_.extend responseJson,
statusCode: response.statusCode
message: "Endpoint '#{endpoint}' not found."
originalRequest: originalRequest
else if response.statusCode is 405
endpoint = response.request.uri.path
# since the API doesn't return an error message for a unsupported method
# we return a custom JSON error message
errMsg = "The chosen HTTP method is not allowed for the endpoint '#{endpoint}'. This might be caused by a malformed request."
reject new SphereHttpError.MethodNotAllowed errMsg,
_.extend responseJson,
statusCode: response.statusCode
message: errMsg
originalRequest: originalRequest
# FIXME: find a better solution
else if response.statusCode is 400 and @constructor.name is 'GraphQLService' and not body.data
graphqlError = new GraphQLError 'GraphQL error', _.extend responseJson, body,
statusCode: 400
originalRequest: originalRequest
return reject graphqlError
else
# a SphereError response e.g.: {statusCode: 400, message: 'Oops, something went wrong'}
errorMessage = body.message or body.error_description or body.error or 'Undefined SPHERE.IO error message'
errorBody = _.extend responseJson, body,
statusCode: body.statusCode or response.statusCode
originalRequest: originalRequest
# TODO: automatically retry code 503, 504
reject switch errorBody.statusCode
when 400 then new SphereHttpError.BadRequest errorMessage, errorBody
when 401 then new SphereHttpError.Unauthorized errorMessage, errorBody
when 409 then new SphereHttpError.ConcurrentModification errorMessage, errorBody
when 500 then new SphereHttpError.InternalServerError errorMessage, errorBody
when 503 then new SphereHttpError.ServiceUnavailable errorMessage, errorBody
else new HttpError require('http').STATUS_CODES[response.statusCode], _.extend responseJson,
statusCode: response.statusCode
originalRequest: originalRequest
module.exports = BaseService
| 120954 | debug = require('debug')('sphere-client')
_ = require 'underscore'
_.mixin require('underscore-mixins')
Promise = require 'bluebird'
Utils = require '../utils'
{HttpError, GraphQLError, SphereHttpError} = require '../errors'
# Private: RegExp to parse time period for last function.
REGEX_LAST = /^(\d+)([s|m|h|d|w])$/
# Abstract: Define a `BaseService` to provide basic methods to interact with the HTTP API.
#
# This class should **not be exposed** and **must be extended** when defining a new `*Service`.
#
# Examples
#
# class FooService extends BaseService
# @baseResourceEndpoint: '/foo'
class BaseService
# Internal: Base path for a API resource endpoint (to be overriden by specific service) ({String})
# constant
@baseResourceEndpoint: ''
# Internal: Indicates whether the current service supports keys or not
# constant
@supportsByKey: false
# Public: Construct a `*Service` object.
#
# options - An {Object} to configure the service
# :_rest - a {Rest} instance
# :_task - a {TaskQueue} instance
# :_stats - an {Object} to configure statistics
constructor: (options = {}) ->
{@_rest, @_task, @_stats} = options
@_setDefaults()
# Private: Reset default _currentEndpoint and _params used to build request endpoints
_setDefaults: ->
# Private: Current path for a API resource endpoint which can be modified by appending ids, queries, etc
@_currentEndpoint = @constructor.baseResourceEndpoint
# Private: Container that holds request parameters such `id`, `query`, etc
@_params =
encoded: ['where', 'expand', 'sort']
plain: ['perPage', 'page']
query:
where: []
operator: 'and'
sort: []
expand: []
@_fetchAll = false
# Public: Build the endpoint path by appending the given id
#
# id - {String} The resource specific id
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byId('123').fetch()
byId: (id) ->
if @_params.key
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/#{id}"
@_params.id = id
debug 'setting endpoint id: %j', @_currentEndpoint
this
# Public: Build the endpoint path by appending the given key query
#
# key - {String} The resource specific key
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.productTypes
# service.byKey('key').fetch()
byKey: (key) ->
if @_params.id
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/key=#{key}"
@_params.key = key
debug 'setting endpoint key: %j', @_currentEndpoint
this
# Public: Define a URI encoded [Predicate](http://dev.sphere.io/http-api.html#predicates)
# from the given string, used for quering and filtering a resource. Can be set multiple times.
#
# predicate - {String} A [Predicate](http://dev.sphere.io/http-api.html#predicates) string for the `where` query parameter.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').fetch()
where: (predicate) ->
# TODO: use query builder (for specific service) to faciliate build queries
# e.g.: `QueryBuilder.product.name('Foo', 'en')`
return this unless predicate
encodedPredicate = encodeURIComponent(predicate)
@_params.query.where.push encodedPredicate
debug 'setting predicate: %s', predicate
this
# Public: Define the logical operator to combine multiple {::where} query parameters.
#
# operator - {String} A logical operator (default `and`)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.whereOperator('or')
# .where('name(en = "<NAME>")')
# .where('name(de = "<NAME>")')
# .fetch()
whereOperator: (operator = 'and') ->
@_params.query.operator = switch operator
when 'and', 'or' then operator
else 'and'
debug 'setting where operator: %s', operator
this
# Public: This is a convenient method to query for the latest changes.
#
# Please be aware that `last` is just another `where` clause and thus
# depends on the `operator` you choose.
#
# predicate - {String} Time period of format `numberX` where `X` is one of the follwing units:
# :s - seconds
# :m - minutes
# :h - hours
# :d - days
# :w - weeks
#
# Throws an {Error} if `period` cannot be parsed
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.last('10d').fetch()
last: (period) ->
throw new Error "Cannot parse period '#{period}'" unless REGEX_LAST.test(period)
matches = REGEX_LAST.exec(period)
amount = matches[1]
if amount is '0'
return this
before = Utils.getTime amount, matches[2]
now = new Date().getTime()
dateTime = new Date(now - before).toISOString()
@where("lastModifiedAt > \"#{dateTime}\"")
# Public: Define how the query should be sorted.
# It is possible to add several sort criteria, thereby the order is relevant.
#
# path - {String} Sort path to search for
# ascending - {Boolean} Whether the direction should be ascending or not, (default `asc`)
# :true - `asc`
# :false - `desc`
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.sort('name.en', true).fetch()
sort: (path, ascending = true) ->
direction = if ascending then 'asc' else 'desc'
@_params.query.sort.push encodeURIComponent("#{path} #{direction}")
debug 'setting sort: %s %s', path, direction
this
# Public: Define the page number to be requested from the complete query result (used for pagination as `offset`)
#
# page - {Number} The page number `>= 1` (default is 1)
#
# Throws an {Error} if `page` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.page(4).fetch()
page: (page) ->
throw new Error 'Page must be a number >= 1' if _.isNumber(page) and page < 1
@_params.query.page = page
debug 'setting page: %s', page
this
# Public: Define the number of results to return from a query (used for pagination as `limit`)
#
# perPage - {Number} How many results in a page, it must be `>= 0` (default is 100)
#
# Throws an {Error} if `perPage` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.perPage(50).fetch()
perPage: (perPage) ->
throw new Error 'PerPage (limit) must be a number >= 0' if _.isNumber(perPage) and perPage < 0
@_params.query.perPage = perPage
debug 'setting perPage: %s', perPage
this
# Public: A convenient method to fetch all pages
# recursively in chunks and return them all together once completed.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.all().fetch()
all: ->
@_fetchAll = true
this
# Public: Define an [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion)
# used for expanding [Reference](http://dev.sphere.io/http-api-types.html#reference)s of a resource.
#
# expansionPath - {String} An [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion) for the `expand` query parameter
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.expand('productType').fetch()
expand: (expansionPath) ->
return this unless expansionPath
encodedExpansionPath = encodeURIComponent(expansionPath)
@_params.query.expand.push encodedExpansionPath
debug 'setting expand: %s', expansionPath
this
# Public: Allow to pass a literal query string
#
# query - {String} The literal query string
# withEncodedParams - {Boolean} Whether the given query string has encoded params or not (default false)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byQueryString('where=slug(en = "my-slug")&limit=5&staged=true', false)
# .fetch()
byQueryString: (query, withEncodedParams = false) ->
parsed = _.parseQuery(query, false)
unless withEncodedParams
# when we rebuild the query string, we need to encode following parameters
_.each @_params.encoded, (param) =>
if parsed[param]
if _.contains @_params.encoded, param
parsed[param] = _.map _.flatten([parsed[param]]), (p) -> encodeURIComponent(p)
@_params.query[param] = parsed[param]
_.each @_params.plain, (param) =>
if parsed[param]
@_params.query[param] = parsed[param]
# API accepts limit parameter instead of perPage which we use here in SDK so this
# quick hash unifies both worlds
parsed.limit = parsed.perPage if parsed.perPage
delete parsed.perPage
@_params.query.perPage = Number(parsed.limit) if parsed.limit
@_params.queryString = _.stringifyQuery(parsed)
debug 'setting queryString: %s', query
this
# Private: Build a query string from (pre)defined params (can be overriden for custom params)
#
# Returns the built query string
_queryString: (params = @_params) ->
qs = if params.queryString
params.queryString
else
Utils.buildQueryString
where: params.query.where
whereOperator: params.query.operator
page: params.query.page
perPage: params.query.perPage
sort: params.query.sort
expand: params.query.expand
debug 'built query string: %s', qs
qs
# Public: Fetch resource defined by the `Service` with all chained query parameters.
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').sort('createdAt desc').fetch()
#
# client.products.fetch()
fetch: ->
_getEndpoint = =>
queryString = @_queryString()
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
endpoint
if not @_params.queryString and @_fetchAll is true
# we should provide a default sorting when fetching all results
@sort 'id' if _.isEmpty @_params.query.sort
@_paged(_getEndpoint())
else
@_get(_getEndpoint())
# Public: Process the resources for each `page` separately using the function `fn`.
# The function `fn` will then be called once per page and has to return a
# {Promise} that should be resolved when all elements of the page are processed.
#
# Batch processing allows to process a lot of resources in chunks.
# Using this approach you can balance between memory usage and parallelism.
#
# fn - {Function} The function called for each processing page (it must return a {Promise})
# options - {Object} To configure the processing
# :accumulate - {Boolean} Whether the results should be accumulated or not (default true)
#
# Throws an {Error} if `fn` is not a {Function}
#
# Returns a {Promise}, fulfilled with an {Array} of the results of each resolved
# page from the `fn`, or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# # Define your custom function, which returns a promise
# fn = (payload) ->
# new Promise (resolve, reject) ->
# # do something with the payload
# if # something unexpected happens
# reject 'BAD'
# else # good case
# resolve 'OK'
# service = client.products
# service.perPage(20).process(fn)
# .then (result) ->
# # here we get the total result, which is just an array of all pages accumulated
# # eg: ['OK', 'OK', 'OK'] if you have 41 to 60 products - the function fn is called three times
# .catch (error) ->
# # eg: 'BAD'
process: (fn, options = {}) ->
throw new Error 'Please provide a function to process the elements' unless _.isFunction fn
new Promise (resolve, reject) =>
options = _.defaults options,
accumulate: true # whether the results should be accumulated or not
endpoint = @constructor.baseResourceEndpoint
originalQuery = @_params.query
if originalQuery.perPage is 0
debug 'using batch size of 20 since 0 wont return any results'
originalQuery.perPage = 20
_processPage = (params, lastId, acc = []) =>
debug 'processing next page with id: %s', lastId
# set the query to the original query
# this is needed since the query is reset after each request
@_params.query = originalQuery
queryString = @_queryString params
if lastId
wherePredicate = encodeURIComponent("id > \"#{lastId}\"")
debug 'process where predicate: %j', wherePredicate
enhancedQueryString = [
"sort=#{encodeURIComponent("id asc")}",
queryString,
"withTotal=false"
# even if the enhanced query string already has a where query
# we can simply add another one, since the API combines
# "the individual predicates in a logical conjunction, just as if
# they had been specified in a single `where` query parameter and
# combined with `and`"
if wherePredicate then "where=#{wherePredicate}" else null,
].filter(Boolean).join('&')
debug 'enhanced query: %s', enhancedQueryString
@_get("#{endpoint}?#{enhancedQueryString}")
.then (payload) ->
fn(payload)
.then (result) ->
resultsSize = _.size(payload.body.results)
debug 'accumulating: size %s, offset %s, count %s', resultsSize, payload.body.offset, payload.body.count
accumulated = acc.concat(result or []) if options.accumulate
if resultsSize < (originalQuery.perPage or 20)
return resolve(accumulated or [])
last = _.last(payload.body.results)
newLastId = last && last.id
_processPage params, newLastId, accumulated
.catch (error) -> reject error
.done()
_processPage(@_params)
# Public: Save a new resource defined by the `Service` by passing the payload {Object}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.save
# name:
# en: 'Foo'
# slug:
# en: 'foo'
# productType:
# id: '123'
# typeId: 'product-type'
save: (body) ->
unless body
throw new Error "Body payload is required for creating a resource (endpoint: #{@constructor.baseResourceEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @constructor.baseResourceEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Alias of {::save}
create: -> @save.apply(@, arguments)
# Public: Update a resource defined by the `Service` by passing the payload {Object}
# with [UpdateAction](http://dev.sphere.io/http-api.html#partial-updates).
# The `id` of the resource must be provided with {::byId}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if resource `id` is missing
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').update
# version: 2
# actions: [
# {
# action: 'changeName'
# name:
# en: Bar
# }
# ]
update: (body) ->
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
unless body
throw new Error "Body payload is required for updating a resource (endpoint: #{@_currentEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Delete an existing resource defined by the `Service`
#
# version - {Number} The current version of the resource to delete
#
# Throws an {Error} if `version` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').delete(2)
delete: (version) ->
# TODO: automatically fetch the resource if no version is given?
# TODO: describe which endpoints support this?
unless version
throw new Error "Version is required for deleting a resource (endpoint: #{@_currentEndpoint})"
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
endpoint = "#{@_currentEndpoint}?version=#{version}"
@_delete(endpoint)
# Private: Return a {Promise} for a GET call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_get: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.GET endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a PAGED call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_paged: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
# fetch all results in chunks
@_rest.PAGED endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a POST call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
# payload - {Object} The body payload as JSON
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_save: (endpoint, payload) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
payload: payload
new Promise (resolve, reject) =>
@_rest.POST endpoint, payload, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a DELETE call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_delete: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.DELETE endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Wrap the HTTP response and decide whether to reject or resolve the promise
#
# resolve - {Function} The function called to `resolve` the {Promise}
# reject - {Function} The function called to `reject` the {Promise}
# originalRequest - {Object} The object containing information about the request, used when the request fails
# error - {Object} An error object when applicable (usually from `http.ClientRequest` object) otherwise `null`
# response - {Object} An `http.IncomingMessage` object containing all kind of information about the request / response
# body - {Object} A JSON object containing the HTTP API resource or error messages
_wrapResponse: (resolve, reject, originalRequest, error, response, body) ->
if @_stats.maskSensitiveHeaderData is true and response
response.req._header = Utils._censorHeaderStr(response.req._header)
response.request.headers = Utils._censorHeaderObj(
response.request.headers
)
response.headers = Utils._censorHeaderObj(response.headers)
responseJson =
if @_stats.includeHeaders and response
http:
request:
method: response.request.method
httpVersion: response.httpVersion
uri: response.request.uri
header: response.req._header
headers: response.request.headers
response:
headers: response.headers
else {}
options = _.deepClone(_.omit(@_rest._options, ['access_token']))
if options.config
options.config = _.omit(options.config, ['client_id', 'client_secret'])
if @_stats.maskSensitiveHeaderData is true
options.headers = Utils._censorHeaderObj(options.headers)
originalRequest.options = options
if error
if error instanceof Error
errorMessage = error.message
else
errorMessage = error
errorResp =
statusCode: response?.statusCode
message: errorMessage
originalRequest: originalRequest
errorResp.body = body if body
errorBody = _.extend(responseJson, errorResp)
reject new HttpError errorMessage, errorBody
else
# check for API deprecation headers
if response.headers?['X-DEPRECATION-NOTICE']
console.warn("Deprecation notice: #{response.headers['X-DEPRECATION-NOTICE']}")
# TODO: check other possible acceptable codes (304, ...)
if 200 <= response.statusCode < 300
return resolve _.extend responseJson,
statusCode: response.statusCode
body: body
else if response.statusCode is 404
endpoint = response.request.uri.path
# since the API doesn't return an error message for a resource not found
# we return a custom JSON error message
reject new SphereHttpError.NotFound "Endpoint '#{endpoint}' not found.",
_.extend responseJson,
statusCode: response.statusCode
message: "Endpoint '#{endpoint}' not found."
originalRequest: originalRequest
else if response.statusCode is 405
endpoint = response.request.uri.path
# since the API doesn't return an error message for a unsupported method
# we return a custom JSON error message
errMsg = "The chosen HTTP method is not allowed for the endpoint '#{endpoint}'. This might be caused by a malformed request."
reject new SphereHttpError.MethodNotAllowed errMsg,
_.extend responseJson,
statusCode: response.statusCode
message: errMsg
originalRequest: originalRequest
# FIXME: find a better solution
else if response.statusCode is 400 and @constructor.name is 'GraphQLService' and not body.data
graphqlError = new GraphQLError 'GraphQL error', _.extend responseJson, body,
statusCode: 400
originalRequest: originalRequest
return reject graphqlError
else
# a SphereError response e.g.: {statusCode: 400, message: 'Oops, something went wrong'}
errorMessage = body.message or body.error_description or body.error or 'Undefined SPHERE.IO error message'
errorBody = _.extend responseJson, body,
statusCode: body.statusCode or response.statusCode
originalRequest: originalRequest
# TODO: automatically retry code 503, 504
reject switch errorBody.statusCode
when 400 then new SphereHttpError.BadRequest errorMessage, errorBody
when 401 then new SphereHttpError.Unauthorized errorMessage, errorBody
when 409 then new SphereHttpError.ConcurrentModification errorMessage, errorBody
when 500 then new SphereHttpError.InternalServerError errorMessage, errorBody
when 503 then new SphereHttpError.ServiceUnavailable errorMessage, errorBody
else new HttpError require('http').STATUS_CODES[response.statusCode], _.extend responseJson,
statusCode: response.statusCode
originalRequest: originalRequest
module.exports = BaseService
| true | debug = require('debug')('sphere-client')
_ = require 'underscore'
_.mixin require('underscore-mixins')
Promise = require 'bluebird'
Utils = require '../utils'
{HttpError, GraphQLError, SphereHttpError} = require '../errors'
# Private: RegExp to parse time period for last function.
REGEX_LAST = /^(\d+)([s|m|h|d|w])$/
# Abstract: Define a `BaseService` to provide basic methods to interact with the HTTP API.
#
# This class should **not be exposed** and **must be extended** when defining a new `*Service`.
#
# Examples
#
# class FooService extends BaseService
# @baseResourceEndpoint: '/foo'
class BaseService
# Internal: Base path for a API resource endpoint (to be overriden by specific service) ({String})
# constant
@baseResourceEndpoint: ''
# Internal: Indicates whether the current service supports keys or not
# constant
@supportsByKey: false
# Public: Construct a `*Service` object.
#
# options - An {Object} to configure the service
# :_rest - a {Rest} instance
# :_task - a {TaskQueue} instance
# :_stats - an {Object} to configure statistics
constructor: (options = {}) ->
{@_rest, @_task, @_stats} = options
@_setDefaults()
# Private: Reset default _currentEndpoint and _params used to build request endpoints
_setDefaults: ->
# Private: Current path for a API resource endpoint which can be modified by appending ids, queries, etc
@_currentEndpoint = @constructor.baseResourceEndpoint
# Private: Container that holds request parameters such `id`, `query`, etc
@_params =
encoded: ['where', 'expand', 'sort']
plain: ['perPage', 'page']
query:
where: []
operator: 'and'
sort: []
expand: []
@_fetchAll = false
# Public: Build the endpoint path by appending the given id
#
# id - {String} The resource specific id
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byId('123').fetch()
byId: (id) ->
if @_params.key
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/#{id}"
@_params.id = id
debug 'setting endpoint id: %j', @_currentEndpoint
this
# Public: Build the endpoint path by appending the given key query
#
# key - {String} The resource specific key
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.productTypes
# service.byKey('key').fetch()
byKey: (key) ->
if @_params.id
throw new Error(
"You cannot fetch or update by Id and Key at the same time"
)
@_currentEndpoint = "#{@constructor.baseResourceEndpoint}/key=#{key}"
@_params.key = key
debug 'setting endpoint key: %j', @_currentEndpoint
this
# Public: Define a URI encoded [Predicate](http://dev.sphere.io/http-api.html#predicates)
# from the given string, used for quering and filtering a resource. Can be set multiple times.
#
# predicate - {String} A [Predicate](http://dev.sphere.io/http-api.html#predicates) string for the `where` query parameter.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').fetch()
where: (predicate) ->
# TODO: use query builder (for specific service) to faciliate build queries
# e.g.: `QueryBuilder.product.name('Foo', 'en')`
return this unless predicate
encodedPredicate = encodeURIComponent(predicate)
@_params.query.where.push encodedPredicate
debug 'setting predicate: %s', predicate
this
# Public: Define the logical operator to combine multiple {::where} query parameters.
#
# operator - {String} A logical operator (default `and`)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.whereOperator('or')
# .where('name(en = "PI:NAME:<NAME>END_PI")')
# .where('name(de = "PI:NAME:<NAME>END_PI")')
# .fetch()
whereOperator: (operator = 'and') ->
@_params.query.operator = switch operator
when 'and', 'or' then operator
else 'and'
debug 'setting where operator: %s', operator
this
# Public: This is a convenient method to query for the latest changes.
#
# Please be aware that `last` is just another `where` clause and thus
# depends on the `operator` you choose.
#
# predicate - {String} Time period of format `numberX` where `X` is one of the follwing units:
# :s - seconds
# :m - minutes
# :h - hours
# :d - days
# :w - weeks
#
# Throws an {Error} if `period` cannot be parsed
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.last('10d').fetch()
last: (period) ->
throw new Error "Cannot parse period '#{period}'" unless REGEX_LAST.test(period)
matches = REGEX_LAST.exec(period)
amount = matches[1]
if amount is '0'
return this
before = Utils.getTime amount, matches[2]
now = new Date().getTime()
dateTime = new Date(now - before).toISOString()
@where("lastModifiedAt > \"#{dateTime}\"")
# Public: Define how the query should be sorted.
# It is possible to add several sort criteria, thereby the order is relevant.
#
# path - {String} Sort path to search for
# ascending - {Boolean} Whether the direction should be ascending or not, (default `asc`)
# :true - `asc`
# :false - `desc`
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.sort('name.en', true).fetch()
sort: (path, ascending = true) ->
direction = if ascending then 'asc' else 'desc'
@_params.query.sort.push encodeURIComponent("#{path} #{direction}")
debug 'setting sort: %s %s', path, direction
this
# Public: Define the page number to be requested from the complete query result (used for pagination as `offset`)
#
# page - {Number} The page number `>= 1` (default is 1)
#
# Throws an {Error} if `page` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.page(4).fetch()
page: (page) ->
throw new Error 'Page must be a number >= 1' if _.isNumber(page) and page < 1
@_params.query.page = page
debug 'setting page: %s', page
this
# Public: Define the number of results to return from a query (used for pagination as `limit`)
#
# perPage - {Number} How many results in a page, it must be `>= 0` (default is 100)
#
# Throws an {Error} if `perPage` is not a positive number
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.perPage(50).fetch()
perPage: (perPage) ->
throw new Error 'PerPage (limit) must be a number >= 0' if _.isNumber(perPage) and perPage < 0
@_params.query.perPage = perPage
debug 'setting perPage: %s', perPage
this
# Public: A convenient method to fetch all pages
# recursively in chunks and return them all together once completed.
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.all().fetch()
all: ->
@_fetchAll = true
this
# Public: Define an [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion)
# used for expanding [Reference](http://dev.sphere.io/http-api-types.html#reference)s of a resource.
#
# expansionPath - {String} An [ExpansionPath](http://dev.sphere.io/http-api.html#reference-expansion) for the `expand` query parameter
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.expand('productType').fetch()
expand: (expansionPath) ->
return this unless expansionPath
encodedExpansionPath = encodeURIComponent(expansionPath)
@_params.query.expand.push encodedExpansionPath
debug 'setting expand: %s', expansionPath
this
# Public: Allow to pass a literal query string
#
# query - {String} The literal query string
# withEncodedParams - {Boolean} Whether the given query string has encoded params or not (default false)
#
# Returns a chained instance of `this` class
#
# Examples
#
# service = client.products
# service.byQueryString('where=slug(en = "my-slug")&limit=5&staged=true', false)
# .fetch()
byQueryString: (query, withEncodedParams = false) ->
parsed = _.parseQuery(query, false)
unless withEncodedParams
# when we rebuild the query string, we need to encode following parameters
_.each @_params.encoded, (param) =>
if parsed[param]
if _.contains @_params.encoded, param
parsed[param] = _.map _.flatten([parsed[param]]), (p) -> encodeURIComponent(p)
@_params.query[param] = parsed[param]
_.each @_params.plain, (param) =>
if parsed[param]
@_params.query[param] = parsed[param]
# API accepts limit parameter instead of perPage which we use here in SDK so this
# quick hash unifies both worlds
parsed.limit = parsed.perPage if parsed.perPage
delete parsed.perPage
@_params.query.perPage = Number(parsed.limit) if parsed.limit
@_params.queryString = _.stringifyQuery(parsed)
debug 'setting queryString: %s', query
this
# Private: Build a query string from (pre)defined params (can be overriden for custom params)
#
# Returns the built query string
_queryString: (params = @_params) ->
qs = if params.queryString
params.queryString
else
Utils.buildQueryString
where: params.query.where
whereOperator: params.query.operator
page: params.query.page
perPage: params.query.perPage
sort: params.query.sort
expand: params.query.expand
debug 'built query string: %s', qs
qs
# Public: Fetch resource defined by the `Service` with all chained query parameters.
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.where('name(en = "Foo")').sort('createdAt desc').fetch()
#
# client.products.fetch()
fetch: ->
_getEndpoint = =>
queryString = @_queryString()
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
endpoint
if not @_params.queryString and @_fetchAll is true
# we should provide a default sorting when fetching all results
@sort 'id' if _.isEmpty @_params.query.sort
@_paged(_getEndpoint())
else
@_get(_getEndpoint())
# Public: Process the resources for each `page` separately using the function `fn`.
# The function `fn` will then be called once per page and has to return a
# {Promise} that should be resolved when all elements of the page are processed.
#
# Batch processing allows to process a lot of resources in chunks.
# Using this approach you can balance between memory usage and parallelism.
#
# fn - {Function} The function called for each processing page (it must return a {Promise})
# options - {Object} To configure the processing
# :accumulate - {Boolean} Whether the results should be accumulated or not (default true)
#
# Throws an {Error} if `fn` is not a {Function}
#
# Returns a {Promise}, fulfilled with an {Array} of the results of each resolved
# page from the `fn`, or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# # Define your custom function, which returns a promise
# fn = (payload) ->
# new Promise (resolve, reject) ->
# # do something with the payload
# if # something unexpected happens
# reject 'BAD'
# else # good case
# resolve 'OK'
# service = client.products
# service.perPage(20).process(fn)
# .then (result) ->
# # here we get the total result, which is just an array of all pages accumulated
# # eg: ['OK', 'OK', 'OK'] if you have 41 to 60 products - the function fn is called three times
# .catch (error) ->
# # eg: 'BAD'
process: (fn, options = {}) ->
throw new Error 'Please provide a function to process the elements' unless _.isFunction fn
new Promise (resolve, reject) =>
options = _.defaults options,
accumulate: true # whether the results should be accumulated or not
endpoint = @constructor.baseResourceEndpoint
originalQuery = @_params.query
if originalQuery.perPage is 0
debug 'using batch size of 20 since 0 wont return any results'
originalQuery.perPage = 20
_processPage = (params, lastId, acc = []) =>
debug 'processing next page with id: %s', lastId
# set the query to the original query
# this is needed since the query is reset after each request
@_params.query = originalQuery
queryString = @_queryString params
if lastId
wherePredicate = encodeURIComponent("id > \"#{lastId}\"")
debug 'process where predicate: %j', wherePredicate
enhancedQueryString = [
"sort=#{encodeURIComponent("id asc")}",
queryString,
"withTotal=false"
# even if the enhanced query string already has a where query
# we can simply add another one, since the API combines
# "the individual predicates in a logical conjunction, just as if
# they had been specified in a single `where` query parameter and
# combined with `and`"
if wherePredicate then "where=#{wherePredicate}" else null,
].filter(Boolean).join('&')
debug 'enhanced query: %s', enhancedQueryString
@_get("#{endpoint}?#{enhancedQueryString}")
.then (payload) ->
fn(payload)
.then (result) ->
resultsSize = _.size(payload.body.results)
debug 'accumulating: size %s, offset %s, count %s', resultsSize, payload.body.offset, payload.body.count
accumulated = acc.concat(result or []) if options.accumulate
if resultsSize < (originalQuery.perPage or 20)
return resolve(accumulated or [])
last = _.last(payload.body.results)
newLastId = last && last.id
_processPage params, newLastId, accumulated
.catch (error) -> reject error
.done()
_processPage(@_params)
# Public: Save a new resource defined by the `Service` by passing the payload {Object}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.save
# name:
# en: 'Foo'
# slug:
# en: 'foo'
# productType:
# id: '123'
# typeId: 'product-type'
save: (body) ->
unless body
throw new Error "Body payload is required for creating a resource (endpoint: #{@constructor.baseResourceEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @constructor.baseResourceEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Alias of {::save}
create: -> @save.apply(@, arguments)
# Public: Update a resource defined by the `Service` by passing the payload {Object}
# with [UpdateAction](http://dev.sphere.io/http-api.html#partial-updates).
# The `id` of the resource must be provided with {::byId}.
#
# body - {Object} The payload described by the related API resource as JSON
#
# Throws an {Error} if resource `id` is missing
# Throws an {Error} if `body` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').update
# version: 2
# actions: [
# {
# action: 'changeName'
# name:
# en: Bar
# }
# ]
update: (body) ->
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
unless body
throw new Error "Body payload is required for updating a resource (endpoint: #{@_currentEndpoint})"
queryString = Utils.buildQueryString
expand: @_params.query.expand
endpoint = @_currentEndpoint
endpoint += "?#{queryString}" if queryString
@_save(endpoint, body)
# Public: Delete an existing resource defined by the `Service`
#
# version - {Number} The current version of the resource to delete
#
# Throws an {Error} if `version` is missing
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
#
# Examples
#
# service = client.products
# service.byId('123').delete(2)
delete: (version) ->
# TODO: automatically fetch the resource if no version is given?
# TODO: describe which endpoints support this?
unless version
throw new Error "Version is required for deleting a resource (endpoint: #{@_currentEndpoint})"
if @constructor.supportsByKey is true
unless (@_params.key or @_params.id)
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'" unless @_params.key or @_params.id
else
throw new Error "Missing resource id. You can set it by chaining '.byId(ID)'" unless @_params.id
endpoint = "#{@_currentEndpoint}?version=#{version}"
@_delete(endpoint)
# Private: Return a {Promise} for a GET call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_get: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.GET endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a PAGED call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_paged: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
# fetch all results in chunks
@_rest.PAGED endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a POST call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
# payload - {Object} The body payload as JSON
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_save: (endpoint, payload) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
payload: payload
new Promise (resolve, reject) =>
@_rest.POST endpoint, payload, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Return a {Promise} for a DELETE call. It can be overridden for custom logic.
#
# endpoint - {String} The resource endpoint
#
# Returns a {Promise}, fulfilled with an {Object} or rejected with an instance of an {HttpError} or {SphereError}
_delete: (endpoint) ->
@_setDefaults()
@_task.addTask =>
originalRequest =
endpoint: endpoint
new Promise (resolve, reject) =>
@_rest.DELETE endpoint, =>
@_wrapResponse.apply(@, [resolve, reject, originalRequest].concat(_.toArray(arguments)))
# Private: Wrap the HTTP response and decide whether to reject or resolve the promise
#
# resolve - {Function} The function called to `resolve` the {Promise}
# reject - {Function} The function called to `reject` the {Promise}
# originalRequest - {Object} The object containing information about the request, used when the request fails
# error - {Object} An error object when applicable (usually from `http.ClientRequest` object) otherwise `null`
# response - {Object} An `http.IncomingMessage` object containing all kind of information about the request / response
# body - {Object} A JSON object containing the HTTP API resource or error messages
_wrapResponse: (resolve, reject, originalRequest, error, response, body) ->
if @_stats.maskSensitiveHeaderData is true and response
response.req._header = Utils._censorHeaderStr(response.req._header)
response.request.headers = Utils._censorHeaderObj(
response.request.headers
)
response.headers = Utils._censorHeaderObj(response.headers)
responseJson =
if @_stats.includeHeaders and response
http:
request:
method: response.request.method
httpVersion: response.httpVersion
uri: response.request.uri
header: response.req._header
headers: response.request.headers
response:
headers: response.headers
else {}
options = _.deepClone(_.omit(@_rest._options, ['access_token']))
if options.config
options.config = _.omit(options.config, ['client_id', 'client_secret'])
if @_stats.maskSensitiveHeaderData is true
options.headers = Utils._censorHeaderObj(options.headers)
originalRequest.options = options
if error
if error instanceof Error
errorMessage = error.message
else
errorMessage = error
errorResp =
statusCode: response?.statusCode
message: errorMessage
originalRequest: originalRequest
errorResp.body = body if body
errorBody = _.extend(responseJson, errorResp)
reject new HttpError errorMessage, errorBody
else
# check for API deprecation headers
if response.headers?['X-DEPRECATION-NOTICE']
console.warn("Deprecation notice: #{response.headers['X-DEPRECATION-NOTICE']}")
# TODO: check other possible acceptable codes (304, ...)
if 200 <= response.statusCode < 300
return resolve _.extend responseJson,
statusCode: response.statusCode
body: body
else if response.statusCode is 404
endpoint = response.request.uri.path
# since the API doesn't return an error message for a resource not found
# we return a custom JSON error message
reject new SphereHttpError.NotFound "Endpoint '#{endpoint}' not found.",
_.extend responseJson,
statusCode: response.statusCode
message: "Endpoint '#{endpoint}' not found."
originalRequest: originalRequest
else if response.statusCode is 405
endpoint = response.request.uri.path
# since the API doesn't return an error message for a unsupported method
# we return a custom JSON error message
errMsg = "The chosen HTTP method is not allowed for the endpoint '#{endpoint}'. This might be caused by a malformed request."
reject new SphereHttpError.MethodNotAllowed errMsg,
_.extend responseJson,
statusCode: response.statusCode
message: errMsg
originalRequest: originalRequest
# FIXME: find a better solution
else if response.statusCode is 400 and @constructor.name is 'GraphQLService' and not body.data
graphqlError = new GraphQLError 'GraphQL error', _.extend responseJson, body,
statusCode: 400
originalRequest: originalRequest
return reject graphqlError
else
# a SphereError response e.g.: {statusCode: 400, message: 'Oops, something went wrong'}
errorMessage = body.message or body.error_description or body.error or 'Undefined SPHERE.IO error message'
errorBody = _.extend responseJson, body,
statusCode: body.statusCode or response.statusCode
originalRequest: originalRequest
# TODO: automatically retry code 503, 504
reject switch errorBody.statusCode
when 400 then new SphereHttpError.BadRequest errorMessage, errorBody
when 401 then new SphereHttpError.Unauthorized errorMessage, errorBody
when 409 then new SphereHttpError.ConcurrentModification errorMessage, errorBody
when 500 then new SphereHttpError.InternalServerError errorMessage, errorBody
when 503 then new SphereHttpError.ServiceUnavailable errorMessage, errorBody
else new HttpError require('http').STATUS_CODES[response.statusCode], _.extend responseJson,
statusCode: response.statusCode
originalRequest: originalRequest
module.exports = BaseService
|
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998893737792969,
"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.9999310374259949,
"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.9998852014541626,
"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.9999350905418396,
"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.9998888373374939,
"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.9999354481697083,
"start": 160,
"tag": "EMAIL",
"value": "bameda@dbarragan.com"
}
] | public/taiga-front/app/coffee/modules/tasks/detail.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/tasks/detail.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
groupBy = @.taiga.groupBy
module = angular.module("taigaTasks")
#############################################################################
## Task Detail Controller
#############################################################################
class TaskDetailController extends mixOf(taiga.Controller, taiga.PageMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$routeParams",
"$q",
"$tgLocation",
"$log",
"$appTitle",
"$tgNavUrls",
"$tgAnalytics",
"tgLoader"
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @params, @q, @location,
@log, @appTitle, @navUrls, @analytics, tgLoader) ->
@scope.taskRef = @params.taskref
@scope.sectionName = "Task Details"
@.initializeEventHandlers()
promise = @.loadInitialData()
promise.then () =>
@appTitle.set(@scope.task.subject + " - " + @scope.project.name)
@.initializeOnDeleteGoToUrl()
tgLoader.pageLoaded()
promise.then null, @.onInitialDataError.bind(@)
initializeEventHandlers: ->
@scope.$on "attachment:create", =>
@analytics.trackEvent("attachment", "create", "create attachment on task", 1)
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:edit", =>
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:delete", =>
@rootscope.$broadcast("history:reload")
initializeOnDeleteGoToUrl: ->
ctx = {project: @scope.project.slug}
@scope.onDeleteGoToUrl = @navUrls.resolve("project", ctx)
if @scope.project.is_backlog_activated
if @scope.task.milestone
ctx.sprint = @scope.sprint.slug
@scope.onDeleteGoToUrl = @navUrls.resolve("project-taskboard", ctx)
else if @scope.task.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
else if @scope.project.is_kanban_activated
if @scope.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
loadProject: ->
return @rs.projects.get(@scope.projectId).then (project) =>
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.statusList = project.task_statuses
@scope.statusById = groupBy(project.task_statuses, (x) -> x.id)
@scope.membersById = groupBy(project.memberships, (x) -> x.user)
return project
loadTask: ->
return @rs.tasks.get(@scope.projectId, @scope.taskId).then (task) =>
@scope.task = task
@scope.commentModel = task
if @scope.task.neighbors.previous.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.previous.ref
}
@scope.previousUrl = @navUrls.resolve("project-tasks-detail", ctx)
if @scope.task.neighbors.next.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.next.ref
}
@scope.nextUrl = @navUrls.resolve("project-tasks-detail", ctx)
return task
loadSprint: ->
if @scope.task.milestone
return @rs.sprints.get(@scope.task.project, @scope.task.milestone).then (sprint) =>
@scope.sprint = sprint
return sprint
loadUserStory: ->
if @scope.task.user_story
return @rs.userstories.get(@scope.task.project, @scope.task.user_story).then (us) =>
@scope.us = us
return us
loadInitialData: ->
params = {
pslug: @params.pslug
taskref: @params.taskref
}
promise = @repo.resolve(params).then (data) =>
@scope.projectId = data.project
@scope.taskId = data.task
return data
return promise.then(=> @.loadProject())
.then(=> @.loadUsersAndRoles())
.then(=> @.loadTask().then(=> @q.all([@.loadUserStory(),
@.loadSprint()])))
module.controller("TaskDetailController", TaskDetailController)
#############################################################################
## Task status display directive
#############################################################################
TaskStatusDisplayDirective = ->
# Display if a Task is open or closed and its taskboard status.
#
# Example:
# tg-task-status-display(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
template = _.template("""
<span>
<% if (status.is_closed) { %>
Closed
<% } else { %>
Open
<% } %>
</span>
<span class="us-detail-status" style="color:<%- status.color %>">
<%- status.name %>
</span>
""") # TODO: i18n
link = ($scope, $el, $attrs) ->
render = (task) ->
html = template({
status: $scope.statusById[task.status]
})
$el.html(html)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task?
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusDisplay", TaskStatusDisplayDirective)
#############################################################################
## Task status button directive
#############################################################################
TaskStatusButtonDirective = ($rootScope, $repo, $confirm, $loading, $qqueue) ->
# Display the status of Task and you can edit it.
#
# Example:
# tg-task-status-button(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
# - $scope.project.my_permissions
template = _.template("""
<div class="status-data <% if(editable){ %>clickable<% }%>">
<span class="level" style="background-color:<%- status.color %>"></span>
<span class="status-status"><%- status.name %></span>
<% if(editable){ %><span class="icon icon-arrow-bottom"></span><% }%>
<span class="level-name">status</span>
<ul class="popover pop-status">
<% _.each(statuses, function(st) { %>
<li><a href="" class="status" title="<%- st.name %>"
data-status-id="<%- st.id %>"><%- st.name %></a></li>
<% }); %>
</ul>
</div>
""") #TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) =>
status = $scope.statusById[task.status]
html = template({
status: status
statuses: $scope.statusList
editable: isEditable()
})
$el.html(html)
save = $qqueue.bindAdd (status) =>
task = $model.$modelValue.clone()
task.status = status
$model.$setViewValue(task)
onSuccess = ->
$confirm.notify("success")
$rootScope.$broadcast("history:reload")
$loading.finish($el.find(".level-name"))
onError = ->
$confirm.notify("error")
task.revert()
$model.$setViewValue(task)
$loading.finish($el.find(".level-name"))
$loading.start($el.find(".level-name"))
$repo.save($model.$modelValue).then(onSuccess, onError)
$el.on "click", ".status-data", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
target = angular.element(event.currentTarget)
$.fn.popover().closeAll()
save(target.data("status-id"))
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue",
TaskStatusButtonDirective])
TaskIsIocaineButtonDirective = ($rootscope, $tgrepo, $confirm, $loading, $qqueue) ->
template = _.template("""
<fieldset title="Feeling a bit overwhelmed by a task? Make sure others know about it by clicking on Iocaine when editing a task. It's possible to become immune to this (fictional) deadly poison by consuming small amounts over time just as it's possible to get better at what you do by occasionally taking on extra challenges!">
<label for="is-iocaine"
class="button button-gray is-iocaine <% if(isEditable){ %>editable<% }; %> <% if(isIocaine){ %>active<% }; %>">
Iocaine
</label>
<input type="checkbox" id="is-iocaine" name="is-iocaine"/>
</fieldset>
""")
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) ->
if not isEditable() and not task.is_iocaine
$el.html("")
return
ctx = {
isIocaine: task.is_iocaine
isEditable: isEditable()
}
html = template(ctx)
$el.html(html)
save = $qqueue.bindAdd (is_iocaine) =>
task = $model.$modelValue.clone()
task.is_iocaine = is_iocaine
$model.$setViewValue(task)
$loading.start($el.find('label'))
promise = $tgrepo.save(task)
promise.then ->
$confirm.notify("success")
$rootscope.$broadcast("history:reload")
promise.then null, ->
task.revert()
$model.$setViewValue(task)
$confirm.notify("error")
promise.finally ->
$loading.finish($el.find('label'))
$el.on "click", ".is-iocaine", (event) ->
return if not isEditable()
is_iocaine = not $model.$modelValue.is_iocaine
save(is_iocaine)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskIsIocaineButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", TaskIsIocaineButtonDirective])
| 16578 | ###
# 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/tasks/detail.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
groupBy = @.taiga.groupBy
module = angular.module("taigaTasks")
#############################################################################
## Task Detail Controller
#############################################################################
class TaskDetailController extends mixOf(taiga.Controller, taiga.PageMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$routeParams",
"$q",
"$tgLocation",
"$log",
"$appTitle",
"$tgNavUrls",
"$tgAnalytics",
"tgLoader"
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @params, @q, @location,
@log, @appTitle, @navUrls, @analytics, tgLoader) ->
@scope.taskRef = @params.taskref
@scope.sectionName = "Task Details"
@.initializeEventHandlers()
promise = @.loadInitialData()
promise.then () =>
@appTitle.set(@scope.task.subject + " - " + @scope.project.name)
@.initializeOnDeleteGoToUrl()
tgLoader.pageLoaded()
promise.then null, @.onInitialDataError.bind(@)
initializeEventHandlers: ->
@scope.$on "attachment:create", =>
@analytics.trackEvent("attachment", "create", "create attachment on task", 1)
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:edit", =>
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:delete", =>
@rootscope.$broadcast("history:reload")
initializeOnDeleteGoToUrl: ->
ctx = {project: @scope.project.slug}
@scope.onDeleteGoToUrl = @navUrls.resolve("project", ctx)
if @scope.project.is_backlog_activated
if @scope.task.milestone
ctx.sprint = @scope.sprint.slug
@scope.onDeleteGoToUrl = @navUrls.resolve("project-taskboard", ctx)
else if @scope.task.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
else if @scope.project.is_kanban_activated
if @scope.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
loadProject: ->
return @rs.projects.get(@scope.projectId).then (project) =>
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.statusList = project.task_statuses
@scope.statusById = groupBy(project.task_statuses, (x) -> x.id)
@scope.membersById = groupBy(project.memberships, (x) -> x.user)
return project
loadTask: ->
return @rs.tasks.get(@scope.projectId, @scope.taskId).then (task) =>
@scope.task = task
@scope.commentModel = task
if @scope.task.neighbors.previous.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.previous.ref
}
@scope.previousUrl = @navUrls.resolve("project-tasks-detail", ctx)
if @scope.task.neighbors.next.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.next.ref
}
@scope.nextUrl = @navUrls.resolve("project-tasks-detail", ctx)
return task
loadSprint: ->
if @scope.task.milestone
return @rs.sprints.get(@scope.task.project, @scope.task.milestone).then (sprint) =>
@scope.sprint = sprint
return sprint
loadUserStory: ->
if @scope.task.user_story
return @rs.userstories.get(@scope.task.project, @scope.task.user_story).then (us) =>
@scope.us = us
return us
loadInitialData: ->
params = {
pslug: @params.pslug
taskref: @params.taskref
}
promise = @repo.resolve(params).then (data) =>
@scope.projectId = data.project
@scope.taskId = data.task
return data
return promise.then(=> @.loadProject())
.then(=> @.loadUsersAndRoles())
.then(=> @.loadTask().then(=> @q.all([@.loadUserStory(),
@.loadSprint()])))
module.controller("TaskDetailController", TaskDetailController)
#############################################################################
## Task status display directive
#############################################################################
TaskStatusDisplayDirective = ->
# Display if a Task is open or closed and its taskboard status.
#
# Example:
# tg-task-status-display(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
template = _.template("""
<span>
<% if (status.is_closed) { %>
Closed
<% } else { %>
Open
<% } %>
</span>
<span class="us-detail-status" style="color:<%- status.color %>">
<%- status.name %>
</span>
""") # TODO: i18n
link = ($scope, $el, $attrs) ->
render = (task) ->
html = template({
status: $scope.statusById[task.status]
})
$el.html(html)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task?
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusDisplay", TaskStatusDisplayDirective)
#############################################################################
## Task status button directive
#############################################################################
TaskStatusButtonDirective = ($rootScope, $repo, $confirm, $loading, $qqueue) ->
# Display the status of Task and you can edit it.
#
# Example:
# tg-task-status-button(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
# - $scope.project.my_permissions
template = _.template("""
<div class="status-data <% if(editable){ %>clickable<% }%>">
<span class="level" style="background-color:<%- status.color %>"></span>
<span class="status-status"><%- status.name %></span>
<% if(editable){ %><span class="icon icon-arrow-bottom"></span><% }%>
<span class="level-name">status</span>
<ul class="popover pop-status">
<% _.each(statuses, function(st) { %>
<li><a href="" class="status" title="<%- st.name %>"
data-status-id="<%- st.id %>"><%- st.name %></a></li>
<% }); %>
</ul>
</div>
""") #TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) =>
status = $scope.statusById[task.status]
html = template({
status: status
statuses: $scope.statusList
editable: isEditable()
})
$el.html(html)
save = $qqueue.bindAdd (status) =>
task = $model.$modelValue.clone()
task.status = status
$model.$setViewValue(task)
onSuccess = ->
$confirm.notify("success")
$rootScope.$broadcast("history:reload")
$loading.finish($el.find(".level-name"))
onError = ->
$confirm.notify("error")
task.revert()
$model.$setViewValue(task)
$loading.finish($el.find(".level-name"))
$loading.start($el.find(".level-name"))
$repo.save($model.$modelValue).then(onSuccess, onError)
$el.on "click", ".status-data", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
target = angular.element(event.currentTarget)
$.fn.popover().closeAll()
save(target.data("status-id"))
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue",
TaskStatusButtonDirective])
TaskIsIocaineButtonDirective = ($rootscope, $tgrepo, $confirm, $loading, $qqueue) ->
template = _.template("""
<fieldset title="Feeling a bit overwhelmed by a task? Make sure others know about it by clicking on Iocaine when editing a task. It's possible to become immune to this (fictional) deadly poison by consuming small amounts over time just as it's possible to get better at what you do by occasionally taking on extra challenges!">
<label for="is-iocaine"
class="button button-gray is-iocaine <% if(isEditable){ %>editable<% }; %> <% if(isIocaine){ %>active<% }; %>">
Iocaine
</label>
<input type="checkbox" id="is-iocaine" name="is-iocaine"/>
</fieldset>
""")
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) ->
if not isEditable() and not task.is_iocaine
$el.html("")
return
ctx = {
isIocaine: task.is_iocaine
isEditable: isEditable()
}
html = template(ctx)
$el.html(html)
save = $qqueue.bindAdd (is_iocaine) =>
task = $model.$modelValue.clone()
task.is_iocaine = is_iocaine
$model.$setViewValue(task)
$loading.start($el.find('label'))
promise = $tgrepo.save(task)
promise.then ->
$confirm.notify("success")
$rootscope.$broadcast("history:reload")
promise.then null, ->
task.revert()
$model.$setViewValue(task)
$confirm.notify("error")
promise.finally ->
$loading.finish($el.find('label'))
$el.on "click", ".is-iocaine", (event) ->
return if not isEditable()
is_iocaine = not $model.$modelValue.is_iocaine
save(is_iocaine)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskIsIocaineButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", TaskIsIocaineButtonDirective])
| 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/tasks/detail.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
groupBy = @.taiga.groupBy
module = angular.module("taigaTasks")
#############################################################################
## Task Detail Controller
#############################################################################
class TaskDetailController extends mixOf(taiga.Controller, taiga.PageMixin)
@.$inject = [
"$scope",
"$rootScope",
"$tgRepo",
"$tgConfirm",
"$tgResources",
"$routeParams",
"$q",
"$tgLocation",
"$log",
"$appTitle",
"$tgNavUrls",
"$tgAnalytics",
"tgLoader"
]
constructor: (@scope, @rootscope, @repo, @confirm, @rs, @params, @q, @location,
@log, @appTitle, @navUrls, @analytics, tgLoader) ->
@scope.taskRef = @params.taskref
@scope.sectionName = "Task Details"
@.initializeEventHandlers()
promise = @.loadInitialData()
promise.then () =>
@appTitle.set(@scope.task.subject + " - " + @scope.project.name)
@.initializeOnDeleteGoToUrl()
tgLoader.pageLoaded()
promise.then null, @.onInitialDataError.bind(@)
initializeEventHandlers: ->
@scope.$on "attachment:create", =>
@analytics.trackEvent("attachment", "create", "create attachment on task", 1)
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:edit", =>
@rootscope.$broadcast("history:reload")
@scope.$on "attachment:delete", =>
@rootscope.$broadcast("history:reload")
initializeOnDeleteGoToUrl: ->
ctx = {project: @scope.project.slug}
@scope.onDeleteGoToUrl = @navUrls.resolve("project", ctx)
if @scope.project.is_backlog_activated
if @scope.task.milestone
ctx.sprint = @scope.sprint.slug
@scope.onDeleteGoToUrl = @navUrls.resolve("project-taskboard", ctx)
else if @scope.task.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
else if @scope.project.is_kanban_activated
if @scope.us
ctx.ref = @scope.us.ref
@scope.onDeleteGoToUrl = @navUrls.resolve("project-userstories-detail", ctx)
loadProject: ->
return @rs.projects.get(@scope.projectId).then (project) =>
@scope.project = project
@scope.$emit('project:loaded', project)
@scope.statusList = project.task_statuses
@scope.statusById = groupBy(project.task_statuses, (x) -> x.id)
@scope.membersById = groupBy(project.memberships, (x) -> x.user)
return project
loadTask: ->
return @rs.tasks.get(@scope.projectId, @scope.taskId).then (task) =>
@scope.task = task
@scope.commentModel = task
if @scope.task.neighbors.previous.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.previous.ref
}
@scope.previousUrl = @navUrls.resolve("project-tasks-detail", ctx)
if @scope.task.neighbors.next.ref?
ctx = {
project: @scope.project.slug
ref: @scope.task.neighbors.next.ref
}
@scope.nextUrl = @navUrls.resolve("project-tasks-detail", ctx)
return task
loadSprint: ->
if @scope.task.milestone
return @rs.sprints.get(@scope.task.project, @scope.task.milestone).then (sprint) =>
@scope.sprint = sprint
return sprint
loadUserStory: ->
if @scope.task.user_story
return @rs.userstories.get(@scope.task.project, @scope.task.user_story).then (us) =>
@scope.us = us
return us
loadInitialData: ->
params = {
pslug: @params.pslug
taskref: @params.taskref
}
promise = @repo.resolve(params).then (data) =>
@scope.projectId = data.project
@scope.taskId = data.task
return data
return promise.then(=> @.loadProject())
.then(=> @.loadUsersAndRoles())
.then(=> @.loadTask().then(=> @q.all([@.loadUserStory(),
@.loadSprint()])))
module.controller("TaskDetailController", TaskDetailController)
#############################################################################
## Task status display directive
#############################################################################
TaskStatusDisplayDirective = ->
# Display if a Task is open or closed and its taskboard status.
#
# Example:
# tg-task-status-display(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
template = _.template("""
<span>
<% if (status.is_closed) { %>
Closed
<% } else { %>
Open
<% } %>
</span>
<span class="us-detail-status" style="color:<%- status.color %>">
<%- status.name %>
</span>
""") # TODO: i18n
link = ($scope, $el, $attrs) ->
render = (task) ->
html = template({
status: $scope.statusById[task.status]
})
$el.html(html)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task?
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusDisplay", TaskStatusDisplayDirective)
#############################################################################
## Task status button directive
#############################################################################
TaskStatusButtonDirective = ($rootScope, $repo, $confirm, $loading, $qqueue) ->
# Display the status of Task and you can edit it.
#
# Example:
# tg-task-status-button(ng-model="task")
#
# Requirements:
# - Task object (ng-model)
# - scope.statusById object
# - $scope.project.my_permissions
template = _.template("""
<div class="status-data <% if(editable){ %>clickable<% }%>">
<span class="level" style="background-color:<%- status.color %>"></span>
<span class="status-status"><%- status.name %></span>
<% if(editable){ %><span class="icon icon-arrow-bottom"></span><% }%>
<span class="level-name">status</span>
<ul class="popover pop-status">
<% _.each(statuses, function(st) { %>
<li><a href="" class="status" title="<%- st.name %>"
data-status-id="<%- st.id %>"><%- st.name %></a></li>
<% }); %>
</ul>
</div>
""") #TODO: i18n
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) =>
status = $scope.statusById[task.status]
html = template({
status: status
statuses: $scope.statusList
editable: isEditable()
})
$el.html(html)
save = $qqueue.bindAdd (status) =>
task = $model.$modelValue.clone()
task.status = status
$model.$setViewValue(task)
onSuccess = ->
$confirm.notify("success")
$rootScope.$broadcast("history:reload")
$loading.finish($el.find(".level-name"))
onError = ->
$confirm.notify("error")
task.revert()
$model.$setViewValue(task)
$loading.finish($el.find(".level-name"))
$loading.start($el.find(".level-name"))
$repo.save($model.$modelValue).then(onSuccess, onError)
$el.on "click", ".status-data", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
$el.find(".pop-status").popover().open()
$el.on "click", ".status", (event) ->
event.preventDefault()
event.stopPropagation()
return if not isEditable()
target = angular.element(event.currentTarget)
$.fn.popover().closeAll()
save(target.data("status-id"))
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskStatusButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue",
TaskStatusButtonDirective])
TaskIsIocaineButtonDirective = ($rootscope, $tgrepo, $confirm, $loading, $qqueue) ->
template = _.template("""
<fieldset title="Feeling a bit overwhelmed by a task? Make sure others know about it by clicking on Iocaine when editing a task. It's possible to become immune to this (fictional) deadly poison by consuming small amounts over time just as it's possible to get better at what you do by occasionally taking on extra challenges!">
<label for="is-iocaine"
class="button button-gray is-iocaine <% if(isEditable){ %>editable<% }; %> <% if(isIocaine){ %>active<% }; %>">
Iocaine
</label>
<input type="checkbox" id="is-iocaine" name="is-iocaine"/>
</fieldset>
""")
link = ($scope, $el, $attrs, $model) ->
isEditable = ->
return $scope.project.my_permissions.indexOf("modify_task") != -1
render = (task) ->
if not isEditable() and not task.is_iocaine
$el.html("")
return
ctx = {
isIocaine: task.is_iocaine
isEditable: isEditable()
}
html = template(ctx)
$el.html(html)
save = $qqueue.bindAdd (is_iocaine) =>
task = $model.$modelValue.clone()
task.is_iocaine = is_iocaine
$model.$setViewValue(task)
$loading.start($el.find('label'))
promise = $tgrepo.save(task)
promise.then ->
$confirm.notify("success")
$rootscope.$broadcast("history:reload")
promise.then null, ->
task.revert()
$model.$setViewValue(task)
$confirm.notify("error")
promise.finally ->
$loading.finish($el.find('label'))
$el.on "click", ".is-iocaine", (event) ->
return if not isEditable()
is_iocaine = not $model.$modelValue.is_iocaine
save(is_iocaine)
$scope.$watch $attrs.ngModel, (task) ->
render(task) if task
$scope.$on "$destroy", ->
$el.off()
return {
link: link
restrict: "EA"
require: "ngModel"
}
module.directive("tgTaskIsIocaineButton", ["$rootScope", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgQqueue", TaskIsIocaineButtonDirective])
|
[
{
"context": "ull: false\n password:\n type: DataTypes.STRING\n allowNull: false\n occupation:\n ",
"end": 947,
"score": 0.5981417894363403,
"start": 941,
"tag": "PASSWORD",
"value": "STRING"
}
] | GOTHAM/Backend/src/Database/Models/Identity.coffee | perara/gotham | 0 |
module.exports = (sequelize, DataTypes) ->
return sequelize.define 'Identity', {
id:
type: DataTypes.INTEGER
allowNull: false
primaryKey: true
autoIncrement: true
fk_user:
type: DataTypes.INTEGER
allowNull: false
references: 'user'
referencesKey: 'id'
first_name:
type: DataTypes.STRING
allowNull: false
last_name:
type: DataTypes.STRING
allowNull: false
birthday:
type: DataTypes.STRING
allowNull: false
address:
type: DataTypes.STRING
allowNull: false
city:
type: DataTypes.STRING
allowNull: false
country:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
username:
type: DataTypes.STRING
allowNull: false
password:
type: DataTypes.STRING
allowNull: false
occupation:
type: DataTypes.STRING
allowNull: false
company:
type: DataTypes.STRING
allowNull: false
lat:
type: DataTypes.DECIMAL
allowNull: false
lng:
type: DataTypes.DECIMAL
allowNull: false
active:
type: DataTypes.BOOLEAN
allowNull: false
},
{
tableName: 'identity'
timestamps: false
}
| 56123 |
module.exports = (sequelize, DataTypes) ->
return sequelize.define 'Identity', {
id:
type: DataTypes.INTEGER
allowNull: false
primaryKey: true
autoIncrement: true
fk_user:
type: DataTypes.INTEGER
allowNull: false
references: 'user'
referencesKey: 'id'
first_name:
type: DataTypes.STRING
allowNull: false
last_name:
type: DataTypes.STRING
allowNull: false
birthday:
type: DataTypes.STRING
allowNull: false
address:
type: DataTypes.STRING
allowNull: false
city:
type: DataTypes.STRING
allowNull: false
country:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
username:
type: DataTypes.STRING
allowNull: false
password:
type: DataTypes.<PASSWORD>
allowNull: false
occupation:
type: DataTypes.STRING
allowNull: false
company:
type: DataTypes.STRING
allowNull: false
lat:
type: DataTypes.DECIMAL
allowNull: false
lng:
type: DataTypes.DECIMAL
allowNull: false
active:
type: DataTypes.BOOLEAN
allowNull: false
},
{
tableName: 'identity'
timestamps: false
}
| true |
module.exports = (sequelize, DataTypes) ->
return sequelize.define 'Identity', {
id:
type: DataTypes.INTEGER
allowNull: false
primaryKey: true
autoIncrement: true
fk_user:
type: DataTypes.INTEGER
allowNull: false
references: 'user'
referencesKey: 'id'
first_name:
type: DataTypes.STRING
allowNull: false
last_name:
type: DataTypes.STRING
allowNull: false
birthday:
type: DataTypes.STRING
allowNull: false
address:
type: DataTypes.STRING
allowNull: false
city:
type: DataTypes.STRING
allowNull: false
country:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
username:
type: DataTypes.STRING
allowNull: false
password:
type: DataTypes.PI:PASSWORD:<PASSWORD>END_PI
allowNull: false
occupation:
type: DataTypes.STRING
allowNull: false
company:
type: DataTypes.STRING
allowNull: false
lat:
type: DataTypes.DECIMAL
allowNull: false
lng:
type: DataTypes.DECIMAL
allowNull: false
active:
type: DataTypes.BOOLEAN
allowNull: false
},
{
tableName: 'identity'
timestamps: false
}
|
[
{
"context": "ck utilized in the application framework.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Call",
"end": 162,
"score": 0.9997761249542236,
"start": 150,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/specification/Callbacks.coffee | qrefdev/qref | 0 | ###
Specification class for the purpose of documenting the signatures and parameters of the callback utilized in the application framework.
@author Nathan Klick
@copyright QRef 2012
@abstract
###
class Callbacks
###
Standard callback used in the DB Manager utility classes for deeply populating a single object.
@param err [Error] An error object if an error occurred or null otherwise.
@param item [Object] The resulting deeply populated object.
###
managerExpandItemCallback: (err, item) ->
###
Standard callback used in the DB Manager utility class for deeply populating arrays of objects.
@param err [Error] An error object if an error occurred or null otherwise.
@param newArray [Array<Object>] The resulting deeply populated array of objects.
###
managerExpandArrayCallback: (err, newArray) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a credential validation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthValidateCredentialCallback: (err, isValid) ->
###
Standard callback used by the {UserAuth#login} method to return the status and token from an authentication operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param token [String] A valid token if successful otherwise null.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthLoginCallback: (err, token, isValid) ->
###
Standard callback used by the {UserAuth#userFromToken} method to return the status and user from a lookup operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param user [UserSchemaInternal] The user associated with the token or null if failed.
###
userAuthUserFromTokenCallback: (err, user) ->
###
Standard callback used by the {UserAuth#createAccount} method to return the status from a user creation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param success [Boolean] True if the operation was successful, false otherwise.
@param errorCode [Number] A numeric errorCode indicating why the request failed or zero otherwise.
###
userAuthCreateAccountCallback: (err, success, errorCode) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a role check operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isInRole [Boolean] An true/false value indicating if the user has the specified role. True indicates that the user possesses the specified role.
###
userAuthIsInRoleCallback: (err, isInRole) ->
module.exports = Callbacks | 117241 | ###
Specification class for the purpose of documenting the signatures and parameters of the callback utilized in the application framework.
@author <NAME>
@copyright QRef 2012
@abstract
###
class Callbacks
###
Standard callback used in the DB Manager utility classes for deeply populating a single object.
@param err [Error] An error object if an error occurred or null otherwise.
@param item [Object] The resulting deeply populated object.
###
managerExpandItemCallback: (err, item) ->
###
Standard callback used in the DB Manager utility class for deeply populating arrays of objects.
@param err [Error] An error object if an error occurred or null otherwise.
@param newArray [Array<Object>] The resulting deeply populated array of objects.
###
managerExpandArrayCallback: (err, newArray) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a credential validation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthValidateCredentialCallback: (err, isValid) ->
###
Standard callback used by the {UserAuth#login} method to return the status and token from an authentication operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param token [String] A valid token if successful otherwise null.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthLoginCallback: (err, token, isValid) ->
###
Standard callback used by the {UserAuth#userFromToken} method to return the status and user from a lookup operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param user [UserSchemaInternal] The user associated with the token or null if failed.
###
userAuthUserFromTokenCallback: (err, user) ->
###
Standard callback used by the {UserAuth#createAccount} method to return the status from a user creation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param success [Boolean] True if the operation was successful, false otherwise.
@param errorCode [Number] A numeric errorCode indicating why the request failed or zero otherwise.
###
userAuthCreateAccountCallback: (err, success, errorCode) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a role check operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isInRole [Boolean] An true/false value indicating if the user has the specified role. True indicates that the user possesses the specified role.
###
userAuthIsInRoleCallback: (err, isInRole) ->
module.exports = Callbacks | true | ###
Specification class for the purpose of documenting the signatures and parameters of the callback utilized in the application framework.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
@abstract
###
class Callbacks
###
Standard callback used in the DB Manager utility classes for deeply populating a single object.
@param err [Error] An error object if an error occurred or null otherwise.
@param item [Object] The resulting deeply populated object.
###
managerExpandItemCallback: (err, item) ->
###
Standard callback used in the DB Manager utility class for deeply populating arrays of objects.
@param err [Error] An error object if an error occurred or null otherwise.
@param newArray [Array<Object>] The resulting deeply populated array of objects.
###
managerExpandArrayCallback: (err, newArray) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a credential validation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthValidateCredentialCallback: (err, isValid) ->
###
Standard callback used by the {UserAuth#login} method to return the status and token from an authentication operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param token [String] A valid token if successful otherwise null.
@param isValid [Boolean] An true/false value indicating if the credential was valid. True indicates a valid credential while false indicates failure or invalid credentials.
###
userAuthLoginCallback: (err, token, isValid) ->
###
Standard callback used by the {UserAuth#userFromToken} method to return the status and user from a lookup operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param user [UserSchemaInternal] The user associated with the token or null if failed.
###
userAuthUserFromTokenCallback: (err, user) ->
###
Standard callback used by the {UserAuth#createAccount} method to return the status from a user creation operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param success [Boolean] True if the operation was successful, false otherwise.
@param errorCode [Number] A numeric errorCode indicating why the request failed or zero otherwise.
###
userAuthCreateAccountCallback: (err, success, errorCode) ->
###
Standard callback used by the {UserAuth} security routines to return the status of a role check operation.
@param err [Error] An error object if an error occurred or null otherwise.
@param isInRole [Boolean] An true/false value indicating if the user has the specified role. True indicates that the user possesses the specified role.
###
userAuthIsInRoleCallback: (err, isInRole) ->
module.exports = Callbacks |
[
{
"context": "doctorLogin(user.login)\n vm.doctorPassword(user.password)\n ko.mapping.fromJS(defaultDoctor, {}, vm.",
"end": 2753,
"score": 0.8185861706733704,
"start": 2740,
"tag": "PASSWORD",
"value": "user.password"
},
{
"context": "Login\"\n \"Логин\"\n ]\n password: [\n \"Password\"\n \"Пароль\"\n \"Parol\"\n \"Парол\"\n ]",
"end": 3332,
"score": 0.997061014175415,
"start": 3324,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "ин\"\n ]\n password: [\n \"Password\"\n \"Пароль\"\n \"Parol\"\n \"Парол\"\n ]\n registrati",
"end": 3347,
"score": 0.9954476952552795,
"start": 3341,
"tag": "PASSWORD",
"value": "Пароль"
},
{
"context": "assword: [\n \"Password\"\n \"Пароль\"\n \"Parol\"\n \"Парол\"\n ]\n registrationForm: [\n ",
"end": 3361,
"score": 0.9980589151382446,
"start": 3356,
"tag": "PASSWORD",
"value": "Parol"
},
{
"context": " \"Password\"\n \"Пароль\"\n \"Parol\"\n \"Парол\"\n ]\n registrationForm: [\n \"Registratio",
"end": 3375,
"score": 0.9954865574836731,
"start": 3370,
"tag": "PASSWORD",
"value": "Парол"
},
{
"context": "ии\"\n \"Ro'yxatdan o'tish shakli\"\n \"Рўйҳатдан ўтиш шакли\"\n ]\n register: [\n \"Register\"\n",
"end": 3510,
"score": 0.7215461730957031,
"start": 3505,
"tag": "NAME",
"value": "дан ў"
},
{
"context": " \"Ro'yxatdan o'tish shakli\"\n \"Рўйҳатдан ўтиш шакли\"\n ]\n register: [\n \"Register\"\n \"Ре",
"end": 3519,
"score": 0.716448187828064,
"start": 3510,
"tag": "NAME",
"value": "тиш шакли"
},
{
"context": " \"Регистрация\"\n \"Ro'yxatdan o'tish\"\n \"Рўйҳатдан ўтиш\"\n ]\n firstName: [\n \"First ",
"end": 3615,
"score": 0.723294734954834,
"start": 3614,
"tag": "NAME",
"value": "ў"
},
{
"context": " \"Регистрация\"\n \"Ro'yxatdan o'tish\"\n \"Рўйҳатдан ўтиш\"\n ]\n firstName: [\n \"First name\"\n ",
"end": 3627,
"score": 0.8316718339920044,
"start": 3615,
"tag": "NAME",
"value": "йҳатдан ўтиш"
},
{
"context": "\n ]\n firstName: [\n \"First name\"\n \"Имя\"\n \"Ism\"\n \"Исм\"\n ]\n lastName: [\n ",
"end": 3681,
"score": 0.998298168182373,
"start": 3678,
"tag": "NAME",
"value": "Имя"
},
{
"context": "irstName: [\n \"First name\"\n \"Имя\"\n \"Ism\"\n \"Исм\"\n ]\n lastName: [\n \"Last na",
"end": 3693,
"score": 0.9976330399513245,
"start": 3690,
"tag": "NAME",
"value": "Ism"
},
{
"context": " \"First name\"\n \"Имя\"\n \"Ism\"\n \"Исм\"\n ]\n lastName: [\n \"Last name\"\n \"Ф",
"end": 3705,
"score": 0.9957335591316223,
"start": 3702,
"tag": "NAME",
"value": "Исм"
},
{
"context": "м\"\n ]\n lastName: [\n \"Last name\"\n \"Фамилия\"\n \"Familiya\"\n \"Фамилия\"\n ]\n email",
"end": 3761,
"score": 0.9962817430496216,
"start": 3754,
"tag": "NAME",
"value": "Фамилия"
},
{
"context": "tName: [\n \"Last name\"\n \"Фамилия\"\n \"Familiya\"\n \"Фамилия\"\n ]\n email: [\n \"Email\"",
"end": 3778,
"score": 0.9974262714385986,
"start": 3770,
"tag": "NAME",
"value": "Familiya"
},
{
"context": "ast name\"\n \"Фамилия\"\n \"Familiya\"\n \"Фамилия\"\n ]\n email: [\n \"Email\"\n \"Эл. адре",
"end": 3794,
"score": 0.9897200465202332,
"start": 3787,
"tag": "NAME",
"value": "Фамилия"
},
{
"context": " \"Email\"\n \"Эл. адрес\"\n \"Email\"\n \"Емаил\"\n ]\n phoneNumber: [\n \"Phone number\"\n ",
"end": 3873,
"score": 0.8039485216140747,
"start": 3868,
"tag": "NAME",
"value": "Емаил"
}
] | app/assets/javascripts/admin.coffee | behruz-b/medical | 8 | $ ->
my.initAjax()
Glob = window.Glob || {}
apiUrl =
addDoctor: '/doc/add-doctor'
getRole: '/admin/get-roles'
defaultDoctor =
firstName: ''
lastName: ''
email: ''
phone: ''
login: ''
role: ''
companyCode: ''
vm = ko.mapping.fromJS
doctor: defaultDoctor
customerId: ''
language: Glob.language
doctorLogin: ''
doctorPassword: ''
getRoleTypeList: []
handleError = (error) ->
$.unblockUI()
if error.status is 401
my.logout()
else if error.status is 500 or (error.status is 400 and error.responseText)
toastr.error(error.responseText)
else
toastr.error('Something went wrong! Please try again.')
$('#show_hide_password a').on 'click', (event) ->
event.preventDefault()
if $('#show_hide_password input').attr('type') == 'text'
$('#show_hide_password input').attr 'type', 'password'
$('#show_hide_password i').addClass 'fa-eye-slash'
$('#show_hide_password i').removeClass 'fa-eye'
else if $('#show_hide_password input').attr('type') == 'password'
$('#show_hide_password input').attr 'type', 'text'
$('#show_hide_password i').removeClass 'fa-eye-slash'
$('#show_hide_password i').addClass 'fa-eye'
vm.getRoleType = ->
$.get(apiUrl.getRole)
.fail handleError
.done (response) ->
vm.getRoleTypeList(response)
$thankYou = $('#thankYou')
vm.onSubmit = ->
toastr.clear()
if !vm.doctor.firstName()
toastr.error("Iltimos ismni kiriting!")
return no
else if !vm.doctor.lastName()
toastr.error("Iltimos familiyani kiriting!")
return no
else if vm.doctor.email() and !my.isValidEmail(vm.doctor.email())
toastr.error("Iltimos emailni to'gri kiriting!")
return no
else if !vm.doctor.phone()
toastr.error("Iltimos telefon raqamni kiriting!")
return no
else if vm.doctor.phone() and !my.isValidPhone(vm.doctor.phone().replace(/[(|)|-]/g, "").trim())
toastr.error("Iltimos telefon raqamni to'gri kiriting!")
return no
else if !vm.doctor.login()
toastr.error("Iltimos loginni kiriting!")
return no
else if !vm.doctor.role()
toastr.error("Iltimos tizimdagi vazifasini tanlang!")
return no
else
doctor =
firstName: vm.doctor.firstName()
lastName: vm.doctor.lastName()
email: vm.doctor.email()
phone: vm.doctor.phone().replace(/[(|)|-]/g, "").trim()
login: vm.doctor.login()
role: vm.doctor.role()
company_code: window.location.host
$.post(apiUrl.addDoctor, JSON.stringify(doctor))
.fail handleError
.done (user) ->
vm.doctorLogin(user.login)
vm.doctorPassword(user.password)
ko.mapping.fromJS(defaultDoctor, {}, vm.doctor)
$thankYou.modal('show')
vm.translate = (fieldName) -> ko.computed () ->
index = if vm.language() is 'en' then 0 else if vm.language() is 'ru' then 1 else if vm.language() is 'uz' then 2 else if vm.language() is 'cy' then 3 else 4
vm.labels[fieldName][index]
vm.labels =
adminPanel: [
"Admin Panel"
"Панель администратора"
"Admin boshqaruvi"
"Aдмин бошқаруви"
]
login: [
"Login"
"Логин"
"Login"
"Логин"
]
password: [
"Password"
"Пароль"
"Parol"
"Парол"
]
registrationForm: [
"Registration Form"
"Форма регистрации"
"Ro'yxatdan o'tish shakli"
"Рўйҳатдан ўтиш шакли"
]
register: [
"Register"
"Регистрация"
"Ro'yxatdan o'tish"
"Рўйҳатдан ўтиш"
]
firstName: [
"First name"
"Имя"
"Ism"
"Исм"
]
lastName: [
"Last name"
"Фамилия"
"Familiya"
"Фамилия"
]
email: [
"Email"
"Эл. адрес"
"Email"
"Емаил"
]
phoneNumber: [
"Phone number"
"Телефонный номер"
"Telefon raqami"
"Телефон рақами"
]
selectRole: [
"Select role"
"Выберите роль"
"Rolni tanlang"
"Ролни танланг"
]
thankYou: [
"Thank you!"
"Спасибо!"
"Rahmat! Siz ro'yxatdan o'tdingiz!"
"Раҳмат! Сиз рўйҳатдан ўтдингиз!"
]
closeModal: [
"Close"
"Закрыть"
"Yopish"
"Ёпиш"
]
ko.applyBindings {vm} | 172476 | $ ->
my.initAjax()
Glob = window.Glob || {}
apiUrl =
addDoctor: '/doc/add-doctor'
getRole: '/admin/get-roles'
defaultDoctor =
firstName: ''
lastName: ''
email: ''
phone: ''
login: ''
role: ''
companyCode: ''
vm = ko.mapping.fromJS
doctor: defaultDoctor
customerId: ''
language: Glob.language
doctorLogin: ''
doctorPassword: ''
getRoleTypeList: []
handleError = (error) ->
$.unblockUI()
if error.status is 401
my.logout()
else if error.status is 500 or (error.status is 400 and error.responseText)
toastr.error(error.responseText)
else
toastr.error('Something went wrong! Please try again.')
$('#show_hide_password a').on 'click', (event) ->
event.preventDefault()
if $('#show_hide_password input').attr('type') == 'text'
$('#show_hide_password input').attr 'type', 'password'
$('#show_hide_password i').addClass 'fa-eye-slash'
$('#show_hide_password i').removeClass 'fa-eye'
else if $('#show_hide_password input').attr('type') == 'password'
$('#show_hide_password input').attr 'type', 'text'
$('#show_hide_password i').removeClass 'fa-eye-slash'
$('#show_hide_password i').addClass 'fa-eye'
vm.getRoleType = ->
$.get(apiUrl.getRole)
.fail handleError
.done (response) ->
vm.getRoleTypeList(response)
$thankYou = $('#thankYou')
vm.onSubmit = ->
toastr.clear()
if !vm.doctor.firstName()
toastr.error("Iltimos ismni kiriting!")
return no
else if !vm.doctor.lastName()
toastr.error("Iltimos familiyani kiriting!")
return no
else if vm.doctor.email() and !my.isValidEmail(vm.doctor.email())
toastr.error("Iltimos emailni to'gri kiriting!")
return no
else if !vm.doctor.phone()
toastr.error("Iltimos telefon raqamni kiriting!")
return no
else if vm.doctor.phone() and !my.isValidPhone(vm.doctor.phone().replace(/[(|)|-]/g, "").trim())
toastr.error("Iltimos telefon raqamni to'gri kiriting!")
return no
else if !vm.doctor.login()
toastr.error("Iltimos loginni kiriting!")
return no
else if !vm.doctor.role()
toastr.error("Iltimos tizimdagi vazifasini tanlang!")
return no
else
doctor =
firstName: vm.doctor.firstName()
lastName: vm.doctor.lastName()
email: vm.doctor.email()
phone: vm.doctor.phone().replace(/[(|)|-]/g, "").trim()
login: vm.doctor.login()
role: vm.doctor.role()
company_code: window.location.host
$.post(apiUrl.addDoctor, JSON.stringify(doctor))
.fail handleError
.done (user) ->
vm.doctorLogin(user.login)
vm.doctorPassword(<PASSWORD>)
ko.mapping.fromJS(defaultDoctor, {}, vm.doctor)
$thankYou.modal('show')
vm.translate = (fieldName) -> ko.computed () ->
index = if vm.language() is 'en' then 0 else if vm.language() is 'ru' then 1 else if vm.language() is 'uz' then 2 else if vm.language() is 'cy' then 3 else 4
vm.labels[fieldName][index]
vm.labels =
adminPanel: [
"Admin Panel"
"Панель администратора"
"Admin boshqaruvi"
"Aдмин бошқаруви"
]
login: [
"Login"
"Логин"
"Login"
"Логин"
]
password: [
"<PASSWORD>"
"<PASSWORD>"
"<PASSWORD>"
"<PASSWORD>"
]
registrationForm: [
"Registration Form"
"Форма регистрации"
"Ro'yxatdan o'tish shakli"
"Рўйҳат<NAME> <NAME>"
]
register: [
"Register"
"Регистрация"
"Ro'yxatdan o'tish"
"Р<NAME> <NAME>"
]
firstName: [
"First name"
"<NAME>"
"<NAME>"
"<NAME>"
]
lastName: [
"Last name"
"<NAME>"
"<NAME>"
"<NAME>"
]
email: [
"Email"
"Эл. адрес"
"Email"
"<NAME>"
]
phoneNumber: [
"Phone number"
"Телефонный номер"
"Telefon raqami"
"Телефон рақами"
]
selectRole: [
"Select role"
"Выберите роль"
"Rolni tanlang"
"Ролни танланг"
]
thankYou: [
"Thank you!"
"Спасибо!"
"Rahmat! Siz ro'yxatdan o'tdingiz!"
"Раҳмат! Сиз рўйҳатдан ўтдингиз!"
]
closeModal: [
"Close"
"Закрыть"
"Yopish"
"Ёпиш"
]
ko.applyBindings {vm} | true | $ ->
my.initAjax()
Glob = window.Glob || {}
apiUrl =
addDoctor: '/doc/add-doctor'
getRole: '/admin/get-roles'
defaultDoctor =
firstName: ''
lastName: ''
email: ''
phone: ''
login: ''
role: ''
companyCode: ''
vm = ko.mapping.fromJS
doctor: defaultDoctor
customerId: ''
language: Glob.language
doctorLogin: ''
doctorPassword: ''
getRoleTypeList: []
handleError = (error) ->
$.unblockUI()
if error.status is 401
my.logout()
else if error.status is 500 or (error.status is 400 and error.responseText)
toastr.error(error.responseText)
else
toastr.error('Something went wrong! Please try again.')
$('#show_hide_password a').on 'click', (event) ->
event.preventDefault()
if $('#show_hide_password input').attr('type') == 'text'
$('#show_hide_password input').attr 'type', 'password'
$('#show_hide_password i').addClass 'fa-eye-slash'
$('#show_hide_password i').removeClass 'fa-eye'
else if $('#show_hide_password input').attr('type') == 'password'
$('#show_hide_password input').attr 'type', 'text'
$('#show_hide_password i').removeClass 'fa-eye-slash'
$('#show_hide_password i').addClass 'fa-eye'
vm.getRoleType = ->
$.get(apiUrl.getRole)
.fail handleError
.done (response) ->
vm.getRoleTypeList(response)
$thankYou = $('#thankYou')
vm.onSubmit = ->
toastr.clear()
if !vm.doctor.firstName()
toastr.error("Iltimos ismni kiriting!")
return no
else if !vm.doctor.lastName()
toastr.error("Iltimos familiyani kiriting!")
return no
else if vm.doctor.email() and !my.isValidEmail(vm.doctor.email())
toastr.error("Iltimos emailni to'gri kiriting!")
return no
else if !vm.doctor.phone()
toastr.error("Iltimos telefon raqamni kiriting!")
return no
else if vm.doctor.phone() and !my.isValidPhone(vm.doctor.phone().replace(/[(|)|-]/g, "").trim())
toastr.error("Iltimos telefon raqamni to'gri kiriting!")
return no
else if !vm.doctor.login()
toastr.error("Iltimos loginni kiriting!")
return no
else if !vm.doctor.role()
toastr.error("Iltimos tizimdagi vazifasini tanlang!")
return no
else
doctor =
firstName: vm.doctor.firstName()
lastName: vm.doctor.lastName()
email: vm.doctor.email()
phone: vm.doctor.phone().replace(/[(|)|-]/g, "").trim()
login: vm.doctor.login()
role: vm.doctor.role()
company_code: window.location.host
$.post(apiUrl.addDoctor, JSON.stringify(doctor))
.fail handleError
.done (user) ->
vm.doctorLogin(user.login)
vm.doctorPassword(PI:PASSWORD:<PASSWORD>END_PI)
ko.mapping.fromJS(defaultDoctor, {}, vm.doctor)
$thankYou.modal('show')
vm.translate = (fieldName) -> ko.computed () ->
index = if vm.language() is 'en' then 0 else if vm.language() is 'ru' then 1 else if vm.language() is 'uz' then 2 else if vm.language() is 'cy' then 3 else 4
vm.labels[fieldName][index]
vm.labels =
adminPanel: [
"Admin Panel"
"Панель администратора"
"Admin boshqaruvi"
"Aдмин бошқаруви"
]
login: [
"Login"
"Логин"
"Login"
"Логин"
]
password: [
"PI:PASSWORD:<PASSWORD>END_PI"
"PI:PASSWORD:<PASSWORD>END_PI"
"PI:PASSWORD:<PASSWORD>END_PI"
"PI:PASSWORD:<PASSWORD>END_PI"
]
registrationForm: [
"Registration Form"
"Форма регистрации"
"Ro'yxatdan o'tish shakli"
"РўйҳатPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
]
register: [
"Register"
"Регистрация"
"Ro'yxatdan o'tish"
"РPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
]
firstName: [
"First name"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
lastName: [
"Last name"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
email: [
"Email"
"Эл. адрес"
"Email"
"PI:NAME:<NAME>END_PI"
]
phoneNumber: [
"Phone number"
"Телефонный номер"
"Telefon raqami"
"Телефон рақами"
]
selectRole: [
"Select role"
"Выберите роль"
"Rolni tanlang"
"Ролни танланг"
]
thankYou: [
"Thank you!"
"Спасибо!"
"Rahmat! Siz ro'yxatdan o'tdingiz!"
"Раҳмат! Сиз рўйҳатдан ўтдингиз!"
]
closeModal: [
"Close"
"Закрыть"
"Yopish"
"Ёпиш"
]
ko.applyBindings {vm} |
[
{
"context": " \"~/.emmet\"\n \"exception-reporting\":\n userId: \"3bb7ed5d-7c63-c5d7-ee9a-d8992962cfb3\"\n welcome:\n showOnStartup: false\n",
"end": 329,
"score": 0.8505613803863525,
"start": 293,
"tag": "PASSWORD",
"value": "3bb7ed5d-7c63-c5d7-ee9a-d8992962cfb3"
}
] | atom/config.cson | keithajackson/dotfiles-bash | 0 | "*":
"auto-run":
commands: [
"auto-update:update-now"
]
"auto-update-packages":
intervalMinutes: 15
core:
themes: [
"one-dark-ui"
"monokai"
]
editor:
invisibles: {}
emmet:
extensionsPath: "~/.emmet"
"exception-reporting":
userId: "3bb7ed5d-7c63-c5d7-ee9a-d8992962cfb3"
welcome:
showOnStartup: false
| 57 | "*":
"auto-run":
commands: [
"auto-update:update-now"
]
"auto-update-packages":
intervalMinutes: 15
core:
themes: [
"one-dark-ui"
"monokai"
]
editor:
invisibles: {}
emmet:
extensionsPath: "~/.emmet"
"exception-reporting":
userId: "<PASSWORD>"
welcome:
showOnStartup: false
| true | "*":
"auto-run":
commands: [
"auto-update:update-now"
]
"auto-update-packages":
intervalMinutes: 15
core:
themes: [
"one-dark-ui"
"monokai"
]
editor:
invisibles: {}
emmet:
extensionsPath: "~/.emmet"
"exception-reporting":
userId: "PI:PASSWORD:<PASSWORD>END_PI"
welcome:
showOnStartup: false
|
[
{
"context": "###*\n * # 显示表单验证错误信息\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Component} ",
"end": 38,
"score": 0.9996921420097351,
"start": 32,
"tag": "USERNAME",
"value": "vfasky"
},
{
"context": "###*\n * # 显示表单验证错误信息\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Component} = require 'mcore'\n",
"end": 56,
"score": 0.999917209148407,
"start": 40,
"tag": "EMAIL",
"value": "vfasky@gmail.com"
}
] | src/coffee/validator.coffee | vfasky/mcore-weui | 0 | ###*
* # 显示表单验证错误信息
* @author vfasky <vfasky@gmail.com>
###
'use strict'
{Component} = require 'mcore'
Dialog = require './dialog'
class Validator extends Component
getTarget: -> @errData.$el.data('proxyEl') or @errData.$el
showError: (@errData)->
$el = @getTarget().off('focus.weui_validator').focus()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$root = $parent.parent().addClass 'weui_cell_warn'
$ft = $root.find '.weui_cell_ft'
if $ft.length == 0
$ft = $ '<div class="weui_cell_ft"><i class="weui_icon_warn"></i></div>'
$ft.appendTo $root
$ft.find('.weui_icon_warn').attr 'title', @errData.err
.off('click.weui_validator')
.on 'click.weui_validator', =>
Dialog.alert @errData.err, null, '错误信息'
false
else
$el.addClass 'weui_cell_warn'
$el.attr 'title', @errData.err
$el.on 'focus.weui_validator', => @hideError()
.off('change.weui_validator').on 'change.weui_validator', => @hideError()
hideError: ->
$el = @getTarget()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$parent.parent().removeClass 'weui_cell_warn'
else
$el.removeClass 'weui_cell_warn'
$el.attr 'title', ''
module.exports = Validator
| 9805 | ###*
* # 显示表单验证错误信息
* @author vfasky <<EMAIL>>
###
'use strict'
{Component} = require 'mcore'
Dialog = require './dialog'
class Validator extends Component
getTarget: -> @errData.$el.data('proxyEl') or @errData.$el
showError: (@errData)->
$el = @getTarget().off('focus.weui_validator').focus()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$root = $parent.parent().addClass 'weui_cell_warn'
$ft = $root.find '.weui_cell_ft'
if $ft.length == 0
$ft = $ '<div class="weui_cell_ft"><i class="weui_icon_warn"></i></div>'
$ft.appendTo $root
$ft.find('.weui_icon_warn').attr 'title', @errData.err
.off('click.weui_validator')
.on 'click.weui_validator', =>
Dialog.alert @errData.err, null, '错误信息'
false
else
$el.addClass 'weui_cell_warn'
$el.attr 'title', @errData.err
$el.on 'focus.weui_validator', => @hideError()
.off('change.weui_validator').on 'change.weui_validator', => @hideError()
hideError: ->
$el = @getTarget()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$parent.parent().removeClass 'weui_cell_warn'
else
$el.removeClass 'weui_cell_warn'
$el.attr 'title', ''
module.exports = Validator
| true | ###*
* # 显示表单验证错误信息
* @author vfasky <PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
{Component} = require 'mcore'
Dialog = require './dialog'
class Validator extends Component
getTarget: -> @errData.$el.data('proxyEl') or @errData.$el
showError: (@errData)->
$el = @getTarget().off('focus.weui_validator').focus()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$root = $parent.parent().addClass 'weui_cell_warn'
$ft = $root.find '.weui_cell_ft'
if $ft.length == 0
$ft = $ '<div class="weui_cell_ft"><i class="weui_icon_warn"></i></div>'
$ft.appendTo $root
$ft.find('.weui_icon_warn').attr 'title', @errData.err
.off('click.weui_validator')
.on 'click.weui_validator', =>
Dialog.alert @errData.err, null, '错误信息'
false
else
$el.addClass 'weui_cell_warn'
$el.attr 'title', @errData.err
$el.on 'focus.weui_validator', => @hideError()
.off('change.weui_validator').on 'change.weui_validator', => @hideError()
hideError: ->
$el = @getTarget()
$parent = $el.parent()
if $parent.is('.weui_cell_bd')
$parent.parent().removeClass 'weui_cell_warn'
else
$el.removeClass 'weui_cell_warn'
$el.attr 'title', ''
module.exports = Validator
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9976469874382019,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "R DEALINGS IN THE SOFTWARE.\n\n# https://github.com/joyent/node/issues/4948\ncommon = require(\"../common\")\nht",
"end": 1141,
"score": 0.9996272325515747,
"start": 1135,
"tag": "USERNAME",
"value": "joyent"
}
] | test/simple/test-regress-GH-4948.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.
# https://github.com/joyent/node/issues/4948
common = require("../common")
http = require("http")
reqCount = 0
# normally the use case would be to call an external site
# does not require connecting locally or to itself to fail
# required, just needs to be in the client response somewhere
# required for test to fail
server = http.createServer((serverReq, serverRes) ->
if reqCount
serverRes.end()
server.close()
return
reqCount = 1
r = http.request(
hostname: "localhost"
port: common.PORT
, (res) ->
serverRes.end()
res.on "data", (data) ->
return
)
r.on "error", (e) ->
r.end()
serverRes.write "some data"
return
).listen(common.PORT)
# simulate a client request that closes early
net = require("net")
sock = new net.Socket()
sock.connect common.PORT, "localhost"
sock.on "connect", ->
sock.write "GET / HTTP/1.1\r\n\r\n"
sock.end()
return
| 91708 | # 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.
# https://github.com/joyent/node/issues/4948
common = require("../common")
http = require("http")
reqCount = 0
# normally the use case would be to call an external site
# does not require connecting locally or to itself to fail
# required, just needs to be in the client response somewhere
# required for test to fail
server = http.createServer((serverReq, serverRes) ->
if reqCount
serverRes.end()
server.close()
return
reqCount = 1
r = http.request(
hostname: "localhost"
port: common.PORT
, (res) ->
serverRes.end()
res.on "data", (data) ->
return
)
r.on "error", (e) ->
r.end()
serverRes.write "some data"
return
).listen(common.PORT)
# simulate a client request that closes early
net = require("net")
sock = new net.Socket()
sock.connect common.PORT, "localhost"
sock.on "connect", ->
sock.write "GET / HTTP/1.1\r\n\r\n"
sock.end()
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.
# https://github.com/joyent/node/issues/4948
common = require("../common")
http = require("http")
reqCount = 0
# normally the use case would be to call an external site
# does not require connecting locally or to itself to fail
# required, just needs to be in the client response somewhere
# required for test to fail
server = http.createServer((serverReq, serverRes) ->
if reqCount
serverRes.end()
server.close()
return
reqCount = 1
r = http.request(
hostname: "localhost"
port: common.PORT
, (res) ->
serverRes.end()
res.on "data", (data) ->
return
)
r.on "error", (e) ->
r.end()
serverRes.write "some data"
return
).listen(common.PORT)
# simulate a client request that closes early
net = require("net")
sock = new net.Socket()
sock.connect common.PORT, "localhost"
sock.on "connect", ->
sock.write "GET / HTTP/1.1\r\n\r\n"
sock.end()
return
|
[
{
"context": "llection = new Collection()\n\n constructor: (name: @name, client: client, sid: @sid, image: @image) ->",
"end": 264,
"score": 0.8599991202354431,
"start": 264,
"tag": "NAME",
"value": ""
},
{
"context": "ection = new Collection()\n\n constructor: (name: @name, client: client, sid: @sid, image: @image) ->\n ",
"end": 270,
"score": 0.8317093849182129,
"start": 266,
"tag": "USERNAME",
"value": "name"
},
{
"context": "tivity').emit('activity', what: 'newbidder', name: @name, image: @image)\n\n # unil we have workflow,",
"end": 480,
"score": 0.7452128529548645,
"start": 480,
"tag": "NAME",
"value": ""
},
{
"context": "vity').emit('activity', what: 'newbidder', name: @name, image: @image)\n\n # unil we have workflow, joi",
"end": 486,
"score": 0.6351200938224792,
"start": 482,
"tag": "USERNAME",
"value": "name"
},
{
"context": "ent.on 'trigger', (data) =>\n console.log \"got #{@name}:#{new_client.id} trigger: \", data\n\n new_clien",
"end": 753,
"score": 0.9325059652328491,
"start": 746,
"tag": "USERNAME",
"value": "#{@name"
},
{
"context": "ent.on 'bid', (data) =>\n console.log \"got bid #{@name}:#{new_client.id} bid: \", data\n if global.li",
"end": 859,
"score": 0.9649767875671387,
"start": 852,
"tag": "USERNAME",
"value": "#{@name"
},
{
"context": " new_client.join('activity')\n\n if @name == 'CharityBid'\n console.log \"admin actions for new connect",
"end": 1182,
"score": 0.9881404042243958,
"start": 1172,
"tag": "USERNAME",
"value": "CharityBid"
}
] | bidder.coffee | kartikmenda/livebids | 0 |
EE = if EventEmitter? then EventEmitter else require('events').EventEmitter
Collection = require('./collection').Collection
Auction = require('./auction').Auction
class Bidder extends EE
@last_used_id = 0
@collection = new Collection()
constructor: (name: @name, client: client, sid: @sid, image: @image) ->
@constructor.collection.add @
@new_client(client)
@state = "logged_out"
global.io.sockets.in('/activity').emit('activity', what: 'newbidder', name: @name, image: @image)
# unil we have workflow, join this bidder the live auction
global.live_auction.trigger 'bidder_joined', @
new_client: (new_client) ->
# set up bindings required....
new_client.on 'trigger', (data) =>
console.log "got #{@name}:#{new_client.id} trigger: ", data
new_client.on 'bid', (data) =>
console.log "got bid #{@name}:#{new_client.id} bid: ", data
if global.live_auction?
global.live_auction.trigger 'bid', data, @
else
console.log "no global live_auction to trigger bid to"
new_client.on 'activityview', =>
new_client.leave('/' + @sid)
new_client.join('activity')
if @name == 'CharityBid'
console.log "admin actions for new connected client"
@emit 'adminbuttons'
new_client.on 'stop_auction', () =>
if global.live_auction?
global.live_auction.trigger 'stop_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'going_auction', () =>
if global.live_auction?
global.live_auction.trigger 'going_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'restart_auction', () =>
if global.live_auction?
global.live_auction.trigger 'restart_auction', @
else
console.log "no global live_auction to trigger stop to"
@emit 'state', state: @state
if global.live_auction? and global.live_auction.current_bid?
@emit 'newbid', global.live_auction.current_bid
login: ->
@state = "logged_in"
logout: ->
@state = "logged_out"
# wrapper function to emit to the sid room
emit: (name, args) ->
global.io.sockets.in(@sid).emit(name, args)
send: (message) ->
global.io.sockets.in(@sid).send(message)
(exports ? window).Bidder = Bidder
| 166697 |
EE = if EventEmitter? then EventEmitter else require('events').EventEmitter
Collection = require('./collection').Collection
Auction = require('./auction').Auction
class Bidder extends EE
@last_used_id = 0
@collection = new Collection()
constructor: (name:<NAME> @name, client: client, sid: @sid, image: @image) ->
@constructor.collection.add @
@new_client(client)
@state = "logged_out"
global.io.sockets.in('/activity').emit('activity', what: 'newbidder', name:<NAME> @name, image: @image)
# unil we have workflow, join this bidder the live auction
global.live_auction.trigger 'bidder_joined', @
new_client: (new_client) ->
# set up bindings required....
new_client.on 'trigger', (data) =>
console.log "got #{@name}:#{new_client.id} trigger: ", data
new_client.on 'bid', (data) =>
console.log "got bid #{@name}:#{new_client.id} bid: ", data
if global.live_auction?
global.live_auction.trigger 'bid', data, @
else
console.log "no global live_auction to trigger bid to"
new_client.on 'activityview', =>
new_client.leave('/' + @sid)
new_client.join('activity')
if @name == 'CharityBid'
console.log "admin actions for new connected client"
@emit 'adminbuttons'
new_client.on 'stop_auction', () =>
if global.live_auction?
global.live_auction.trigger 'stop_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'going_auction', () =>
if global.live_auction?
global.live_auction.trigger 'going_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'restart_auction', () =>
if global.live_auction?
global.live_auction.trigger 'restart_auction', @
else
console.log "no global live_auction to trigger stop to"
@emit 'state', state: @state
if global.live_auction? and global.live_auction.current_bid?
@emit 'newbid', global.live_auction.current_bid
login: ->
@state = "logged_in"
logout: ->
@state = "logged_out"
# wrapper function to emit to the sid room
emit: (name, args) ->
global.io.sockets.in(@sid).emit(name, args)
send: (message) ->
global.io.sockets.in(@sid).send(message)
(exports ? window).Bidder = Bidder
| true |
EE = if EventEmitter? then EventEmitter else require('events').EventEmitter
Collection = require('./collection').Collection
Auction = require('./auction').Auction
class Bidder extends EE
@last_used_id = 0
@collection = new Collection()
constructor: (name:PI:NAME:<NAME>END_PI @name, client: client, sid: @sid, image: @image) ->
@constructor.collection.add @
@new_client(client)
@state = "logged_out"
global.io.sockets.in('/activity').emit('activity', what: 'newbidder', name:PI:NAME:<NAME>END_PI @name, image: @image)
# unil we have workflow, join this bidder the live auction
global.live_auction.trigger 'bidder_joined', @
new_client: (new_client) ->
# set up bindings required....
new_client.on 'trigger', (data) =>
console.log "got #{@name}:#{new_client.id} trigger: ", data
new_client.on 'bid', (data) =>
console.log "got bid #{@name}:#{new_client.id} bid: ", data
if global.live_auction?
global.live_auction.trigger 'bid', data, @
else
console.log "no global live_auction to trigger bid to"
new_client.on 'activityview', =>
new_client.leave('/' + @sid)
new_client.join('activity')
if @name == 'CharityBid'
console.log "admin actions for new connected client"
@emit 'adminbuttons'
new_client.on 'stop_auction', () =>
if global.live_auction?
global.live_auction.trigger 'stop_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'going_auction', () =>
if global.live_auction?
global.live_auction.trigger 'going_auction', @
else
console.log "no global live_auction to trigger stop to"
new_client.on 'restart_auction', () =>
if global.live_auction?
global.live_auction.trigger 'restart_auction', @
else
console.log "no global live_auction to trigger stop to"
@emit 'state', state: @state
if global.live_auction? and global.live_auction.current_bid?
@emit 'newbid', global.live_auction.current_bid
login: ->
@state = "logged_in"
logout: ->
@state = "logged_out"
# wrapper function to emit to the sid room
emit: (name, args) ->
global.io.sockets.in(@sid).emit(name, args)
send: (message) ->
global.io.sockets.in(@sid).send(message)
(exports ? window).Bidder = Bidder
|
[
{
"context": "] = Meteor.userId()\n uobj['X-Auth-Token'] = Accounts._storedLoginToken()\n url = Meteor.absoluteUrl() + 'api/workf",
"end": 628,
"score": 0.6867185831069946,
"start": 602,
"tag": "PASSWORD",
"value": "Accounts._storedLoginToken"
}
] | packages/steedos-creator/client/views/initiate_approval.coffee | zonglu233/fuel-car | 0 | Template.initiate_approval.helpers
flows: () ->
return _.where Creator.object_workflows, { object_name: this.object_name }
Template.initiate_approval.events
'click .weui_cell' : (e, t) ->
workflowUrl = window.location.protocol + '//' + window.location.host + '/'
flowId = e.currentTarget.dataset.flow
object_name = t.data.object_name
record_id = t.data.record_id
record_ids = [{ o: object_name, ids: [record_id] }]
uobj = {}
uobj.methodOverride = 'POST'
uobj['X-User-Id'] = Meteor.userId()
uobj['X-Auth-Token'] = Accounts._storedLoginToken()
url = Meteor.absoluteUrl() + 'api/workflow/drafts?' + $.param(uobj)
data = 'Instances': [ {
'flow': flowId
'applicant': Meteor.userId()
'space': Session.get('spaceId')
'record_ids': record_ids
} ]
data = JSON.stringify(data)
$(document.body).addClass 'loading'
$.ajax
url: url
type: 'POST'
async: true
data: data
dataType: 'json'
processData: false
contentType: 'application/json'
success: (responseText, status) ->
$(document.body).removeClass 'loading'
if responseText.errors
responseText.errors.forEach (e) ->
toastr.error e.errorMessage
return
return
instance = responseText.inserts[0]
# 跳转到APPS草稿
Steedos.openWindow workflowUrl + 'workflow/space/' + Session.get('spaceId') + '/draft/' + instance._id
return
error: (xhr, msg, ex) ->
$(document.body).removeClass 'loading'
toastr.error msg
return
return
| 88251 | Template.initiate_approval.helpers
flows: () ->
return _.where Creator.object_workflows, { object_name: this.object_name }
Template.initiate_approval.events
'click .weui_cell' : (e, t) ->
workflowUrl = window.location.protocol + '//' + window.location.host + '/'
flowId = e.currentTarget.dataset.flow
object_name = t.data.object_name
record_id = t.data.record_id
record_ids = [{ o: object_name, ids: [record_id] }]
uobj = {}
uobj.methodOverride = 'POST'
uobj['X-User-Id'] = Meteor.userId()
uobj['X-Auth-Token'] = <PASSWORD>()
url = Meteor.absoluteUrl() + 'api/workflow/drafts?' + $.param(uobj)
data = 'Instances': [ {
'flow': flowId
'applicant': Meteor.userId()
'space': Session.get('spaceId')
'record_ids': record_ids
} ]
data = JSON.stringify(data)
$(document.body).addClass 'loading'
$.ajax
url: url
type: 'POST'
async: true
data: data
dataType: 'json'
processData: false
contentType: 'application/json'
success: (responseText, status) ->
$(document.body).removeClass 'loading'
if responseText.errors
responseText.errors.forEach (e) ->
toastr.error e.errorMessage
return
return
instance = responseText.inserts[0]
# 跳转到APPS草稿
Steedos.openWindow workflowUrl + 'workflow/space/' + Session.get('spaceId') + '/draft/' + instance._id
return
error: (xhr, msg, ex) ->
$(document.body).removeClass 'loading'
toastr.error msg
return
return
| true | Template.initiate_approval.helpers
flows: () ->
return _.where Creator.object_workflows, { object_name: this.object_name }
Template.initiate_approval.events
'click .weui_cell' : (e, t) ->
workflowUrl = window.location.protocol + '//' + window.location.host + '/'
flowId = e.currentTarget.dataset.flow
object_name = t.data.object_name
record_id = t.data.record_id
record_ids = [{ o: object_name, ids: [record_id] }]
uobj = {}
uobj.methodOverride = 'POST'
uobj['X-User-Id'] = Meteor.userId()
uobj['X-Auth-Token'] = PI:PASSWORD:<PASSWORD>END_PI()
url = Meteor.absoluteUrl() + 'api/workflow/drafts?' + $.param(uobj)
data = 'Instances': [ {
'flow': flowId
'applicant': Meteor.userId()
'space': Session.get('spaceId')
'record_ids': record_ids
} ]
data = JSON.stringify(data)
$(document.body).addClass 'loading'
$.ajax
url: url
type: 'POST'
async: true
data: data
dataType: 'json'
processData: false
contentType: 'application/json'
success: (responseText, status) ->
$(document.body).removeClass 'loading'
if responseText.errors
responseText.errors.forEach (e) ->
toastr.error e.errorMessage
return
return
instance = responseText.inserts[0]
# 跳转到APPS草稿
Steedos.openWindow workflowUrl + 'workflow/space/' + Session.get('spaceId') + '/draft/' + instance._id
return
error: (xhr, msg, ex) ->
$(document.body).removeClass 'loading'
toastr.error msg
return
return
|
[
{
"context": "before ->\n @skip() if __globalTest.offline\n\n [Alice, Bob] = [null, null]\n it 'create mailboxes', ->\n",
"end": 518,
"score": 0.5226253271102905,
"start": 513,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ull]\n it 'create mailboxes', ->\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.ne",
"end": 590,
"score": 0.9953148365020752,
"start": 585,
"tag": "NAME",
"value": "Alice"
},
{
"context": "s', ->\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n ",
"end": 617,
"score": 0.9137420654296875,
"start": 612,
"tag": "NAME",
"value": "Alice"
},
{
"context": "then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n Alice.ke",
"end": 646,
"score": 0.9923335313796997,
"start": 643,
"tag": "NAME",
"value": "Bob"
},
{
"context": " ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n Alice.keyRing.addGuest('Bob', Bob.g",
"end": 673,
"score": 0.8655411005020142,
"start": 670,
"tag": "NAME",
"value": "Bob"
},
{
"context": " Bob = ret\n Alice.keyRing.addGuest('Bob', Bob.getPubCommKey()).then ->\n Bob.keyR",
"end": 715,
"score": 0.8993934988975525,
"start": 712,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ommKey()).then ->\n Bob.keyRing.addGuest('Alice', Alice.getPubCommKey())\n\n code1 = {id: 1, code:",
"end": 784,
"score": 0.9906461238861084,
"start": 779,
"tag": "NAME",
"value": "Alice"
},
{
"context": "new Relay(__globalTest.host)\n Alice.sendToVia('Bob', r, code1).then ->\n Alice.relaySend('Bob', ",
"end": 1102,
"score": 0.9899801015853882,
"start": 1099,
"tag": "NAME",
"value": "Bob"
},
{
"context": "a('Bob', r, code1).then ->\n Alice.relaySend('Bob', code2, r).then ->\n Alice.relaySend('Bob'",
"end": 1149,
"score": 0.9861536026000977,
"start": 1146,
"tag": "NAME",
"value": "Bob"
},
{
"context": "'Bob', code2, r).then ->\n Alice.relaySend('Bob', code3, r).then ->\n Bob.connectToRelay(",
"end": 1198,
"score": 0.9557538032531738,
"start": 1195,
"tag": "NAME",
"value": "Bob"
},
{
"context": " expect(count).equal 3\n\n download = null\n it 'Bob gets missile codes', ->\n r = new Relay(__globa",
"end": 1368,
"score": 0.9486553072929382,
"start": 1365,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ect(msgs).deep.equal [code1, code2, code3]\n\n it 'Bob erases his tracks', ->\n r = new Relay(__global",
"end": 1649,
"score": 0.997979462146759,
"start": 1646,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ect(count).equal 0\n\n it 'clear mailboxes', ->\n Alice.selfDestruct(true).then ->\n Bob.selfDestruct",
"end": 2007,
"score": 0.9162238836288452,
"start": 2002,
"tag": "NAME",
"value": "Alice"
}
] | tests/specs/06b.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
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
Utils = require 'utils'
describe 'Relay Bulk Ops', ->
return unless window.__globalTest.runTests['relay bulk']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.mid)
before ->
@skip() if __globalTest.offline
[Alice, Bob] = [null, null]
it 'create mailboxes', ->
MailBox.new('Alice').then (ret)->
Alice = ret
MailBox.new('Bob').then (ret)->
Bob = ret
Alice.keyRing.addGuest('Bob', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('Alice', Alice.getPubCommKey())
code1 = {id: 1, code: 12345, msg: 'Missile code #1 is 12345'}
code2 = {id: 2, code: 67890, msg: 'Missile code #2 is 67890'}
code3 = {id: 3, code: 11111, msg: 'Missile code #3 is 11111'}
it 'Give missile codes to Bob', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('Bob', r, code1).then ->
Alice.relaySend('Bob', code2, r).then ->
Alice.relaySend('Bob', code3, r).then ->
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
download = null
it 'Bob gets missile codes', ->
r = new Relay(__globalTest.host)
Bob.getRelayMessages(r).then (_download)->
download = _download
expect(download).to.have.a.lengthOf 3
msgs = download.map (m) -> m.msg
expect(msgs).deep.equal [code1, code2, code3]
it 'Bob erases his tracks', ->
r = new Relay(__globalTest.host)
list = download.map (i) -> i.nonce
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
Bob.relayDelete(list, r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 0
it 'clear mailboxes', ->
Alice.selfDestruct(true).then ->
Bob.selfDestruct(true)
| 129222 | # 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
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
Utils = require 'utils'
describe 'Relay Bulk Ops', ->
return unless window.__globalTest.runTests['relay bulk']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.mid)
before ->
@skip() if __globalTest.offline
[<NAME>, Bob] = [null, null]
it 'create mailboxes', ->
MailBox.new('<NAME>').then (ret)->
<NAME> = ret
MailBox.new('<NAME>').then (ret)->
<NAME> = ret
Alice.keyRing.addGuest('<NAME>', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('<NAME>', Alice.getPubCommKey())
code1 = {id: 1, code: 12345, msg: 'Missile code #1 is 12345'}
code2 = {id: 2, code: 67890, msg: 'Missile code #2 is 67890'}
code3 = {id: 3, code: 11111, msg: 'Missile code #3 is 11111'}
it 'Give missile codes to Bob', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('<NAME>', r, code1).then ->
Alice.relaySend('<NAME>', code2, r).then ->
Alice.relaySend('<NAME>', code3, r).then ->
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
download = null
it '<NAME> gets missile codes', ->
r = new Relay(__globalTest.host)
Bob.getRelayMessages(r).then (_download)->
download = _download
expect(download).to.have.a.lengthOf 3
msgs = download.map (m) -> m.msg
expect(msgs).deep.equal [code1, code2, code3]
it '<NAME> erases his tracks', ->
r = new Relay(__globalTest.host)
list = download.map (i) -> i.nonce
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
Bob.relayDelete(list, r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 0
it 'clear mailboxes', ->
<NAME>.selfDestruct(true).then ->
Bob.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
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
Utils = require 'utils'
describe 'Relay Bulk Ops', ->
return unless window.__globalTest.runTests['relay bulk']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.mid)
before ->
@skip() if __globalTest.offline
[PI:NAME:<NAME>END_PI, Bob] = [null, null]
it 'create mailboxes', ->
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
Alice.keyRing.addGuest('PI:NAME:<NAME>END_PI', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('PI:NAME:<NAME>END_PI', Alice.getPubCommKey())
code1 = {id: 1, code: 12345, msg: 'Missile code #1 is 12345'}
code2 = {id: 2, code: 67890, msg: 'Missile code #2 is 67890'}
code3 = {id: 3, code: 11111, msg: 'Missile code #3 is 11111'}
it 'Give missile codes to Bob', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('PI:NAME:<NAME>END_PI', r, code1).then ->
Alice.relaySend('PI:NAME:<NAME>END_PI', code2, r).then ->
Alice.relaySend('PI:NAME:<NAME>END_PI', code3, r).then ->
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
download = null
it 'PI:NAME:<NAME>END_PI gets missile codes', ->
r = new Relay(__globalTest.host)
Bob.getRelayMessages(r).then (_download)->
download = _download
expect(download).to.have.a.lengthOf 3
msgs = download.map (m) -> m.msg
expect(msgs).deep.equal [code1, code2, code3]
it 'PI:NAME:<NAME>END_PI erases his tracks', ->
r = new Relay(__globalTest.host)
list = download.map (i) -> i.nonce
Bob.connectToRelay(r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 3
Bob.relayDelete(list, r).then ->
Bob.relayCount(r).then (count)->
expect(count).equal 0
it 'clear mailboxes', ->
PI:NAME:<NAME>END_PI.selfDestruct(true).then ->
Bob.selfDestruct(true)
|
[
{
"context": "ftRating}\"\n\t\tredisKey = keyPrefix()\n\t\tuserRunKey = userId + \":\" + ticketId\n\t\tmulti = @redis.multi() # start",
"end": 1704,
"score": 0.9449189901351929,
"start": 1698,
"tag": "KEY",
"value": "userId"
},
{
"context": "tId}\"\n\n\t\tredisRiftKey = keyPrefix()\n\t\tuserRunKey = userId + \":\" + ticketId\n\n\t\treturn @redis.zrevrankAsync(r",
"end": 2361,
"score": 0.9868475794792175,
"start": 2355,
"tag": "KEY",
"value": "userId"
},
{
"context": "iftKey = keyPrefix()\n\t\tuserRunKey = userId + \":\" + ticketId\n\n\t\treturn @redis.zrevrankAsync(redisRiftKey, user",
"end": 2378,
"score": 0.7733348608016968,
"start": 2370,
"tag": "KEY",
"value": "ticketId"
},
{
"context": "RunFromLadder: (userId,ticketId)\t->\n\t\tuserRunKey = userId + \":\" + ticketId\n\t\tLogger.module(\"REDIS\").debug \"",
"end": 3320,
"score": 0.9909582138061523,
"start": 3314,
"tag": "KEY",
"value": "userId"
},
{
"context": "dder: (userId,ticketId)\t->\n\t\tuserRunKey = userId + \":\" + ticketId\n\t\tLogger.module(\"REDIS\").debug \"update",
"end": 3326,
"score": 0.7298382520675659,
"start": 3323,
"tag": "KEY",
"value": "\":\""
},
{
"context": "(userId,ticketId)\t->\n\t\tuserRunKey = userId + \":\" + ticketId\n\t\tLogger.module(\"REDIS\").debug \"updateUserLadderR",
"end": 3337,
"score": 0.7119309902191162,
"start": 3329,
"tag": "KEY",
"value": "ticketId"
}
] | server/redis/r-riftmanager.coffee | willroberts/duelyst | 5 | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
ttl = config.get("redis.ttl")
generatePushID = require '../../app/common/generate_push_id'
zlib = Promise.promisifyAll(require 'zlib')
# Helper returns the SRank Ladder Redis key prefix
keyPrefix = () ->
if not RedisRiftManager.unitTestMode
return "#{env}:rift_ladder"
else
return "#{env}:rift_ladder:test"
expireAtTime = (systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
if not RedisRiftManager.unitTestMode
expireAtMoment = MOMENT_NOW_UTC.clone().add(2,"week")
return expireAtMoment.valueOf()
else
return moment.utc().add(1,"hour").valueOf()
###*
# Class 'RedisRiftManager'
# Manages storage of rift ladder ratings/position in Redis
# ttl sets the expiration time of keys, defaults to 2 weeks
###
class RedisRiftManager
@unitTestMode: false # This will change the way timeouts are handled so expires can more easily be tested
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
@redis = redis
return
###*
# Updates the ladder rating of a player by user id and rift ticket id
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @param {Integer} riftRating players new ladder rating
# @return {Promise}
###
updateUserRunRiftRating: (userId,ticketId, riftRating,systemTime) ->
Logger.module("REDIS").debug "updateUserRunHighestRiftRating() -> updating Rift rating for player #{userId} run #{ticketId} to #{riftRating}"
redisKey = keyPrefix()
userRunKey = userId + ":" + ticketId
multi = @redis.multi() # start a multi command
multi.zadd(redisKey, riftRating, userRunKey)
multi.expireat(redisKey, expireAtTime(systemTime))
return multi.execAsync()
###*
# Retrieves player's srank ladder position
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @return {Promise} Resolves to a integer for players ladder position
###
getUserRunLadderPosition: (userId,ticketId,systemTime) ->
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for user #{userId} run #{ticketId}"
redisRiftKey = keyPrefix()
userRunKey = userId + ":" + ticketId
return @redis.zrevrankAsync(redisRiftKey, userRunKey)
.then (ladderPosition) ->
if ladderPosition?
return Promise.resolve(parseInt(ladderPosition)+1)
else
return Promise.resolve(null)
###*
# Gets top rift ladder player&run id tuples
# @param {integer} numPlayers
# @return {Promise} An array of "userId:runId" in order of top players
###
getTopLadderUserIdAndRunIds: (numPlayers) ->
Logger.module("REDIS").debug "getTopLadderUserIds() -> retrieving top #{numPlayers} rift players"
redisKey = keyPrefix()
return @redis.zrevrangeAsync(redisKey, 0, numPlayers-1)
###*
# This method has no use in normal user flow, it's only purpose is QA and wiping a user
# @param {String} userId user id being removed
# @param {String} ticketId run id being removed
# @return {Promise} Promise that returns on operation completion, no value
###
_removeUserRunFromLadder: (userId,ticketId) ->
userRunKey = userId + ":" + ticketId
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for #{userRunKey}"
redisKey = keyPrefix()
return @redis.zremAsync(redisKey,userRunKey)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RiftManager = new RedisRiftManager(redis, opts)
return RiftManager
| 52940 | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
ttl = config.get("redis.ttl")
generatePushID = require '../../app/common/generate_push_id'
zlib = Promise.promisifyAll(require 'zlib')
# Helper returns the SRank Ladder Redis key prefix
keyPrefix = () ->
if not RedisRiftManager.unitTestMode
return "#{env}:rift_ladder"
else
return "#{env}:rift_ladder:test"
expireAtTime = (systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
if not RedisRiftManager.unitTestMode
expireAtMoment = MOMENT_NOW_UTC.clone().add(2,"week")
return expireAtMoment.valueOf()
else
return moment.utc().add(1,"hour").valueOf()
###*
# Class 'RedisRiftManager'
# Manages storage of rift ladder ratings/position in Redis
# ttl sets the expiration time of keys, defaults to 2 weeks
###
class RedisRiftManager
@unitTestMode: false # This will change the way timeouts are handled so expires can more easily be tested
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
@redis = redis
return
###*
# Updates the ladder rating of a player by user id and rift ticket id
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @param {Integer} riftRating players new ladder rating
# @return {Promise}
###
updateUserRunRiftRating: (userId,ticketId, riftRating,systemTime) ->
Logger.module("REDIS").debug "updateUserRunHighestRiftRating() -> updating Rift rating for player #{userId} run #{ticketId} to #{riftRating}"
redisKey = keyPrefix()
userRunKey = <KEY> + ":" + ticketId
multi = @redis.multi() # start a multi command
multi.zadd(redisKey, riftRating, userRunKey)
multi.expireat(redisKey, expireAtTime(systemTime))
return multi.execAsync()
###*
# Retrieves player's srank ladder position
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @return {Promise} Resolves to a integer for players ladder position
###
getUserRunLadderPosition: (userId,ticketId,systemTime) ->
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for user #{userId} run #{ticketId}"
redisRiftKey = keyPrefix()
userRunKey = <KEY> + ":" + <KEY>
return @redis.zrevrankAsync(redisRiftKey, userRunKey)
.then (ladderPosition) ->
if ladderPosition?
return Promise.resolve(parseInt(ladderPosition)+1)
else
return Promise.resolve(null)
###*
# Gets top rift ladder player&run id tuples
# @param {integer} numPlayers
# @return {Promise} An array of "userId:runId" in order of top players
###
getTopLadderUserIdAndRunIds: (numPlayers) ->
Logger.module("REDIS").debug "getTopLadderUserIds() -> retrieving top #{numPlayers} rift players"
redisKey = keyPrefix()
return @redis.zrevrangeAsync(redisKey, 0, numPlayers-1)
###*
# This method has no use in normal user flow, it's only purpose is QA and wiping a user
# @param {String} userId user id being removed
# @param {String} ticketId run id being removed
# @return {Promise} Promise that returns on operation completion, no value
###
_removeUserRunFromLadder: (userId,ticketId) ->
userRunKey = <KEY> + <KEY> + <KEY>
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for #{userRunKey}"
redisKey = keyPrefix()
return @redis.zremAsync(redisKey,userRunKey)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RiftManager = new RedisRiftManager(redis, opts)
return RiftManager
| true | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
ttl = config.get("redis.ttl")
generatePushID = require '../../app/common/generate_push_id'
zlib = Promise.promisifyAll(require 'zlib')
# Helper returns the SRank Ladder Redis key prefix
keyPrefix = () ->
if not RedisRiftManager.unitTestMode
return "#{env}:rift_ladder"
else
return "#{env}:rift_ladder:test"
expireAtTime = (systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
if not RedisRiftManager.unitTestMode
expireAtMoment = MOMENT_NOW_UTC.clone().add(2,"week")
return expireAtMoment.valueOf()
else
return moment.utc().add(1,"hour").valueOf()
###*
# Class 'RedisRiftManager'
# Manages storage of rift ladder ratings/position in Redis
# ttl sets the expiration time of keys, defaults to 2 weeks
###
class RedisRiftManager
@unitTestMode: false # This will change the way timeouts are handled so expires can more easily be tested
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
@redis = redis
return
###*
# Updates the ladder rating of a player by user id and rift ticket id
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @param {Integer} riftRating players new ladder rating
# @return {Promise}
###
updateUserRunRiftRating: (userId,ticketId, riftRating,systemTime) ->
Logger.module("REDIS").debug "updateUserRunHighestRiftRating() -> updating Rift rating for player #{userId} run #{ticketId} to #{riftRating}"
redisKey = keyPrefix()
userRunKey = PI:KEY:<KEY>END_PI + ":" + ticketId
multi = @redis.multi() # start a multi command
multi.zadd(redisKey, riftRating, userRunKey)
multi.expireat(redisKey, expireAtTime(systemTime))
return multi.execAsync()
###*
# Retrieves player's srank ladder position
# @param {String} userId user id being updated
# @param {String} ticketId run/ticket id being updated
# @return {Promise} Resolves to a integer for players ladder position
###
getUserRunLadderPosition: (userId,ticketId,systemTime) ->
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for user #{userId} run #{ticketId}"
redisRiftKey = keyPrefix()
userRunKey = PI:KEY:<KEY>END_PI + ":" + PI:KEY:<KEY>END_PI
return @redis.zrevrankAsync(redisRiftKey, userRunKey)
.then (ladderPosition) ->
if ladderPosition?
return Promise.resolve(parseInt(ladderPosition)+1)
else
return Promise.resolve(null)
###*
# Gets top rift ladder player&run id tuples
# @param {integer} numPlayers
# @return {Promise} An array of "userId:runId" in order of top players
###
getTopLadderUserIdAndRunIds: (numPlayers) ->
Logger.module("REDIS").debug "getTopLadderUserIds() -> retrieving top #{numPlayers} rift players"
redisKey = keyPrefix()
return @redis.zrevrangeAsync(redisKey, 0, numPlayers-1)
###*
# This method has no use in normal user flow, it's only purpose is QA and wiping a user
# @param {String} userId user id being removed
# @param {String} ticketId run id being removed
# @return {Promise} Promise that returns on operation completion, no value
###
_removeUserRunFromLadder: (userId,ticketId) ->
userRunKey = PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI
Logger.module("REDIS").debug "updateUserLadderRating() -> getting Ladder Position for #{userRunKey}"
redisKey = keyPrefix()
return @redis.zremAsync(redisKey,userRunKey)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RiftManager = new RedisRiftManager(redis, opts)
return RiftManager
|
[
{
"context": "Id: \"123\"\n\n model.update \"abc\", json, \"bob\"\n expect(mockCrudModel.findById.called",
"end": 6606,
"score": 0.6409777402877808,
"start": 6603,
"tag": "NAME",
"value": "bob"
},
{
"context": "Id: \"123\"\n\n model.update \"abc\", json, \"bob\"\n expect(mockCrudModel.findById.called",
"end": 6935,
"score": 0.7396408915519714,
"start": 6932,
"tag": "NAME",
"value": "bob"
}
] | test/server/models/timePatterns.coffee | valueflowquality/gi-util-update | 0 | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'TimePatterns', ->
modelFactory = require dir + '/models/timePatterns'
model = null
expectedDefinition =
name: 'TimePattern'
schemaDefinition:
systemId: 'ObjectId'
name: 'String'
pattern: ['Number']
recurrence: 'String'
base: 'Date'
it 'Exports a factory function', (done) ->
expect(modelFactory).to.be.a('function')
done()
describe 'Constructor: (dal) -> { object }', ->
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
sinon.spy mocks.dal, 'modelFactory'
sinon.spy mocks.dal, 'crudFactory'
model = modelFactory mocks.dal
afterEach ->
mocks.dal.modelFactory.restore()
mocks.dal.schemaFactory.restore()
mocks.dal.crudFactory.restore()
it 'Creates a timePatterns schema', (done) ->
expect(mocks.dal.schemaFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Creates a timePatterns model', (done) ->
expect(mocks.dal.modelFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Uses Crud Factory with returned model', (done) ->
returnedModel = mocks.dal.modelFactory.returnValues[0]
expect(mocks.dal.crudFactory.calledWithMatch(returnedModel))
.to.be.true
done()
describe 'Schema', ->
schema = null
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
model = modelFactory mocks.dal
schema = mocks.dal.schemaFactory.returnValues[0]
afterEach ->
mocks.dal.schemaFactory.restore()
it 'systemId: ObjectId', (done) ->
expect(schema).to.have.property 'systemId', 'ObjectId'
done()
it 'name: String', (done) ->
expect(schema).to.have.property 'name', 'String'
done()
it 'pattern: [Number]', (done) ->
expect(schema).to.have.property('pattern').with.length 1
expect(schema.pattern[0]).to.equal 'Number'
done()
it 'recurrence: String', (done) ->
expect(schema).to.have.property 'recurrence', 'String'
done()
it 'base: Date', (done) ->
expect(schema).to.have.property 'base', 'Date'
done()
describe 'Exports', ->
mockCrudModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
findOne: ->
findOneBy: ->
find: ->
count: ->
mockCrudModelFactory = () ->
mockCrudModel
beforeEach ->
mockDal = mocks.dal
mockDal.crudFactory = mockCrudModelFactory
model = modelFactory mocks.dal
mocks.exportsCrudModel 'TimePattern'
, modelFactory(mocks.dal)
, {create: true, update: true}
describe 'Overridden Crud', ->
describe 'create: function(json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'create'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.create.restore()
model._checkValidPattern.restore()
it 'calls crud.create with json and callback if no json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls crud.create with json and callback if no json.recurrence'
, (done) ->
json =
an: "object"
pattern: "a pattern"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls checkValidPattern if recurrence and pattern are given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
done()
it 'callsback with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.notCalled).to.be.true
expect(res).to.not.exist
expect(err).to.equal "pattern exceeds recurrence"
done()
it 'calls crud create with json and callback if checkValidPattern ok'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns true
model.create json, "bob"
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
describe 'update: function(id, json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'update'
sinon.stub mockCrudModel, 'findById'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.update.restore()
mockCrudModel.findById.restore()
model._checkValidPattern.restore()
it 'calls crud.update with json and callback if no json.pattern ' +
'and no json.recurrence', (done) ->
json =
an: "object"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.notCalled).to.be.true
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls crud.findById if json.pattern given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
systemId: "123"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById if json.recurrence given'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById with id and json.systemId'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.calledWith "abc"
, json.systemId, sinon.match.func).to.be.true
done()
it 'calls back with error if findById returns an error', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, "an error", null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'calls back with error if findById returns null', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, null, null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'could not find time pattern with id abc'
expect(obj).to.not.exist
done()
it 'calls check valid pattern with json.recurrence and json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(model._checkValidPattern.calledWith(
"a recurrence", "a pattern"
)).to.be.true
done()
it 'calls crud update if checkValidPattern returns true'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls back with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns false
model.update "abc", json, (err, obj) ->
expect(mockCrudModel.update.notCalled).to.be.true
expect(err).to.equal "pattern exceeds recurrence"
expect(obj).to.not.exist
done()
describe 'Other', ->
stubs = null
beforeEach ->
stubs =
'../common':
timePatterns:
timeOnBetween: sinon.stub()
timeAfterXSecondsOnFrom: sinon.stub()
model = proxyquire(dir + '/models/timePatterns', stubs)(
mocks.dal
)
sinon.stub mockCrudModel, 'findById'
afterEach ->
mockCrudModel.findById.restore()
describe 'timeOnBetween: function(start, stop, patternId, systemId,' +
' callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeOnBetween "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeOnBetween with start, stop, pattern and recurrence'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeOnBetween "a", "b", "c", "d"
expect(stubs['../common'].timePatterns.timeOnBetween.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns.timeOnBetween.returns "bob"
model.timeOnBetween "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'timeAfterXSecondsOnFrom: function(start, x, patternId,' +
' systemId, callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeAfterXSecondsOnFrom with start, stop, pattern' +
' and recurrence', (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeAfterXSecondsOnFrom "a", "b", "c", "d"
expect(stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.returns "bob"
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'Private methods', ->
describe 'checkValidPattern: func(...)', ->
it 'returns true if recurrence not specified', (done) ->
expect(model._checkValidPattern null, "pattern").to.be.true
done()
it 'returns true if pattern not specified', (done) ->
expect(model._checkValidPattern "recurrence").to.be.true
done()
describe 'recurrence: weekly', ->
it 'returns true if period sums is <= than sec per week (604800)'
, (done) ->
expect(model._checkValidPattern "weekly", [0, 4]).to.be.true
expect(model._checkValidPattern "weekly", []).to.be.true
expect(model._checkValidPattern "weekly", [604800]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "weekly", [10000000]).to.be.false
expect(model._checkValidPattern "weekly", [1, 604800]).to.be.false
expect(model._checkValidPattern "weekly", [604800, 1]).to.be.false
done()
describe 'recurrence: monthly', ->
it 'returns true if period sums is <= than sec per week (2678400)'
, (done) ->
expect(model._checkValidPattern "monthly", [0, 4]).to.be.true
expect(model._checkValidPattern "monthly", []).to.be.true
expect(model._checkValidPattern "monthly", [2678400]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "monthly", [10000000]).to.be.false
expect(model._checkValidPattern "monthly", [1, 2678400]).to.be.false
expect(model._checkValidPattern "monthly", [2678400, 1]).to.be.false
done()
describe 'recurrence: yearly', ->
it 'returns true if period sums is <= than sec per week (31536000)'
, (done) ->
expect(model._checkValidPattern "yearly", [0, 4]).to.be.true
expect(model._checkValidPattern "yearly", []).to.be.true
expect(model._checkValidPattern "yearly", [31536000]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "yearly", [100000000]).to.be.false
expect(model._checkValidPattern "yearly", [1, 31536000]).to.be.false
expect(model._checkValidPattern "yearly", [31536000, 1]).to.be.false
done()
| 212533 | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'TimePatterns', ->
modelFactory = require dir + '/models/timePatterns'
model = null
expectedDefinition =
name: 'TimePattern'
schemaDefinition:
systemId: 'ObjectId'
name: 'String'
pattern: ['Number']
recurrence: 'String'
base: 'Date'
it 'Exports a factory function', (done) ->
expect(modelFactory).to.be.a('function')
done()
describe 'Constructor: (dal) -> { object }', ->
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
sinon.spy mocks.dal, 'modelFactory'
sinon.spy mocks.dal, 'crudFactory'
model = modelFactory mocks.dal
afterEach ->
mocks.dal.modelFactory.restore()
mocks.dal.schemaFactory.restore()
mocks.dal.crudFactory.restore()
it 'Creates a timePatterns schema', (done) ->
expect(mocks.dal.schemaFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Creates a timePatterns model', (done) ->
expect(mocks.dal.modelFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Uses Crud Factory with returned model', (done) ->
returnedModel = mocks.dal.modelFactory.returnValues[0]
expect(mocks.dal.crudFactory.calledWithMatch(returnedModel))
.to.be.true
done()
describe 'Schema', ->
schema = null
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
model = modelFactory mocks.dal
schema = mocks.dal.schemaFactory.returnValues[0]
afterEach ->
mocks.dal.schemaFactory.restore()
it 'systemId: ObjectId', (done) ->
expect(schema).to.have.property 'systemId', 'ObjectId'
done()
it 'name: String', (done) ->
expect(schema).to.have.property 'name', 'String'
done()
it 'pattern: [Number]', (done) ->
expect(schema).to.have.property('pattern').with.length 1
expect(schema.pattern[0]).to.equal 'Number'
done()
it 'recurrence: String', (done) ->
expect(schema).to.have.property 'recurrence', 'String'
done()
it 'base: Date', (done) ->
expect(schema).to.have.property 'base', 'Date'
done()
describe 'Exports', ->
mockCrudModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
findOne: ->
findOneBy: ->
find: ->
count: ->
mockCrudModelFactory = () ->
mockCrudModel
beforeEach ->
mockDal = mocks.dal
mockDal.crudFactory = mockCrudModelFactory
model = modelFactory mocks.dal
mocks.exportsCrudModel 'TimePattern'
, modelFactory(mocks.dal)
, {create: true, update: true}
describe 'Overridden Crud', ->
describe 'create: function(json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'create'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.create.restore()
model._checkValidPattern.restore()
it 'calls crud.create with json and callback if no json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls crud.create with json and callback if no json.recurrence'
, (done) ->
json =
an: "object"
pattern: "a pattern"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls checkValidPattern if recurrence and pattern are given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
done()
it 'callsback with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.notCalled).to.be.true
expect(res).to.not.exist
expect(err).to.equal "pattern exceeds recurrence"
done()
it 'calls crud create with json and callback if checkValidPattern ok'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns true
model.create json, "bob"
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
describe 'update: function(id, json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'update'
sinon.stub mockCrudModel, 'findById'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.update.restore()
mockCrudModel.findById.restore()
model._checkValidPattern.restore()
it 'calls crud.update with json and callback if no json.pattern ' +
'and no json.recurrence', (done) ->
json =
an: "object"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.notCalled).to.be.true
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls crud.findById if json.pattern given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
systemId: "123"
model.update "abc", json, "<NAME>"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById if json.recurrence given'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "<NAME>"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById with id and json.systemId'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.calledWith "abc"
, json.systemId, sinon.match.func).to.be.true
done()
it 'calls back with error if findById returns an error', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, "an error", null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'calls back with error if findById returns null', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, null, null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'could not find time pattern with id abc'
expect(obj).to.not.exist
done()
it 'calls check valid pattern with json.recurrence and json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(model._checkValidPattern.calledWith(
"a recurrence", "a pattern"
)).to.be.true
done()
it 'calls crud update if checkValidPattern returns true'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls back with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns false
model.update "abc", json, (err, obj) ->
expect(mockCrudModel.update.notCalled).to.be.true
expect(err).to.equal "pattern exceeds recurrence"
expect(obj).to.not.exist
done()
describe 'Other', ->
stubs = null
beforeEach ->
stubs =
'../common':
timePatterns:
timeOnBetween: sinon.stub()
timeAfterXSecondsOnFrom: sinon.stub()
model = proxyquire(dir + '/models/timePatterns', stubs)(
mocks.dal
)
sinon.stub mockCrudModel, 'findById'
afterEach ->
mockCrudModel.findById.restore()
describe 'timeOnBetween: function(start, stop, patternId, systemId,' +
' callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeOnBetween "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeOnBetween with start, stop, pattern and recurrence'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeOnBetween "a", "b", "c", "d"
expect(stubs['../common'].timePatterns.timeOnBetween.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns.timeOnBetween.returns "bob"
model.timeOnBetween "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'timeAfterXSecondsOnFrom: function(start, x, patternId,' +
' systemId, callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeAfterXSecondsOnFrom with start, stop, pattern' +
' and recurrence', (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeAfterXSecondsOnFrom "a", "b", "c", "d"
expect(stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.returns "bob"
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'Private methods', ->
describe 'checkValidPattern: func(...)', ->
it 'returns true if recurrence not specified', (done) ->
expect(model._checkValidPattern null, "pattern").to.be.true
done()
it 'returns true if pattern not specified', (done) ->
expect(model._checkValidPattern "recurrence").to.be.true
done()
describe 'recurrence: weekly', ->
it 'returns true if period sums is <= than sec per week (604800)'
, (done) ->
expect(model._checkValidPattern "weekly", [0, 4]).to.be.true
expect(model._checkValidPattern "weekly", []).to.be.true
expect(model._checkValidPattern "weekly", [604800]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "weekly", [10000000]).to.be.false
expect(model._checkValidPattern "weekly", [1, 604800]).to.be.false
expect(model._checkValidPattern "weekly", [604800, 1]).to.be.false
done()
describe 'recurrence: monthly', ->
it 'returns true if period sums is <= than sec per week (2678400)'
, (done) ->
expect(model._checkValidPattern "monthly", [0, 4]).to.be.true
expect(model._checkValidPattern "monthly", []).to.be.true
expect(model._checkValidPattern "monthly", [2678400]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "monthly", [10000000]).to.be.false
expect(model._checkValidPattern "monthly", [1, 2678400]).to.be.false
expect(model._checkValidPattern "monthly", [2678400, 1]).to.be.false
done()
describe 'recurrence: yearly', ->
it 'returns true if period sums is <= than sec per week (31536000)'
, (done) ->
expect(model._checkValidPattern "yearly", [0, 4]).to.be.true
expect(model._checkValidPattern "yearly", []).to.be.true
expect(model._checkValidPattern "yearly", [31536000]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "yearly", [100000000]).to.be.false
expect(model._checkValidPattern "yearly", [1, 31536000]).to.be.false
expect(model._checkValidPattern "yearly", [31536000, 1]).to.be.false
done()
| true | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'TimePatterns', ->
modelFactory = require dir + '/models/timePatterns'
model = null
expectedDefinition =
name: 'TimePattern'
schemaDefinition:
systemId: 'ObjectId'
name: 'String'
pattern: ['Number']
recurrence: 'String'
base: 'Date'
it 'Exports a factory function', (done) ->
expect(modelFactory).to.be.a('function')
done()
describe 'Constructor: (dal) -> { object }', ->
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
sinon.spy mocks.dal, 'modelFactory'
sinon.spy mocks.dal, 'crudFactory'
model = modelFactory mocks.dal
afterEach ->
mocks.dal.modelFactory.restore()
mocks.dal.schemaFactory.restore()
mocks.dal.crudFactory.restore()
it 'Creates a timePatterns schema', (done) ->
expect(mocks.dal.schemaFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Creates a timePatterns model', (done) ->
expect(mocks.dal.modelFactory.calledWithMatch(expectedDefinition))
.to.be.true
done()
it 'Uses Crud Factory with returned model', (done) ->
returnedModel = mocks.dal.modelFactory.returnValues[0]
expect(mocks.dal.crudFactory.calledWithMatch(returnedModel))
.to.be.true
done()
describe 'Schema', ->
schema = null
beforeEach ->
sinon.spy mocks.dal, 'schemaFactory'
model = modelFactory mocks.dal
schema = mocks.dal.schemaFactory.returnValues[0]
afterEach ->
mocks.dal.schemaFactory.restore()
it 'systemId: ObjectId', (done) ->
expect(schema).to.have.property 'systemId', 'ObjectId'
done()
it 'name: String', (done) ->
expect(schema).to.have.property 'name', 'String'
done()
it 'pattern: [Number]', (done) ->
expect(schema).to.have.property('pattern').with.length 1
expect(schema.pattern[0]).to.equal 'Number'
done()
it 'recurrence: String', (done) ->
expect(schema).to.have.property 'recurrence', 'String'
done()
it 'base: Date', (done) ->
expect(schema).to.have.property 'base', 'Date'
done()
describe 'Exports', ->
mockCrudModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
findOne: ->
findOneBy: ->
find: ->
count: ->
mockCrudModelFactory = () ->
mockCrudModel
beforeEach ->
mockDal = mocks.dal
mockDal.crudFactory = mockCrudModelFactory
model = modelFactory mocks.dal
mocks.exportsCrudModel 'TimePattern'
, modelFactory(mocks.dal)
, {create: true, update: true}
describe 'Overridden Crud', ->
describe 'create: function(json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'create'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.create.restore()
model._checkValidPattern.restore()
it 'calls crud.create with json and callback if no json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls crud.create with json and callback if no json.recurrence'
, (done) ->
json =
an: "object"
pattern: "a pattern"
model.create json, "bob"
expect(model._checkValidPattern.notCalled).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
it 'calls checkValidPattern if recurrence and pattern are given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
done()
it 'callsback with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns false
model.create json, (err, res) ->
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.notCalled).to.be.true
expect(res).to.not.exist
expect(err).to.equal "pattern exceeds recurrence"
done()
it 'calls crud create with json and callback if checkValidPattern ok'
, (done) ->
json =
an: "object"
pattern: "a pattern"
recurrence: "a recurrence"
model._checkValidPattern.returns true
model.create json, "bob"
expect(model._checkValidPattern.calledOnce).to.be.true
expect(mockCrudModel.create.calledWith json, "bob").to.be.true
done()
describe 'update: function(id, json, callback)', ->
beforeEach ->
sinon.stub mockCrudModel, 'update'
sinon.stub mockCrudModel, 'findById'
sinon.stub model, '_checkValidPattern'
afterEach ->
mockCrudModel.update.restore()
mockCrudModel.findById.restore()
model._checkValidPattern.restore()
it 'calls crud.update with json and callback if no json.pattern ' +
'and no json.recurrence', (done) ->
json =
an: "object"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.notCalled).to.be.true
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls crud.findById if json.pattern given'
, (done) ->
json =
an: "object"
pattern: "a pattern"
systemId: "123"
model.update "abc", json, "PI:NAME:<NAME>END_PI"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById if json.recurrence given'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "PI:NAME:<NAME>END_PI"
expect(mockCrudModel.findById.calledOnce).to.be.true
done()
it 'calls crud.findById with id and json.systemId'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
model.update "abc", json, "bob"
expect(mockCrudModel.findById.calledWith "abc"
, json.systemId, sinon.match.func).to.be.true
done()
it 'calls back with error if findById returns an error', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, "an error", null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'calls back with error if findById returns null', (done) ->
json =
an: "object"
recurrence: "a recurrence"
systemId: "123"
mockCrudModel.findById.callsArgWith 2, null, null
model.update "abc", json, (err, obj) ->
expect(err).to.equal 'could not find time pattern with id abc'
expect(obj).to.not.exist
done()
it 'calls check valid pattern with json.recurrence and json.pattern'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(model._checkValidPattern.calledWith(
"a recurrence", "a pattern"
)).to.be.true
done()
it 'calls crud update if checkValidPattern returns true'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns true
model.update "abc", json, "bob"
expect(mockCrudModel.update.calledWith "abc", json, "bob")
.to.be.true
done()
it 'calls back with an error if checkValidPattern returns false'
, (done) ->
json =
an: "object"
recurrence: "a recurrence"
pattern: "a pattern"
systemId: "123"
obj =
recurrence: "another recurrence"
pattern: "another pattern"
mockCrudModel.findById.callsArgWith 2, null, obj
model._checkValidPattern.returns false
model.update "abc", json, (err, obj) ->
expect(mockCrudModel.update.notCalled).to.be.true
expect(err).to.equal "pattern exceeds recurrence"
expect(obj).to.not.exist
done()
describe 'Other', ->
stubs = null
beforeEach ->
stubs =
'../common':
timePatterns:
timeOnBetween: sinon.stub()
timeAfterXSecondsOnFrom: sinon.stub()
model = proxyquire(dir + '/models/timePatterns', stubs)(
mocks.dal
)
sinon.stub mockCrudModel, 'findById'
afterEach ->
mockCrudModel.findById.restore()
describe 'timeOnBetween: function(start, stop, patternId, systemId,' +
' callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeOnBetween "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeOnBetween "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeOnBetween with start, stop, pattern and recurrence'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeOnBetween "a", "b", "c", "d"
expect(stubs['../common'].timePatterns.timeOnBetween.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns.timeOnBetween.returns "bob"
model.timeOnBetween "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'timeAfterXSecondsOnFrom: function(start, x, patternId,' +
' systemId, callback) -> (err, obj)', ->
it 'calls crud.findById', (done) ->
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", "e"
expect(mockCrudModel.findById.calledWith("c","d",sinon.match.func))
.to.be.true
done()
it 'callsback with error if findById errors', (done) ->
mockCrudModel.findById.callsArgWith 2, "an error", {}
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls back with error if findById finds nothing', (done) ->
mockCrudModel.findById.callsArgWith 2, null, null
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, obj) ->
expect(err).to.equal 'Could not find pattern with id: c'
done()
it 'calls timeAfterXSecondsOnFrom with start, stop, pattern' +
' and recurrence', (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
model.timeAfterXSecondsOnFrom "a", "b", "c", "d"
expect(stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.calledWith(
"a", "b", obj.pattern, obj.recurrence
)).to.be.true
done()
it 'returns result and no error if callback given'
, (done) ->
obj =
pattern: "a pattern"
recurrence: "a recurrence"
mockCrudModel.findById.callsArgWith 2, null, obj
stubs['../common'].timePatterns
.timeAfterXSecondsOnFrom.returns "bob"
model.timeAfterXSecondsOnFrom "a", "b", "c", "d", (err, result) ->
expect(err).to.not.exist
expect(result).to.equal "bob"
done()
describe 'Private methods', ->
describe 'checkValidPattern: func(...)', ->
it 'returns true if recurrence not specified', (done) ->
expect(model._checkValidPattern null, "pattern").to.be.true
done()
it 'returns true if pattern not specified', (done) ->
expect(model._checkValidPattern "recurrence").to.be.true
done()
describe 'recurrence: weekly', ->
it 'returns true if period sums is <= than sec per week (604800)'
, (done) ->
expect(model._checkValidPattern "weekly", [0, 4]).to.be.true
expect(model._checkValidPattern "weekly", []).to.be.true
expect(model._checkValidPattern "weekly", [604800]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "weekly", [10000000]).to.be.false
expect(model._checkValidPattern "weekly", [1, 604800]).to.be.false
expect(model._checkValidPattern "weekly", [604800, 1]).to.be.false
done()
describe 'recurrence: monthly', ->
it 'returns true if period sums is <= than sec per week (2678400)'
, (done) ->
expect(model._checkValidPattern "monthly", [0, 4]).to.be.true
expect(model._checkValidPattern "monthly", []).to.be.true
expect(model._checkValidPattern "monthly", [2678400]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "monthly", [10000000]).to.be.false
expect(model._checkValidPattern "monthly", [1, 2678400]).to.be.false
expect(model._checkValidPattern "monthly", [2678400, 1]).to.be.false
done()
describe 'recurrence: yearly', ->
it 'returns true if period sums is <= than sec per week (31536000)'
, (done) ->
expect(model._checkValidPattern "yearly", [0, 4]).to.be.true
expect(model._checkValidPattern "yearly", []).to.be.true
expect(model._checkValidPattern "yearly", [31536000]).to.be.true
done()
it 'returns false otherwise', (done) ->
expect(model._checkValidPattern "yearly", [100000000]).to.be.false
expect(model._checkValidPattern "yearly", [1, 31536000]).to.be.false
expect(model._checkValidPattern "yearly", [31536000, 1]).to.be.false
done()
|
[
{
"context": "er.name == process.env.REMOTE_USER && user.pass == process.env.REMOTE_PASS\n next()\n else\n unauthorize",
"end": 436,
"score": 0.6047549247741699,
"start": 429,
"tag": "PASSWORD",
"value": "process"
}
] | lib/authentication.coffee | okize/snapdash | 0 | # applies basic authorization; checks against REMOTE_USER && REMOTE_PASSWORD
basicAuth = require 'basic-auth'
module.exports = (req, res, next) ->
unauthorized = (res) ->
res.set 'WWW-Authenticate', 'Basic realm=Authorization Required'
res.status(401).end()
user = basicAuth(req)
if not user or not user.name or not user.pass
return unauthorized(res)
if user.name == process.env.REMOTE_USER && user.pass == process.env.REMOTE_PASS
next()
else
unauthorized(res) | 206161 | # applies basic authorization; checks against REMOTE_USER && REMOTE_PASSWORD
basicAuth = require 'basic-auth'
module.exports = (req, res, next) ->
unauthorized = (res) ->
res.set 'WWW-Authenticate', 'Basic realm=Authorization Required'
res.status(401).end()
user = basicAuth(req)
if not user or not user.name or not user.pass
return unauthorized(res)
if user.name == process.env.REMOTE_USER && user.pass == <PASSWORD>.env.REMOTE_PASS
next()
else
unauthorized(res) | true | # applies basic authorization; checks against REMOTE_USER && REMOTE_PASSWORD
basicAuth = require 'basic-auth'
module.exports = (req, res, next) ->
unauthorized = (res) ->
res.set 'WWW-Authenticate', 'Basic realm=Authorization Required'
res.status(401).end()
user = basicAuth(req)
if not user or not user.name or not user.pass
return unauthorized(res)
if user.name == process.env.REMOTE_USER && user.pass == PI:PASSWORD:<PASSWORD>END_PI.env.REMOTE_PASS
next()
else
unauthorized(res) |
[
{
"context": " pass) ->\n socket.emit \"login\",\n username: user\n password: pass\n\n\n # transition to onoardin",
"end": 866,
"score": 0.9972046613693237,
"start": 862,
"tag": "USERNAME",
"value": "user"
},
{
"context": "emit \"login\",\n username: user\n password: pass\n\n\n # transition to onoarding\n $scope.to_onboard",
"end": 887,
"score": 0.9986668825149536,
"start": 883,
"tag": "PASSWORD",
"value": "pass"
}
] | mobile/www/js/controllers/auth.coffee | 1egoman/bag-node | 0 | angular.module 'bag.controllers.login', []
.controller 'authCtrl', (
$scope
$http
$state
socket
$ionicLoading
$cordovaDialogs
) ->
socket.on "login:callback", (data) ->
if data.err
$cordovaDialogs.alert \
"Those login credentials don't match what we have on file. Give it another try?", \
"Incorrect Credentials", "OK"
else
localStorage.user = JSON.stringify
id: data._id
token: data.token
# the loading spinner thing
$ionicLoading.show template: 'Loading<br/><br/><ion-spinner></ion-spinner>'
# HACKY ALERT!!!
# to get the page to re "pull in" all the stuff, reload
setTimeout ->
location.replace('#/tab/bag')
$ionicLoading.hide()
location.reload()
, 2000
$scope.login = (user, pass) ->
socket.emit "login",
username: user
password: pass
# transition to onoarding
$scope.to_onboarding = ->
$state.go "tab.onboard", step: 'welcome'
| 199223 | angular.module 'bag.controllers.login', []
.controller 'authCtrl', (
$scope
$http
$state
socket
$ionicLoading
$cordovaDialogs
) ->
socket.on "login:callback", (data) ->
if data.err
$cordovaDialogs.alert \
"Those login credentials don't match what we have on file. Give it another try?", \
"Incorrect Credentials", "OK"
else
localStorage.user = JSON.stringify
id: data._id
token: data.token
# the loading spinner thing
$ionicLoading.show template: 'Loading<br/><br/><ion-spinner></ion-spinner>'
# HACKY ALERT!!!
# to get the page to re "pull in" all the stuff, reload
setTimeout ->
location.replace('#/tab/bag')
$ionicLoading.hide()
location.reload()
, 2000
$scope.login = (user, pass) ->
socket.emit "login",
username: user
password: <PASSWORD>
# transition to onoarding
$scope.to_onboarding = ->
$state.go "tab.onboard", step: 'welcome'
| true | angular.module 'bag.controllers.login', []
.controller 'authCtrl', (
$scope
$http
$state
socket
$ionicLoading
$cordovaDialogs
) ->
socket.on "login:callback", (data) ->
if data.err
$cordovaDialogs.alert \
"Those login credentials don't match what we have on file. Give it another try?", \
"Incorrect Credentials", "OK"
else
localStorage.user = JSON.stringify
id: data._id
token: data.token
# the loading spinner thing
$ionicLoading.show template: 'Loading<br/><br/><ion-spinner></ion-spinner>'
# HACKY ALERT!!!
# to get the page to re "pull in" all the stuff, reload
setTimeout ->
location.replace('#/tab/bag')
$ionicLoading.hide()
location.reload()
, 2000
$scope.login = (user, pass) ->
socket.emit "login",
username: user
password: PI:PASSWORD:<PASSWORD>END_PI
# transition to onoarding
$scope.to_onboarding = ->
$state.go "tab.onboard", step: 'welcome'
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998383522033691,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\n This so",
"end": 231,
"score": 0.9999300837516785,
"start": 218,
"tag": "EMAIL",
"value": "ben@pxljs.com"
}
] | src/gl/fbo.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Framebuffer objects - reads the current active context from the exports and creates a FBO
Basic FBO with depth, linear filtering and RGBA with unsigned bytes
Remember, NPOT textures are support but not with repeats or mipmapping
- TODO
* Depth options
###
{PXLError, PXLDebug} = require '../util/log'
{RGB,RGBA} = require '../colour/colour'
{Vec2} = require '../math/math'
{TextureBase} = require './texture'
# ## Fbo
# A class for Framebuffer objects
# Simply provide the the constructor variables and then bind in order to draw to this
class Fbo
# **constructor** -
# - **width** - a Number
# - **height** - a Number
# - **channels** - gl.R, gl.RGB, gl.RGBA or similar, optional, default gl.RGBA
# - **datatype** - gl.UNSIGNED_BYTE or similar, optional, default gl.UNSIGNED_BYTE
# - **depth** - a boolean, optional, default true
constructor: (@width, @height, @channels, @datatype, @depth) ->
gl = PXL.Context.gl
if not (@width? and @height?)
@width = PXL.Context.width
@height = PXL.Context.height
@channels= gl.RGBA if not @channels?
@datatype = gl.UNSIGNED_BYTE if not @datatype?
@depth = true if not @depth?
@framebuffer = gl.createFramebuffer()
PXLDebug "Created an FBO with dimensions: " + @width + "," + @height
@_build()
# **resize** - Given width and height (as either a Vec2 or two seperate numbers), resize this FBO
# - **w** - a Number - Integer - Reequired
# - **h** - a Number - Integer - Reequired
# - returns this
resize: (w,h) ->
if w instanceof Vec2
@width = w.x
@height = w.y
else if w? and h?
@width = w
@height = h
else
return @
@_build()
@
# _build - internal function that actually creates the Fbo
_build : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
if not @texture?
params =
"min" : gl.LINEAR
"max" : gl.LINEAR
"wraps" : gl.CLAMP_TO_EDGE
"wrapt" : gl.CLAMP_TO_EDGE
"width" : @width
"height" : @height
"channels" : @channels
"datatype" : @datatype
@texture = new TextureBase(params)
@texture.build()
else
@texture.bind()
gl.texImage2D(gl.TEXTURE_2D,0, @channels, @width, @height, 0, @channels, @datatype ,null)
@renderbuffer = gl.createRenderbuffer()
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @texture.texture, 0)
if @depth
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, @width, @height)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, @renderbuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
@texture.unbind()
if gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE
PXLError "Failed to Create Framebuffer!"
# **bind** - Bind this fbo to the current drawing context
# - returns this
bind : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
@
# **unbind** - remove this fbo from the context
# - returns this
unbind: () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
@
# **clear** - Clear the FBO with an optional colour
# - **colour** - a Colour
# - returns this
clear : (colour) ->
gl = PXL.Context.gl
if not colour?
gl.clearColor(0.0, 0.0, 0.0, 0.0)
else
if colour instanceof RGBA
gl.clearColor(colour.r, colour.g, colour.b, colour.a)
else if colour instanceof RGB
gl.clearColor(colour.r, colour.g, colour.b, 1.0)
if @depth
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
else
gl.clear gl.COLOR_BUFFER_BIT
@
# **washUp** - delete this Fbo from the Graphics Card
# - returns this
washUp : () ->
gl = PXL.Context.gl
gl.deleteFramebuffer(@framebuffer)
gl.deleteRenderbuffer(@renderbuffer)
gl.deleteTexture(@texture.texture)
@
module.exports =
Fbo : Fbo
| 822 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Framebuffer objects - reads the current active context from the exports and creates a FBO
Basic FBO with depth, linear filtering and RGBA with unsigned bytes
Remember, NPOT textures are support but not with repeats or mipmapping
- TODO
* Depth options
###
{PXLError, PXLDebug} = require '../util/log'
{RGB,RGBA} = require '../colour/colour'
{Vec2} = require '../math/math'
{TextureBase} = require './texture'
# ## Fbo
# A class for Framebuffer objects
# Simply provide the the constructor variables and then bind in order to draw to this
class Fbo
# **constructor** -
# - **width** - a Number
# - **height** - a Number
# - **channels** - gl.R, gl.RGB, gl.RGBA or similar, optional, default gl.RGBA
# - **datatype** - gl.UNSIGNED_BYTE or similar, optional, default gl.UNSIGNED_BYTE
# - **depth** - a boolean, optional, default true
constructor: (@width, @height, @channels, @datatype, @depth) ->
gl = PXL.Context.gl
if not (@width? and @height?)
@width = PXL.Context.width
@height = PXL.Context.height
@channels= gl.RGBA if not @channels?
@datatype = gl.UNSIGNED_BYTE if not @datatype?
@depth = true if not @depth?
@framebuffer = gl.createFramebuffer()
PXLDebug "Created an FBO with dimensions: " + @width + "," + @height
@_build()
# **resize** - Given width and height (as either a Vec2 or two seperate numbers), resize this FBO
# - **w** - a Number - Integer - Reequired
# - **h** - a Number - Integer - Reequired
# - returns this
resize: (w,h) ->
if w instanceof Vec2
@width = w.x
@height = w.y
else if w? and h?
@width = w
@height = h
else
return @
@_build()
@
# _build - internal function that actually creates the Fbo
_build : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
if not @texture?
params =
"min" : gl.LINEAR
"max" : gl.LINEAR
"wraps" : gl.CLAMP_TO_EDGE
"wrapt" : gl.CLAMP_TO_EDGE
"width" : @width
"height" : @height
"channels" : @channels
"datatype" : @datatype
@texture = new TextureBase(params)
@texture.build()
else
@texture.bind()
gl.texImage2D(gl.TEXTURE_2D,0, @channels, @width, @height, 0, @channels, @datatype ,null)
@renderbuffer = gl.createRenderbuffer()
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @texture.texture, 0)
if @depth
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, @width, @height)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, @renderbuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
@texture.unbind()
if gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE
PXLError "Failed to Create Framebuffer!"
# **bind** - Bind this fbo to the current drawing context
# - returns this
bind : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
@
# **unbind** - remove this fbo from the context
# - returns this
unbind: () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
@
# **clear** - Clear the FBO with an optional colour
# - **colour** - a Colour
# - returns this
clear : (colour) ->
gl = PXL.Context.gl
if not colour?
gl.clearColor(0.0, 0.0, 0.0, 0.0)
else
if colour instanceof RGBA
gl.clearColor(colour.r, colour.g, colour.b, colour.a)
else if colour instanceof RGB
gl.clearColor(colour.r, colour.g, colour.b, 1.0)
if @depth
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
else
gl.clear gl.COLOR_BUFFER_BIT
@
# **washUp** - delete this Fbo from the Graphics Card
# - returns this
washUp : () ->
gl = PXL.Context.gl
gl.deleteFramebuffer(@framebuffer)
gl.deleteRenderbuffer(@renderbuffer)
gl.deleteTexture(@texture.texture)
@
module.exports =
Fbo : Fbo
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Framebuffer objects - reads the current active context from the exports and creates a FBO
Basic FBO with depth, linear filtering and RGBA with unsigned bytes
Remember, NPOT textures are support but not with repeats or mipmapping
- TODO
* Depth options
###
{PXLError, PXLDebug} = require '../util/log'
{RGB,RGBA} = require '../colour/colour'
{Vec2} = require '../math/math'
{TextureBase} = require './texture'
# ## Fbo
# A class for Framebuffer objects
# Simply provide the the constructor variables and then bind in order to draw to this
class Fbo
# **constructor** -
# - **width** - a Number
# - **height** - a Number
# - **channels** - gl.R, gl.RGB, gl.RGBA or similar, optional, default gl.RGBA
# - **datatype** - gl.UNSIGNED_BYTE or similar, optional, default gl.UNSIGNED_BYTE
# - **depth** - a boolean, optional, default true
constructor: (@width, @height, @channels, @datatype, @depth) ->
gl = PXL.Context.gl
if not (@width? and @height?)
@width = PXL.Context.width
@height = PXL.Context.height
@channels= gl.RGBA if not @channels?
@datatype = gl.UNSIGNED_BYTE if not @datatype?
@depth = true if not @depth?
@framebuffer = gl.createFramebuffer()
PXLDebug "Created an FBO with dimensions: " + @width + "," + @height
@_build()
# **resize** - Given width and height (as either a Vec2 or two seperate numbers), resize this FBO
# - **w** - a Number - Integer - Reequired
# - **h** - a Number - Integer - Reequired
# - returns this
resize: (w,h) ->
if w instanceof Vec2
@width = w.x
@height = w.y
else if w? and h?
@width = w
@height = h
else
return @
@_build()
@
# _build - internal function that actually creates the Fbo
_build : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
if not @texture?
params =
"min" : gl.LINEAR
"max" : gl.LINEAR
"wraps" : gl.CLAMP_TO_EDGE
"wrapt" : gl.CLAMP_TO_EDGE
"width" : @width
"height" : @height
"channels" : @channels
"datatype" : @datatype
@texture = new TextureBase(params)
@texture.build()
else
@texture.bind()
gl.texImage2D(gl.TEXTURE_2D,0, @channels, @width, @height, 0, @channels, @datatype ,null)
@renderbuffer = gl.createRenderbuffer()
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @texture.texture, 0)
if @depth
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, @width, @height)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, @renderbuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
@texture.unbind()
if gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE
PXLError "Failed to Create Framebuffer!"
# **bind** - Bind this fbo to the current drawing context
# - returns this
bind : () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,@framebuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER,@renderbuffer)
@
# **unbind** - remove this fbo from the context
# - returns this
unbind: () ->
gl = PXL.Context.gl
gl.bindFramebuffer(gl.FRAMEBUFFER,null)
gl.bindRenderbuffer(gl.RENDERBUFFER,null)
@
# **clear** - Clear the FBO with an optional colour
# - **colour** - a Colour
# - returns this
clear : (colour) ->
gl = PXL.Context.gl
if not colour?
gl.clearColor(0.0, 0.0, 0.0, 0.0)
else
if colour instanceof RGBA
gl.clearColor(colour.r, colour.g, colour.b, colour.a)
else if colour instanceof RGB
gl.clearColor(colour.r, colour.g, colour.b, 1.0)
if @depth
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
else
gl.clear gl.COLOR_BUFFER_BIT
@
# **washUp** - delete this Fbo from the Graphics Card
# - returns this
washUp : () ->
gl = PXL.Context.gl
gl.deleteFramebuffer(@framebuffer)
gl.deleteRenderbuffer(@renderbuffer)
gl.deleteTexture(@texture.texture)
@
module.exports =
Fbo : Fbo
|
[
{
"context": "iew._id\n#\t\t\t\tif listview.is_default\n#\t\t\t\t\t_key = \"all\"\n\t\t\t\tlist_views[_key] = _list_view\n\t\t\t\tlist_views",
"end": 1531,
"score": 0.6419870853424072,
"start": 1528,
"tag": "KEY",
"value": "all"
}
] | creator/packages/steedos-creator/client/subscribe.coffee | yicone/steedos-platform | 42 | Creator.subs["Creator"] = new SubsManager()
Creator.subs["CreatorListViews"] = new SubsManager()
Creator.subs["TabularSetting"] = new SubsManager()
Creator.subs["CreatorRecord"] = new SubsManager()
Creator.subs["CreatorActionRecord"] = new SubsManager()
Creator.subs["objectRecentViewed"] = new SubsManager()
Steedos.subs["PendingSpace"] = new SubsManager();
Meteor.startup ->
# Tracker.autorun (c)->
# if Session.get("object_name")
# Creator.subs["objectRecentViewed"].subscribe "object_recent_viewed", Session.get("object_name")
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("spaceId")
Creator.subs["CreatorListViews"].subscribe "object_listviews", Session.get("object_name"), Session.get("spaceId")
Tracker.autorun (c)->
if Creator.subs["CreatorListViews"].ready() && Creator.bootstrapLoaded.get()
object_listViews = Creator.getCollection("object_listviews").find({space: Session.get("spaceId"), object_name: Session.get("object_name")})
if !Creator.getObject(Session.get("object_name"))
return
list_views = Creator.getObject(Session.get("object_name")).list_views
list_views_byname = Creator.getObject(Session.get("object_name")).list_views
defaultView = Creator.getObjectDefaultView(Session.get("object_name"))
object_listViews.forEach (listview)->
_list_view = Creator.convertListView(defaultView, listview, listview.name)
if listview.api_name
_key = listview.api_name
else
_key = listview._id
# if listview.is_default
# _key = "all"
list_views[_key] = _list_view
list_views_byname[_key] = _list_view
Session.set("change_list_views", Random.id())
Creator.getCollection("object_listviews").find().observe {
removed: (oldDocument) ->
# if oldDocument.name == "recent"
# key = oldDocument.name
# else
# key = oldDocument._id
if oldDocument.api_name
key = oldDocument.api_name
else
key = oldDocument._id
delete Creator.Objects[Session.get("object_name")].list_views[key]
delete Creator.getObject(Session.get("object_name")).list_views[key]
}
Meteor.startup ->
Tracker.autorun (c)->
object_name = Session.get("object_name")
related_object_name = Session.get("related_object_name")
if object_name or related_object_name
object_a = [object_name, related_object_name]
object_a = _.compact(object_a)
Creator.subs["TabularSetting"].subscribe "user_tabular_settings", object_a
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("record_id")
Creator.subs["CreatorRecord"].subscribe "creator_object_record", Session.get("object_name"), Session.get("record_id"), Session.get('spaceId')
#
# Tracker.autorun (c)->
# if Session.get("action_object_name") and Session.get("action_record_id")
# Creator.subs["CreatorActionRecord"].subscribe "creator_object_record", Session.get("action_object_name"), Session.get("action_record_id"), Session.get('spaceId')
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("spaceId")
Meteor.subscribe("myFollows", Session.get("spaceId"))
Meteor.startup ->
Tracker.autorun (c)->
if Meteor.userId()
Steedos.subs["PendingSpace"].subscribe "space_need_to_confirm"
spaceNeedToConfirm = db.space_users.find({user: Meteor.userId(), invite_state: "pending"}).fetch() || []
spaceNeedToConfirm.forEach (obj) ->
Meteor.call 'getPendingSpaceInfo', obj.created_by, obj.space, (error,result) ->
console.log("getPendingSpaceInfo=====", result);
if error
console.log error
else
swal {
title: t("pending_space_invite_info", {inviter: result.inviter, space: result.space})
type: "info"
showCancelButton: true
cancelButtonText: "拒绝"
confirmButtonColor: "#2196f3"
confirmButtonText: t('OK')
closeOnConfirm: true
allowEscapeKey: false
allowOutsideClick: false
}, (option)->
if option
Meteor.call 'acceptJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'acceptJoinSpace'
else
Meteor.call 'refuseJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'refuseJoinSpace'
| 62230 | Creator.subs["Creator"] = new SubsManager()
Creator.subs["CreatorListViews"] = new SubsManager()
Creator.subs["TabularSetting"] = new SubsManager()
Creator.subs["CreatorRecord"] = new SubsManager()
Creator.subs["CreatorActionRecord"] = new SubsManager()
Creator.subs["objectRecentViewed"] = new SubsManager()
Steedos.subs["PendingSpace"] = new SubsManager();
Meteor.startup ->
# Tracker.autorun (c)->
# if Session.get("object_name")
# Creator.subs["objectRecentViewed"].subscribe "object_recent_viewed", Session.get("object_name")
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("spaceId")
Creator.subs["CreatorListViews"].subscribe "object_listviews", Session.get("object_name"), Session.get("spaceId")
Tracker.autorun (c)->
if Creator.subs["CreatorListViews"].ready() && Creator.bootstrapLoaded.get()
object_listViews = Creator.getCollection("object_listviews").find({space: Session.get("spaceId"), object_name: Session.get("object_name")})
if !Creator.getObject(Session.get("object_name"))
return
list_views = Creator.getObject(Session.get("object_name")).list_views
list_views_byname = Creator.getObject(Session.get("object_name")).list_views
defaultView = Creator.getObjectDefaultView(Session.get("object_name"))
object_listViews.forEach (listview)->
_list_view = Creator.convertListView(defaultView, listview, listview.name)
if listview.api_name
_key = listview.api_name
else
_key = listview._id
# if listview.is_default
# _key = "<KEY>"
list_views[_key] = _list_view
list_views_byname[_key] = _list_view
Session.set("change_list_views", Random.id())
Creator.getCollection("object_listviews").find().observe {
removed: (oldDocument) ->
# if oldDocument.name == "recent"
# key = oldDocument.name
# else
# key = oldDocument._id
if oldDocument.api_name
key = oldDocument.api_name
else
key = oldDocument._id
delete Creator.Objects[Session.get("object_name")].list_views[key]
delete Creator.getObject(Session.get("object_name")).list_views[key]
}
Meteor.startup ->
Tracker.autorun (c)->
object_name = Session.get("object_name")
related_object_name = Session.get("related_object_name")
if object_name or related_object_name
object_a = [object_name, related_object_name]
object_a = _.compact(object_a)
Creator.subs["TabularSetting"].subscribe "user_tabular_settings", object_a
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("record_id")
Creator.subs["CreatorRecord"].subscribe "creator_object_record", Session.get("object_name"), Session.get("record_id"), Session.get('spaceId')
#
# Tracker.autorun (c)->
# if Session.get("action_object_name") and Session.get("action_record_id")
# Creator.subs["CreatorActionRecord"].subscribe "creator_object_record", Session.get("action_object_name"), Session.get("action_record_id"), Session.get('spaceId')
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("spaceId")
Meteor.subscribe("myFollows", Session.get("spaceId"))
Meteor.startup ->
Tracker.autorun (c)->
if Meteor.userId()
Steedos.subs["PendingSpace"].subscribe "space_need_to_confirm"
spaceNeedToConfirm = db.space_users.find({user: Meteor.userId(), invite_state: "pending"}).fetch() || []
spaceNeedToConfirm.forEach (obj) ->
Meteor.call 'getPendingSpaceInfo', obj.created_by, obj.space, (error,result) ->
console.log("getPendingSpaceInfo=====", result);
if error
console.log error
else
swal {
title: t("pending_space_invite_info", {inviter: result.inviter, space: result.space})
type: "info"
showCancelButton: true
cancelButtonText: "拒绝"
confirmButtonColor: "#2196f3"
confirmButtonText: t('OK')
closeOnConfirm: true
allowEscapeKey: false
allowOutsideClick: false
}, (option)->
if option
Meteor.call 'acceptJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'acceptJoinSpace'
else
Meteor.call 'refuseJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'refuseJoinSpace'
| true | Creator.subs["Creator"] = new SubsManager()
Creator.subs["CreatorListViews"] = new SubsManager()
Creator.subs["TabularSetting"] = new SubsManager()
Creator.subs["CreatorRecord"] = new SubsManager()
Creator.subs["CreatorActionRecord"] = new SubsManager()
Creator.subs["objectRecentViewed"] = new SubsManager()
Steedos.subs["PendingSpace"] = new SubsManager();
Meteor.startup ->
# Tracker.autorun (c)->
# if Session.get("object_name")
# Creator.subs["objectRecentViewed"].subscribe "object_recent_viewed", Session.get("object_name")
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("spaceId")
Creator.subs["CreatorListViews"].subscribe "object_listviews", Session.get("object_name"), Session.get("spaceId")
Tracker.autorun (c)->
if Creator.subs["CreatorListViews"].ready() && Creator.bootstrapLoaded.get()
object_listViews = Creator.getCollection("object_listviews").find({space: Session.get("spaceId"), object_name: Session.get("object_name")})
if !Creator.getObject(Session.get("object_name"))
return
list_views = Creator.getObject(Session.get("object_name")).list_views
list_views_byname = Creator.getObject(Session.get("object_name")).list_views
defaultView = Creator.getObjectDefaultView(Session.get("object_name"))
object_listViews.forEach (listview)->
_list_view = Creator.convertListView(defaultView, listview, listview.name)
if listview.api_name
_key = listview.api_name
else
_key = listview._id
# if listview.is_default
# _key = "PI:KEY:<KEY>END_PI"
list_views[_key] = _list_view
list_views_byname[_key] = _list_view
Session.set("change_list_views", Random.id())
Creator.getCollection("object_listviews").find().observe {
removed: (oldDocument) ->
# if oldDocument.name == "recent"
# key = oldDocument.name
# else
# key = oldDocument._id
if oldDocument.api_name
key = oldDocument.api_name
else
key = oldDocument._id
delete Creator.Objects[Session.get("object_name")].list_views[key]
delete Creator.getObject(Session.get("object_name")).list_views[key]
}
Meteor.startup ->
Tracker.autorun (c)->
object_name = Session.get("object_name")
related_object_name = Session.get("related_object_name")
if object_name or related_object_name
object_a = [object_name, related_object_name]
object_a = _.compact(object_a)
Creator.subs["TabularSetting"].subscribe "user_tabular_settings", object_a
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("object_name") and Session.get("record_id")
Creator.subs["CreatorRecord"].subscribe "creator_object_record", Session.get("object_name"), Session.get("record_id"), Session.get('spaceId')
#
# Tracker.autorun (c)->
# if Session.get("action_object_name") and Session.get("action_record_id")
# Creator.subs["CreatorActionRecord"].subscribe "creator_object_record", Session.get("action_object_name"), Session.get("action_record_id"), Session.get('spaceId')
Meteor.startup ->
Tracker.autorun (c)->
if Session.get("spaceId")
Meteor.subscribe("myFollows", Session.get("spaceId"))
Meteor.startup ->
Tracker.autorun (c)->
if Meteor.userId()
Steedos.subs["PendingSpace"].subscribe "space_need_to_confirm"
spaceNeedToConfirm = db.space_users.find({user: Meteor.userId(), invite_state: "pending"}).fetch() || []
spaceNeedToConfirm.forEach (obj) ->
Meteor.call 'getPendingSpaceInfo', obj.created_by, obj.space, (error,result) ->
console.log("getPendingSpaceInfo=====", result);
if error
console.log error
else
swal {
title: t("pending_space_invite_info", {inviter: result.inviter, space: result.space})
type: "info"
showCancelButton: true
cancelButtonText: "拒绝"
confirmButtonColor: "#2196f3"
confirmButtonText: t('OK')
closeOnConfirm: true
allowEscapeKey: false
allowOutsideClick: false
}, (option)->
if option
Meteor.call 'acceptJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'acceptJoinSpace'
else
Meteor.call 'refuseJoinSpace', obj._id, (error,result) ->
if error
console.log error
else
console.log 'refuseJoinSpace'
|
[
{
"context": "-----------------------------\n# Copyright (c) 2012 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.",
"end": 117,
"score": 0.9998291730880737,
"start": 102,
"tag": "NAME",
"value": "Patrick Mueller"
}
] | lib/offl-site/Processor.coffee | pmuellr/offl-site | 1 | #-------------------------------------------------------------------------------
# Copyright (c) 2012 Patrick Mueller
#
# 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.
#-------------------------------------------------------------------------------
fs = require 'fs'
path = require 'path'
events = require 'events'
util = require 'util'
crypto = require 'crypto'
utils = require '../utils'
FileSet = require '../FileSet'
#-------------------------------------------------------------------------------
module.exports = class Processor extends events.EventEmitter
#---------------------------------------------------------------------------
constructor: (@iDir, @oDir, @options) ->
@records = []
#---------------------------------------------------------------------------
process: ->
@iDirFull = path.resolve @iDir
@oDirFull = path.resolve @oDir
if !path.existsSync @iDirFull
@emitErrorMessage "input directory '#{@iDir}' does not exist"
return
if !path.existsSync @oDirFull
@emitErrorMessage "output directory '#{@oDir}' does not exist"
return
iStats = fs.statSync @iDirFull
oStats = fs.statSync @oDirFull
if !iStats.isDirectory()
@emitErrorMessage "input directory '#{@iDir}' is not a directory"
return
if !oStats.isDirectory()
@emitErrorMessage "output directory '#{@oDir}' is not a directory"
return
if @iDirFull == @oDirFull
@emitErrorMessage "the input and output directory cannot be the same"
return
@checkForMain @iDirFull
# console.log "iDir: #{@iDir} #{@iDirFull}"
# console.log "oDir: #{@oDir} #{@oDirFull}"
# console.log "options: #{JSON.stringify(@options)}"
# console.log ""
# iFileSet = FileSet.fromDir(@iDirFull)
# oFileSet = FileSet.fromDir(@oDirFull)
# console.log "iDir files:"
# iFileSet.dump()
# console.log ""
# console.log "oDir files:"
# oFileSet.dump()
@emptyDir(@oDirFull)
@copyFiles(@oDirFull, @iDirFull, @)
@writeManifest()
@writeHtAccess()
@writeGitIgnore()
utils.log "site created in: #{@oDir}"
@emit 'done'
#---------------------------------------------------------------------------
writeHtAccess: ->
htAccess = path.join(@oDirFull, '.htaccess')
return if path.existsSync(htAccess)
contents = """
# add header for CORS
Header set Access-Control-Allow-Origin *
"""
fs.writeFileSync htAccess, contents
utils.logVerbose "created: #{htAccess}"
#---------------------------------------------------------------------------
writeGitIgnore: ->
gitIgnore = path.join(@oDirFull, '.gitignore')
return if path.existsSync(gitIgnore)
contents = """
# skip base64 encoded binaries
*.jpg.data
*.png.data
*.gif.data
"""
fs.writeFileSync gitIgnore, contents
utils.logVerbose "created: #{gitIgnore}"
#---------------------------------------------------------------------------
writeManifest: ->
manifest = path.join(@oDirFull, 'offl-site.manifest.json')
contents = JSON.stringify(@records, null, 4)
fs.writeFileSync manifest, contents
manifest = path.join(@oDir, path.basename(manifest))
utils.logVerbose "created: #{manifest}"
#---------------------------------------------------------------------------
checkForMain: (dir) ->
exts = [
".html"
".ms.html"
".md"
".ms.md"
]
for ext in exts
fileName = "#{dir}/main#{ext}"
return if path.existsSync(fileName)
@emitErrorMessage "a 'main' page was not found in the input directory"
#---------------------------------------------------------------------------
addFileRecord: (file, origFile, stats, encoding) ->
record =
path: file
size: stats.size
if file != origFile
record.origPath = origFile
if encoding
record.encoding = encoding
@records.push record
#---------------------------------------------------------------------------
emitErrorMessage: (message) ->
@emit 'error', new Error(message)
#---------------------------------------------------------------------------
copyFiles: (toDir, fromDir, processor) ->
fileSet = FileSet.fromDir(fromDir)
for dir in fileSet.relDirs()
dir = path.join(toDir, dir)
fs.mkdirSync(dir)
utils.logVerbose "created: #{dir}/"
for file in fileSet.relFiles()
fromFile = path.join(fromDir, file)
toFile = path.join(toDir, file)
@copyFile(toFile, fromFile, file)
#---------------------------------------------------------------------------
copyFile: (toFile, fromFile, relFile) ->
origRelFile = relFile
contents = fs.readFileSync(fromFile)
encoding = null
if @shouldUseBase64 toFile
toFile = "#{toFile}.data"
relFile = "#{relFile}.data"
contents = contents.toString 'base64'
encoding = 'base64'
fs.writeFileSync(toFile, contents)
fStats = fs.statSync fromFile
tStats = fs.statSync toFile
fs.utimesSync toFile, fStats.atime, fStats.mtime
utils.logVerbose "copied: #{relFile}"
@addFileRecord relFile, origRelFile, fStats, encoding
#---------------------------------------------------------------------------
shouldUseBase64: (file) ->
matchers = [
/.*\.JPG$/
/.*\.GIF$/
/.*\.PNG$/
]
file = file.toUpperCase()
for matcher in matchers
return true if file.match matcher
return false
#---------------------------------------------------------------------------
emptyDir: (dir) ->
fileSet = FileSet.fromDir(dir)
for file in fileSet.fullFiles()
utils.logVerbose "erased: #{file}"
fs.unlinkSync file
for dir in fileSet.fullDirs().reverse()
utils.logVerbose "rmdir: #{dir}"
fs.rmdirSync dir
| 186168 | #-------------------------------------------------------------------------------
# Copyright (c) 2012 <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.
#-------------------------------------------------------------------------------
fs = require 'fs'
path = require 'path'
events = require 'events'
util = require 'util'
crypto = require 'crypto'
utils = require '../utils'
FileSet = require '../FileSet'
#-------------------------------------------------------------------------------
module.exports = class Processor extends events.EventEmitter
#---------------------------------------------------------------------------
constructor: (@iDir, @oDir, @options) ->
@records = []
#---------------------------------------------------------------------------
process: ->
@iDirFull = path.resolve @iDir
@oDirFull = path.resolve @oDir
if !path.existsSync @iDirFull
@emitErrorMessage "input directory '#{@iDir}' does not exist"
return
if !path.existsSync @oDirFull
@emitErrorMessage "output directory '#{@oDir}' does not exist"
return
iStats = fs.statSync @iDirFull
oStats = fs.statSync @oDirFull
if !iStats.isDirectory()
@emitErrorMessage "input directory '#{@iDir}' is not a directory"
return
if !oStats.isDirectory()
@emitErrorMessage "output directory '#{@oDir}' is not a directory"
return
if @iDirFull == @oDirFull
@emitErrorMessage "the input and output directory cannot be the same"
return
@checkForMain @iDirFull
# console.log "iDir: #{@iDir} #{@iDirFull}"
# console.log "oDir: #{@oDir} #{@oDirFull}"
# console.log "options: #{JSON.stringify(@options)}"
# console.log ""
# iFileSet = FileSet.fromDir(@iDirFull)
# oFileSet = FileSet.fromDir(@oDirFull)
# console.log "iDir files:"
# iFileSet.dump()
# console.log ""
# console.log "oDir files:"
# oFileSet.dump()
@emptyDir(@oDirFull)
@copyFiles(@oDirFull, @iDirFull, @)
@writeManifest()
@writeHtAccess()
@writeGitIgnore()
utils.log "site created in: #{@oDir}"
@emit 'done'
#---------------------------------------------------------------------------
writeHtAccess: ->
htAccess = path.join(@oDirFull, '.htaccess')
return if path.existsSync(htAccess)
contents = """
# add header for CORS
Header set Access-Control-Allow-Origin *
"""
fs.writeFileSync htAccess, contents
utils.logVerbose "created: #{htAccess}"
#---------------------------------------------------------------------------
writeGitIgnore: ->
gitIgnore = path.join(@oDirFull, '.gitignore')
return if path.existsSync(gitIgnore)
contents = """
# skip base64 encoded binaries
*.jpg.data
*.png.data
*.gif.data
"""
fs.writeFileSync gitIgnore, contents
utils.logVerbose "created: #{gitIgnore}"
#---------------------------------------------------------------------------
writeManifest: ->
manifest = path.join(@oDirFull, 'offl-site.manifest.json')
contents = JSON.stringify(@records, null, 4)
fs.writeFileSync manifest, contents
manifest = path.join(@oDir, path.basename(manifest))
utils.logVerbose "created: #{manifest}"
#---------------------------------------------------------------------------
checkForMain: (dir) ->
exts = [
".html"
".ms.html"
".md"
".ms.md"
]
for ext in exts
fileName = "#{dir}/main#{ext}"
return if path.existsSync(fileName)
@emitErrorMessage "a 'main' page was not found in the input directory"
#---------------------------------------------------------------------------
addFileRecord: (file, origFile, stats, encoding) ->
record =
path: file
size: stats.size
if file != origFile
record.origPath = origFile
if encoding
record.encoding = encoding
@records.push record
#---------------------------------------------------------------------------
emitErrorMessage: (message) ->
@emit 'error', new Error(message)
#---------------------------------------------------------------------------
copyFiles: (toDir, fromDir, processor) ->
fileSet = FileSet.fromDir(fromDir)
for dir in fileSet.relDirs()
dir = path.join(toDir, dir)
fs.mkdirSync(dir)
utils.logVerbose "created: #{dir}/"
for file in fileSet.relFiles()
fromFile = path.join(fromDir, file)
toFile = path.join(toDir, file)
@copyFile(toFile, fromFile, file)
#---------------------------------------------------------------------------
copyFile: (toFile, fromFile, relFile) ->
origRelFile = relFile
contents = fs.readFileSync(fromFile)
encoding = null
if @shouldUseBase64 toFile
toFile = "#{toFile}.data"
relFile = "#{relFile}.data"
contents = contents.toString 'base64'
encoding = 'base64'
fs.writeFileSync(toFile, contents)
fStats = fs.statSync fromFile
tStats = fs.statSync toFile
fs.utimesSync toFile, fStats.atime, fStats.mtime
utils.logVerbose "copied: #{relFile}"
@addFileRecord relFile, origRelFile, fStats, encoding
#---------------------------------------------------------------------------
shouldUseBase64: (file) ->
matchers = [
/.*\.JPG$/
/.*\.GIF$/
/.*\.PNG$/
]
file = file.toUpperCase()
for matcher in matchers
return true if file.match matcher
return false
#---------------------------------------------------------------------------
emptyDir: (dir) ->
fileSet = FileSet.fromDir(dir)
for file in fileSet.fullFiles()
utils.logVerbose "erased: #{file}"
fs.unlinkSync file
for dir in fileSet.fullDirs().reverse()
utils.logVerbose "rmdir: #{dir}"
fs.rmdirSync dir
| true | #-------------------------------------------------------------------------------
# Copyright (c) 2012 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.
#-------------------------------------------------------------------------------
fs = require 'fs'
path = require 'path'
events = require 'events'
util = require 'util'
crypto = require 'crypto'
utils = require '../utils'
FileSet = require '../FileSet'
#-------------------------------------------------------------------------------
module.exports = class Processor extends events.EventEmitter
#---------------------------------------------------------------------------
constructor: (@iDir, @oDir, @options) ->
@records = []
#---------------------------------------------------------------------------
process: ->
@iDirFull = path.resolve @iDir
@oDirFull = path.resolve @oDir
if !path.existsSync @iDirFull
@emitErrorMessage "input directory '#{@iDir}' does not exist"
return
if !path.existsSync @oDirFull
@emitErrorMessage "output directory '#{@oDir}' does not exist"
return
iStats = fs.statSync @iDirFull
oStats = fs.statSync @oDirFull
if !iStats.isDirectory()
@emitErrorMessage "input directory '#{@iDir}' is not a directory"
return
if !oStats.isDirectory()
@emitErrorMessage "output directory '#{@oDir}' is not a directory"
return
if @iDirFull == @oDirFull
@emitErrorMessage "the input and output directory cannot be the same"
return
@checkForMain @iDirFull
# console.log "iDir: #{@iDir} #{@iDirFull}"
# console.log "oDir: #{@oDir} #{@oDirFull}"
# console.log "options: #{JSON.stringify(@options)}"
# console.log ""
# iFileSet = FileSet.fromDir(@iDirFull)
# oFileSet = FileSet.fromDir(@oDirFull)
# console.log "iDir files:"
# iFileSet.dump()
# console.log ""
# console.log "oDir files:"
# oFileSet.dump()
@emptyDir(@oDirFull)
@copyFiles(@oDirFull, @iDirFull, @)
@writeManifest()
@writeHtAccess()
@writeGitIgnore()
utils.log "site created in: #{@oDir}"
@emit 'done'
#---------------------------------------------------------------------------
writeHtAccess: ->
htAccess = path.join(@oDirFull, '.htaccess')
return if path.existsSync(htAccess)
contents = """
# add header for CORS
Header set Access-Control-Allow-Origin *
"""
fs.writeFileSync htAccess, contents
utils.logVerbose "created: #{htAccess}"
#---------------------------------------------------------------------------
writeGitIgnore: ->
gitIgnore = path.join(@oDirFull, '.gitignore')
return if path.existsSync(gitIgnore)
contents = """
# skip base64 encoded binaries
*.jpg.data
*.png.data
*.gif.data
"""
fs.writeFileSync gitIgnore, contents
utils.logVerbose "created: #{gitIgnore}"
#---------------------------------------------------------------------------
writeManifest: ->
manifest = path.join(@oDirFull, 'offl-site.manifest.json')
contents = JSON.stringify(@records, null, 4)
fs.writeFileSync manifest, contents
manifest = path.join(@oDir, path.basename(manifest))
utils.logVerbose "created: #{manifest}"
#---------------------------------------------------------------------------
checkForMain: (dir) ->
exts = [
".html"
".ms.html"
".md"
".ms.md"
]
for ext in exts
fileName = "#{dir}/main#{ext}"
return if path.existsSync(fileName)
@emitErrorMessage "a 'main' page was not found in the input directory"
#---------------------------------------------------------------------------
addFileRecord: (file, origFile, stats, encoding) ->
record =
path: file
size: stats.size
if file != origFile
record.origPath = origFile
if encoding
record.encoding = encoding
@records.push record
#---------------------------------------------------------------------------
emitErrorMessage: (message) ->
@emit 'error', new Error(message)
#---------------------------------------------------------------------------
copyFiles: (toDir, fromDir, processor) ->
fileSet = FileSet.fromDir(fromDir)
for dir in fileSet.relDirs()
dir = path.join(toDir, dir)
fs.mkdirSync(dir)
utils.logVerbose "created: #{dir}/"
for file in fileSet.relFiles()
fromFile = path.join(fromDir, file)
toFile = path.join(toDir, file)
@copyFile(toFile, fromFile, file)
#---------------------------------------------------------------------------
copyFile: (toFile, fromFile, relFile) ->
origRelFile = relFile
contents = fs.readFileSync(fromFile)
encoding = null
if @shouldUseBase64 toFile
toFile = "#{toFile}.data"
relFile = "#{relFile}.data"
contents = contents.toString 'base64'
encoding = 'base64'
fs.writeFileSync(toFile, contents)
fStats = fs.statSync fromFile
tStats = fs.statSync toFile
fs.utimesSync toFile, fStats.atime, fStats.mtime
utils.logVerbose "copied: #{relFile}"
@addFileRecord relFile, origRelFile, fStats, encoding
#---------------------------------------------------------------------------
shouldUseBase64: (file) ->
matchers = [
/.*\.JPG$/
/.*\.GIF$/
/.*\.PNG$/
]
file = file.toUpperCase()
for matcher in matchers
return true if file.match matcher
return false
#---------------------------------------------------------------------------
emptyDir: (dir) ->
fileSet = FileSet.fromDir(dir)
for file in fileSet.fullFiles()
utils.logVerbose "erased: #{file}"
fs.unlinkSync file
for dir in fileSet.fullDirs().reverse()
utils.logVerbose "rmdir: #{dir}"
fs.rmdirSync dir
|
[
{
"context": " ITS OWN PACKAGE. PLEASE USE\n# https://github.com/lorenzhs/hubot-tell INSTEAD!\n#\n# Description:\n# Tell Hub",
"end": 84,
"score": 0.998997688293457,
"start": 76,
"tag": "USERNAME",
"value": "lorenzhs"
},
{
"context": "oo\" also matches \"Foo\" and \"foooo\"\n#\n# Author:\n# christianchristensen, lorenzhs, xhochy\n\nmodule.exports = (robot) ->\n ",
"end": 504,
"score": 0.9969038963317871,
"start": 484,
"tag": "NAME",
"value": "christianchristensen"
},
{
"context": " and \"foooo\"\n#\n# Author:\n# christianchristensen, lorenzhs, xhochy\n\nmodule.exports = (robot) ->\n robot.log",
"end": 514,
"score": 0.998574435710907,
"start": 506,
"tag": "USERNAME",
"value": "lorenzhs"
},
{
"context": "o\"\n#\n# Author:\n# christianchristensen, lorenzhs, xhochy\n\nmodule.exports = (robot) ->\n robot.logger.warn",
"end": 522,
"score": 0.9989222288131714,
"start": 516,
"tag": "USERNAME",
"value": "xhochy"
},
{
"context": "cripts to its own package. See https://github.com/lorenzhs/hubot-tell/blob/master/UPGRADING.md for upgrade i",
"end": 669,
"score": 0.9970774054527283,
"start": 661,
"tag": "USERNAME",
"value": "lorenzhs"
}
] | src/scripts/tell.coffee | Snagajob/hubot-scripts | 9 | # THIS SCRIPT HAS MOVED TO ITS OWN PACKAGE. PLEASE USE
# https://github.com/lorenzhs/hubot-tell INSTEAD!
#
# Description:
# Tell Hubot to send a user a message when present in the room
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot tell <username> <some message> - tell <username> <some message> next time they are present. Case-Insensitive prefix matching is employed when matching usernames, so "foo" also matches "Foo" and "foooo"
#
# Author:
# christianchristensen, lorenzhs, xhochy
module.exports = (robot) ->
robot.logger.warning "tell.coffee has moved from hubot-scripts to its own package. See https://github.com/lorenzhs/hubot-tell/blob/master/UPGRADING.md for upgrade instructions"
localstorage = {}
robot.respond /tell ([\w.-]*):? (.*)/i, (msg) ->
datetime = new Date()
username = msg.match[1]
room = msg.message.user.room
tellmessage = msg.message.user.name + " @ " + datetime.toLocaleString() + " said: " + msg.match[2] + "\r\n"
if not localstorage[room]?
localstorage[room] = {}
if localstorage[room][username]?
localstorage[room][username] += tellmessage
else
localstorage[room][username] = tellmessage
msg.send "Ok, I'll tell #{username} you said '#{msg.match[2]}'."
return
# When a user enters, check if someone left them a message
robot.enter (msg) ->
username = msg.message.user.name
room = msg.message.user.room
if localstorage[room]?
for recipient, message of localstorage[room]
# Check if the recipient matches username
if username.match(new RegExp "^"+recipient, "i")
tellmessage = username + ": " + localstorage[room][recipient]
delete localstorage[room][recipient]
msg.send tellmessage
return
| 1503 | # THIS SCRIPT HAS MOVED TO ITS OWN PACKAGE. PLEASE USE
# https://github.com/lorenzhs/hubot-tell INSTEAD!
#
# Description:
# Tell Hubot to send a user a message when present in the room
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot tell <username> <some message> - tell <username> <some message> next time they are present. Case-Insensitive prefix matching is employed when matching usernames, so "foo" also matches "Foo" and "foooo"
#
# Author:
# <NAME>, lorenzhs, xhochy
module.exports = (robot) ->
robot.logger.warning "tell.coffee has moved from hubot-scripts to its own package. See https://github.com/lorenzhs/hubot-tell/blob/master/UPGRADING.md for upgrade instructions"
localstorage = {}
robot.respond /tell ([\w.-]*):? (.*)/i, (msg) ->
datetime = new Date()
username = msg.match[1]
room = msg.message.user.room
tellmessage = msg.message.user.name + " @ " + datetime.toLocaleString() + " said: " + msg.match[2] + "\r\n"
if not localstorage[room]?
localstorage[room] = {}
if localstorage[room][username]?
localstorage[room][username] += tellmessage
else
localstorage[room][username] = tellmessage
msg.send "Ok, I'll tell #{username} you said '#{msg.match[2]}'."
return
# When a user enters, check if someone left them a message
robot.enter (msg) ->
username = msg.message.user.name
room = msg.message.user.room
if localstorage[room]?
for recipient, message of localstorage[room]
# Check if the recipient matches username
if username.match(new RegExp "^"+recipient, "i")
tellmessage = username + ": " + localstorage[room][recipient]
delete localstorage[room][recipient]
msg.send tellmessage
return
| true | # THIS SCRIPT HAS MOVED TO ITS OWN PACKAGE. PLEASE USE
# https://github.com/lorenzhs/hubot-tell INSTEAD!
#
# Description:
# Tell Hubot to send a user a message when present in the room
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot tell <username> <some message> - tell <username> <some message> next time they are present. Case-Insensitive prefix matching is employed when matching usernames, so "foo" also matches "Foo" and "foooo"
#
# Author:
# PI:NAME:<NAME>END_PI, lorenzhs, xhochy
module.exports = (robot) ->
robot.logger.warning "tell.coffee has moved from hubot-scripts to its own package. See https://github.com/lorenzhs/hubot-tell/blob/master/UPGRADING.md for upgrade instructions"
localstorage = {}
robot.respond /tell ([\w.-]*):? (.*)/i, (msg) ->
datetime = new Date()
username = msg.match[1]
room = msg.message.user.room
tellmessage = msg.message.user.name + " @ " + datetime.toLocaleString() + " said: " + msg.match[2] + "\r\n"
if not localstorage[room]?
localstorage[room] = {}
if localstorage[room][username]?
localstorage[room][username] += tellmessage
else
localstorage[room][username] = tellmessage
msg.send "Ok, I'll tell #{username} you said '#{msg.match[2]}'."
return
# When a user enters, check if someone left them a message
robot.enter (msg) ->
username = msg.message.user.name
room = msg.message.user.room
if localstorage[room]?
for recipient, message of localstorage[room]
# Check if the recipient matches username
if username.match(new RegExp "^"+recipient, "i")
tellmessage = username + ": " + localstorage[room][recipient]
delete localstorage[room][recipient]
msg.send tellmessage
return
|
[
{
"context": "ssage', => done()\n @sut.send 'message', 'Minerva Walters'\n\n it 'should call socket.send', ->\n ",
"end": 1717,
"score": 0.9993731379508972,
"start": 1702,
"tag": "NAME",
"value": "Minerva Walters"
}
] | test/src/reconnect-socket-spec.coffee | octoblu/npm | 3 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
ReconnectSocket = require '../../src/reconnect-socket'
AsymmetricSocket = require '../asymmetric-socket'
describe 'ReconnectSocket', ->
describe '->constructor', ->
describe 'when srvOptions are passed in', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.connect = sinon.stub()
srvOptions = {port: 123, hostname: 'foo.biz'}
@SrvSocket = sinon.spy(=> @socket)
new ReconnectSocket {srvOptions}, {@SrvSocket}
it 'should pass them to the SrvSocket constructor', ->
expect(@SrvSocket).to.have.been.calledWithNew
expect(@SrvSocket).to.have.been.calledWith {port: 123, hostname: 'foo.biz'}
describe 'when constructed', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.close = sinon.stub()
@sut = new ReconnectSocket {backoffMin: 10, connectionTimeout: 10}, {SrvSocket: => @socket}
describe '->close', ->
beforeEach (done) ->
@socket.close.yields()
@sut.close done
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->connect', ->
describe 'when connect yields right away', ->
beforeEach ->
@socket.connect = sinon.stub()
@sut.connect()
it 'should call socket.connect', ->
expect(@socket.connect).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'send'
@socket.outgoing.on 'message', => done()
@sut.send 'message', 'Minerva Walters'
it 'should call socket.send', ->
expect(@socket.send).to.have.been.called
| 20999 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
ReconnectSocket = require '../../src/reconnect-socket'
AsymmetricSocket = require '../asymmetric-socket'
describe 'ReconnectSocket', ->
describe '->constructor', ->
describe 'when srvOptions are passed in', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.connect = sinon.stub()
srvOptions = {port: 123, hostname: 'foo.biz'}
@SrvSocket = sinon.spy(=> @socket)
new ReconnectSocket {srvOptions}, {@SrvSocket}
it 'should pass them to the SrvSocket constructor', ->
expect(@SrvSocket).to.have.been.calledWithNew
expect(@SrvSocket).to.have.been.calledWith {port: 123, hostname: 'foo.biz'}
describe 'when constructed', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.close = sinon.stub()
@sut = new ReconnectSocket {backoffMin: 10, connectionTimeout: 10}, {SrvSocket: => @socket}
describe '->close', ->
beforeEach (done) ->
@socket.close.yields()
@sut.close done
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->connect', ->
describe 'when connect yields right away', ->
beforeEach ->
@socket.connect = sinon.stub()
@sut.connect()
it 'should call socket.connect', ->
expect(@socket.connect).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'send'
@socket.outgoing.on 'message', => done()
@sut.send 'message', '<NAME>'
it 'should call socket.send', ->
expect(@socket.send).to.have.been.called
| true | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
ReconnectSocket = require '../../src/reconnect-socket'
AsymmetricSocket = require '../asymmetric-socket'
describe 'ReconnectSocket', ->
describe '->constructor', ->
describe 'when srvOptions are passed in', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.connect = sinon.stub()
srvOptions = {port: 123, hostname: 'foo.biz'}
@SrvSocket = sinon.spy(=> @socket)
new ReconnectSocket {srvOptions}, {@SrvSocket}
it 'should pass them to the SrvSocket constructor', ->
expect(@SrvSocket).to.have.been.calledWithNew
expect(@SrvSocket).to.have.been.calledWith {port: 123, hostname: 'foo.biz'}
describe 'when constructed', ->
beforeEach ->
@socket = new AsymmetricSocket
@socket.close = sinon.stub()
@sut = new ReconnectSocket {backoffMin: 10, connectionTimeout: 10}, {SrvSocket: => @socket}
describe '->close', ->
beforeEach (done) ->
@socket.close.yields()
@sut.close done
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->connect', ->
describe 'when connect yields right away', ->
beforeEach ->
@socket.connect = sinon.stub()
@sut.connect()
it 'should call socket.connect', ->
expect(@socket.connect).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'send'
@socket.outgoing.on 'message', => done()
@sut.send 'message', 'PI:NAME:<NAME>END_PI'
it 'should call socket.send', ->
expect(@socket.send).to.have.been.called
|
[
{
"context": "with hold I\\n\\n\n... elided paragraph last ...\\n\\n\nFrost Robert -----------------------'\n\nreverseString = (s) ->\n",
"end": 233,
"score": 0.9994321465492249,
"start": 221,
"tag": "NAME",
"value": "Frost Robert"
}
] | Task/Reverse-words-in-a-string/CoffeeScript/reverse-words-in-a-string.coffee | LaudateCorpus1/RosettaCodeData | 1 | strReversed = '---------- Ice and Fire ------------\n\n
fire, in end will world the say Some\n
ice. in say Some\n
desire of tasted I\'ve what From\n
fire. favor who those with hold I\n\n
... elided paragraph last ...\n\n
Frost Robert -----------------------'
reverseString = (s) ->
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'
console.log reverseString(strReversed)
| 126480 | strReversed = '---------- Ice and Fire ------------\n\n
fire, in end will world the say Some\n
ice. in say Some\n
desire of tasted I\'ve what From\n
fire. favor who those with hold I\n\n
... elided paragraph last ...\n\n
<NAME> -----------------------'
reverseString = (s) ->
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'
console.log reverseString(strReversed)
| true | strReversed = '---------- Ice and Fire ------------\n\n
fire, in end will world the say Some\n
ice. in say Some\n
desire of tasted I\'ve what From\n
fire. favor who those with hold I\n\n
... elided paragraph last ...\n\n
PI:NAME:<NAME>END_PI -----------------------'
reverseString = (s) ->
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'
console.log reverseString(strReversed)
|
[
{
"context": " doesn't have the same set of params.\n# \n# @author Jeremy Trufier <jeremy@trufier.com> (https://github.com/Tronix11",
"end": 1617,
"score": 0.9999035596847534,
"start": 1603,
"tag": "NAME",
"value": "Jeremy Trufier"
},
{
"context": " same set of params.\n# \n# @author Jeremy Trufier <jeremy@trufier.com> (https://github.com/Tronix117)\n# @gist https://g",
"end": 1637,
"score": 0.999929666519165,
"start": 1619,
"tag": "EMAIL",
"value": "jeremy@trufier.com"
},
{
"context": " Trufier <jeremy@trufier.com> (https://github.com/Tronix117)\n# @gist https://gist.github.com/Tronix117/79179",
"end": 1667,
"score": 0.998834490776062,
"start": 1659,
"tag": "USERNAME",
"value": "Tronix11"
},
{
"context": "ub.com/Tronix117)\n# @gist https://gist.github.com/Tronix117/7917925\n# @license MIT\n# ------------------------",
"end": 1711,
"score": 0.9995860457420349,
"start": 1702,
"tag": "USERNAME",
"value": "Tronix117"
}
] | app/lib/smart-navigate.coffee | Tronix117/kingdomtools | 1 | # Chaplin Smart Navigation
#
# Chaplin.mediator.smartNavigate params, options
#
# Add a smartNavigate method to Chaplin.mediator, it will automaticaly select
# the best route using only route params in first argument.
#
# Keep automaticaly current route params, except if they are explicitely set to
# null or if `reset: true` is passed as second argument.
#
# Exemple:
#
# First, don't forget to require this file before Application is initialized.
#
# Then, simply add an option `smart: true` on each route that should benefit
# from smart navigation.
#
# `routes.coffee` exemple:
# ...
# match '/posts' , 'posts#show', smart: true
# match '/posts/:postId' , 'posts#show', smart: true
# match '/users/:userId/posts' , 'user#show' , smart: true
# match '/users/:userId/posts/:postId', 'posts#show', smart: true
# ...
#
# Now you can call Chaplin.mediator.smartNavigate wherever you want:
# # Following methods are called in this specific order
#
# Chaplin.mediator.smartNavigate userId: 12
# # -> will trigger '/users/12/posts'
#
# Chaplin.mediator.smartNavigate postId: 23
# # -> will trigger '/users/12/posts/23'
#
# Chaplin.mediator.smartNavigate userId: null
# # -> will trigger '/posts/23'
#
# Chaplin.mediator.smartNavigate()
# # -> will trigger '/posts/23' again
#
# Chaplin.mediator.smartNavigate null, reset: true
# # -> will trigger '/posts'
#
# Magic! Just make sure two routes doesn't have the same set of params.
#
# @author Jeremy Trufier <jeremy@trufier.com> (https://github.com/Tronix117)
# @gist https://gist.github.com/Tronix117/7917925
# @license MIT
# -------------------------------------
mediator = module.exports = Chaplin.mediator
# Will keep an history of last know route parameters
mediator.lastRouteParams = {}
# Register smart route using sorted paramNames as key, format of key is:
# `paramsName0|paramsNameA|paramsNameB|paramsNameC`
mediator._smartRoutes = {}
# Subscribe to the global event that match routes, before controller get called
mediator.subscribe 'router:match', (route, actionParams, options)->
mediator.lastRouteParams = actionParams
# Override match method of the Router to get routes as they are created
Chaplin.Router.prototype._match = Chaplin.Router.prototype.match
Chaplin.Router.prototype.match = ->
# Call the former method, which will create the route
route = Chaplin.Router.prototype._match.apply @, arguments
# if the route as the `smart` option, then we can use it
if route.options.smart
# Format the route as _smartRoutes expects
sortedParams = route.paramNames.slice().sort().join('|')
# Make sure no two routes use same params to avoid development mistakes
if mediator._smartRoutes[sortedParams]
throw new Error "router#match: smart routes must have unique params set. \
Route <#{route.name}> and <#{mediator._smartRoutes[sortedParams].name}> have \
the same params set"
# Finaly save this route for smart use
mediator._smartRoutes[sortedParams] = route
# Finaly return the route like former method does
route
# Keep last known parameters when navigate, eventually add new ones, remove
# `null` ones and select the best route for those parameters.
#
# `options` may contain following:
# reset: if true only new parameters will be kept, old ones will be removed
mediator.smartNavigate = (params = {}, options = {})->
# Add lastRouteParams to params unless reset option is true
params = _.extend {}, mediator.lastRouteParams, params unless options.reset
# Get list of params key for params that contain a value and format it as
# _smartRoutes expects
keys = _.compact((key if val) for key, val of params).sort().join('|')
# Retrieve the best route using params
unless route = mediator._smartRoutes[keys]
throw new Error 'mediator#smartNavigate: request was not smart routed'
# Finaly trigger the route
mediator.execute 'router:route', route.name, params | 51707 | # Chaplin Smart Navigation
#
# Chaplin.mediator.smartNavigate params, options
#
# Add a smartNavigate method to Chaplin.mediator, it will automaticaly select
# the best route using only route params in first argument.
#
# Keep automaticaly current route params, except if they are explicitely set to
# null or if `reset: true` is passed as second argument.
#
# Exemple:
#
# First, don't forget to require this file before Application is initialized.
#
# Then, simply add an option `smart: true` on each route that should benefit
# from smart navigation.
#
# `routes.coffee` exemple:
# ...
# match '/posts' , 'posts#show', smart: true
# match '/posts/:postId' , 'posts#show', smart: true
# match '/users/:userId/posts' , 'user#show' , smart: true
# match '/users/:userId/posts/:postId', 'posts#show', smart: true
# ...
#
# Now you can call Chaplin.mediator.smartNavigate wherever you want:
# # Following methods are called in this specific order
#
# Chaplin.mediator.smartNavigate userId: 12
# # -> will trigger '/users/12/posts'
#
# Chaplin.mediator.smartNavigate postId: 23
# # -> will trigger '/users/12/posts/23'
#
# Chaplin.mediator.smartNavigate userId: null
# # -> will trigger '/posts/23'
#
# Chaplin.mediator.smartNavigate()
# # -> will trigger '/posts/23' again
#
# Chaplin.mediator.smartNavigate null, reset: true
# # -> will trigger '/posts'
#
# Magic! Just make sure two routes doesn't have the same set of params.
#
# @author <NAME> <<EMAIL>> (https://github.com/Tronix117)
# @gist https://gist.github.com/Tronix117/7917925
# @license MIT
# -------------------------------------
mediator = module.exports = Chaplin.mediator
# Will keep an history of last know route parameters
mediator.lastRouteParams = {}
# Register smart route using sorted paramNames as key, format of key is:
# `paramsName0|paramsNameA|paramsNameB|paramsNameC`
mediator._smartRoutes = {}
# Subscribe to the global event that match routes, before controller get called
mediator.subscribe 'router:match', (route, actionParams, options)->
mediator.lastRouteParams = actionParams
# Override match method of the Router to get routes as they are created
Chaplin.Router.prototype._match = Chaplin.Router.prototype.match
Chaplin.Router.prototype.match = ->
# Call the former method, which will create the route
route = Chaplin.Router.prototype._match.apply @, arguments
# if the route as the `smart` option, then we can use it
if route.options.smart
# Format the route as _smartRoutes expects
sortedParams = route.paramNames.slice().sort().join('|')
# Make sure no two routes use same params to avoid development mistakes
if mediator._smartRoutes[sortedParams]
throw new Error "router#match: smart routes must have unique params set. \
Route <#{route.name}> and <#{mediator._smartRoutes[sortedParams].name}> have \
the same params set"
# Finaly save this route for smart use
mediator._smartRoutes[sortedParams] = route
# Finaly return the route like former method does
route
# Keep last known parameters when navigate, eventually add new ones, remove
# `null` ones and select the best route for those parameters.
#
# `options` may contain following:
# reset: if true only new parameters will be kept, old ones will be removed
mediator.smartNavigate = (params = {}, options = {})->
# Add lastRouteParams to params unless reset option is true
params = _.extend {}, mediator.lastRouteParams, params unless options.reset
# Get list of params key for params that contain a value and format it as
# _smartRoutes expects
keys = _.compact((key if val) for key, val of params).sort().join('|')
# Retrieve the best route using params
unless route = mediator._smartRoutes[keys]
throw new Error 'mediator#smartNavigate: request was not smart routed'
# Finaly trigger the route
mediator.execute 'router:route', route.name, params | true | # Chaplin Smart Navigation
#
# Chaplin.mediator.smartNavigate params, options
#
# Add a smartNavigate method to Chaplin.mediator, it will automaticaly select
# the best route using only route params in first argument.
#
# Keep automaticaly current route params, except if they are explicitely set to
# null or if `reset: true` is passed as second argument.
#
# Exemple:
#
# First, don't forget to require this file before Application is initialized.
#
# Then, simply add an option `smart: true` on each route that should benefit
# from smart navigation.
#
# `routes.coffee` exemple:
# ...
# match '/posts' , 'posts#show', smart: true
# match '/posts/:postId' , 'posts#show', smart: true
# match '/users/:userId/posts' , 'user#show' , smart: true
# match '/users/:userId/posts/:postId', 'posts#show', smart: true
# ...
#
# Now you can call Chaplin.mediator.smartNavigate wherever you want:
# # Following methods are called in this specific order
#
# Chaplin.mediator.smartNavigate userId: 12
# # -> will trigger '/users/12/posts'
#
# Chaplin.mediator.smartNavigate postId: 23
# # -> will trigger '/users/12/posts/23'
#
# Chaplin.mediator.smartNavigate userId: null
# # -> will trigger '/posts/23'
#
# Chaplin.mediator.smartNavigate()
# # -> will trigger '/posts/23' again
#
# Chaplin.mediator.smartNavigate null, reset: true
# # -> will trigger '/posts'
#
# Magic! Just make sure two routes doesn't have the same set of params.
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/Tronix117)
# @gist https://gist.github.com/Tronix117/7917925
# @license MIT
# -------------------------------------
mediator = module.exports = Chaplin.mediator
# Will keep an history of last know route parameters
mediator.lastRouteParams = {}
# Register smart route using sorted paramNames as key, format of key is:
# `paramsName0|paramsNameA|paramsNameB|paramsNameC`
mediator._smartRoutes = {}
# Subscribe to the global event that match routes, before controller get called
mediator.subscribe 'router:match', (route, actionParams, options)->
mediator.lastRouteParams = actionParams
# Override match method of the Router to get routes as they are created
Chaplin.Router.prototype._match = Chaplin.Router.prototype.match
Chaplin.Router.prototype.match = ->
# Call the former method, which will create the route
route = Chaplin.Router.prototype._match.apply @, arguments
# if the route as the `smart` option, then we can use it
if route.options.smart
# Format the route as _smartRoutes expects
sortedParams = route.paramNames.slice().sort().join('|')
# Make sure no two routes use same params to avoid development mistakes
if mediator._smartRoutes[sortedParams]
throw new Error "router#match: smart routes must have unique params set. \
Route <#{route.name}> and <#{mediator._smartRoutes[sortedParams].name}> have \
the same params set"
# Finaly save this route for smart use
mediator._smartRoutes[sortedParams] = route
# Finaly return the route like former method does
route
# Keep last known parameters when navigate, eventually add new ones, remove
# `null` ones and select the best route for those parameters.
#
# `options` may contain following:
# reset: if true only new parameters will be kept, old ones will be removed
mediator.smartNavigate = (params = {}, options = {})->
# Add lastRouteParams to params unless reset option is true
params = _.extend {}, mediator.lastRouteParams, params unless options.reset
# Get list of params key for params that contain a value and format it as
# _smartRoutes expects
keys = _.compact((key if val) for key, val of params).sort().join('|')
# Retrieve the best route using params
unless route = mediator._smartRoutes[keys]
throw new Error 'mediator#smartNavigate: request was not smart routed'
# Finaly trigger the route
mediator.execute 'router:route', route.name, params |
[
{
"context": "ngth: 'wrong length'\n is: 4\n\n m.name('foob')\n v.length(m, 'name', options).then(() ->\n ",
"end": 395,
"score": 0.8493344783782959,
"start": 391,
"tag": "USERNAME",
"value": "foob"
},
{
"context": ") ->\n options =\n is: 4\n\n m.name('foobz')\n v.length(m, 'name', options).then(() ->\n ",
"end": 641,
"score": 0.8205575346946716,
"start": 636,
"tag": "NAME",
"value": "foobz"
},
{
"context": "wrongLength: 'wrong'\n is: 4\n\n m.name('foo')\n v.length(m, 'name', options).then(() ->\n ",
"end": 958,
"score": 0.7867090106010437,
"start": 955,
"tag": "NAME",
"value": "foo"
},
{
"context": " options =\n minimum: 5\n\n m.name('fooba')\n v.length(m, 'name', options).then((succes",
"end": 1755,
"score": 0.913847029209137,
"start": 1750,
"tag": "NAME",
"value": "fooba"
},
{
"context": "Short: 'wrong!'\n minimum: 5\n\n m.name('foob')\n v.length(m, 'name', options).then((succes",
"end": 2062,
"score": 0.9982662200927734,
"start": 2058,
"tag": "USERNAME",
"value": "foob"
},
{
"context": " minimum: 3\n maximum: 5\n\n m.name('foobar')\n v.length(m, 'name', options).then((succes",
"end": 2412,
"score": 0.9993113875389099,
"start": 2406,
"tag": "USERNAME",
"value": "foobar"
}
] | samplenode/samplenode/node_modules/nodejs-model/test/validators/test-length.coffee | thakurarun/Basic-nodejs-express-app | 19 | v = require '../../lib/validators/length'
model = require '../../lib/index'
m = null
describe 'Length validator tests', ->
beforeEach (done) ->
M = model("M").attr('name')
m = M.create()
done()
describe 'Is tests', ->
it 'When is: 4 and value length is 4', (done) ->
options =
messages:
wrongLength: 'wrong length'
is: 4
m.name('foob')
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When is: 4 and value length is 5 (longer) but no message defined', (done) ->
options =
is: 4
m.name('foobz')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['length is incorrect']
done()
)
it 'When is: 4 and value length is 3 (shorter) and message defined', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 4
m.name('foo')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is: 3 and value is blank, (absence of allowBlank=true eq blank not allowed)', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 3
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is:3 and allowBlank=true, value is blank', (done) ->
options =
is: 3
allowBlank: true
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 5', (done) ->
describe 'Minimum, Maximum', ->
options =
minimum: 5
m.name('fooba')
v.length(m, 'name', options).then((success) ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 4', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooShort: 'wrong!'
minimum: 5
m.name('foob')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['wrong!']
done()
)
it 'When minimum: 3, maximum: 5, value is: 6', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooLong: 'long!'
minimum: 3
maximum: 5
m.name('foobar')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['long!']
done()
)
| 170380 | v = require '../../lib/validators/length'
model = require '../../lib/index'
m = null
describe 'Length validator tests', ->
beforeEach (done) ->
M = model("M").attr('name')
m = M.create()
done()
describe 'Is tests', ->
it 'When is: 4 and value length is 4', (done) ->
options =
messages:
wrongLength: 'wrong length'
is: 4
m.name('foob')
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When is: 4 and value length is 5 (longer) but no message defined', (done) ->
options =
is: 4
m.name('<NAME>')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['length is incorrect']
done()
)
it 'When is: 4 and value length is 3 (shorter) and message defined', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 4
m.name('<NAME>')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is: 3 and value is blank, (absence of allowBlank=true eq blank not allowed)', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 3
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is:3 and allowBlank=true, value is blank', (done) ->
options =
is: 3
allowBlank: true
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 5', (done) ->
describe 'Minimum, Maximum', ->
options =
minimum: 5
m.name('<NAME>')
v.length(m, 'name', options).then((success) ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 4', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooShort: 'wrong!'
minimum: 5
m.name('foob')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['wrong!']
done()
)
it 'When minimum: 3, maximum: 5, value is: 6', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooLong: 'long!'
minimum: 3
maximum: 5
m.name('foobar')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['long!']
done()
)
| true | v = require '../../lib/validators/length'
model = require '../../lib/index'
m = null
describe 'Length validator tests', ->
beforeEach (done) ->
M = model("M").attr('name')
m = M.create()
done()
describe 'Is tests', ->
it 'When is: 4 and value length is 4', (done) ->
options =
messages:
wrongLength: 'wrong length'
is: 4
m.name('foob')
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When is: 4 and value length is 5 (longer) but no message defined', (done) ->
options =
is: 4
m.name('PI:NAME:<NAME>END_PI')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['length is incorrect']
done()
)
it 'When is: 4 and value length is 3 (shorter) and message defined', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 4
m.name('PI:NAME:<NAME>END_PI')
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is: 3 and value is blank, (absence of allowBlank=true eq blank not allowed)', (done) ->
options =
messages:
wrongLength: 'wrong'
is: 3
v.length(m, 'name', options).then(() ->
m.errors.name.should.deep.equal ['wrong']
done()
)
it 'When is:3 and allowBlank=true, value is blank', (done) ->
options =
is: 3
allowBlank: true
v.length(m, 'name', options).then(() ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 5', (done) ->
describe 'Minimum, Maximum', ->
options =
minimum: 5
m.name('PI:NAME:<NAME>END_PI')
v.length(m, 'name', options).then((success) ->
m.errors.should.deep.equal {}
done()
)
it 'When minimum: 5 and size is 4', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooShort: 'wrong!'
minimum: 5
m.name('foob')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['wrong!']
done()
)
it 'When minimum: 3, maximum: 5, value is: 6', (done) ->
describe 'Minimum, Maximum', ->
options =
messages:
tooLong: 'long!'
minimum: 3
maximum: 5
m.name('foobar')
v.length(m, 'name', options).then((success) ->
m.errors.name.should.deep.equal ['long!']
done()
)
|
[
{
"context": "gular: [\n { key: \"options.ipAddress\" }\n { key: \"options.apiUsername\" }\n]\n",
"end": 71,
"score": 0.7954440116882324,
"start": 52,
"tag": "KEY",
"value": "options.apiUsername"
}
] | configs/advanced/form.cson | octoblu/meshblu-connector-hue | 0 | angular: [
{ key: "options.ipAddress" }
{ key: "options.apiUsername" }
]
| 77552 | angular: [
{ key: "options.ipAddress" }
{ key: "<KEY>" }
]
| true | angular: [
{ key: "options.ipAddress" }
{ key: "PI:KEY:<KEY>END_PI" }
]
|
[
{
"context": " can be white or black.\n '''\n\n scientificName: 'Connochaetes taurinus'\n mainImage: 'assets/fieldguide-content/mammals/",
"end": 531,
"score": 0.9871063232421875,
"start": 510,
"tag": "NAME",
"value": "Connochaetes taurinus"
}
] | app/lib/field-guide-content/wildebeest.coffee | zooniverse/wildcam-gorongosa-facebook | 7 | module.exports =
description: '''
The wildebeest is an unusual-looking antelope with high shoulders and a large, boxlike head with curving horns. The front end of the body is heavily built, while the hindquarters are slender with skinny legs. They have a blue-gray or brown coat that is lighter above and darker below, with black vertical stripes on their forequarters. They have a black mane and longer hair on their forequarters as well as a beard that can be white or black.
'''
scientificName: 'Connochaetes taurinus'
mainImage: 'assets/fieldguide-content/mammals/wildebeest/wildebeest-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.9-2.1 m'
}, {
label: 'Height'
value: '1.15-1.45 m'
}, {
label: 'Weight'
value: '160-272 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '8-8.5 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'The blue wildebeest is found in short-grass plains and bordering acacia savannas. They are also found in open bushlands and in woodlands within drier areas.'
}, {
title: 'Diet'
content: 'Short grass'
}, {
title: 'Predators'
content: 'Lions, wild dogs, crocodiles, and hyenas'
}, {
title: 'Behavior'
content: '''
<p>The blue wildebeest is a grazer, and their need to follow seasonal grazing and water supplies leads them to form some of the largest migratory herds of any antelopes, with those in the Serengeti and Maasai Mara ecosystem of Tanzania and Kenya forming part of the world’s largest remaining aggregations of large land mammals. They are extremely noisy, especially in large numbers, as they make a variety of loud vocalizations that take the form of moans and explosive snorts.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>The blue wildebeest has a restricted breeding season with around 80 to 90 percent of calves being born within a two- to three-week period, usually at the start of the rainy season. After a gestation period of 8-8.5 months, a single calf is born. Calves will follow their mother from the moment they can stand until they are weaned by nine months.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common name wildebeest means “wild beast.”</li>
<li>Wildebeests can run up to 40 miles per hour</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/Wildebeest/Wildebeest-map.jpg"/>'
}]
| 194613 | module.exports =
description: '''
The wildebeest is an unusual-looking antelope with high shoulders and a large, boxlike head with curving horns. The front end of the body is heavily built, while the hindquarters are slender with skinny legs. They have a blue-gray or brown coat that is lighter above and darker below, with black vertical stripes on their forequarters. They have a black mane and longer hair on their forequarters as well as a beard that can be white or black.
'''
scientificName: '<NAME>'
mainImage: 'assets/fieldguide-content/mammals/wildebeest/wildebeest-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.9-2.1 m'
}, {
label: 'Height'
value: '1.15-1.45 m'
}, {
label: 'Weight'
value: '160-272 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '8-8.5 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'The blue wildebeest is found in short-grass plains and bordering acacia savannas. They are also found in open bushlands and in woodlands within drier areas.'
}, {
title: 'Diet'
content: 'Short grass'
}, {
title: 'Predators'
content: 'Lions, wild dogs, crocodiles, and hyenas'
}, {
title: 'Behavior'
content: '''
<p>The blue wildebeest is a grazer, and their need to follow seasonal grazing and water supplies leads them to form some of the largest migratory herds of any antelopes, with those in the Serengeti and Maasai Mara ecosystem of Tanzania and Kenya forming part of the world’s largest remaining aggregations of large land mammals. They are extremely noisy, especially in large numbers, as they make a variety of loud vocalizations that take the form of moans and explosive snorts.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>The blue wildebeest has a restricted breeding season with around 80 to 90 percent of calves being born within a two- to three-week period, usually at the start of the rainy season. After a gestation period of 8-8.5 months, a single calf is born. Calves will follow their mother from the moment they can stand until they are weaned by nine months.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common name wildebeest means “wild beast.”</li>
<li>Wildebeests can run up to 40 miles per hour</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/Wildebeest/Wildebeest-map.jpg"/>'
}]
| true | module.exports =
description: '''
The wildebeest is an unusual-looking antelope with high shoulders and a large, boxlike head with curving horns. The front end of the body is heavily built, while the hindquarters are slender with skinny legs. They have a blue-gray or brown coat that is lighter above and darker below, with black vertical stripes on their forequarters. They have a black mane and longer hair on their forequarters as well as a beard that can be white or black.
'''
scientificName: 'PI:NAME:<NAME>END_PI'
mainImage: 'assets/fieldguide-content/mammals/wildebeest/wildebeest-feature.jpg'
conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.9-2.1 m'
}, {
label: 'Height'
value: '1.15-1.45 m'
}, {
label: 'Weight'
value: '160-272 kg'
}, {
label: 'Lifespan'
value: '20 years'
}, {
label: 'Gestation'
value: '8-8.5 months'
}, {
label: 'Avg. number of offspring'
value: '1'
}]
sections: [{
title: 'Habitat'
content: 'The blue wildebeest is found in short-grass plains and bordering acacia savannas. They are also found in open bushlands and in woodlands within drier areas.'
}, {
title: 'Diet'
content: 'Short grass'
}, {
title: 'Predators'
content: 'Lions, wild dogs, crocodiles, and hyenas'
}, {
title: 'Behavior'
content: '''
<p>The blue wildebeest is a grazer, and their need to follow seasonal grazing and water supplies leads them to form some of the largest migratory herds of any antelopes, with those in the Serengeti and Maasai Mara ecosystem of Tanzania and Kenya forming part of the world’s largest remaining aggregations of large land mammals. They are extremely noisy, especially in large numbers, as they make a variety of loud vocalizations that take the form of moans and explosive snorts.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>The blue wildebeest has a restricted breeding season with around 80 to 90 percent of calves being born within a two- to three-week period, usually at the start of the rainy season. After a gestation period of 8-8.5 months, a single calf is born. Calves will follow their mother from the moment they can stand until they are weaned by nine months.</p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The common name wildebeest means “wild beast.”</li>
<li>Wildebeests can run up to 40 miles per hour</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/mammals/Wildebeest/Wildebeest-map.jpg"/>'
}]
|
[
{
"context": "ool, i in @props.task.tools\n# tool._key ?= Math.random()\n# toolMarks = (mark for mark in @props.",
"end": 2097,
"score": 0.9524478912353516,
"start": 2086,
"tag": "KEY",
"value": "Math.random"
},
{
"context": "i in toolMarks\n# mark._key ?= Math.random()\n# <div key={mark._key}>\n# ",
"end": 2498,
"score": 0.6192768812179565,
"start": 2492,
"tag": "KEY",
"value": "random"
},
{
"context": "or tool, i in @props.task.tools\n tool._key ?= Math.random()\n\n count = (true for mark in @props.",
"end": 3169,
"score": 0.9262891411781311,
"start": 3165,
"tag": "KEY",
"value": "Math"
},
{
"context": "l, i in @props.task.tools\n tool._key ?= Math.random()\n\n count = (true for mark in @props.annotat",
"end": 3176,
"score": 0.6156620979309082,
"start": 3170,
"tag": "KEY",
"value": "random"
}
] | app/assets/javascripts/components/core-tools/transcribe.cjsx | ogugugugugua/PRED-Crowdsourcing-2020 | 88 | React = require 'react'
GenericTask = require './generic'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
icons =
point: <svg viewBox="0 0 100 100">
<circle className="shape" r="30" cx="50" cy="50" />
<line className="shape" x1="50" y1="5" x2="50" y2="40" />
<line className="shape" x1="95" y1="50" x2="60" y2="50" />
<line className="shape" x1="50" y1="95" x2="50" y2="60" />
<line className="shape" x1="5" y1="50" x2="40" y2="50" />
</svg>
line: <svg viewBox="0 0 100 100">
<line className="shape" x1="25" y1="90" x2="75" y2="10" />
</svg>
rectangle: <svg viewBox="0 0 100 100">
<rect className="shape" x="10" y="30" width="80" height="40" />
</svg>
polygon: <svg viewBox="0 0 100 100">
<polyline className="shape" points="50, 5 90, 90 50, 70 5, 90 50, 5" />
</svg>
circle: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="33" ry="33" cx="50" cy="50" />
</svg>
ellipse: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="45" ry="25" cx="50" cy="50" transform="rotate(-30, 50, 50)" />
</svg>
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.instruction}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# {if @props.onToggle?
# if @props.inactive
# <button type="button"><i className="fa fa-eye fa-fw"></i></button>
# else
# <button type="button"><i className="fa fa-eye-slash fa-fw"></i></button>}
# </div>
# {for tool, i in @props.task.tools
# tool._key ?= Math.random()
# toolMarks = (mark for mark in @props.annotation.value when mark.tool is i)
# if @state.expanded or toolMarks.length isnt 0
# <div key={tool._key} className="answer">
# {tool.type} <strong>{tool.label}</strong> ({[].concat toolMarks.length})
# {if @state.expanded
# for mark, i in toolMarks
# mark._key ?= Math.random()
# <div key={mark._key}>
# {i + 1}){' '}
# {for key, value of mark when key not in ['tool', 'sources'] and key.charAt(0) isnt '_'
# <code key={key}><strong>{key}</strong>: {JSON.stringify value} </code>}
# </div>}
# </div>}
# </div>
module.exports = React.createClass
displayName: 'TranscribeTask'
statics:
# Summary: Summary
getDefaultAnnotation: ->
_toolIndex: 0
value: []
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
render: ->
tools = for tool, i in @props.task.tools
tool._key ?= Math.random()
count = (true for mark in @props.annotation.value when mark.tool is i).length
<label key={tool._key} className="minor-button #{if i is (@props.annotation._toolIndex ? 0) then 'active' else ''}">
<span className="drawing-tool-icon" style={color: tool.color}>{icons[tool.type]}</span>{' '}
<input type="radio" className="drawing-tool-input" checked={i is (@props.annotation._toolIndex ? 0)} onChange={@handleChange.bind this, i} />
<span>{tool.label}</span>
{unless count is 0
<span className="tool-count">({count})</span>}
</label>
<GenericTask question={@props.task.instruction} help={@props.task.help} answers={tools} />
handleChange: (index, e) ->
if e.target.checked
@props.annotation._toolIndex = index
@props.onChange? e
@forceUpdate()
| 46601 | React = require 'react'
GenericTask = require './generic'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
icons =
point: <svg viewBox="0 0 100 100">
<circle className="shape" r="30" cx="50" cy="50" />
<line className="shape" x1="50" y1="5" x2="50" y2="40" />
<line className="shape" x1="95" y1="50" x2="60" y2="50" />
<line className="shape" x1="50" y1="95" x2="50" y2="60" />
<line className="shape" x1="5" y1="50" x2="40" y2="50" />
</svg>
line: <svg viewBox="0 0 100 100">
<line className="shape" x1="25" y1="90" x2="75" y2="10" />
</svg>
rectangle: <svg viewBox="0 0 100 100">
<rect className="shape" x="10" y="30" width="80" height="40" />
</svg>
polygon: <svg viewBox="0 0 100 100">
<polyline className="shape" points="50, 5 90, 90 50, 70 5, 90 50, 5" />
</svg>
circle: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="33" ry="33" cx="50" cy="50" />
</svg>
ellipse: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="45" ry="25" cx="50" cy="50" transform="rotate(-30, 50, 50)" />
</svg>
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.instruction}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# {if @props.onToggle?
# if @props.inactive
# <button type="button"><i className="fa fa-eye fa-fw"></i></button>
# else
# <button type="button"><i className="fa fa-eye-slash fa-fw"></i></button>}
# </div>
# {for tool, i in @props.task.tools
# tool._key ?= <KEY>()
# toolMarks = (mark for mark in @props.annotation.value when mark.tool is i)
# if @state.expanded or toolMarks.length isnt 0
# <div key={tool._key} className="answer">
# {tool.type} <strong>{tool.label}</strong> ({[].concat toolMarks.length})
# {if @state.expanded
# for mark, i in toolMarks
# mark._key ?= Math.<KEY>()
# <div key={mark._key}>
# {i + 1}){' '}
# {for key, value of mark when key not in ['tool', 'sources'] and key.charAt(0) isnt '_'
# <code key={key}><strong>{key}</strong>: {JSON.stringify value} </code>}
# </div>}
# </div>}
# </div>
module.exports = React.createClass
displayName: 'TranscribeTask'
statics:
# Summary: Summary
getDefaultAnnotation: ->
_toolIndex: 0
value: []
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
render: ->
tools = for tool, i in @props.task.tools
tool._key ?= <KEY>.<KEY>()
count = (true for mark in @props.annotation.value when mark.tool is i).length
<label key={tool._key} className="minor-button #{if i is (@props.annotation._toolIndex ? 0) then 'active' else ''}">
<span className="drawing-tool-icon" style={color: tool.color}>{icons[tool.type]}</span>{' '}
<input type="radio" className="drawing-tool-input" checked={i is (@props.annotation._toolIndex ? 0)} onChange={@handleChange.bind this, i} />
<span>{tool.label}</span>
{unless count is 0
<span className="tool-count">({count})</span>}
</label>
<GenericTask question={@props.task.instruction} help={@props.task.help} answers={tools} />
handleChange: (index, e) ->
if e.target.checked
@props.annotation._toolIndex = index
@props.onChange? e
@forceUpdate()
| true | React = require 'react'
GenericTask = require './generic'
# Markdown = require '../../components/markdown'
NOOP = Function.prototype
icons =
point: <svg viewBox="0 0 100 100">
<circle className="shape" r="30" cx="50" cy="50" />
<line className="shape" x1="50" y1="5" x2="50" y2="40" />
<line className="shape" x1="95" y1="50" x2="60" y2="50" />
<line className="shape" x1="50" y1="95" x2="50" y2="60" />
<line className="shape" x1="5" y1="50" x2="40" y2="50" />
</svg>
line: <svg viewBox="0 0 100 100">
<line className="shape" x1="25" y1="90" x2="75" y2="10" />
</svg>
rectangle: <svg viewBox="0 0 100 100">
<rect className="shape" x="10" y="30" width="80" height="40" />
</svg>
polygon: <svg viewBox="0 0 100 100">
<polyline className="shape" points="50, 5 90, 90 50, 70 5, 90 50, 5" />
</svg>
circle: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="33" ry="33" cx="50" cy="50" />
</svg>
ellipse: <svg viewBox="0 0 100 100">
<ellipse className="shape" rx="45" ry="25" cx="50" cy="50" transform="rotate(-30, 50, 50)" />
</svg>
# Summary = React.createClass
# displayName: 'SingleChoiceSummary'
# getDefaultProps: ->
# task: null
# annotation: null
# expanded: false
# getInitialState: ->
# expanded: @props.expanded
# render: ->
# <div className="classification-task-summary">
# <div className="question">
# {@props.task.instruction}
# {if @state.expanded
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: false, null}>Less</button>
# else
# <button type="button" className="toggle-more" onClick={@setState.bind this, expanded: true, null}>More</button>}
# {if @props.onToggle?
# if @props.inactive
# <button type="button"><i className="fa fa-eye fa-fw"></i></button>
# else
# <button type="button"><i className="fa fa-eye-slash fa-fw"></i></button>}
# </div>
# {for tool, i in @props.task.tools
# tool._key ?= PI:KEY:<KEY>END_PI()
# toolMarks = (mark for mark in @props.annotation.value when mark.tool is i)
# if @state.expanded or toolMarks.length isnt 0
# <div key={tool._key} className="answer">
# {tool.type} <strong>{tool.label}</strong> ({[].concat toolMarks.length})
# {if @state.expanded
# for mark, i in toolMarks
# mark._key ?= Math.PI:KEY:<KEY>END_PI()
# <div key={mark._key}>
# {i + 1}){' '}
# {for key, value of mark when key not in ['tool', 'sources'] and key.charAt(0) isnt '_'
# <code key={key}><strong>{key}</strong>: {JSON.stringify value} </code>}
# </div>}
# </div>}
# </div>
module.exports = React.createClass
displayName: 'TranscribeTask'
statics:
# Summary: Summary
getDefaultAnnotation: ->
_toolIndex: 0
value: []
getDefaultProps: ->
task: null
annotation: null
onChange: NOOP
render: ->
tools = for tool, i in @props.task.tools
tool._key ?= PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI()
count = (true for mark in @props.annotation.value when mark.tool is i).length
<label key={tool._key} className="minor-button #{if i is (@props.annotation._toolIndex ? 0) then 'active' else ''}">
<span className="drawing-tool-icon" style={color: tool.color}>{icons[tool.type]}</span>{' '}
<input type="radio" className="drawing-tool-input" checked={i is (@props.annotation._toolIndex ? 0)} onChange={@handleChange.bind this, i} />
<span>{tool.label}</span>
{unless count is 0
<span className="tool-count">({count})</span>}
</label>
<GenericTask question={@props.task.instruction} help={@props.task.help} answers={tools} />
handleChange: (index, e) ->
if e.target.checked
@props.annotation._toolIndex = index
@props.onChange? e
@forceUpdate()
|
[
{
"context": "#Language: Portuguese\n#Translators: alanmeira\n\npt =\n\n#>add: \"add\"\n and: \"e\"\n#>back: \"back\"\n#>c",
"end": 45,
"score": 0.9992709159851074,
"start": 36,
"tag": "USERNAME",
"value": "alanmeira"
},
{
"context": " createAccount: \"Criar Conta\"\n#>currentPassword: \"Current Password\"\n dontHaveAnAccount: \"Não tem conta?\"\n email: \"",
"end": 314,
"score": 0.9814924001693726,
"start": 298,
"tag": "PASSWORD",
"value": "Current Password"
},
{
"context": "count: \"Se você já tem uma conta\"\n#>newPassword: \"New Password\"\n#>newPasswordAgain: \"New Password (again)\"\n opt",
"end": 570,
"score": 0.9772831201553345,
"start": 558,
"tag": "PASSWORD",
"value": "New Password"
},
{
"context": ">newPassword: \"New Password\"\n#>newPasswordAgain: \"New Password (again)\"\n optional: \"Opcional\"\n OR: \"O",
"end": 596,
"score": 0.5508058071136475,
"start": 593,
"tag": "PASSWORD",
"value": "New"
},
{
"context": ")\"\n optional: \"Opcional\"\n OR: \"OU\"\n password: \"Senha\"\n#>passwordAgain: \"Password (again)\"\n privacyPol",
"end": 667,
"score": 0.9776869416236877,
"start": 662,
"tag": "PASSWORD",
"value": "Senha"
},
{
"context": "acidade\"\n#>remove: \"remove\"\n resetYourPassword: \"Gerar nova senha\"\n#>setPassword: \"Set Password\"\n sign: \"Entrar\"\n ",
"end": 805,
"score": 0.9241955876350403,
"start": 789,
"tag": "PASSWORD",
"value": "Gerar nova senha"
},
{
"context": "tYourPassword: \"Gerar nova senha\"\n#>setPassword: \"Set Password\"\n sign: \"Entrar\"\n signIn: \"Entrar\"\n signin: \"e",
"end": 835,
"score": 0.9671438932418823,
"start": 823,
"tag": "PASSWORD",
"value": "Set Password"
},
{
"context": "\"\n terms: \"Termos de Uso\"\n updateYourPassword: \"Atualizar senha\"\n username: \"Nome de usuário\"\n usernameOrEmail:",
"end": 1096,
"score": 0.9793890714645386,
"start": 1081,
"tag": "PASSWORD",
"value": "Atualizar senha"
},
{
"context": "pdateYourPassword: \"Atualizar senha\"\n username: \"Nome de usuário\"\n usernameOrEmail: \"Usuario ou e-mail\"\n with: \"",
"end": 1126,
"score": 0.9992849230766296,
"start": 1111,
"tag": "USERNAME",
"value": "Nome de usuário"
},
{
"context": "lVerified: \"Email verified\"\n#> passwordChanged: \"Password Changed\"\n#> passwordReset: \"Password Reset\"\n\n\n error:\n ",
"end": 1293,
"score": 0.7782425880432129,
"start": 1277,
"tag": "PASSWORD",
"value": "Password Changed"
},
{
"context": "rdChanged: \"Password Changed\"\n#> passwordReset: \"Password Reset\"\n\n\n error:\n emailRequired: \"E-mail é obrigató",
"end": 1329,
"score": 0.6556462049484253,
"start": 1315,
"tag": "PASSWORD",
"value": "Password Reset"
},
{
"context": "er um endereço de e-mail.\"\n usernameRequired: \"Nome de usuário é obrigatório.\"\n\n\n #accounts:\n\n #---- accounts-base\n ",
"end": 1907,
"score": 0.6667718291282654,
"start": 1878,
"tag": "USERNAME",
"value": "Nome de usuário é obrigatório"
}
] | t9n/pt.coffee | timbrandin/meteor-accounts-t9n | 0 | #Language: Portuguese
#Translators: alanmeira
pt =
#>add: "add"
and: "e"
#>back: "back"
#>changePassword: "Change Password"
#>choosePassword: "Choose a Password"
clickAgree: "Ao clicar em Entrar, você aceita nosso"
configure: "Configurar"
createAccount: "Criar Conta"
#>currentPassword: "Current Password"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Gerar nova senha"
forgotPassword: "Esqueceu sua senha?"
ifYouAlreadyHaveAnAccount: "Se você já tem uma conta"
#>newPassword: "New Password"
#>newPasswordAgain: "New Password (again)"
optional: "Opcional"
OR: "OU"
password: "Senha"
#>passwordAgain: "Password (again)"
privacyPolicy: "Política de Privacidade"
#>remove: "remove"
resetYourPassword: "Gerar nova senha"
#>setPassword: "Set Password"
sign: "Entrar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sair"
signUp: "Registrar"
signupCode: "Código de acesso"
signUpWithYourEmailAddress: "Entre usando seu endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "Atualizar senha"
username: "Nome de usuário"
usernameOrEmail: "Usuario ou e-mail"
with: "com"
#>info:
#> emailSent: "Email Sent"
#> emailVerified: "Email verified"
#> passwordChanged: "Password Changed"
#> passwordReset: "Password Reset"
error:
emailRequired: "E-mail é obrigatório."
minChar: "Senha requer um mínimo de 7 caracteres."
#> pwdsDontMatch: "Passwords don't match"
pwOneDigit: "Senha deve conter pelo menos um digito."
pwOneLetter: "Senha deve conter pelo menos uma letra."
signInRequired: "Você precisa estar logado para fazer isso."
signupCodeIncorrect: "Código de acesso incorreto."
signupCodeRequired: "É necessário um código de acesso."
usernameIsEmail: "Nome de usuário não pode ser um endereço de e-mail."
usernameRequired: "Nome de usuário é obrigatório."
#accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
#> "Email already exists.":
#> "Email doesn't match the criteria.":
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
#> "User validation failed":
#> "Username already exists.":
#> "You are not logged in.":
#> "You've been logged out by the server. Please log in again.":
#> "Your session has expired. Please log in again.":
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
#> "Incorrect password":
#> "Invalid email":
#> "Must be logged in":
#> "Need to set a username or email":
#> "old password format":
#> "Password may not be empty":
#> "Signups forbidden":
#> "Token expired":
#> "Token has invalid email address":
#> "User has no password set":
#> "User not found": "Usuário não encontrado"
#> "Verify email link expired":
#> "Verify email link is for unknown address":
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "pt", pt | 90760 | #Language: Portuguese
#Translators: alanmeira
pt =
#>add: "add"
and: "e"
#>back: "back"
#>changePassword: "Change Password"
#>choosePassword: "Choose a Password"
clickAgree: "Ao clicar em Entrar, você aceita nosso"
configure: "Configurar"
createAccount: "Criar Conta"
#>currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Gerar nova senha"
forgotPassword: "Esqueceu sua senha?"
ifYouAlreadyHaveAnAccount: "Se você já tem uma conta"
#>newPassword: "<PASSWORD>"
#>newPasswordAgain: "<PASSWORD> Password (again)"
optional: "Opcional"
OR: "OU"
password: "<PASSWORD>"
#>passwordAgain: "Password (again)"
privacyPolicy: "Política de Privacidade"
#>remove: "remove"
resetYourPassword: "<PASSWORD>"
#>setPassword: "<PASSWORD>"
sign: "Entrar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sair"
signUp: "Registrar"
signupCode: "Código de acesso"
signUpWithYourEmailAddress: "Entre usando seu endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "<PASSWORD>"
username: "Nome de usuário"
usernameOrEmail: "Usuario ou e-mail"
with: "com"
#>info:
#> emailSent: "Email Sent"
#> emailVerified: "Email verified"
#> passwordChanged: "<PASSWORD>"
#> passwordReset: "<PASSWORD>"
error:
emailRequired: "E-mail é obrigatório."
minChar: "Senha requer um mínimo de 7 caracteres."
#> pwdsDontMatch: "Passwords don't match"
pwOneDigit: "Senha deve conter pelo menos um digito."
pwOneLetter: "Senha deve conter pelo menos uma letra."
signInRequired: "Você precisa estar logado para fazer isso."
signupCodeIncorrect: "Código de acesso incorreto."
signupCodeRequired: "É necessário um código de acesso."
usernameIsEmail: "Nome de usuário não pode ser um endereço de e-mail."
usernameRequired: "Nome de usuário é obrigatório."
#accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
#> "Email already exists.":
#> "Email doesn't match the criteria.":
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
#> "User validation failed":
#> "Username already exists.":
#> "You are not logged in.":
#> "You've been logged out by the server. Please log in again.":
#> "Your session has expired. Please log in again.":
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
#> "Incorrect password":
#> "Invalid email":
#> "Must be logged in":
#> "Need to set a username or email":
#> "old password format":
#> "Password may not be empty":
#> "Signups forbidden":
#> "Token expired":
#> "Token has invalid email address":
#> "User has no password set":
#> "User not found": "Usuário não encontrado"
#> "Verify email link expired":
#> "Verify email link is for unknown address":
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "pt", pt | true | #Language: Portuguese
#Translators: alanmeira
pt =
#>add: "add"
and: "e"
#>back: "back"
#>changePassword: "Change Password"
#>choosePassword: "Choose a Password"
clickAgree: "Ao clicar em Entrar, você aceita nosso"
configure: "Configurar"
createAccount: "Criar Conta"
#>currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Não tem conta?"
email: "E-mail"
emailAddress: "Endereço de e-mail"
emailResetLink: "Gerar nova senha"
forgotPassword: "Esqueceu sua senha?"
ifYouAlreadyHaveAnAccount: "Se você já tem uma conta"
#>newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
#>newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI Password (again)"
optional: "Opcional"
OR: "OU"
password: "PI:PASSWORD:<PASSWORD>END_PI"
#>passwordAgain: "Password (again)"
privacyPolicy: "Política de Privacidade"
#>remove: "remove"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
#>setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Entrar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sair"
signUp: "Registrar"
signupCode: "Código de acesso"
signUpWithYourEmailAddress: "Entre usando seu endereço de e-mail"
terms: "Termos de Uso"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
username: "Nome de usuário"
usernameOrEmail: "Usuario ou e-mail"
with: "com"
#>info:
#> emailSent: "Email Sent"
#> emailVerified: "Email verified"
#> passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
#> passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "E-mail é obrigatório."
minChar: "Senha requer um mínimo de 7 caracteres."
#> pwdsDontMatch: "Passwords don't match"
pwOneDigit: "Senha deve conter pelo menos um digito."
pwOneLetter: "Senha deve conter pelo menos uma letra."
signInRequired: "Você precisa estar logado para fazer isso."
signupCodeIncorrect: "Código de acesso incorreto."
signupCodeRequired: "É necessário um código de acesso."
usernameIsEmail: "Nome de usuário não pode ser um endereço de e-mail."
usernameRequired: "Nome de usuário é obrigatório."
#accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
#> "Email already exists.":
#> "Email doesn't match the criteria.":
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
#> "User validation failed":
#> "Username already exists.":
#> "You are not logged in.":
#> "You've been logged out by the server. Please log in again.":
#> "Your session has expired. Please log in again.":
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
#> "Incorrect password":
#> "Invalid email":
#> "Must be logged in":
#> "Need to set a username or email":
#> "old password format":
#> "Password may not be empty":
#> "Signups forbidden":
#> "Token expired":
#> "Token has invalid email address":
#> "User has no password set":
#> "User not found": "Usuário não encontrado"
#> "Verify email link expired":
#> "Verify email link is for unknown address":
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "pt", pt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.