code
stringlengths
2
1.05M
tinymce.addI18n('ga',{ "Cut": "Gearr", "Heading 5": "Ceannteideal 5", "Header 2": "Ceannt\u00e1sc 2", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "N\u00ed f\u00e9idir le do bhrabhs\u00e1la\u00ed teacht go d\u00edreach ar an ngearrthaisce. Bain \u00fas\u00e1id as na haicearra\u00ed Ctrl+X\/C\/V. ", "Heading 4": "Ceannteideal 4", "Div": "Deighilt", "Heading 2": "Ceannteideal 2", "Paste": "Greamaigh", "Close": "D\u00fan", "Font Family": "Cl\u00f3fhoireann", "Pre": "R\u00e9amh", "Align right": "Ail\u00ednigh ar dheis", "New document": "C\u00e1ip\u00e9is nua", "Blockquote": "Athfhriotal", "Numbered list": "Liosta Uimhrithe", "Heading 1": "Ceannteideal 1", "Headings": "Ceannteidil", "Increase indent": "M\u00e9adaigh eang", "Formats": "Form\u00e1id\u00ed", "Headers": "Ceannt\u00e1sca", "Select all": "Roghnaigh uile", "Header 3": "Ceannt\u00e1sc 3", "Blocks": "Blocanna", "Undo": "Cealaigh", "Strikethrough": "L\u00edne tr\u00edd", "Bullet list": "Liosta Urchar", "Header 1": "Ceannt\u00e1sc 1", "Superscript": "Forscript", "Clear formatting": "Glan form\u00e1idi\u00fa", "Font Sizes": "Cl\u00f3mh\u00e9ideanna", "Subscript": "Foscript", "Header 6": "Ceannt\u00e1sc 6", "Redo": "Athdh\u00e9an", "Paragraph": "Alt", "Ok": "OK", "Bold": "Trom", "Code": "C\u00f3d", "Italic": "Iod\u00e1lach", "Align center": "Ail\u00ednigh sa l\u00e1r", "Header 5": "Ceannt\u00e1sc 5", "Heading 6": "Ceannteideal 6", "Heading 3": "Ceannteideal 3", "Decrease indent": "Laghdaigh eang", "Header 4": "Ceannt\u00e1sc 4", "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Sa m\u00f3d gn\u00e1th-th\u00e9acs anois. Gream\u00f3far \u00e1bhar mar ghn\u00e1th-th\u00e9acs go dt\u00ed go m\u00fachfaidh t\u00fa an rogha seo.", "Underline": "Fol\u00edne", "Cancel": "Cealaigh", "Justify": "Comhfhadaigh", "Inline": "Inl\u00edne", "Copy": "C\u00f3ipe\u00e1il", "Align left": "Ail\u00ednigh ar chl\u00e9", "Visual aids": "\u00c1iseanna amhairc", "Lower Greek": "Litir Bheag Ghr\u00e9agach", "Square": "Cearn\u00f3g", "Default": "R\u00e9amhshocr\u00fa", "Lower Alpha": "Alfa Beag", "Circle": "Ciorcal", "Disc": "Diosca", "Upper Alpha": "Alfa M\u00f3r", "Upper Roman": "Litir Mh\u00f3r R\u00f3mh\u00e1nach", "Lower Roman": "Litir Bheag R\u00f3mh\u00e1nach", "Name": "Ainm", "Anchor": "Ancaire", "You have unsaved changes are you sure you want to navigate away?": "T\u00e1 athruithe gan s\u00e1bh\u00e1il ann. An bhfuil t\u00fa cinnte gur mhaith leat imeacht amach as seo?", "Restore last draft": "Oscail an dr\u00e9acht is d\u00e9ana\u00ed", "Special character": "Carachtar speisialta", "Source code": "C\u00f3d foinseach", "B": "G", "R": "D", "G": "U", "Color": "Dath", "Right to left": "Deas-go-cl\u00e9", "Left to right": "Cl\u00e9-go-Deas", "Emoticons": "Straoiseoga", "Robots": "R\u00f3bait", "Document properties": "Air\u00edonna na C\u00e1ip\u00e9ise", "Title": "Teideal", "Keywords": "Lorgfhocail", "Encoding": "Ionch\u00f3d\u00fa", "Description": "Cur S\u00edos", "Author": "\u00dadar", "Fullscreen": "L\u00e1nsc\u00e1ile\u00e1n", "Horizontal line": "L\u00edne chothrom\u00e1nach", "Horizontal space": "Sp\u00e1s cothrom\u00e1nach", "Insert\/edit image": "Cuir \u00edomh\u00e1 isteach\/in eagar", "General": "Ginear\u00e1lta", "Advanced": "Casta", "Source": "Foinse", "Border": "Iml\u00edne", "Constrain proportions": "Comhr\u00e9ir faoi ghlas", "Vertical space": "Sp\u00e1s ingearach", "Image description": "Cur s\u00edos ar an \u00edomh\u00e1", "Style": "St\u00edl", "Dimensions": "Tois\u00ed", "Insert image": "Cuir \u00edomh\u00e1 isteach", "Zoom in": "Z\u00fam\u00e1il isteach", "Contrast": "Codarsnacht", "Back": "Siar", "Gamma": "G\u00e1ma", "Flip horizontally": "Cas go cothrom\u00e1nach", "Resize": "Athraigh m\u00e9id", "Sharpen": "G\u00e9araigh", "Zoom out": "Z\u00fam\u00e1il amach", "Image options": "Roghanna \u00edomh\u00e1", "Apply": "Cuir i bhfeidhm", "Brightness": "Gile", "Rotate clockwise": "Rothlaigh ar deiseal", "Rotate counterclockwise": "Rothlaigh ar tuathal", "Edit image": "Cuir an \u00edomh\u00e1 in eagar", "Color levels": "Leibh\u00e9il datha", "Crop": "Bear", "Orientation": "Treoshu\u00edomh", "Flip vertically": "Cas go hingearach", "Invert": "Inbh\u00e9artaigh", "Insert date\/time": "Cuir d\u00e1ta\/am isteach", "Remove link": "Bain an nasc", "Url": "URL", "Text to display": "T\u00e9acs le taispe\u00e1int", "Anchors": "Ancair\u00ed", "Insert link": "Cuir nasc isteach", "New window": "Fuinneog nua", "None": "Dada", "The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "Is nasc seachtrach \u00e9 an URL a chuir t\u00fa isteach. An bhfuil fonn ort an r\u00e9im\u00edr riachtanach http:\/\/ a chur leis?", "Target": "Sprioc", "The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "Is seoladh r\u00edomhphoist \u00e9 an URL a chuir t\u00fa isteach. An bhfuil fonn ort an r\u00e9im\u00edr riachtanach mailto: a chur leis?", "Insert\/edit link": "Cuir nasc isteach\/in eagar", "Insert\/edit video": "Cuir f\u00edse\u00e1n isteach\/in eagar", "Poster": "P\u00f3staer", "Alternative source": "Foinse mhalartach", "Paste your embed code below:": "Greamaigh do ch\u00f3d leabaithe th\u00edos:", "Insert video": "Cuir f\u00edse\u00e1n isteach", "Embed": "Leabaigh", "Nonbreaking space": "Sp\u00e1s neamhbhristeach", "Page break": "Briseadh leathanaigh", "Paste as text": "Greamaigh mar th\u00e9acs", "Preview": "R\u00e9amhamharc", "Print": "Priont\u00e1il", "Save": "S\u00e1bh\u00e1il", "Could not find the specified string.": "N\u00edor aims\u00edodh an teaghr\u00e1n.", "Replace": "Ionadaigh", "Next": "Ar aghaidh", "Whole words": "Focail ioml\u00e1na", "Find and replace": "Aimsigh agus ionadaigh", "Replace with": "Ionadaigh le", "Find": "Aimsigh", "Replace all": "Ionadaigh uile", "Match case": "C\u00e1s-\u00edogair", "Prev": "Siar", "Spellcheck": "Seice\u00e1il an litri\u00fa", "Finish": "Cr\u00edochnaigh", "Ignore all": "D\u00e9an neamhaird orthu go l\u00e9ir", "Ignore": "D\u00e9an neamhaird air", "Add to Dictionary": "Cuir leis an bhFocl\u00f3ir \u00e9", "Insert row before": "Ions\u00e1igh r\u00f3 os a chionn", "Rows": "R\u00f3nna", "Height": "Airde", "Paste row after": "Greamaigh r\u00f3 faoi", "Alignment": "Ail\u00edni\u00fa", "Border color": "Dath na himl\u00edne", "Column group": "Gr\u00fapa col\u00fan", "Row": "R\u00f3", "Insert column before": "Ions\u00e1igh col\u00fan ar chl\u00e9", "Split cell": "Roinn cill", "Cell padding": "Stu\u00e1il ceall", "Cell spacing": "Sp\u00e1s\u00e1il ceall", "Row type": "Cine\u00e1l an r\u00f3", "Insert table": "Ions\u00e1igh t\u00e1bla", "Body": "Corp", "Caption": "Fotheideal", "Footer": "Bunt\u00e1sc", "Delete row": "Scrios an r\u00f3", "Paste row before": "Greamaigh r\u00f3 os a chionn", "Scope": "Sc\u00f3ip", "Delete table": "Scrios an t\u00e1bla", "H Align": "Ail\u00edni\u00fa C.", "Top": "Barr", "Header cell": "Cill cheannt\u00e1isc", "Column": "Col\u00fan", "Row group": "Gr\u00fapa r\u00f3nna", "Cell": "Cill", "Middle": "L\u00e1r", "Cell type": "Cine\u00e1l na cille", "Copy row": "C\u00f3ipe\u00e1il an r\u00f3", "Row properties": "Air\u00edonna an r\u00f3", "Table properties": "Air\u00edonna an t\u00e1bla", "Bottom": "Bun", "V Align": "Ail\u00edni\u00fa I.", "Header": "Ceannt\u00e1sc", "Right": "Ar Dheis", "Insert column after": "Ions\u00e1igh col\u00fan ar dheis", "Cols": "Col\u00fain", "Insert row after": "Ions\u00e1igh r\u00f3 faoi", "Width": "Leithead", "Cell properties": "Air\u00edonna na cille", "Left": "Ar Chl\u00e9", "Cut row": "Gearr an r\u00f3", "Delete column": "Scrios an col\u00fan", "Center": "Sa L\u00e1r", "Merge cells": "Cumaisc cealla", "Insert template": "Ions\u00e1igh teimpl\u00e9ad", "Templates": "Teimpl\u00e9id", "Background color": "Dath an ch\u00falra", "Custom...": "Saincheap...", "Custom color": "Dath saincheaptha", "No color": "Gan dath", "Text color": "Dath an t\u00e9acs", "Show blocks": "Taispe\u00e1in blocanna", "Show invisible characters": "Taispe\u00e1in carachtair dhofheicthe", "Words: {0}": "Focail: {0}", "Insert": "Ions\u00e1ig", "File": "Comhad", "Edit": "Eagar", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Limist\u00e9ar M\u00e9ith-Th\u00e9acs. Br\u00faigh ALT-F9 le haghaidh roghchl\u00e1ir, ALT-F10 le haghaidh barra uirlis\u00ed, agus ALT-0 le c\u00fanamh a fh\u00e1il", "Tools": "Uirlis\u00ed", "View": "Amharc", "Table": "T\u00e1bla", "Format": "Form\u00e1id", "Insert\/Edit code sample": "Cuir c\u00f3d samplach isteach\/in eagar", "Language": "Teanga" });
require('../modules/es6.object.to-string'); require('../modules/es6.string.iterator'); require('../modules/web.dom.iterable'); require('../modules/es6.promise'); module.exports = require('../modules/_core').Promise;
require('./angular-locale_zh-hans'); module.exports = 'ngLocale';
/* A JavaScript implementation of the SHA family of hashes, as defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation as defined in FIPS PUB 198a Copyright Brian Turek 2008-2015 Distributed under the BSD License See http://caligatio.github.com/jsSHA/ for more information Several functions taken from Paul Johnston */ 'use strict';(function(T){function y(c,a,d){var b=0,f=[],k=0,g,e,n,h,m,u,r,p=!1,q=!1,t=[],v=[],x,w=!1;d=d||{};g=d.encoding||"UTF8";x=d.numRounds||1;n=J(a,g);if(x!==parseInt(x,10)||1>x)throw Error("numRounds must a integer >= 1");if("SHA-1"===c)m=512,u=K,r=U,h=160;else if(u=function(a,d){return L(a,d,c)},r=function(a,d,b,f){var k,e;if("SHA-224"===c||"SHA-256"===c)k=(d+72>>>9<<4)+15,e=16;else if("SHA-384"===c||"SHA-512"===c)k=(d+136>>>10<<5)+31,e=32;else throw Error("Unexpected error in SHA-2 implementation"); for(;a.length<=k;)a.push(0);a[d>>>5]|=128<<24-d%32;a[k]=d+b;b=a.length;for(d=0;d<b;d+=e)f=L(a.slice(d,d+e),f,c);if("SHA-224"===c)a=[f[0],f[1],f[2],f[3],f[4],f[5],f[6]];else if("SHA-256"===c)a=f;else if("SHA-384"===c)a=[f[0].a,f[0].b,f[1].a,f[1].b,f[2].a,f[2].b,f[3].a,f[3].b,f[4].a,f[4].b,f[5].a,f[5].b];else if("SHA-512"===c)a=[f[0].a,f[0].b,f[1].a,f[1].b,f[2].a,f[2].b,f[3].a,f[3].b,f[4].a,f[4].b,f[5].a,f[5].b,f[6].a,f[6].b,f[7].a,f[7].b];else throw Error("Unexpected error in SHA-2 implementation"); return a},"SHA-224"===c)m=512,h=224;else if("SHA-256"===c)m=512,h=256;else if("SHA-384"===c)m=1024,h=384;else if("SHA-512"===c)m=1024,h=512;else throw Error("Chosen SHA variant is not supported");e=z(c);this.setHMACKey=function(a,d,f){var k;if(!0===q)throw Error("HMAC key already set");if(!0===p)throw Error("Cannot set HMAC key after finalizing hash");if(!0===w)throw Error("Cannot set HMAC key after calling update");g=(f||{}).encoding||"UTF8";d=J(d,g)(a);a=d.binLen;d=d.value;k=m>>>3;f=k/4-1;if(k< a/8){for(d=r(d,a,0,z(c));d.length<=f;)d.push(0);d[f]&=4294967040}else if(k>a/8){for(;d.length<=f;)d.push(0);d[f]&=4294967040}for(a=0;a<=f;a+=1)t[a]=d[a]^909522486,v[a]=d[a]^1549556828;e=u(t,e);b=m;q=!0};this.update=function(a){var c,d,g,h=0,p=m>>>5;c=n(a,f,k);a=c.binLen;d=c.value;c=a>>>5;for(g=0;g<c;g+=p)h+m<=a&&(e=u(d.slice(g,g+p),e),h+=m);b+=h;f=d.slice(h>>>5);k=a%m;w=!0};this.getHash=function(a,d){var g,m,n;if(!0===q)throw Error("Cannot call getHash after setting HMAC key");n=M(d);switch(a){case "HEX":g= function(a){return N(a,n)};break;case "B64":g=function(a){return O(a,n)};break;case "BYTES":g=P;break;default:throw Error("format must be HEX, B64, or BYTES");}if(!1===p)for(e=r(f,k,b,e),m=1;m<x;m+=1)e=r(e,h,0,z(c));p=!0;return g(e)};this.getHMAC=function(a,d){var g,n,t;if(!1===q)throw Error("Cannot call getHMAC without first setting HMAC key");t=M(d);switch(a){case "HEX":g=function(a){return N(a,t)};break;case "B64":g=function(a){return O(a,t)};break;case "BYTES":g=P;break;default:throw Error("outputFormat must be HEX, B64, or BYTES"); }!1===p&&(n=r(f,k,b,e),e=u(v,z(c)),e=r(n,h,m,e));p=!0;return g(e)}}function b(c,a){this.a=c;this.b=a}function V(c,a,d){var b=c.length,f,k,e,l,n;a=a||[0];d=d||0;n=d>>>3;if(0!==b%2)throw Error("String of HEX type must be in byte increments");for(f=0;f<b;f+=2){k=parseInt(c.substr(f,2),16);if(isNaN(k))throw Error("String of HEX type contains invalid characters");l=(f>>>1)+n;for(e=l>>>2;a.length<=e;)a.push(0);a[e]|=k<<8*(3-l%4)}return{value:a,binLen:4*b+d}}function W(c,a,d){var b=[],f,k,e,l,b=a||[0];d= d||0;k=d>>>3;for(f=0;f<c.length;f+=1)a=c.charCodeAt(f),l=f+k,e=l>>>2,b.length<=e&&b.push(0),b[e]|=a<<8*(3-l%4);return{value:b,binLen:8*c.length+d}}function X(c,a,d){var b=[],f=0,e,g,l,n,h,m,b=a||[0];d=d||0;a=d>>>3;if(-1===c.search(/^[a-zA-Z0-9=+\/]+$/))throw Error("Invalid character in base-64 string");g=c.indexOf("=");c=c.replace(/\=/g,"");if(-1!==g&&g<c.length)throw Error("Invalid '=' found in base-64 string");for(g=0;g<c.length;g+=4){h=c.substr(g,4);for(l=n=0;l<h.length;l+=1)e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(h[l]), n|=e<<18-6*l;for(l=0;l<h.length-1;l+=1){m=f+a;for(e=m>>>2;b.length<=e;)b.push(0);b[e]|=(n>>>16-8*l&255)<<8*(3-m%4);f+=1}}return{value:b,binLen:8*f+d}}function N(c,a){var d="",b=4*c.length,f,e;for(f=0;f<b;f+=1)e=c[f>>>2]>>>8*(3-f%4),d+="0123456789abcdef".charAt(e>>>4&15)+"0123456789abcdef".charAt(e&15);return a.outputUpper?d.toUpperCase():d}function O(c,a){var d="",b=4*c.length,f,e,g;for(f=0;f<b;f+=3)for(g=f+1>>>2,e=c.length<=g?0:c[g],g=f+2>>>2,g=c.length<=g?0:c[g],g=(c[f>>>2]>>>8*(3-f%4)&255)<<16| (e>>>8*(3-(f+1)%4)&255)<<8|g>>>8*(3-(f+2)%4)&255,e=0;4>e;e+=1)8*f+6*e<=32*c.length?d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>>6*(3-e)&63):d+=a.b64Pad;return d}function P(c){var a="",d=4*c.length,b,f;for(b=0;b<d;b+=1)f=c[b>>>2]>>>8*(3-b%4)&255,a+=String.fromCharCode(f);return a}function M(c){var a={outputUpper:!1,b64Pad:"="};c=c||{};a.outputUpper=c.outputUpper||!1;a.b64Pad=c.b64Pad||"=";if("boolean"!==typeof a.outputUpper)throw Error("Invalid outputUpper formatting option"); if("string"!==typeof a.b64Pad)throw Error("Invalid b64Pad formatting option");return a}function J(c,a){var d;switch(a){case "UTF8":case "UTF16BE":case "UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE");}switch(c){case "HEX":d=V;break;case "TEXT":d=function(c,d,b){var e=[],l=[],n=0,h,m,u,r,p,e=d||[0];d=b||0;u=d>>>3;if("UTF8"===a)for(h=0;h<c.length;h+=1)for(b=c.charCodeAt(h),l=[],128>b?l.push(b):2048>b?(l.push(192|b>>>6),l.push(128|b&63)):55296>b||57344<=b?l.push(224| b>>>12,128|b>>>6&63,128|b&63):(h+=1,b=65536+((b&1023)<<10|c.charCodeAt(h)&1023),l.push(240|b>>>18,128|b>>>12&63,128|b>>>6&63,128|b&63)),m=0;m<l.length;m+=1){p=n+u;for(r=p>>>2;e.length<=r;)e.push(0);e[r]|=l[m]<<8*(3-p%4);n+=1}else if("UTF16BE"===a||"UTF16LE"===a)for(h=0;h<c.length;h+=1){b=c.charCodeAt(h);"UTF16LE"===a&&(m=b&255,b=m<<8|b>>>8);p=n+u;for(r=p>>>2;e.length<=r;)e.push(0);e[r]|=b<<8*(2-p%4);n+=2}return{value:e,binLen:8*n+d}};break;case "B64":d=X;break;case "BYTES":d=W;break;default:throw Error("format must be HEX, TEXT, B64, or BYTES"); }return d}function w(c,a){return c<<a|c>>>32-a}function q(c,a){return c>>>a|c<<32-a}function v(c,a){var d=null,d=new b(c.a,c.b);return d=32>=a?new b(d.a>>>a|d.b<<32-a&4294967295,d.b>>>a|d.a<<32-a&4294967295):new b(d.b>>>a-32|d.a<<64-a&4294967295,d.a>>>a-32|d.b<<64-a&4294967295)}function Q(c,a){var d=null;return d=32>=a?new b(c.a>>>a,c.b>>>a|c.a<<32-a&4294967295):new b(0,c.a>>>a-32)}function Y(c,a,d){return c&a^~c&d}function Z(c,a,d){return new b(c.a&a.a^~c.a&d.a,c.b&a.b^~c.b&d.b)}function R(c,a,d){return c& a^c&d^a&d}function aa(c,a,d){return new b(c.a&a.a^c.a&d.a^a.a&d.a,c.b&a.b^c.b&d.b^a.b&d.b)}function ba(c){return q(c,2)^q(c,13)^q(c,22)}function ca(c){var a=v(c,28),d=v(c,34);c=v(c,39);return new b(a.a^d.a^c.a,a.b^d.b^c.b)}function da(c){return q(c,6)^q(c,11)^q(c,25)}function ea(c){var a=v(c,14),d=v(c,18);c=v(c,41);return new b(a.a^d.a^c.a,a.b^d.b^c.b)}function fa(c){return q(c,7)^q(c,18)^c>>>3}function ga(c){var a=v(c,1),d=v(c,8);c=Q(c,7);return new b(a.a^d.a^c.a,a.b^d.b^c.b)}function ha(c){return q(c, 17)^q(c,19)^c>>>10}function ia(c){var a=v(c,19),d=v(c,61);c=Q(c,6);return new b(a.a^d.a^c.a,a.b^d.b^c.b)}function B(c,a){var d=(c&65535)+(a&65535);return((c>>>16)+(a>>>16)+(d>>>16)&65535)<<16|d&65535}function ja(c,a,d,b){var f=(c&65535)+(a&65535)+(d&65535)+(b&65535);return((c>>>16)+(a>>>16)+(d>>>16)+(b>>>16)+(f>>>16)&65535)<<16|f&65535}function C(c,a,d,b,f){var e=(c&65535)+(a&65535)+(d&65535)+(b&65535)+(f&65535);return((c>>>16)+(a>>>16)+(d>>>16)+(b>>>16)+(f>>>16)+(e>>>16)&65535)<<16|e&65535}function ka(c, a){var d,e,f;d=(c.b&65535)+(a.b&65535);e=(c.b>>>16)+(a.b>>>16)+(d>>>16);f=(e&65535)<<16|d&65535;d=(c.a&65535)+(a.a&65535)+(e>>>16);e=(c.a>>>16)+(a.a>>>16)+(d>>>16);return new b((e&65535)<<16|d&65535,f)}function la(c,a,d,e){var f,k,g;f=(c.b&65535)+(a.b&65535)+(d.b&65535)+(e.b&65535);k=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(f>>>16);g=(k&65535)<<16|f&65535;f=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(k>>>16);k=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(f>>>16);return new b((k&65535)<<16| f&65535,g)}function ma(c,a,d,e,f){var k,g,l;k=(c.b&65535)+(a.b&65535)+(d.b&65535)+(e.b&65535)+(f.b&65535);g=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(f.b>>>16)+(k>>>16);l=(g&65535)<<16|k&65535;k=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(f.a&65535)+(g>>>16);g=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(f.a>>>16)+(k>>>16);return new b((g&65535)<<16|k&65535,l)}function z(c){var a,d;if("SHA-1"===c)c=[1732584193,4023233417,2562383102,271733878,3285377520];else switch(a=[3238371032,914150663, 812702999,4144912697,4290775857,1750603025,1694076839,3204075428],d=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],c){case "SHA-224":c=a;break;case "SHA-256":c=d;break;case "SHA-384":c=[new b(3418070365,a[0]),new b(1654270250,a[1]),new b(2438529370,a[2]),new b(355462360,a[3]),new b(1731405415,a[4]),new b(41048885895,a[5]),new b(3675008525,a[6]),new b(1203062813,a[7])];break;case "SHA-512":c=[new b(d[0],4089235720),new b(d[1],2227873595),new b(d[2],4271175723), new b(d[3],1595750129),new b(d[4],2917565137),new b(d[5],725511199),new b(d[6],4215389547),new b(d[7],327033209)];break;default:throw Error("Unknown SHA variant");}return c}function K(c,a){var d=[],b,e,k,g,l,n,h;b=a[0];e=a[1];k=a[2];g=a[3];l=a[4];for(h=0;80>h;h+=1)d[h]=16>h?c[h]:w(d[h-3]^d[h-8]^d[h-14]^d[h-16],1),n=20>h?C(w(b,5),e&k^~e&g,l,1518500249,d[h]):40>h?C(w(b,5),e^k^g,l,1859775393,d[h]):60>h?C(w(b,5),R(e,k,g),l,2400959708,d[h]):C(w(b,5),e^k^g,l,3395469782,d[h]),l=g,g=k,k=w(e,30),e=b,b=n;a[0]= B(b,a[0]);a[1]=B(e,a[1]);a[2]=B(k,a[2]);a[3]=B(g,a[3]);a[4]=B(l,a[4]);return a}function U(c,a,b,e){var f;for(f=(a+72>>>9<<4)+15;c.length<=f;)c.push(0);c[a>>>5]|=128<<24-a%32;c[f]=a+b;b=c.length;for(a=0;a<b;a+=16)e=K(c.slice(a,a+16),e);return e}function L(c,a,d){var q,f,k,g,l,n,h,m,u,r,p,v,t,w,x,y,z,D,E,F,G,H,A=[],I;if("SHA-224"===d||"SHA-256"===d)r=64,v=1,H=Number,t=B,w=ja,x=C,y=fa,z=ha,D=ba,E=da,G=R,F=Y,I=e;else if("SHA-384"===d||"SHA-512"===d)r=80,v=2,H=b,t=ka,w=la,x=ma,y=ga,z=ia,D=ca,E=ea,G=aa, F=Z,I=S;else throw Error("Unexpected error in SHA-2 implementation");d=a[0];q=a[1];f=a[2];k=a[3];g=a[4];l=a[5];n=a[6];h=a[7];for(p=0;p<r;p+=1)16>p?(u=p*v,m=c.length<=u?0:c[u],u=c.length<=u+1?0:c[u+1],A[p]=new H(m,u)):A[p]=w(z(A[p-2]),A[p-7],y(A[p-15]),A[p-16]),m=x(h,E(g),F(g,l,n),I[p],A[p]),u=t(D(d),G(d,q,f)),h=n,n=l,l=g,g=t(k,m),k=f,f=q,q=d,d=t(m,u);a[0]=t(d,a[0]);a[1]=t(q,a[1]);a[2]=t(f,a[2]);a[3]=t(k,a[3]);a[4]=t(g,a[4]);a[5]=t(l,a[5]);a[6]=t(n,a[6]);a[7]=t(h,a[7]);return a}var e,S;e=[1116352408, 1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344, 430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];S=[new b(e[0],3609767458),new b(e[1],602891725),new b(e[2],3964484399),new b(e[3],2173295548),new b(e[4],4081628472),new b(e[5],3053834265),new b(e[6],2937671579),new b(e[7],3664609560),new b(e[8],2734883394),new b(e[9],1164996542),new b(e[10],1323610764),new b(e[11],3590304994),new b(e[12],4068182383),new b(e[13],991336113),new b(e[14], 633803317),new b(e[15],3479774868),new b(e[16],2666613458),new b(e[17],944711139),new b(e[18],2341262773),new b(e[19],2007800933),new b(e[20],1495990901),new b(e[21],1856431235),new b(e[22],3175218132),new b(e[23],2198950837),new b(e[24],3999719339),new b(e[25],766784016),new b(e[26],2566594879),new b(e[27],3203337956),new b(e[28],1034457026),new b(e[29],2466948901),new b(e[30],3758326383),new b(e[31],168717936),new b(e[32],1188179964),new b(e[33],1546045734),new b(e[34],1522805485),new b(e[35],2643833823), new b(e[36],2343527390),new b(e[37],1014477480),new b(e[38],1206759142),new b(e[39],344077627),new b(e[40],1290863460),new b(e[41],3158454273),new b(e[42],3505952657),new b(e[43],106217008),new b(e[44],3606008344),new b(e[45],1432725776),new b(e[46],1467031594),new b(e[47],851169720),new b(e[48],3100823752),new b(e[49],1363258195),new b(e[50],3750685593),new b(e[51],3785050280),new b(e[52],3318307427),new b(e[53],3812723403),new b(e[54],2003034995),new b(e[55],3602036899),new b(e[56],1575990012), new b(e[57],1125592928),new b(e[58],2716904306),new b(e[59],442776044),new b(e[60],593698344),new b(e[61],3733110249),new b(e[62],2999351573),new b(e[63],3815920427),new b(3391569614,3928383900),new b(3515267271,566280711),new b(3940187606,3454069534),new b(4118630271,4000239992),new b(116418474,1914138554),new b(174292421,2731055270),new b(289380356,3203993006),new b(460393269,320620315),new b(685471733,587496836),new b(852142971,1086792851),new b(1017036298,365543100),new b(1126000580,2618297676), new b(1288033470,3409855158),new b(1501505948,4234509866),new b(1607167915,987167468),new b(1816402316,1246189591)];"function"===typeof define&&define.amd?define(function(){return y}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=y:exports=y:T.jsSHA=y})(this);
/** * Copyright 2012 Craig Campbell * * 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. * * Rainbow is a simple code syntax highlighter * * @preserve @version 1.1.8 * @url rainbowco.de */ window['Rainbow'] = (function() { /** * array of replacements to process at the end * * @type {Object} */ var replacements = {}, /** * an array of start and end positions of blocks to be replaced * * @type {Object} */ replacement_positions = {}, /** * an array of the language patterns specified for each language * * @type {Object} */ language_patterns = {}, /** * an array of languages and whether they should bypass the default patterns * * @type {Object} */ bypass_defaults = {}, /** * processing level * * replacements are stored at this level so if there is a sub block of code * (for example php inside of html) it runs at a different level * * @type {number} */ CURRENT_LEVEL = 0, /** * constant used to refer to the default language * * @type {number} */ DEFAULT_LANGUAGE = 0, /** * used as counters so we can selectively call setTimeout * after processing a certain number of matches/replacements * * @type {number} */ match_counter = 0, /** * @type {number} */ replacement_counter = 0, /** * @type {null|string} */ global_class, /** * @type {null|Function} */ onHighlight; /** * cross browser get attribute for an element * * @see http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method * * @param {Node} el * @param {string} attr attribute you are trying to get * @returns {string|number} */ function _attr(el, attr, attrs, i) { var result = (el.getAttribute && el.getAttribute(attr)) || 0; if (!result) { attrs = el.attributes; for (i = 0; i < attrs.length; ++i) { if (attrs[i].nodeName === attr) { return attrs[i].nodeValue; } } } return result; } /** * adds a class to a given code block * * @param {Element} el * @param {string} class_name class name to add * @returns void */ function _addClass(el, class_name) { el.className += el.className ? ' ' + class_name : class_name; } /** * checks if a block has a given class * * @param {Element} el * @param {string} class_name class name to check for * @returns {boolean} */ function _hasClass(el, class_name) { return (' ' + el.className + ' ').indexOf(' ' + class_name + ' ') > -1; } /** * gets the language for this block of code * * @param {Element} block * @returns {string|null} */ function _getLanguageForBlock(block) { // if this doesn't have a language but the parent does then use that // this means if for example you have: <pre data-language="php"> // with a bunch of <code> blocks inside then you do not have // to specify the language for each block var language = _attr(block, 'data-language') || _attr(block.parentNode, 'data-language'); // this adds support for specifying language via a css class // you can use the Google Code Prettify style: <pre class="lang-php"> // or the HTML5 style: <pre><code class="language-php"> if (!language) { var pattern = /\blang(?:uage)?-(\w+)/, match = block.className.match(pattern) || block.parentNode.className.match(pattern); if (match) { language = match[1]; } } return language; } /** * makes sure html entities are always used for tags * * @param {string} code * @returns {string} */ function _htmlEntities(code) { return code.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&(?![\w\#]+;)/g, '&amp;'); } /** * determines if a new match intersects with an existing one * * @param {number} start1 start position of existing match * @param {number} end1 end position of existing match * @param {number} start2 start position of new match * @param {number} end2 end position of new match * @returns {boolean} */ function _intersects(start1, end1, start2, end2) { if (start2 >= start1 && start2 < end1) { return true; } return end2 > start1 && end2 < end1; } /** * determines if two different matches have complete overlap with each other * * @param {number} start1 start position of existing match * @param {number} end1 end position of existing match * @param {number} start2 start position of new match * @param {number} end2 end position of new match * @returns {boolean} */ function _hasCompleteOverlap(start1, end1, start2, end2) { // if the starting and end positions are exactly the same // then the first one should stay and this one should be ignored if (start2 == start1 && end2 == end1) { return false; } return start2 <= start1 && end2 >= end1; } /** * determines if the match passed in falls inside of an existing match * this prevents a regex pattern from matching inside of a bigger pattern * * @param {number} start - start position of new match * @param {number} end - end position of new match * @returns {boolean} */ function _matchIsInsideOtherMatch(start, end) { for (var key in replacement_positions[CURRENT_LEVEL]) { key = parseInt(key, 10); // if this block completely overlaps with another block // then we should remove the other block and return false if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { delete replacement_positions[CURRENT_LEVEL][key]; delete replacements[CURRENT_LEVEL][key]; } if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) { return true; } } return false; } /** * takes a string of code and wraps it in a span tag based on the name * * @param {string} name name of the pattern (ie keyword.regex) * @param {string} code block of code to wrap * @returns {string} */ function _wrapCodeInSpan(name, code) { return '<span class="' + name.replace(/\./g, ' ') + (global_class ? ' ' + global_class : '') + '">' + code + '</span>'; } /** * finds out the position of group match for a regular expression * * @see http://stackoverflow.com/questions/1985594/how-to-find-index-of-groups-in-match * * @param {Object} match * @param {number} group_number * @returns {number} */ function _indexOfGroup(match, group_number) { var index = 0, i; for (i = 1; i < group_number; ++i) { if (match[i]) { index += match[i].length; } } return index; } /** * matches a regex pattern against a block of code * finds all matches that should be processed and stores the positions * of where they should be replaced within the string * * this is where pretty much all the work is done but it should not * be called directly * * @param {RegExp} pattern * @param {string} code * @returns void */ function _processPattern(regex, pattern, code, callback) { var match = regex.exec(code); if (!match) { return callback(); } ++match_counter; // treat match 0 the same way as name if (!pattern['name'] && typeof pattern['matches'][0] == 'string') { pattern['name'] = pattern['matches'][0]; delete pattern['matches'][0]; } var replacement = match[0], start_pos = match.index, end_pos = match[0].length + start_pos, /** * callback to process the next match of this pattern */ processNext = function() { var nextCall = function() { _processPattern(regex, pattern, code, callback); }; // every 50 items we process let's call set timeout // to let the ui breathe a little return match_counter % 50 > 0 ? nextCall() : setTimeout(nextCall, 0); }; // if this is not a child match and it falls inside of another // match that already happened we should skip it and continue processing if (_matchIsInsideOtherMatch(start_pos, end_pos)) { return processNext(); } /** * callback for when a match was successfully processed * * @param {string} replacement * @returns void */ var onMatchSuccess = function(replacement) { // if this match has a name then wrap it in a span tag if (pattern['name']) { replacement = _wrapCodeInSpan(pattern['name'], replacement); } // console.log('LEVEL', CURRENT_LEVEL, 'replace', match[0], 'with', replacement, 'at position', start_pos, 'to', end_pos); // store what needs to be replaced with what at this position if (!replacements[CURRENT_LEVEL]) { replacements[CURRENT_LEVEL] = {}; replacement_positions[CURRENT_LEVEL] = {}; } replacements[CURRENT_LEVEL][start_pos] = { 'replace': match[0], 'with': replacement }; // store the range of this match so we can use it for comparisons // with other matches later replacement_positions[CURRENT_LEVEL][start_pos] = end_pos; // process the next match processNext(); }, // if this pattern has sub matches for different groups in the regex // then we should process them one at a time by rerunning them through // this function to generate the new replacement // // we run through them backwards because the match position of earlier // matches will not change depending on what gets replaced in later // matches group_keys = keys(pattern['matches']), /** * callback for processing a sub group * * @param {number} i * @param {Array} group_keys * @param {Function} callback */ processGroup = function(i, group_keys, callback) { if (i >= group_keys.length) { return callback(replacement); } var processNextGroup = function() { processGroup(++i, group_keys, callback); }, block = match[group_keys[i]]; // if there is no match here then move on if (!block) { return processNextGroup(); } var group = pattern['matches'][group_keys[i]], language = group['language'], /** * process group is what group we should use to actually process * this match group * * for example if the subgroup pattern looks like this * 2: { * 'name': 'keyword', * 'pattern': /true/g * } * * then we use that as is, but if it looks like this * * 2: { * 'name': 'keyword', * 'matches': { * 'name': 'special', * 'pattern': /whatever/g * } * } * * we treat the 'matches' part as the pattern and keep * the name around to wrap it with later */ process_group = group['name'] && group['matches'] ? group['matches'] : group, /** * takes the code block matched at this group, replaces it * with the highlighted block, and optionally wraps it with * a span with a name * * @param {string} block * @param {string} replace_block * @param {string|null} match_name */ _replaceAndContinue = function(block, replace_block, match_name) { replacement = _replaceAtPosition(_indexOfGroup(match, group_keys[i]), block, match_name ? _wrapCodeInSpan(match_name, replace_block) : replace_block, replacement); processNextGroup(); }; // if this is a sublanguage go and process the block using that language if (language) { return _highlightBlockForLanguage(block, language, function(code) { _replaceAndContinue(block, code); }); } // if this is a string then this match is directly mapped to selector // so all we have to do is wrap it in a span and continue if (typeof group === 'string') { return _replaceAndContinue(block, block, group); } // the process group can be a single pattern or an array of patterns // _processCodeWithPatterns always expects an array so we convert it here _processCodeWithPatterns(block, process_group.length ? process_group : [process_group], function(code) { _replaceAndContinue(block, code, group['matches'] ? group['name'] : 0); }); }; processGroup(0, group_keys, onMatchSuccess); } /** * should a language bypass the default patterns? * * if you call Rainbow.extend() and pass true as the third argument * it will bypass the defaults */ function _bypassDefaultPatterns(language) { return bypass_defaults[language]; } /** * returns a list of regex patterns for this language * * @param {string} language * @returns {Array} */ function _getPatternsForLanguage(language) { var patterns = language_patterns[language] || [], default_patterns = language_patterns[DEFAULT_LANGUAGE] || []; return _bypassDefaultPatterns(language) ? patterns : patterns.concat(default_patterns); } /** * substring replace call to replace part of a string at a certain position * * @param {number} position the position where the replacement should happen * @param {string} replace the text we want to replace * @param {string} replace_with the text we want to replace it with * @param {string} code the code we are doing the replacing in * @returns {string} */ function _replaceAtPosition(position, replace, replace_with, code) { var sub_string = code.substr(position); return code.substr(0, position) + sub_string.replace(replace, replace_with); } /** * sorts an object by index descending * * @param {Object} object * @return {Array} */ function keys(object) { var locations = [], replacement, pos; for(var location in object) { if (object.hasOwnProperty(location)) { locations.push(location); } } // numeric descending return locations.sort(function(a, b) { return b - a; }); } /** * processes a block of code using specified patterns * * @param {string} code * @param {Array} patterns * @returns void */ function _processCodeWithPatterns(code, patterns, callback) { // we have to increase the level here so that the // replacements will not conflict with each other when // processing sub blocks of code ++CURRENT_LEVEL; // patterns are processed one at a time through this function function _workOnPatterns(patterns, i) { // still have patterns to process, keep going if (i < patterns.length) { return _processPattern(patterns[i]['pattern'], patterns[i], code, function() { _workOnPatterns(patterns, ++i); }); } // we are done processing the patterns // process the replacements and update the DOM _processReplacements(code, function(code) { // when we are done processing replacements // we are done at this level so we can go back down delete replacements[CURRENT_LEVEL]; delete replacement_positions[CURRENT_LEVEL]; --CURRENT_LEVEL; callback(code); }); } _workOnPatterns(patterns, 0); } /** * process replacements in the string of code to actually update the markup * * @param {string} code the code to process replacements in * @param {Function} onComplete what to do when we are done processing * @returns void */ function _processReplacements(code, onComplete) { /** * processes a single replacement * * @param {string} code * @param {Array} positions * @param {number} i * @param {Function} onComplete * @returns void */ function _processReplacement(code, positions, i, onComplete) { if (i < positions.length) { ++replacement_counter; var pos = positions[i], replacement = replacements[CURRENT_LEVEL][pos]; code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code); // process next function var next = function() { _processReplacement(code, positions, ++i, onComplete); }; // use a timeout every 250 to not freeze up the UI return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0); } onComplete(code); } var string_positions = keys(replacements[CURRENT_LEVEL]); _processReplacement(code, string_positions, 0, onComplete); } /** * takes a string of code and highlights it according to the language specified * * @param {string} code * @param {string} language * @param {Function} onComplete * @returns void */ function _highlightBlockForLanguage(code, language, onComplete) { var patterns = _getPatternsForLanguage(language); _processCodeWithPatterns(_htmlEntities(code), patterns, onComplete); } /** * highlight an individual code block * * @param {Array} code_blocks * @param {number} i * @returns void */ function _highlightCodeBlock(code_blocks, i, onComplete) { if (i < code_blocks.length) { var block = code_blocks[i], language = _getLanguageForBlock(block); if (!_hasClass(block, 'rainbow') && language) { language = language.toLowerCase(); _addClass(block, 'rainbow'); return _highlightBlockForLanguage(block.innerHTML, language, function(code) { block.innerHTML = code; // reset the replacement arrays replacements = {}; replacement_positions = {}; // if you have a listener attached tell it that this block is now highlighted if (onHighlight) { onHighlight(block, language); } // process the next block setTimeout(function() { _highlightCodeBlock(code_blocks, ++i, onComplete); }, 0); }); } return _highlightCodeBlock(code_blocks, ++i, onComplete); } if (onComplete) { onComplete(); } } /** * start highlighting all the code blocks * * @returns void */ function _highlight(node, onComplete) { // the first argument can be an Event or a DOM Element // I was originally checking instanceof Event but that makes it break // when using mootools // // @see https://github.com/ccampbell/rainbow/issues/32 // node = node && typeof node.getElementsByTagName == 'function' ? node : document; var pre_blocks = node.getElementsByTagName('pre'), code_blocks = node.getElementsByTagName('code'), i, final_blocks = []; // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript // we are going to process all <code> blocks for (i = 0; i < code_blocks.length; ++i) { final_blocks.push(code_blocks[i]); } // loop through the pre blocks to see which ones we should add for (i = 0; i < pre_blocks.length; ++i) { // if the pre block has no code blocks then process it directly if (!pre_blocks[i].getElementsByTagName('code').length) { final_blocks.push(pre_blocks[i]); } } _highlightCodeBlock(final_blocks, 0, onComplete); } /** * public methods */ return { /** * extends the language pattern matches * * @param {*} language name of language * @param {*} patterns array of patterns to add on * @param {boolean|null} bypass if true this will bypass the default language patterns */ extend: function(language, patterns, bypass) { // if there is only one argument then we assume that we want to // extend the default language rules if (arguments.length == 1) { patterns = language; language = DEFAULT_LANGUAGE; } bypass_defaults[language] = bypass; language_patterns[language] = patterns.concat(language_patterns[language] || []); }, /** * call back to let you do stuff in your app after a piece of code has been highlighted * * @param {Function} callback */ onHighlight: function(callback) { onHighlight = callback; }, /** * method to set a global class that will be applied to all spans * * @param {string} class_name */ addClass: function(class_name) { global_class = class_name; }, /** * starts the magic rainbow * * @returns void */ color: function() { // if you want to straight up highlight a string you can pass the string of code, // the language, and a callback function if (typeof arguments[0] == 'string') { return _highlightBlockForLanguage(arguments[0], arguments[1], arguments[2]); } // if you pass a callback function then we rerun the color function // on all the code and call the callback function on complete if (typeof arguments[0] == 'function') { return _highlight(0, arguments[0]); } // otherwise we use whatever node you passed in with an optional // callback function as the second parameter _highlight(arguments[0], arguments[1]); } }; }) (); /** * adds event listener to start highlighting */ (function() { if (window.addEventListener) { return window.addEventListener('load', Rainbow.color, false); } window.attachEvent('onload', Rainbow.color); }) (); // When using Google closure compiler in advanced mode some methods // get renamed. This keeps a public reference to these methods so they can // still be referenced from outside this library. Rainbow["onHighlight"] = Rainbow.onHighlight; Rainbow["addClass"] = Rainbow.addClass;
YUI.add('event-touch', function(Y) { /** * Adds touch event facade normalization properties (touches, changedTouches, targetTouches etc.) to the DOM event facade * * @module event-touch */ var SCALE = "scale", ROTATION = "rotation", IDENTIFIER = "identifier"; /** * Adds touch event facade normalization properties to the DOM event facade * * @method _touch * @for DOMEventFacade * @private * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ Y.DOMEventFacade.prototype._touch = function(e, currentTarget, wrapper) { var i,l, etCached, et,touchCache; if (e.touches) { /** * Array of individual touch events for touch points that are still in * contact with the touch surface. * * @property touches * @type {DOMEventFacade[]} */ this.touches = []; touchCache = {}; for (i = 0, l = e.touches.length; i < l; ++i) { et = e.touches[i]; touchCache[Y.stamp(et)] = this.touches[i] = new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (e.targetTouches) { /** * Array of individual touch events still in contact with the touch * surface and whose `touchstart` event occurred inside the same taregt * element as the current target element. * * @property targetTouches * @type {DOMEventFacade[]} */ this.targetTouches = []; for (i = 0, l = e.targetTouches.length; i < l; ++i) { et = e.targetTouches[i]; etCached = touchCache && touchCache[Y.stamp(et, true)]; this.targetTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (e.changedTouches) { /** An array of event-specific touch events. For `touchstart`, the touch points that became active with the current event. For `touchmove`, the touch points that have changed since the last event. For `touchend`, the touch points that have been removed from the touch surface. @property changedTouches @type {DOMEventFacade[]} **/ this.changedTouches = []; for (i = 0, l = e.changedTouches.length; i < l; ++i) { et = e.changedTouches[i]; etCached = touchCache && touchCache[Y.stamp(et, true)]; this.changedTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (SCALE in e) { this[SCALE] = e[SCALE]; } if (ROTATION in e) { this[ROTATION] = e[ROTATION]; } if (IDENTIFIER in e) { this[IDENTIFIER] = e[IDENTIFIER]; } }; if (Y.Node.DOM_EVENTS) { Y.mix(Y.Node.DOM_EVENTS, { touchstart:1, touchmove:1, touchend:1, touchcancel:1, gesturestart:1, gesturechange:1, gestureend:1 }); } }, '@VERSION@' ,{requires:['node-base']});
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("widget","hr",{move:"Klikni i povuci da pomakneš",label:"%1 widget"});
/*! Qoopido.js library 3.7.1, 2015-07-25 | https://github.com/dlueth/qoopido.js | (c) 2015 Dirk Lueth */ !function(t){var e=["../emitter"];window.matchMedia||e.push("../polyfill/window/matchmedia"),window.qoopido.register("component/sense",t,e)}(function(t,e,n,i,c,o,a){"use strict";function r(){var t=this,e=t.mql;t.emit(e.matches===!0?"matched":"dematched")}var m,s={};return m=t.emitter.extend({mql:null,_constructor:function(t){var e=this,n=e.mql=s[t]||(s[t]=c.matchMedia(t)),i=function(){r.call(e)};m._parent._constructor.call(e),n.addListener(i),c.setTimeout(i,0)},matches:function(){return this.mql.matches}})});
/** * @license Highmaps JS v1.0.3 (2014-07-03) * * Standalone Highcharts Framework * * License: MIT License */ /*global Highcharts */ var HighchartsAdapter = (function () { var UNDEFINED, doc = document, emptyArray = [], timers = [], timerId, Fx; Math.easeInOutSine = function (t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }; /** * Extend given object with custom events */ function augment(obj) { function removeOneEvent(el, type, fn) { el.removeEventListener(type, fn, false); } function IERemoveOneEvent(el, type, fn) { fn = el.HCProxiedMethods[fn.toString()]; el.detachEvent('on' + type, fn); } function removeAllEvents(el, type) { var events = el.HCEvents, remove, types, len, n; if (el.removeEventListener) { remove = removeOneEvent; } else if (el.attachEvent) { remove = IERemoveOneEvent; } else { return; // break on non-DOM events } if (type) { types = {}; types[type] = true; } else { types = events; } for (n in types) { if (events[n]) { len = events[n].length; while (len--) { remove(el, n, events[n][len]); } } } } if (!obj.HCExtended) { Highcharts.extend(obj, { HCExtended: true, HCEvents: {}, bind: function (name, fn) { var el = this, events = this.HCEvents, wrappedFn; // handle DOM events in modern browsers if (el.addEventListener) { el.addEventListener(name, fn, false); // handle old IE implementation } else if (el.attachEvent) { wrappedFn = function (e) { e.target = e.srcElement || window; // #2820 fn.call(el, e); }; if (!el.HCProxiedMethods) { el.HCProxiedMethods = {}; } // link wrapped fn with original fn, so we can get this in removeEvent el.HCProxiedMethods[fn.toString()] = wrappedFn; el.attachEvent('on' + name, wrappedFn); } if (events[name] === UNDEFINED) { events[name] = []; } events[name].push(fn); }, unbind: function (name, fn) { var events, index; if (name) { events = this.HCEvents[name] || []; if (fn) { index = HighchartsAdapter.inArray(fn, events); if (index > -1) { events.splice(index, 1); this.HCEvents[name] = events; } if (this.removeEventListener) { removeOneEvent(this, name, fn); } else if (this.attachEvent) { IERemoveOneEvent(this, name, fn); } } else { removeAllEvents(this, name); this.HCEvents[name] = []; } } else { removeAllEvents(this); this.HCEvents = {}; } }, trigger: function (name, args) { var events = this.HCEvents[name] || [], target = this, len = events.length, i, preventDefault, fn; // Attach a simple preventDefault function to skip default handler if called preventDefault = function () { args.defaultPrevented = true; }; for (i = 0; i < len; i++) { fn = events[i]; // args is never null here if (args.stopped) { return; } args.preventDefault = preventDefault; args.target = target; // If the type is not set, we're running a custom event (#2297). If it is set, // we're running a browser event, and setting it will cause en error in // IE8 (#2465). if (!args.type) { args.type = name; } // If the event handler return false, prevent the default handler from executing if (fn.call(this, args) === false) { args.preventDefault(); } } } }); } return obj; } return { /** * Initialize the adapter. This is run once as Highcharts is first run. */ init: function (pathAnim) { /** * Compatibility section to add support for legacy IE. This can be removed if old IE * support is not needed. */ if (!doc.defaultView) { this._getStyle = function (el, prop) { var val; if (el.style[prop]) { return el.style[prop]; } else { if (prop === 'opacity') { prop = 'filter'; } /*jslint unparam: true*/ val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace( /alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100; } ); } /*jslint unparam: false*/ return val === '' ? 1 : val; } }; this.adapterRun = function (elem, method) { var alias = { width: 'clientWidth', height: 'clientHeight' }[method]; if (alias) { elem.style.zoom = 1; return elem[alias] - 2 * parseInt(HighchartsAdapter._getStyle(elem, 'padding'), 10); } }; } if (!Array.prototype.forEach) { this.each = function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; } if (!Array.prototype.indexOf) { this.inArray = function (item, arr) { var len, i = 0; if (arr) { len = arr.length; for (; i < len; i++) { if (arr[i] === item) { return i; } } } return -1; }; } if (!Array.prototype.filter) { this.grep = function (elements, callback) { var ret = [], i = 0, length = elements.length; for (; i < length; i++) { if (!!callback(elements[i], i)) { ret.push(elements[i]); } } return ret; }; } //--- End compatibility section --- /** * Start of animation specific code */ Fx = function (elem, options, prop) { this.options = options; this.elem = elem; this.prop = prop; }; Fx.prototype = { update: function () { var styles, paths = this.paths, elem = this.elem, elemelem = elem.element; // if destroyed, it is null // Animating a path definition on SVGElement if (paths && elemelem) { elem.attr('d', pathAnim.step(paths[0], paths[1], this.now, this.toD)); // Other animations on SVGElement } else if (elem.attr) { if (elemelem) { elem.attr(this.prop, this.now); } // HTML styles } else { styles = {}; styles[this.prop] = this.now + this.unit; Highcharts.css(elem, styles); } if (this.options.step) { this.options.step.call(this.elem, this.now, this); } }, custom: function (from, to, unit) { var self = this, t = function (gotoEnd) { return self.step(gotoEnd); }, i; this.startTime = +new Date(); this.start = from; this.end = to; this.unit = unit; this.now = this.start; this.pos = this.state = 0; t.elem = this.elem; if (t() && timers.push(t) === 1) { timerId = setInterval(function () { for (i = 0; i < timers.length; i++) { if (!timers[i]()) { timers.splice(i--, 1); } } if (!timers.length) { clearInterval(timerId); } }, 13); } }, step: function (gotoEnd) { var t = +new Date(), ret, done, options = this.options, elem = this.elem, i; if (elem.stopAnimation || (elem.attr && !elem.element)) { // #2616, element including flag is destroyed ret = false; } else if (gotoEnd || t >= options.duration + this.startTime) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[this.prop] = true; done = true; for (i in options.curAnim) { if (options.curAnim[i] !== true) { done = false; } } if (done) { if (options.complete) { options.complete.call(elem); } } ret = false; } else { var n = t - this.startTime; this.state = n / options.duration; this.pos = options.easing(n, 0, 1, options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); ret = true; } return ret; } }; /** * The adapter animate method */ this.animate = function (el, prop, opt) { var start, unit = '', end, fx, args, name; el.stopAnimation = false; // ready for new if (typeof opt !== 'object' || opt === null) { args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration !== 'number') { opt.duration = 400; } opt.easing = Math[opt.easing] || Math.easeInOutSine; opt.curAnim = Highcharts.extend({}, prop); for (name in prop) { fx = new Fx(el, opt, name); end = null; if (name === 'd') { fx.paths = pathAnim.init( el, el.d, prop.d ); fx.toD = prop.d; start = 0; end = 1; } else if (el.attr) { start = el.attr(name); } else { start = parseFloat(HighchartsAdapter._getStyle(el, name)) || 0; if (name !== 'opacity') { unit = 'px'; } } if (!end) { end = parseFloat(prop[name]); } fx.custom(start, end, unit); } }; }, /** * Internal method to return CSS value for given element and property */ _getStyle: function (el, prop) { return window.getComputedStyle(el, undefined).getPropertyValue(prop); }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: function (scriptLocation, callback) { // We cannot assume that Assets class from mootools-more is available so instead insert a script tag to download script. var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); }, /** * Return the index of an item in an array, or -1 if not found */ inArray: function (item, arr) { return arr.indexOf ? arr.indexOf(item) : emptyArray.indexOf.call(arr, item); }, /** * A direct link to adapter methods */ adapterRun: function (elem, method) { return parseInt(HighchartsAdapter._getStyle(elem, method), 10); }, /** * Filter an array */ grep: function (elements, callback) { return emptyArray.filter.call(elements, callback); }, /** * Map an array */ map: function (arr, fn) { var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the element's offset position, corrected by overflow:auto. Loosely based on jQuery's offset method. */ offset: function (el) { var docElem = document.documentElement, box = el.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }, /** * Add an event listener */ addEvent: function (el, type, fn) { augment(el).bind(type, fn); }, /** * Remove event added with addEvent */ removeEvent: function (el, type, fn) { augment(el).unbind(type, fn); }, /** * Fire an event on a custom object */ fireEvent: function (el, type, eventArguments, defaultFunction) { var e; if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) { e = doc.createEvent('Events'); e.initEvent(type, true, true); e.target = el; Highcharts.extend(e, eventArguments); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent(type, e); } } else if (el.HCExtended === true) { eventArguments = eventArguments || {}; el.trigger(type, eventArguments); } if (eventArguments && eventArguments.defaultPrevented) { defaultFunction = null; } if (defaultFunction) { defaultFunction(eventArguments); } }, washMouseEvent: function (e) { return e; }, /** * Stop running animation */ stop: function (el) { el.stopAnimation = true; }, /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ each: function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } }; }());
/** * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods * @author Keith Cirkel <http://keithcirkel.co.uk> * @deprecated in ESLint v3.9.0 */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "require `Reflect` methods where applicable", category: "ECMAScript 6", recommended: false, replacedBy: [] }, deprecated: true, schema: [ { type: "object", properties: { exceptions: { type: "array", items: { enum: [ "apply", "call", "delete", "defineProperty", "getOwnPropertyDescriptor", "getPrototypeOf", "setPrototypeOf", "isExtensible", "getOwnPropertyNames", "preventExtensions" ] }, uniqueItems: true } }, additionalProperties: false } ] }, create(context) { const existingNames = { apply: "Function.prototype.apply", call: "Function.prototype.call", defineProperty: "Object.defineProperty", getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", getPrototypeOf: "Object.getPrototypeOf", setPrototypeOf: "Object.setPrototypeOf", isExtensible: "Object.isExtensible", getOwnPropertyNames: "Object.getOwnPropertyNames", preventExtensions: "Object.preventExtensions" }; const reflectSubsitutes = { apply: "Reflect.apply", call: "Reflect.apply", defineProperty: "Reflect.defineProperty", getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", getPrototypeOf: "Reflect.getPrototypeOf", setPrototypeOf: "Reflect.setPrototypeOf", isExtensible: "Reflect.isExtensible", getOwnPropertyNames: "Reflect.getOwnPropertyNames", preventExtensions: "Reflect.preventExtensions" }; const exceptions = (context.options[0] || {}).exceptions || []; /** * Reports the Reflect violation based on the `existing` and `substitute` * @param {Object} node The node that violates the rule. * @param {string} existing The existing method name that has been used. * @param {string} substitute The Reflect substitute that should be used. * @returns {void} */ function report(node, existing, substitute) { context.report({ node, message: "Avoid using {{existing}}, instead use {{substitute}}.", data: { existing, substitute } }); } return { CallExpression(node) { const methodName = (node.callee.property || {}).name; const isReflectCall = (node.callee.object || {}).name === "Reflect"; const hasReflectSubsitute = reflectSubsitutes.hasOwnProperty(methodName); const userConfiguredException = exceptions.indexOf(methodName) !== -1; if (hasReflectSubsitute && !isReflectCall && !userConfiguredException) { report(node, existingNames[methodName], reflectSubsitutes[methodName]); } }, UnaryExpression(node) { const isDeleteOperator = node.operator === "delete"; const targetsIdentifier = node.argument.type === "Identifier"; const userConfiguredException = exceptions.indexOf("delete") !== -1; if (isDeleteOperator && !targetsIdentifier && !userConfiguredException) { report(node, "the delete keyword", "Reflect.deleteProperty"); } } }; } };
"use strict" // Description of supported double byte encodings and aliases. // Tables are not require()-d until they are needed to speed up library load. // require()-s are direct to support Browserify. module.exports = { // == Japanese/ShiftJIS ==================================================== // All japanese encodings are based on JIS X set of standards: // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. // Has several variations in 1978, 1983, 1990 and 1997. // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. // 2 planes, first is superset of 0208, second - revised 0212. // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) // Byte encodings are: // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. // 0x00-0x7F - lower part of 0201 // 0x8E, 0xA1-0xDF - upper part of 0201 // (0xA1-0xFE)x2 - 0208 plane (94x94). // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. // Used as-is in ISO2022 family. // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, // 0201-1976 Roman, 0208-1978, 0208-1983. // * ISO2022-JP-1: Adds esc seq for 0212-1990. // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. // // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. // // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html 'shiftjis': { type: '_dbcs', table: function() { return require('./tables/shiftjis.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, encodeSkipVals: [{from: 0xED40, to: 0xF940}], }, 'csshiftjis': 'shiftjis', 'mskanji': 'shiftjis', 'sjis': 'shiftjis', 'windows31j': 'shiftjis', 'xsjis': 'shiftjis', 'windows932': 'shiftjis', '932': 'shiftjis', 'cp932': 'shiftjis', 'eucjp': { type: '_dbcs', table: function() { return require('./tables/eucjp.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, }, // TODO: KDDI extension to Shift_JIS // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. // == Chinese/GBK ========================================================== // http://en.wikipedia.org/wiki/GBK // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 'gb2312': 'cp936', 'gb231280': 'cp936', 'gb23121980': 'cp936', 'csgb2312': 'cp936', 'csiso58gb231280': 'cp936', 'euccn': 'cp936', 'isoir58': 'gbk', // Microsoft's CP936 is a subset and approximation of GBK. // TODO: Euro = 0x80 in cp936, but not in GBK (where it's valid but undefined) 'windows936': 'cp936', '936': 'cp936', 'cp936': { type: '_dbcs', table: function() { return require('./tables/cp936.json') }, }, // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. 'gbk': { type: '_dbcs', table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, }, 'xgbk': 'gbk', // GB18030 is an algorithmic extension of GBK. 'gb18030': { type: '_dbcs', table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, gb18030: function() { return require('./tables/gb18030-ranges.json') }, }, 'chinese': 'gb18030', // TODO: Support GB18030 (~27000 chars + whole unicode mapping, cp54936) // http://icu-project.org/docs/papers/gb18030.html // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 // == Korean =============================================================== // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. 'windows949': 'cp949', '949': 'cp949', 'cp949': { type: '_dbcs', table: function() { return require('./tables/cp949.json') }, }, 'cseuckr': 'cp949', 'csksc56011987': 'cp949', 'euckr': 'cp949', 'isoir149': 'cp949', 'korean': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'ksc5601': 'cp949', // == Big5/Taiwan/Hong Kong ================================================ // There are lots of tables for Big5 and cp950. Please see the following links for history: // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html // Variations, in roughly number of defined chars: // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ // * Big5-2003 (Taiwan standard) almost superset of cp950. // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. // Plus, it has 4 combining sequences. // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. // Implementations are not consistent within browsers; sometimes labeled as just big5. // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt // // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. 'windows950': 'cp950', '950': 'cp950', 'cp950': { type: '_dbcs', table: function() { return require('./tables/cp950.json') }, }, // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, encodeSkipVals: [0xa2cc], }, 'cnbig5': 'big5hkscs', 'csbig5': 'big5hkscs', 'xxbig5': 'big5hkscs', };
"use strict"; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.ClassDeclaration = ClassDeclaration; exports.ClassExpression = ClassExpression; exports.__esModule = true; var memoiseDecorators = _interopRequire(require("../../helpers/memoise-decorators")); var ReplaceSupers = _interopRequire(require("../../helpers/replace-supers")); var nameMethod = _interopRequireWildcard(require("../../helpers/name-method")); var defineMap = _interopRequireWildcard(require("../../helpers/define-map")); var messages = _interopRequireWildcard(require("../../../messages")); var util = _interopRequireWildcard(require("../../../util")); var traverse = _interopRequire(require("../../../traversal")); var each = _interopRequire(require("lodash/collection/each")); var has = _interopRequire(require("lodash/object/has")); var t = _interopRequireWildcard(require("../../../types")); var PROPERTY_COLLISION_METHOD_NAME = "__initializeProperties"; var check = t.isClass; exports.check = check; function ClassDeclaration(node, parent, scope, file) { return t.variableDeclaration("let", [t.variableDeclarator(node.id, t.toExpression(node))]); } function ClassExpression(node, parent, scope, file) { return new ClassTransformer(this, file).run(); } var collectPropertyReferencesVisitor = { Identifier: { enter: function enter(node, parent, scope, state) { if (this.parentPath.isClassProperty({ key: node })) { return; } if (this.isReferenced() && scope.getBinding(node.name) === state.scope.getBinding(node.name)) { state.references[node.name] = true; } } } }; var constructorVisitor = traverse.explode({ ThisExpression: { enter: function enter(node, parent, scope, ref) { return ref; } }, Function: { enter: function enter(node) { if (!node.shadow) { this.skip(); } } } }); var verifyConstructorVisitor = traverse.explode({ MethodDefinition: { enter: function enter() { this.skip(); } }, Property: { enter: function enter(node) { if (node.method) this.skip(); } }, CallExpression: { exit: function exit(node, parent, scope, state) { if (this.get("callee").isSuper()) { state.hasBareSuper = true; state.bareSuper = this; if (!state.hasSuper) { throw this.errorWithNode("super call is only allowed in derived constructor"); } } } }, FunctionDeclaration: { enter: function enter() { this.skip(); } }, FunctionExpression: { enter: function enter() { this.skip(); } }, ThisExpression: { enter: function enter(node, parent, scope, state) { if (state.hasSuper && !state.hasBareSuper) { throw this.errorWithNode("'this' is not allowed before super()"); } if (state.isNativeSuper) { return state.nativeSuperRef; } } } }); var ClassTransformer = (function () { /** * Description */ function ClassTransformer(path, file) { _classCallCheck(this, ClassTransformer); this.parent = path.parent; this.scope = path.scope; this.node = path.node; this.path = path; this.file = file; this.hasInstanceDescriptors = false; this.hasStaticDescriptors = false; this.instanceMutatorMap = {}; this.staticMutatorMap = {}; this.instancePropBody = []; this.instancePropRefs = {}; this.staticPropBody = []; this.body = []; this.hasConstructor = false; this.hasDecorators = false; this.className = this.node.id; this.classRef = this.node.id || this.scope.generateUidIdentifier("class"); this.superName = this.node.superClass || t.identifier("Function"); this.hasSuper = !!this.node.superClass; this.isLoose = file.isLoose("es6.classes"); } /** * Description * * @returns {Array} */ ClassTransformer.prototype.run = function run() { var superName = this.superName; var className = this.className; var classBody = this.node.body.body; var classRef = this.classRef; var file = this.file; // var superClass = this.node.superClass; this.isNativeSuper = superClass && t.isIdentifier(superClass) && t.NATIVE_TYPE_NAMES.indexOf(superClass.name) >= 0; if (this.isNativeSuper) { this.nativeSuperRef = this.scope.generateUidIdentifier("this"); } // var body = this.body; // var constructorBody = this.constructorBody = t.blockStatement([]); var constructor; if (this.className) { constructor = t.functionDeclaration(this.className, [], constructorBody); body.push(constructor); } else { constructor = t.functionExpression(null, [], constructorBody); } this.constructor = constructor; // var closureParams = []; var closureArgs = []; // if (this.hasSuper) { closureArgs.push(superName); superName = this.scope.generateUidBasedOnNode(superName); closureParams.push(superName); this.superName = superName; body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [classRef, superName]))); } // var decorators = this.node.decorators; if (decorators) { // create a class reference to use later on this.classRef = this.scope.generateUidIdentifier(classRef); // this is so super calls and the decorators have access to the raw function body.push(t.variableDeclaration("var", [t.variableDeclarator(this.classRef, classRef)])); } // this.buildBody(); // make sure this class isn't directly called constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [t.thisExpression(), this.classRef]))); // if (decorators) { // reverse the decorators so we execute them in the right order decorators = decorators.reverse(); for (var i = 0; i < decorators.length; i++) { var decorator = decorators[i]; var decoratorNode = util.template("class-decorator", { DECORATOR: decorator.expression, CLASS_REF: classRef }, true); decoratorNode.expression._ignoreModulesRemap = true; body.push(decoratorNode); } } if (this.isNativeSuper) { // we've determined this is inheriting from a native class so return the constructed // instance constructorBody.body.push(t.returnStatement(this.nativeSuperRef)); } if (this.className) { // named class with only a constructor if (body.length === 1) return t.toExpression(body[0]); } else { // infer class name if this is a nameless class expression constructor = nameMethod.bare(constructor, this.parent, this.scope); body.unshift(t.variableDeclaration("var", [t.variableDeclarator(classRef, constructor)])); t.inheritsComments(body[0], this.node); } body = body.concat(this.staticPropBody); // body.push(t.returnStatement(classRef)); return t.callExpression(t.functionExpression(null, closureParams, t.blockStatement(body)), closureArgs); }; /** * Description */ ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { var kind = arguments[2] === undefined ? "value" : arguments[2]; var mutatorMap; if (node["static"]) { this.hasStaticDescriptors = true; mutatorMap = this.staticMutatorMap; } else { this.hasInstanceDescriptors = true; mutatorMap = this.instanceMutatorMap; } var map = defineMap.push(mutatorMap, node, kind, this.file); if (enumerable) { map.enumerable = t.literal(true); } if (map.decorators) { this.hasDecorators = true; } }; /** * Description */ ClassTransformer.prototype.buildBody = function buildBody() { var constructorBody = this.constructorBody; var constructor = this.constructor; var className = this.className; var superName = this.superName; var classBody = this.node.body.body; var body = this.body; var classBodyPaths = this.path.get("body").get("body"); for (var i = 0; i < classBody.length; i++) { var node = classBody[i]; var path = classBodyPaths[i]; if (node.decorators) { memoiseDecorators(node.decorators, this.scope); } if (t.isMethodDefinition(node)) { var isConstructor = node.kind === "constructor"; if (isConstructor) this.verifyConstructor(path); var replaceSupers = new ReplaceSupers({ methodPath: path, methodNode: node, objectRef: this.classRef, superRef: this.superName, isStatic: node["static"], isLoose: this.isLoose, scope: this.scope, file: this.file }, true); replaceSupers.replace(); if (isConstructor) { this.pushConstructor(node, path); } else { this.pushMethod(node); } } else if (t.isClassProperty(node)) { this.pushProperty(node); } } // we have no constructor, but we're a derived class if (!this.hasConstructor && this.hasSuper) { var helperName = "class-super-constructor-call"; if (this.isLoose) helperName += "-loose"; if (this.isNativeSuper) helperName = "class-super-native-constructor-call"; constructorBody.body.push(util.template(helperName, { NATIVE_REF: this.nativeSuperRef, CLASS_NAME: className, SUPER_NAME: this.superName }, true)); } // this.placePropertyInitializers(); // if (this.userConstructor) { constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); t.inherits(this.constructor, this.userConstructor); t.inherits(this.constructorBody, this.userConstructor.body); } var instanceProps; var staticProps; var classHelper = "create-class"; if (this.hasDecorators) classHelper = "create-decorated-class"; if (this.hasInstanceDescriptors) { instanceProps = defineMap.toClassObject(this.instanceMutatorMap); } if (this.hasStaticDescriptors) { staticProps = defineMap.toClassObject(this.staticMutatorMap); } if (instanceProps || staticProps) { if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); var nullNode = t.literal(null); // (Constructor, instanceDescriptors, staticDescriptors, instanceInitializers, staticInitializers) var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; if (instanceProps) args[1] = instanceProps; if (staticProps) args[2] = staticProps; if (this.instanceInitializersId) { args[3] = this.instanceInitializersId; body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); } if (this.staticInitializersId) { args[4] = this.staticInitializersId; body.unshift(this.buildObjectAssignment(this.staticInitializersId)); } var lastNonNullIndex = 0; for (var i = 0; i < args.length; i++) { if (args[i] !== nullNode) lastNonNullIndex = i; } args = args.slice(0, lastNonNullIndex + 1); body.push(t.expressionStatement(t.callExpression(this.file.addHelper(classHelper), args))); } }; ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); }; /** * Description */ ClassTransformer.prototype.placePropertyInitializers = function placePropertyInitializers() { var body = this.instancePropBody; if (!body.length) return; if (this.hasPropertyCollision()) { var call = t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier(PROPERTY_COLLISION_METHOD_NAME)), [])); this.pushMethod(t.methodDefinition(t.identifier(PROPERTY_COLLISION_METHOD_NAME), t.functionExpression(null, [], t.blockStatement(body))), true); if (this.hasSuper) { this.bareSuper.insertAfter(call); } else { this.constructorBody.body.unshift(call); } } else { if (this.hasSuper) { if (this.hasConstructor) { this.bareSuper.insertAfter(body); } else { this.constructorBody.body = this.constructorBody.body.concat(body); } } else { this.constructorBody.body = body.concat(this.constructorBody.body); } } }; /** * Description */ ClassTransformer.prototype.hasPropertyCollision = function hasPropertyCollision() { if (this.userConstructorPath) { for (var name in this.instancePropRefs) { if (this.userConstructorPath.scope.hasOwnBinding(name)) { return true; } } } return false; }; /** * Description */ ClassTransformer.prototype.verifyConstructor = function verifyConstructor(path) { var state = { nativeSuperRef: this.nativeSuperRef, isNativeSuper: this.isNativeSuper, hasBareSuper: false, bareSuper: null, hasSuper: this.hasSuper, file: this.file }; path.get("value").traverse(verifyConstructorVisitor, state); this.bareSuper = state.bareSuper; if (!state.hasBareSuper && this.hasSuper) { throw path.errorWithNode("Derived constructor must call super()"); } if (this.isNativeSuper && this.bareSuper) { this.bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(this.nativeSuperRef, t.newExpression(this.superName, this.bareSuper.node.arguments))]), t.expressionStatement(t.assignmentExpression("=", t.memberExpression(this.nativeSuperRef, t.identifier("__proto__")), t.memberExpression(this.classRef, t.identifier("prototype")))), t.expressionStatement(this.nativeSuperRef)]); } }; /** * Push a method to its respective mutatorMap. */ ClassTransformer.prototype.pushMethod = function pushMethod(node, allowedIllegal) { if (!allowedIllegal && t.isLiteral(t.toComputedKey(node), { value: PROPERTY_COLLISION_METHOD_NAME })) { throw this.file.errorWithNode(node, messages.get("illegalMethodName", PROPERTY_COLLISION_METHOD_NAME)); } if (node.kind === "method") { nameMethod.property(node, this.file, this.scope); if (this.isLoose) { // use assignments instead of define properties for loose classes var classRef = this.classRef; if (!node["static"]) classRef = t.memberExpression(classRef, t.identifier("prototype")); var methodName = t.memberExpression(classRef, node.key, node.computed); var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value)); t.inheritsComments(expr, node); this.body.push(expr); return; } } this.pushToMap(node); }; /** * Description */ ClassTransformer.prototype.pushProperty = function pushProperty(node) { var key; this.scope.traverse(node, collectPropertyReferencesVisitor, { references: this.instancePropRefs, scope: this.scope }); if (node.decorators) { var body = []; if (node.value) body.push(t.returnStatement(node.value)); node.value = t.functionExpression(null, [], t.blockStatement(body)); this.pushToMap(node, true, "initializer"); var initializers; var body; var target; if (node["static"]) { var _ref; initializers = (_ref = this, !_ref.staticInitializersId && (_ref.staticInitializersId = this.scope.generateUidIdentifier("staticInitializers")), _ref.staticInitializersId); body = this.staticPropBody; target = this.classRef; } else { var _ref2; initializers = (_ref2 = this, !_ref2.instanceInitializersId && (_ref2.instanceInitializersId = this.scope.generateUidIdentifier("instanceInitializers")), _ref2.instanceInitializersId); body = this.instancePropBody; target = t.thisExpression(); } body.push(t.expressionStatement(t.callExpression(this.file.addHelper("define-decorated-property-descriptor"), [target, t.literal(node.key.name), initializers]))); } else { var _node = node; if (!_node.value) _node.value = t.identifier("undefined"); if (node["static"]) { // can just be added to the static map this.pushToMap(node, true); } else if (node.value) { // add this to the instancePropBody which will be added after the super call in a derived constructor // or at the start of a constructor for a non-derived constructor this.instancePropBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(t.thisExpression(), node.key), node.value))); } } }; /** * Replace the constructor body of our class. */ ClassTransformer.prototype.pushConstructor = function pushConstructor(method, path) { // https://github.com/babel/babel/issues/1077 var fnPath = path.get("value"); if (fnPath.scope.hasOwnBinding(this.classRef.name)) { fnPath.scope.rename(this.classRef.name); } if (this.isNativeSuper) { fnPath.traverse(constructorVisitor, this.nativeSuperRef); } var construct = this.constructor; var fn = method.value; this.userConstructorPath = fnPath; this.userConstructor = fn; this.hasConstructor = true; t.inheritsComments(construct, method); construct._ignoreUserWhitespace = true; construct.params = fn.params; t.inherits(construct.body, fn.body); }; return ClassTransformer; })();
var os = require('os'), fs = require('fs'), path = require('path'), childProcess = require('child_process'), glob = require('glob'), chokidar = require('chokidar'), mv = require('mv'), db = require(__dirname + '/utils/mongodb.js'), models = require(__dirname + '/models'), config = require(__dirname + '/../config.js'), stringUtil = require(__dirname + "/utils/string.js"), watcher = chokidar.watch(config.scanDir + "/*.(pdf|jpg|jpeg|png|bmp|gif|txt|md)", { awaitWriteFinish : true }); var tmpDir = os.tmpdir() + '/archiver' if (!fs.existsSync(tmpDir)){ fs.mkdirSync(tmpDir); } function createDocument (file, callback) { var docTags = []; models.Tag.find({}, (err, tags) => { tags.forEach(tag => { var regexp = new RegExp(stringUtil.escapeRegExp(tag.filter)) if (tag.isRegexp) { regexp = tag.filter.match(/^\/(.*?)\/([gim]*)$/); if (!regexp) return; regexp = new RegExp(regexp[1], regexp[2]); } if (file.data.match(regexp)) { docTags.push(tag.name); } }); models.Document.create({ name: file.format.name, fileName: file.filename, content: file.data, tags: docTags, type: file.format.ext.replace('.', '') }, (err, document) => { if (file.images) { file.images.forEach(image => { fs.unlink(image); }); } if (err) { callback(err); return; } mv(file.tmp, file.newPath, function (err) { callback(null, document); }); }); }); } function getDataFromIMG (file, callback) { childProcess.exec("tesseract " + file.tmp + " stdout", (error, stdout, stderr) => { if (error) { return callback(stderr); } file.data = stdout; createDocument(file, callback); }); } function getDataFromTXT (file, callback) { fs.readFile(file.filePath, (err, data) => { if (err) { return callback(err); } file.data = data.toString('utf8'); createDocument(file, callback); }); } function getDataFromPDF (file, callback) { childProcess.exec("convert -density 300 -depth 8 -type grayscale " + file.tmp + " " + file.tmp + "-convert.png", (error, stdout, stderr) => { if (error) { return callback(stderr); } glob(tmpDir + "/**/" + file.filename + "-convert*", { nodir: true }, (err, files) => { var data = "", docTags = []; file.images = files; file.images.forEach(image => { data += childProcess.execSync("tesseract " + image + " stdout"); }); file.data = data; createDocument(file, callback); }); }); } watcher.on('add', (filePath, infos) => { var date = +(new Date), format = path.parse(filePath), file = { filePath: filePath, date : +(new Date), format: format, }, callback = (err, document) => { if (err) { console.log(err); return; } console.log("Finish consuming "+file.format.base); }; file.filename = date + '-' + format.base.replace(/ /g, '-'); file.newPath = config.archiveDir + '/' + file.filename; file.tmp = tmpDir + "/" + file.filename; //rename file to prevent space crash mv(file.filePath, tmpDir + '/' + file.filename, function (err) { if (err) throw err; console.log("Consuming "+file.format.base); if (file.format.ext.indexOf("pdf") > -1) { getDataFromPDF(file, callback); return } if (file.format.ext.match(/jpg|jpeg|png|bmp|gif/gi)) { getDataFromIMG(file, callback); return } if (file.format.ext.match(/txt|md/gi)) { getDataFromTXT(file, callback); return } console.log(file.format.base+ " cannot be consumed. Check file type"); }); });
var shpwrite = require('shp-write'), clone = require('clone'), geojson2dsv = require('geojson2dsv'), topojson = require('topojson'), saveAs = require('filesaver.js'), tokml = require('tokml'), githubBrowser = require('@mapbox/github-file-browser'), gistBrowser = require('@mapbox/gist-map-browser'), geojsonNormalize = require('geojson-normalize'), wellknown = require('wellknown'); var share = require('./share'), modal = require('./modal.js'), flash = require('./flash'), zoomextent = require('../lib/zoomextent'), readFile = require('../lib/readfile'), meta = require('../lib/meta.js'), saver = require('../ui/saver.js'), config = require('../config.js')(location.hostname); /** * This module provides the file picking & status bar above the map interface. * It dispatches to source implementations that interface with specific * sources, like GitHub. */ module.exports = function fileBar(context) { var shpSupport = typeof ArrayBuffer !== 'undefined'; var mapboxAPI = /a\.tiles\.mapbox.com/.test(L.mapbox.config.HTTP_URL); var githubAPI = !!config.GithubAPI; var githubBase = githubAPI ? config.GithubAPI + '/api/v3': 'https://api.github.com'; var exportFormats = [{ title: 'GeoJSON', action: downloadGeoJSON }, { title: 'TopoJSON', action: downloadTopo }, { title: 'CSV', action: downloadDSV }, { title: 'KML', action: downloadKML }, { title: 'WKT', action: downloadWKT }]; if (shpSupport) { exportFormats.push({ title: 'Shapefile', action: downloadShp }); } function bar(selection) { var actions = [{ title: 'Save', action: (mapboxAPI || githubAPI) ? saveAction : function() {}, children: exportFormats }, { title: 'New', action: function() { window.open(window.location.origin + window.location.pathname + '#new'); } }, { title: 'Meta', action: function() {}, children: [ { title: 'Add map layer', alt: 'Add a custom tile layer', action: function() { var layerURL = prompt('Layer URL \n(http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg)'); if (layerURL === null) return; var layerName = prompt('Layer name'); if (layerName === null) return; meta.adduserlayer(context, layerURL, layerName); } }, { title: 'Zoom to features', alt: 'Zoom to the extent of all features', action: function() { meta.zoomextent(context); } }, { title: 'Clear', alt: 'Delete all features from the map', action: function() { if (confirm('Are you sure you want to delete all features from this map?')) { meta.clear(context); } } }, { title: 'Random: Points', alt: 'Add random points to your map', action: function() { var response = prompt('Number of points (default: 100)'); if (response === null) return; var count = parseInt(response, 10); if (isNaN(count)) count = 100; meta.random(context, count, 'point'); } }, { title: 'Add bboxes', alt: 'Add bounding box members to all applicable GeoJSON objects', action: function() { meta.bboxify(context); } }, { title: 'Flatten Multi Features', alt: 'Flatten MultiPolygons, MultiLines, and GeometryCollections into simple geometries', action: function() { meta.flatten(context); } } ] }]; if (mapboxAPI || githubAPI) { actions.unshift({ title: 'Open', children: [ { title: 'File', alt: 'GeoJSON, TopoJSON, GTFS, KML, CSV, GPX and OSM XML supported', action: blindImport }, { title: 'GitHub', alt: 'GeoJSON files in GitHub Repositories', authenticated: true, action: clickGitHubOpen }, { title: 'Gist', alt: 'GeoJSON files in GitHub Gists', authenticated: true, action: clickGist } ] }); actions[1].children.unshift({ title: 'GitHub', alt: 'GeoJSON files in GitHub Repositories', authenticated: true, action: clickGitHubSave }, { title: 'Gist', alt: 'GeoJSON files in GitHub Gists', authenticated: true, action: clickGistSave }, { title: 'GeofenceAPI', alt: 'GeoJSON files as geofences', authenticated: true, action: clickGeofenceApiSave }); if (mapboxAPI) actions.splice(3, 0, { title: 'Share', action: function() { context.container.call(share(context)); } }); } else { actions.unshift({ title: 'Open', alt: 'CSV, GTFS, KML, GPX, and other filetypes', action: blindImport }); } var items = selection.append('div') .attr('class', 'inline') .selectAll('div.item') .data(actions) .enter() .append('div') .attr('class', 'item'); var buttons = items.append('a') .attr('class', 'parent') .on('click', function(d) { if (d.action) d.action.apply(this, d); }) .text(function(d) { return ' ' + d.title; }); items.each(function(d) { if (!d.children) return; d3.select(this) .append('div') .attr('class', 'children') .call(submenu(d.children)); }); var name = selection.append('div') .attr('class', 'name'); if (mapboxAPI || githubAPI) { var filetype = name.append('a') .attr('target', '_blank') .attr('class', 'icon-file-alt'); var filename = name.append('span') .attr('class', 'filename') .text('unsaved'); } function clickGistSave() { if (d3.event) d3.event.preventDefault(); context.data.set({ type: 'gist' }); saver(context); } function clickGeofenceApiSave() { if (d3.event) d3.event.preventDefault(); context.data.set({ type: 'geofenceapi' }); saver(context); } function saveAction() { if (d3.event) d3.event.preventDefault(); saver(context); } function sourceIcon(type) { if (type == 'github') return 'icon-github'; else if (type == 'gist') return 'icon-github-alt'; else return 'icon-file-alt'; } function saveNoun(_) { buttons.filter(function(b) { return b.title === 'Save'; }).select('span.title').text(_); } function submenu(children) { return function(selection) { selection .selectAll('a') .data(children) .enter() .append('a') .attr('title', function(d) { if (d.title == 'File' || d.title == 'GitHub' || d.title == 'Gist' || d.title == 'Add map layer' || d.title == 'Zoom to features' || d.title == 'Clear' || d.title == 'Random: Points' || d.title == 'Add bboxes' || d.title == 'Flatten Multi Features') return d.alt; }) .text(function(d) { return d.title; }) .on('click', function(d) { d.action.apply(this, d); }); }; } context.dispatch.on('change.filebar', onchange); function clickGitHubOpen() { if (!context.user.token()) return flash(context.container, 'You must authenticate to use this API.'); var m = modal(d3.select('div.geojsonio')); m.select('.m') .attr('class', 'modal-splash modal col6'); m.select('.content') .append('div') .attr('class', 'header pad2 fillD') .append('h1') .text('GitHub'); githubBrowser(context.user.token(), false, githubBase) .open() .onclick(function(d) { if (!d || !d.length) return; var last = d[d.length - 1]; if (!last.path) { throw new Error('last is invalid: ' + JSON.stringify(last)); } if (!last.path.match(/\.(geo)?json/i)) { return alert('only GeoJSON files are supported from GitHub'); } if (last.type === 'blob') { githubBrowser.request('/repos/' + d[1].full_name + '/git/blobs/' + last.sha, function(err, blob) { d.content = JSON.parse(decodeURIComponent(Array.prototype.map.call(atob(blob[0].content), function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join(''))); context.data.parse(d); zoomextent(context); m.close(); }); } }) .appendTo( m.select('.content') .append('div') .attr('class', 'repos pad2') .node()); } function clickGitHubSave() { if (!context.user.token()) return flash(context.container, 'You must authenticate to use this API.'); var m = modal(d3.select('div.geojsonio')); m.select('.m') .attr('class', 'modal-splash modal col6'); m.select('.content') .append('div') .attr('class', 'header pad2 fillD') .append('h1') .text('GitHub'); githubBrowser(context.user.token(), true, githubBase) .open() .onclick(function(d) { if (!d || !d.length) return; var last = d[d.length - 1]; var pathparts; var partial; // New file if (last.type === 'new') { var filename = prompt('New file name'); if (!filename) { m.close(); return; } pathparts = d.slice(3); pathparts.pop(); pathparts.push({ path: filename }); partial = pathparts.map(function(p) { return p.path; }).join('/'); context.data.set({ source: { url: githubBase + '/repos/' + d[0].login + '/' + d[1].name + '/contents/' + partial + '?ref=' + d[2].name }, type: 'github', meta: { branch: d[2].name, login: d[0].login, repo: d[1].name } }); context.data.set({ newpath: partial + filename }); m.close(); saver(context); } // Update a file else if (last.type === 'blob') { // Build the path pathparts = d.slice(3); partial = pathparts.map(function(p) { return p.path; }).join('/'); context.data.set( { source: { url: githubBase + '/repos/' + d[0].login + '/' + d[1].name + '/contents/' + partial + '?ref=' + d[2].name, sha: last.sha }, type: 'github', meta: { branch: d[2].name, login: d[0].login, repo: d[1].name } }); m.close(); saver(context); } }) .appendTo( m.select('.content') .append('div') .attr('class', 'repos pad2') .node()); } function clickGist() { if (!context.user.token()) return flash(context.container, 'You must authenticate to use this API.'); var m = modal(d3.select('div.geojsonio')); m.select('.m') .attr('class', 'modal-splash modal col6'); gistBrowser(context.user.token(), githubBase) .open() .onclick(function(d) { context.data.parse(d); zoomextent(context); m.close(); }) .appendTo( m.select('.content') .append('div') .attr('class', 'repos pad2') .node()); } function onchange(d) { var data = d.obj, type = data.type, path = data.path; if (mapboxAPI || githubAPI) filename .text(path ? path : 'unsaved') .classed('deemphasize', context.data.dirty); if (mapboxAPI || githubAPI) filetype .attr('href', data.url) .attr('class', sourceIcon(type)); saveNoun(type == 'github' ? 'Commit' : 'Save'); } function blindImport() { var put = d3.select('body') .append('input') .attr('type', 'file') .style('visibility', 'hidden') .style('position', 'absolute') .style('height', '0') .on('change', function() { var files = this.files; if (!(files && files[0])) return; readFile.readAsText(files[0], function(err, text) { readFile.readFile(files[0], text, onImport); if (files[0].path) { context.data.set({ path: files[0].path }); } }); put.remove(); }); put.node().click(); } function onImport(err, gj, warning) { gj = geojsonNormalize(gj); if (gj) { context.data.mergeFeatures(gj.features); if (warning) { flash(context.container, warning.message); } else { flash(context.container, 'Imported ' + gj.features.length + ' features.') .classed('success', 'true'); } zoomextent(context); } } d3.select(document).call( d3.keybinding('file_bar') .on('⌘+o', function() { blindImport(); d3.event.preventDefault(); }) .on('⌘+s', saveAction)); } function downloadTopo() { var content = JSON.stringify(topojson.topology({ collection: clone(context.data.get('map')) }, {'property-transform': allProperties})); saveAs(new Blob([content], { type: 'text/plain;charset=utf-8' }), 'map.topojson'); } function downloadGeoJSON() { if (d3.event) d3.event.preventDefault(); var content = JSON.stringify(context.data.get('map')); var meta = context.data.get('meta'); saveAs(new Blob([content], { type: 'text/plain;charset=utf-8' }), (meta && meta.name) || 'map.geojson'); } function downloadDSV() { if (d3.event) d3.event.preventDefault(); var content = geojson2dsv(context.data.get('map')); saveAs(new Blob([content], { type: 'text/plain;charset=utf-8' }), 'points.csv'); } function downloadKML() { if (d3.event) d3.event.preventDefault(); var content = tokml(context.data.get('map')); var meta = context.data.get('meta'); saveAs(new Blob([content], { type: 'text/plain;charset=utf-8' }), 'map.kml'); } function downloadShp() { if (d3.event) d3.event.preventDefault(); d3.select('.map').classed('loading', true); try { shpwrite.download(context.data.get('map')); } finally { d3.select('.map').classed('loading', false); } } function downloadWKT() { if (d3.event) d3.event.preventDefault(); var contentArray = []; var features = context.data.get('map').features; if (features.length === 0) return; var content = features.map(wellknown.stringify).join('\n'); var meta = context.data.get('meta'); saveAs(new Blob([content], { type: 'text/plain;charset=utf-8' }), 'map.wkt'); } function allProperties(properties, key, value) { properties[key] = value; return true; } return bar; };
import serviceGeoservice from './geoservice'; import serviceMapillary from './mapillary'; import serviceNominatim from './nominatim'; import serviceOpenstreetcam from './openstreetcam'; import serviceOsm from './osm'; import serviceTaginfo from './taginfo'; import serviceWikidata from './wikidata'; import serviceWikipedia from './wikipedia'; export var services = { geocoder: serviceNominatim, geoservice: serviceGeoservice, mapillary: serviceMapillary, openstreetcam: serviceOpenstreetcam, osm: serviceOsm, taginfo: serviceTaginfo, wikidata: serviceWikidata, wikipedia: serviceWikipedia }; export { serviceGeoservice, serviceMapillary, serviceNominatim, serviceOpenstreetcam, serviceOsm, serviceTaginfo, serviceWikidata, serviceWikipedia };
'use strict'; const compressAndCompare = require('../src/aws/compressAndCompare'), fs = require('fs'), crypto = require('crypto'), yaml = require('js-yaml'), path = require('path'), tmp = require('tmp'), unzip = require('adm-zip'), fsReadFile = require('../src/utils/fs').fsReadFile; describe('compressAndCompare', function() { let session, cwdOrig, tmpDir, funcFiles; const createFolder = function(path) { fs.mkdirSync(path); funcFiles.push(path); }, writeFile = function(path, content) { fs.writeFileSync(path, content, { encoding: 'utf8' }); funcFiles.push(path); }; beforeEach(function() { cwdOrig = process.cwd(); tmpDir = tmp.dirSync(); funcFiles = []; process.chdir(tmpDir.name); const routesJSON = { paths: { '/': { get: { 'x-rise': { function: 'listTasks' } }, put: { 'x-rise': { function: 'createTasks' } } } } }; const profilesJSON = { default: { provider: 'aws', region: 'us-west-2', bucket: 'test-bucket' } }; const funcsJSON = { default: { memory: 128, timeout: 3, exclude: 'CHANGELOG.*' }, listTasks: { memory: 128, timeout: 1, exclude: 'README.*' }, createTasks: null }; // config yaml files writeFile(path.join(tmpDir.name, 'routes.yaml'), yaml.safeDump(routesJSON)); writeFile(path.join(tmpDir.name, 'rise.yaml'), yaml.safeDump({ profiles: profilesJSON, functions: funcsJSON })); // function files const appDir = path.join(tmpDir.name, 'functions'); const indexFnPath = path.join(tmpDir.name, 'functions', 'listTasks'); const createFnPath = path.join(tmpDir.name, 'functions', 'createTasks'); createFolder(appDir); createFolder(indexFnPath); createFolder(createFnPath); writeFile(path.join(indexFnPath, 'index.js'), "console.log('index!');"); writeFile(path.join(createFnPath, 'create.js'), "console.log('create!');"); // lib functions const libDir = path.join(tmpDir.name, 'lib'); createFolder(libDir); writeFile(path.join(libDir, 'lib.js'), "console.log('lib!');"); // README.md writeFile(path.join(tmpDir.name, 'README.md'), "# README"); // CHANGELOG.md writeFile(path.join(tmpDir.name, 'CHANGELOG.md'), "# No updates"); session = { functions: funcsJSON, compressedFunctions: [], hasher: crypto.createHash('sha256'), riseJSON: { active_version: 'v1', version_hashes: {} } }; }); afterEach(function() { process.chdir(cwdOrig); for (let i = 0; i < session.compressedFunctions.length; ++i) { const p = session.compressedFunctions[i].filePath; fs.unlinkSync(p); } if (tmpDir) { for (let i = funcFiles.length - 1; i >= 0; --i) { const p = funcFiles[i]; if (fs.statSync(p).isDirectory()) { fs.rmdirSync(p); } else { fs.unlinkSync(p); } } tmpDir.removeCallback(); } }); it('updates version and hash for next version', function() { return compressAndCompare(session) .then(function(session) { expect(session).to.exist; expect(session.state).to.equal('COMPRESSED'); expect(session.version).to.equal('v2'); expect(session.riseJSON.active_version).to.equal('v1'); expect(session.riseJSON.version_hashes['v2']).to.not.be.null; }); }); it('compresses files for each function', function() { const expectedFiles = { listTasks: [ "functions/listTasks/index.js", "routes.yaml", "rise.yaml", "index.js", "lib/", "lib/lib.js" ], createTasks: [ "functions/createTasks/create.js", "routes.yaml", "rise.yaml", "index.js", "lib/", "lib/lib.js", "README.md" ] }; return compressAndCompare(session) .then(function(session) { expect(session.compressedFunctions).to.have.length(2); for (let i = 0; i < session.compressedFunctions.length; ++i) { const p = session.compressedFunctions[i]; expect(p.filePath).to.exist; expect(fs.statSync(p.filePath)).to.not.be.null; expect(p.uploadPath).to.exist; const entries = new unzip(p.filePath).getEntries(); expect(entries).to.not.be.empty; const paths = []; for (let j = 0; j < entries.length; j++) { const content = entries[j].getData().toString(); if (!entries[j].isDirectory && entries[j].entryName !== 'index.js') { expect(fsReadFile(entries[j].entryName)).to.equal(content); } else if (entries[j].entryName === 'index.js') { const expected = ` const rise = require('rise-framework'); const appModule = require('./app'), functionModule = require('./functions/${p.functionName}'); exports.handle = rise.wrap.amazon(functionModule, appModule, {});`; expect(content).to.equal(expected); } paths.push(entries[j].entryName); } expect(paths).same.members(expectedFiles[p.functionName]); } }); }); context("when the checksum is same as current version", function() { beforeEach(function() { const checksum = require('../src/utils/checksum'); return checksum('CHANGELOG.md') .then(function(checksumResult) { session.riseJSON.version_hashes['v1'] = checksumResult; }); }); it("does not continue to compress files", function() { return compressAndCompare(session) .then(function() { fail('this promise should not have been resolved'); }) .catch(function(err) { expect(err).to.contain('No change is present'); expect(session.compressedFunctions).to.have.length(0); }); }); }); context("when the checksum is not same as current version", function() { beforeEach(function() { session.riseJSON.version_hashes['v1'] = '123456'; }); it("does not continue to compress files", function() { return compressAndCompare(session) .then(function(session) { expect(session.compressedFunctions).to.have.length(2); }); }); }); context("when there are no functions", function() { beforeEach(function() { session.functions = {}; }); it("returns an error", function() { return compressAndCompare(session) .then(function() { fail('this promise should not have been resolved'); }) .catch(function(err) { expect(err).to.contain('No functions found in rise.yaml'); }); }); }); context("when folders don't exist for functions", function() { beforeEach(function() { session.functions.thisIsNotFunc = null; }); it("returns an error", function() { return compressAndCompare(session) .then(function() { fail('this promise should not have been resolved'); }) .catch(function(err) { expect(err).to.contain('"functions/thisIsNotFunc" is invalid or does not exist'); }); }); }); });
const Router = require('express').Router() const ApiController = require('../controllers/api') Router.get('/short', ApiController.index) Router.post('/short', ApiController.post) Router.get('/short/:short', ApiController.get) Router.put('/short/:short', ApiController.put) Router.delete('/short/:short', ApiController.delete) module.exports = Router
import sign from "./sign.js"; /** * [Bisection method](https://en.wikipedia.org/wiki/Bisection_method) is a root-finding * method that repeatedly bisects an interval to find the root. * * This function returns a numerical approximation to the exact value. * * @param {Function} func input function * @param {number} start - start of interval * @param {number} end - end of interval * @param {number} maxIterations - the maximum number of iterations * @param {number} errorTolerance - the error tolerance * @returns {number} estimated root value * @throws {TypeError} Argument func must be a function * * @example * bisect(Math.cos,0,4,100,0.003); // => 1.572265625 */ function bisect(func, start, end, maxIterations, errorTolerance) { if (typeof func !== "function") throw new TypeError("func must be a function"); for (let i = 0; i < maxIterations; i++) { const output = (start + end) / 2; if ( func(output) === 0 || Math.abs((end - start) / 2) < errorTolerance ) { return output; } if (sign(func(output)) === sign(func(start))) { start = output; } else { end = output; } } throw new Error("maximum number of iterations exceeded"); } export default bisect;
var Actions = require('ui/comment-actions') , React = require('react') , test = require('tap').test ; test('new Actions()', function (tap) { tap.ok(React.isValidClass(Actions), 'is React Class'); tap.end(); }); test('Actions html', function (tap) { var actions = new Actions(); var actionsHTML = React.renderComponentToString(actions); tap.ok(actionsHTML.indexOf('reply') > -1, 'renders reply'); tap.end(); });
'use strict'; test(() => { assert_equals(document.currentFragment, document.querySelector('#test-8-1-nested')); }, 'Fixture 8-1 see document.currentFragment - fragment8-1');
import React from 'react' import {navigate} from '../actions' export default (props) => { const click = (event) => { if (event.metaKey) return event.preventDefault() navigate(props.href) } return <a {...props} onClick={click}>{props.children}</a> }
import assert from "assert"; import {utcHour} from "../src/index.js"; import {utc} from "./date.js"; it("utcHour.floor(date) returns hours", () => { assert.deepStrictEqual(utcHour.floor(utc(2010, 11, 31, 23, 59)), utc(2010, 11, 31, 23)); assert.deepStrictEqual(utcHour.floor(utc(2011, 0, 1, 0, 0)), utc(2011, 0, 1, 0)); assert.deepStrictEqual(utcHour.floor(utc(2011, 0, 1, 0, 1)), utc(2011, 0, 1, 0)); }); it("utcHour.floor(date) observes start of daylight savings time", () => { assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 8, 59)), utc(2011, 2, 13, 8)); assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 9, 0)), utc(2011, 2, 13, 9)); assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 9, 1)), utc(2011, 2, 13, 9)); assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 9, 59)), utc(2011, 2, 13, 9)); assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 10, 0)), utc(2011, 2, 13, 10)); assert.deepStrictEqual(utcHour.floor(utc(2011, 2, 13, 10, 1)), utc(2011, 2, 13, 10)); }); it("utcHour.floor(date) observes end of daylight savings time", () => { assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 7, 59)), utc(2011, 10, 6, 7)); assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 8, 0)), utc(2011, 10, 6, 8)); assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 8, 1)), utc(2011, 10, 6, 8)); assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 8, 59)), utc(2011, 10, 6, 8)); assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 9, 0)), utc(2011, 10, 6, 9)); assert.deepStrictEqual(utcHour.floor(utc(2011, 10, 6, 9, 1)), utc(2011, 10, 6, 9)); }); it("utcHour.ceil(date) returns hours", () => { assert.deepStrictEqual(utcHour.ceil(utc(2010, 11, 31, 23, 59)), utc(2011, 0, 1, 0)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 0, 1, 0, 0)), utc(2011, 0, 1, 0)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 0, 1, 0, 1)), utc(2011, 0, 1, 1)); }); it("utcHour.ceil(date) observes start of daylight savings time", () => { assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 8, 59)), utc(2011, 2, 13, 9)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 9, 0)), utc(2011, 2, 13, 9)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 9, 1)), utc(2011, 2, 13, 10)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 9, 59)), utc(2011, 2, 13, 10)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 10, 0)), utc(2011, 2, 13, 10)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 2, 13, 10, 1)), utc(2011, 2, 13, 11)); }); it("utcHour.ceil(date) observes end of daylight savings time", () => { assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 7, 59)), utc(2011, 10, 6, 8)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 8, 0)), utc(2011, 10, 6, 8)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 8, 1)), utc(2011, 10, 6, 9)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 8, 59)), utc(2011, 10, 6, 9)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 9, 0)), utc(2011, 10, 6, 9)); assert.deepStrictEqual(utcHour.ceil(utc(2011, 10, 6, 9, 1)), utc(2011, 10, 6, 10)); }); it("utcHour.offset(date) does not modify the passed-in date", () => { const d = utc(2010, 11, 31, 23, 59, 59, 999); utcHour.offset(d, +1); assert.deepStrictEqual(d, utc(2010, 11, 31, 23, 59, 59, 999)); }); it("utcHour.offset(date) does not round the passed-in-date", () => { assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23, 59, 59, 999), +1), utc(2011, 0, 1, 0, 59, 59, 999)); assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23, 59, 59, 456), -2), utc(2010, 11, 31, 21, 59, 59, 456)); }); it("utcHour.offset(date) allows negative offsets", () => { assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 12), -1), utc(2010, 11, 31, 11)); assert.deepStrictEqual(utcHour.offset(utc(2011, 0, 1, 1), -2), utc(2010, 11, 31, 23)); assert.deepStrictEqual(utcHour.offset(utc(2011, 0, 1, 0), -1), utc(2010, 11, 31, 23)); }); it("utcHour.offset(date) allows positive offsets", () => { assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 11), +1), utc(2010, 11, 31, 12)); assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23), +2), utc(2011, 0, 1, 1)); assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23), +1), utc(2011, 0, 1, 0)); }); it("utcHour.offset(date) allows zero offset", () => { assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23, 59, 59, 999), 0), utc(2010, 11, 31, 23, 59, 59, 999)); assert.deepStrictEqual(utcHour.offset(utc(2010, 11, 31, 23, 59, 58, 0), 0), utc(2010, 11, 31, 23, 59, 58, 0)); }); it("utcHour.range(start, stop) returns hours", () => { assert.deepStrictEqual(utcHour.range(utc(2010, 11, 31, 12, 30), utc(2010, 11, 31, 15, 30)), [ utc(2010, 11, 31, 13), utc(2010, 11, 31, 14), utc(2010, 11, 31, 15) ]); }); it("utcHour.range(start, stop) has an inclusive lower bound", () => { assert.deepStrictEqual(utcHour.range(utc(2010, 11, 31, 23), utc(2011, 0, 1, 2))[0], utc(2010, 11, 31, 23)); }); it("utcHour.range(start, stop) has an exclusive upper bound", () => { assert.deepStrictEqual(utcHour.range(utc(2010, 11, 31, 23), utc(2011, 0, 1, 2))[2], utc(2011, 0, 1, 1)); }); it("utcHour.range(start, stop) can skip hours", () => { assert.deepStrictEqual(utcHour.range(utc(2011, 1, 1, 1), utc(2011, 1, 1, 13), 3), [ utc(2011, 1, 1, 1), utc(2011, 1, 1, 4), utc(2011, 1, 1, 7), utc(2011, 1, 1, 10) ]); }); it("utcHour.range(start, stop) does not observe the start of daylight savings time", () => { assert.deepStrictEqual(utcHour.range(utc(2011, 2, 13, 1), utc(2011, 2, 13, 5)), [ utc(2011, 2, 13, 1), utc(2011, 2, 13, 2), utc(2011, 2, 13, 3), utc(2011, 2, 13, 4) ]); }); it("utcHour.range(start, stop) does not observe the end of daylight savings time", () => { assert.deepStrictEqual(utcHour.range(utc(2011, 10, 6, 0), utc(2011, 10, 6, 2)), [ utc(2011, 10, 6, 0), utc(2011, 10, 6, 1) ]); }); it("utcHour.every(step) returns every stepth hour, starting with the first hour of the day", () => { assert.deepStrictEqual(utcHour.every(4).range(utc(2008, 11, 30, 12, 47), utc(2008, 11, 31, 13, 57)), [utc(2008, 11, 30, 16), utc(2008, 11, 30, 20), utc(2008, 11, 31, 0), utc(2008, 11, 31, 4), utc(2008, 11, 31, 8), utc(2008, 11, 31, 12)]); assert.deepStrictEqual(utcHour.every(12).range(utc(2008, 11, 30, 12, 47), utc(2008, 11, 31, 13, 57)), [utc(2008, 11, 31, 0), utc(2008, 11, 31, 12)]); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinKey = void 0; /** * A class representation of the BSON MinKey type. * @public */ var MinKey = /** @class */ (function () { function MinKey() { if (!(this instanceof MinKey)) return new MinKey(); } /** @internal */ MinKey.prototype.toExtendedJSON = function () { return { $minKey: 1 }; }; /** @internal */ MinKey.fromExtendedJSON = function () { return new MinKey(); }; /** @internal */ MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; MinKey.prototype.inspect = function () { return 'new MinKey()'; }; return MinKey; }()); exports.MinKey = MinKey; Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); //# sourceMappingURL=min_key.js.map
const mongoose = require('mongoose'); //Use our own promise library. Mongoose's is deprecated. mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI); module.exports = { mongoose };
angular.module('beer-tab.services', []) .factory('AuthService', function ($http, $location, $window) { var authService = {}; authService.login = function (credentials) { return $http .post('/api/users/login', credentials) .then(function (resp) { return resp.data.token; }); }; authService.signup = function(credentials) { console.log('cred:', credentials); return $http .post('/api/users/signup', credentials) .then(function (resp) { return resp.data.token; }); }; authService.isAuth = function () { return !!$window.localStorage.getItem('com.beer-tab'); }; authService.signout = function () { $window.localStorage.removeItem('com.beer-tab'); $location.path('/login'); }; return authService; }) .factory('getTable', function ($window, $http) { var getTable = function (username) { return $http({ method: 'POST', url: '/api/users/table', data: {username: username} }) .then(function (resp) { //console.log(resp.data); return resp.data; }); }; return { getTable: getTable, }; }) .factory('beerPmt', function ($window, $http) { var newIOU = function (user) { return $http({ method: 'POST', url: '/api/users/tabs', data: {token: $window.localStorage.getItem('com.beer-tab'), user: user} }) .then(function (resp) { //console.log(resp.data); return resp.data; }); }; var findUsers = function(){ return $http({ method: 'GET', url: '/tabs' }) .then(function(resp){ console.log(resp.data); return resp.data; }) } var findUsers = function(){ return $http({ method: 'GET', url: '/api/tabs' }) .then(function(resp){ console.log(resp.data); return resp.data; }) } return { findUsers: findUsers, newIOU: newIOU }; }) .factory('util', function(){ var helper = {}; helper.toArr = function (obj){ var temp = []; for(var key in obj){ temp.push({ username: key, tab: obj[key] }); } return temp; }; return helper; });
import round from 'round-to' export default function (accountData) { return { guildCount: guildCount(accountData), wvwRank: wvwRank(accountData), playtime: playtime(accountData), playtimePerDay: playtimePerDay(accountData), _luckFromAccount: luckFromAccount(accountData) } } // Count of joined guilds function guildCount (accountData) { if (!accountData.account) { return null } if (!accountData.account.guilds) { return null } return accountData.account.guilds.length } // The wvw rank function wvwRank (accountData) { if (!accountData.account) { return null } if (typeof accountData.account.wvw_rank === 'undefined') { return null } return accountData.account.wvw_rank } // The amount of seconds played on this account function playtime (accountData) { if (!accountData.account) { return null } if (!accountData.account.age) { return null } return accountData.account.age } // The amount of seconds played on this account per day function playtimePerDay (accountData) { if (!accountData.account) { return null } if (!accountData.account.age || !accountData.account.created) { return null } const playtime = accountData.account.age const now = (new Date()).getTime() const creation = (new Date(accountData.account.created)).getTime() const daysSinceCreation = Math.ceil((now - creation) / (1000 * 60 * 60 * 24)) return daysSinceCreation > 1 ? round(playtime / daysSinceCreation, 2) : null } // The amount of luck unlocked on the account function luckFromAccount (accountData) { if (!accountData.luck) { return null } return accountData.luck }
var TestObj = { alertMe: function (text) { alert(text); }, logMe: function (text) { console.info("Foo " + text); } };
/** * @file mip-zmall-yunfei 组件 * @author liu.xianggui@zol.com.cn */ define(function (require) { var customElement = require('customElement').create(); var util = require('util'); // toast function toast(str, pause) { var element = this.element; var toastHtml = '<div class="mip-dialog-toast">' + str + '</div>'; if (element.dataset.toastMask && element.dataset.toastMask === 'true') { toastHtml += '<div class="mip-dialog-mask"></div>'; } element.innerHTML = toastHtml; setDailogElementCover(element); var toastElm = element.querySelector('.mip-dialog-toast'); setTimeout(function () { toastElm.classList.add('show'); }, 0); pause = pause || 1500; setTimeout(function () { toastElm.classList.remove('show'); removeDailogElementCover(element); }, pause); } function confirm(str, options) { var element = this.element; var yesBtnText = (options && options.ok && options.ok !== '') ? options.ok : '确定'; var noBtnText = (options && options.cansel && options.cansel !== '') ? options.cansel : '取消'; var uiConfirmHtml = [ '<div id="_ui_confirm" class="mip-dialog-confirm">', '<div class="mip-confirm-body"><p>' + str + '</p></div>', '<div id="_ui_confirm_button" class="mip-confirm-button">', '<button class="mip-confirm-cansel">' + noBtnText + '</button>', '<button class="mip-confirm-yes">' + yesBtnText + '</button>', '</div></div>' ].join(''); if (element.dataset.confirmMask && element.dataset.confirmMask === 'true') { uiConfirmHtml += '<div class="mip-dialog-mask"></div>'; } element.innerHTML = uiConfirmHtml; setDailogElementCover(element); var uiConfirmElement = element.querySelector('#_ui_confirm'); setTimeout(function () { uiConfirmElement.classList.add('show'); }, 0); var button = element.querySelector('#_ui_confirm_button'); button.addEventListener('click', function (e) { var targetButton = e.target; removeDailogElementCover(element); if (targetButton.classList.contains('mip-confirm-yes')) { (options && typeof options.okCallback === 'function') && options.okCallback(); } else { (options && typeof options.canselCallback === 'function') && options.canselCallback(); } }); } function selector(options) { var element = this.element; var title = options.title; var buttonText = options.buttonText; var optionsList = ''; var type = options.type ? options.type : 'radio'; options.list.forEach(function (item) { var value = item.value; var name = item.name; var checked = item.checked ? ' checked' : ''; var customInput = ''; if (item.custom) { customInput = [ '<div class="ui-mip-selecor-area">', '<textarea id="_ui_options_custom_content"></textarea>', '</div>' ].join(''); } optionsList += [ '<div class="ui-mip-selecor-item">', '<input name="selector" type="' + type + '" id="_ui_options_' + value + '" ', 'data-name="' + name + '" value="' + value + '"' + checked + ' />', '<label for="_ui_options_' + value + '">' + name + '</label>', customInput + '</div>' ].join(''); }); var uiSelectorHtml = [ '<div id="_ui_selector" class="mip-dialog-selector">', '<div class="ui-mip-selecor-title">' + title + '</div>', '<div id="_ui_selector_close" class="ui-mip-selecor-close"></div>', '<div class="ui-mip-selecor-options">' + optionsList + '</div>', '<div id="_ui_selector_button" class="ui-mip-selecor-button">' + buttonText + '</div>', '</div>' ].join(''); uiSelectorHtml += '<div class="mip-dialog-mask"></div>'; element.innerHTML = uiSelectorHtml; setDailogElementCover(element); var uiSelectorElement = element.querySelector('#_ui_selector'); setTimeout(function () { uiSelectorElement.classList.add('show'); }, 0); var closeElm = element.querySelector('#_ui_selector_close'); closeElm.addEventListener('click', function () { removeDailogElementCover(element); }); var button = element.querySelector('#_ui_selector_button'); button.addEventListener('click', function () { var checkedInput = uiSelectorElement.querySelectorAll('input:checked'); var selectedResult = getSelectedFormData(checkedInput); removeDailogElementCover(element); if (options.callback && typeof options.callback === 'function') { options.callback(selectedResult); } }); } function getSelectedFormData(selectedElement) { var formData = []; [].forEach.call(selectedElement, function (item) { var ret = {}; ret.value = item.value; ret.name = item.dataset.name; var textarea = item.parentNode.querySelector('textarea'); if (textarea) { ret.content = textarea.value; } formData.push(ret); }); return formData; } function setDailogElementCover(element) { var elementParentNode = element.parentNode; if (elementParentNode.tagName === 'MIP-FIXED') { util.css(elementParentNode, { height: '100%' }); } util.css(element, { height: '100%' }); if (element.dataset.mask && element.dataset.mask === 'true') { var maskElement = element.querySelector('.mip-dialog-cover'); maskElement.addEventListener('touchmove', function (e) { e.preventDefault(); }); } } function removeDailogElementCover(element) { var elementParentNode = element.parentNode; setTimeout(function () { if (elementParentNode.tagName === 'MIP-FIXED') { util.css(elementParentNode, { height: 'auto' }); } util.css(element, { height: 'auto' }); element.innerHTML = ''; }, 201); } customElement.prototype.build = function () { var self = this; // 自定义事件给DOM来触发 self.addEventAction('toast', function (e, str) { var msg = str && str !== '' ? str : (e.msg && e.msg !== '' ? e.msg : ''); toast.call(self, msg); }); self.addEventAction('confirm', function (e, str) { if (str) { confirm.call(self, str); } else { confirm.call(self, e.msg, e.options); } }); self.addEventAction('selector', function (e, options) { if (options) { selector.call(self, options); } else { selector.call(self, e.options); } }); }; // 自定义方法给别的组件来调用 customElement.prototype.toast = function (str) { toast.call(this, str); }; customElement.prototype.confirm = function (str, options) { confirm.call(this, str, options); }; customElement.prototype.selector = function (options) { selector.call(this, options); }; return customElement; });
import React, {Component} from 'react' import '../../assets/styles/Footer.styl' class Footer extends Component { render () { return ( <div id='Footer'> <div className='Footer_park1'> <h2><img src={require('../../assets/images/Footer_img/footer_img1.png')} />电影订座 就上卖座</h2> <div className='contact'> <img src={require('../../assets/images/Footer_img/footer_img2.png')} /> <span>电话: </span> <span className='tel'>400-1808-400</span> <span> 周日-周四:9:00-22:00 周五-周六:9:00-22:30 </span> </div> <div className='externalLinks'> <div><a href='http://crm2.qq.com/page/portalpage/wpa.php?uin=4001808400&aty=0&a=0&curl=&ty=1'><img src={require('../../assets/images/Footer_img/footer_img3.png')} /></a> </div> <div className='hover1'> <a><img src={require('../../assets/images/Footer_img/footer_img4.png')} /></a> <div className='Footer_hover1'> <img className='houver1_img' src={require('../../assets/images/Footer_img/footer_img4_hover.png')} /> <img className='houver1_triangular' src={require('../../assets/images/Footer_img/Triangular.png')} /> <p>扫码下载卖座电影APP</p> </div> </div> <div className='hover2'> <a> <img src={require('../../assets/images/Footer_img/footer_img5.png')} /> </a> <div className='Footer_hover2'> <img className='houver1_img' src={require('../../assets/images/Footer_img/footer_img5_hover.png')} /> <img className='houver1_triangular' src={require('../../assets/images/Footer_img/Triangular.png')} /> <p>扫码下载卖座电影APP</p> </div> </div> <div> <a href='http://weibo.com/maizuo'> <img src={require('../../assets/images/Footer_img/footer_img6.png')} /> </a> </div> </div> </div> <div className='Footer_park2'> <ul> <li><a href='about.html'>关于卖座</a> |</li> <li><a href='contact.html'>联系我们</a> |</li> <li><a href='business.html'>商务合作</a> |</li> <li><a href='teamwork.html'>合作伙伴</a> |</li> <li><a href='sincere.html'>诚聘英才</a> |</li> <li><a href='employ.html'>使用帮助</a> |</li> <li><a href='refund.html'>退票服务</a> |</li> <li><a href='clause.html'>服务条款</a> |</li> <li><a href='community.html'>社区管理</a></li> </ul> <p>Copyright © 2017 maizuo. All Rights Reserved 卖座网 版权所有 增值业务经营许可证:粤B2-200502318</p> <img src={require('../../assets/images/Footer_img/footer_img7.png')} /> </div> </div> ) } } export default Footer
import {takeLast} from './takeLast' test('with arrays', () => { expect(takeLast(1, ['foo', 'bar', 'baz'])).toEqual(['baz']) expect(takeLast(2)(['foo', 'bar', 'baz'])).toEqual(['bar', 'baz']) expect(takeLast(3, ['foo', 'bar', 'baz'])).toEqual(['foo', 'bar', 'baz']) expect(takeLast(4, ['foo', 'bar', 'baz'])).toEqual(['foo', 'bar', 'baz']) expect(takeLast(10, ['foo', 'bar', 'baz'])).toEqual(['foo', 'bar', 'baz']) }) test('with strings', () => { expect(takeLast(3, 'rambda')).toEqual('bda') expect(takeLast(7, 'rambda')).toEqual('rambda') }) test('with negative index', () => { expect(takeLast(-1, [1, 2, 3])).toEqual([1, 2, 3]) expect(takeLast(-Infinity, [1, 2, 3])).toEqual([1, 2, 3]) })
/* * cli-test.js: Tests for the cli levels available in winston. * * (C) 2010 Charlie Robbins * MIT LICENSE * */ var path = require('path'), vows = require('vows'), assert = require('assert'), winston = require('../lib/winston'), helpers = require('./helpers'); vows.describe('winston/logger/cli').addBatch({ "When an instance of winston.transports.Console()": { "has colorize true": { topic: function () { var transport = new winston.transports.Console({ colorize: true }); transport.log('prompt', 'This had better work.', { test: true }, this.callback); }, "should function without error": function (err, ok) { assert.isNull(err); assert.isTrue(ok); } } }, "When an instance of winston.Logger": { topic: function () { return new winston.Logger({ transports: [ new winston.transports.Console() ] }) }, "the cli() method": { "should set the appropriate values on the logger": function (logger) { logger.cli(); assert.isTrue(logger.padLevels); assert.isTrue(logger.transports.console.colorize); assert.isFalse(logger.transports.console.timestamp); Object.keys(winston.config.cli.levels).forEach(function (level) { assert.isNumber(logger.levels[level]); }); Object.keys(winston.config.cli.colors).forEach(function (color) { assert.isString(winston.config.allColors[color]); }); } } } }).export(module);
module.exports = { deploy: { username: 'user.name@yourcompany.com', password: 'YourPasswordAndPossiblySecurityToken', login_url: 'https://login.salesforce.com', api_version: 36.0, timeout: 120000, poll_interval: 5000, }, visualforce: { template: 'index.page.html', page: 'AngularApp', controller: 'AngularAppController' }, resources: { app_resource_name: 'AngularApp', node_module_resource_name: 'NodeModules', }, options: { } }
// @flow import { PLACEHOLDERS_ALIAS } from "../definitions"; /** * Test if a `placeholderType` is a `targetType` or if `targetType` is an alias of `placeholderType`. */ export default function isPlaceholderType( placeholderType: ?string, targetType: string, ): boolean { if (placeholderType === targetType) return true; const aliases: ?Array<string> = PLACEHOLDERS_ALIAS[placeholderType]; if (aliases) { for (const alias of aliases) { if (targetType === alias) return true; } } return false; }
var request = require('request'); var crypto = require('crypto'); var xml2js = new require('xml2js').Parser(); var config = require('../config'); var Log = require('log'), log = new Log(config.log.level); FRITZ_NUMBER_OF_ENTRIES = '<?xml version="1.0" encoding="utf-8"?>' + '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ' + 'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' + '<s:Body><u:GetHostNumberOfEntries xmlns:u="urn:dslforum-org:service:Hosts:1">' + '</u:GetHostNumberOfEntries></s:Body></s:Envelope>'; FRITZ_GENERIC_HOST = '<?xml version="1.0" encoding="utf-8"?>' + '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ' + 'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' + '<s:Body><u:GetGenericHostEntry xmlns:u="urn:dslforum-org:service:Hosts:1">' + '<s:NewIndex>@@INDEX@@</s:NewIndex></u:GetGenericHostEntry></s:Body></s:Envelope>'; var FritzBoxService = function (devices) { var self = this; self.devices = devices; this.sessionInfo = function (callback) { request.get('http://' + config.fritzbox.host + '/login_sid.lua', function (error, response, body) { if (!error) { xml2js.parseString(body, function (error, data) { if (!error) { callback({ sid: data.SessionInfo.SID[0], challenge: data.SessionInfo.Challenge[0], blocktime: data.SessionInfo.BlockTime[0] }); } else { log.error(error); setTimeout(self.update, config.fritzbox.interval * 1000); } }); } else { log.error(error); setTimeout(self.update, config.fritzbox.interval * 1000); } }); }; this.login = function (callback) { self.sessionInfo(function (sessionInfo) { var loginToken = sessionInfo.challenge + '-' + config.fritzbox.password; var md5 = crypto.createHash('md5'); md5.update(loginToken, 'ucs2'); var digest = md5.digest('hex'); loginToken = sessionInfo.challenge + '-' + digest; request.get('http://' + config.fritzbox.host + '/login_sid.lua?username=&response=' + loginToken, function (error, response, body) { if (!error) { xml2js.parseString(body, function (err, data) { if (data.SessionInfo.SID[0] === '0000000000000000') { log.error('Fritzbox: Login error!'); } else { callback(data.SessionInfo.SID[0]) } }); } else { log.error(error); setTimeout(self.update, config.fritzbox.interval * 1000); } }); }); }; this.update = function () { log.debug('Starting fritzbox update...'); self.login(function (sid) { request.get('http://' + config.fritzbox.host + '/net/network_user_devices.lua?sid=' + sid, function (error, response, body) { if (!error) { var regex = /<td class="iconrow led_green"[^>]*><\/td><td class="cut_overflow" title="[^"]*">([^<]*)<\/td><td>([^<]*)<\/td><td>([a-zA-Z0-9:]{17})<\/td><td class="connection_type"><div><(img|a)/g; var match; while (match = regex.exec(body)) { self.devices.update({ name: match[1], ip: match[2], mac: match[3] }); } regex = /<td class="iconrow led_green"[^>]*><\/td><td class="cut_overflow" title="[^"]*"><a target=[^>]*>([^<]*)<\/a><\/td><td>([^<]*)<\/td><td>([a-zA-Z0-9:]{17})<\/td><td class="connection_type"><div><<(img|a)/g; while (match = regex.exec(body)) { self.devices.update({ name: match[1], ip: match[2], mac: match[3] }); } } else { log.error(error); } log.debug('...fritzbox update finished!'); setTimeout(self.update, config.fritzbox.interval * 1000); }); }); }; self.update(); }; module.exports = FritzBoxService;
IntlMessageFormat.__addLocaleData({locale:"smn",pluralRuleFunction:function(e,o){return o?"other":1==e?"one":2==e?"two":"other"}});
'use strict' import { removeUser, removePet, modifyUser, modifyPet, getUsers, getPets, getUser, getPet, addUser, addPet, } from './' addUser({name: 'Tyler', age: 27, gender: 'Male', friends: ['Joseph']}) .then(result => { console.log(result) return getUser({name: 'Tyler'}) .then(result => console.log(result.data)) }) .catch(err => console.error(err.stack || err))
//TASK1 & TASK4 var str = 'something'; var int = 123; var float = 12.3; var obj = { name: 'Pesho', age: 25 }; var arr = [1, 2, 3]; var bool = true; var func = function() { alert('This is a function!'); }; var nullValue = null; var undef; //TASK2 var quotedStrFirstWay = '\'How you doin\'?\', Joey said.'; var quotedStrSecondWay = "'How you doin'?', Joey said."; console.log('TASK 2'); console.log(quotedStrFirstWay); console.log(quotedStrSecondWay); //TASK3 var arrVariables = [str, int, float, obj, arr, bool, func, nullValue, undef]; console.log('TASK 3 and TASK 4'); for (var variable in arrVariables) { console.log('Type of ' + arrVariables[variable] + ' is ' + typeof(arrVariables[variable])); } //VISUALIZATION document.getElementById("wrapper").style.width = "400px"; document.getElementById("wrapper").style.background = "#fff3b3"; var listOfElements = document.querySelectorAll('[id^="task"]'); for (var count = 0; count < listOfElements.length; count += 1) { listOfElements[count].style.color = "red"; listOfElements[count].style.borderBottom = "1px solid black"; listOfElements[count].style.borderTop = "1px solid black"; } var container = document.getElementById('edit'), firstChild = container.childNodes[1]; if (container && firstChild) { var newDiv = document.createElement("div"); newDiv.setAttribute("contentEditable", "true"); newDiv.innerHTML = quotedStrFirstWay; firstChild.parentNode.insertBefore(newDiv, firstChild.nextSibling); } document.getElementById("str").innerHTML = typeof(str); document.getElementById("int").innerHTML = typeof(int); document.getElementById("float").innerHTML = typeof(float); document.getElementById("obj").innerHTML = typeof(obj); document.getElementById("arr").innerHTML = typeof(arr); document.getElementById("bool").innerHTML = typeof(bool); document.getElementById("func").innerHTML = typeof(func); document.getElementById("null").innerHTML = typeof(nullValue); document.getElementById("undef").innerHTML = typeof(undef); var spans = document.getElementsByTagName("span"); for (var i = 0; i < spans.length; i += 1) { spans[i].style.background = "skyblue"; }
module.exports = '<div class="greeting-target"></div>\n';
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var fs = require('fs'); var resolve = require('resolve'); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; function startsWith(string, prefix) { return string.lastIndexOf(prefix, 0) === 0; } var DEFAULT_OPTIONS = { path: '.babelrc', findRollupPresets: false, addModuleOptions: true, addExternalHelpersPlugin: true, resolve: resolve.sync }; function babelrc() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (typeof options === 'string') { options = { path: options }; } var resolvedOptions = _extends({}, DEFAULT_OPTIONS, options); if (!resolvedOptions.config && typeof resolvedOptions.path === 'string') { resolvedOptions.config = JSON.parse(fs.readFileSync(resolvedOptions.path, { encoding: 'utf8' })); } return configWithoutModules(resolvedOptions.config, resolvedOptions); } function configWithoutModules(config, options) { var result = {}; for (var _key in config) { if (Object.prototype.hasOwnProperty.call(config, _key)) { if (_key === 'presets' && config.presets) { // Replace the es2015 preset with the es2015-rollup preset. result.presets = config.presets.map(function (preset) { return mapPreset(preset, options); }); } else if (_key === 'plugins' && config.plugins) { // Remove any explicit module plugins, e.g. es2015-modules-commonjs. result.plugins = config.plugins.filter(function (plugin) { return !startsWith(plugin, 'es2015-modules-'); }); } else { result[_key] = config[_key]; } } } if (options.addExternalHelpersPlugin) { if (!result.plugins) { result.plugins = ['external-helpers']; } else { result.plugins = [].concat(toConsumableArray(result.plugins), ['external-helpers']); } } // Make sure babel does not look for the babelrc file. result.babelrc = false; return result; } function mapPreset(preset, options) { var info = getPresetInfo(preset); if (!info) { return preset; } if (options.findRollupPresets && hasRollupVersionOfPreset(info.name, options.resolve || resolve.sync)) { return [info.name + '-rollup', info.options]; } else if (options.addModuleOptions) { return [info.name, _extends({}, info.options, { modules: false })]; } else { return preset; } } function getPresetInfo(preset) { if (typeof preset === 'string') { return { name: preset, options: {} }; } else if (Array.isArray(preset)) { var _name = preset[0]; var _options = preset[1] || {}; if (typeof _name === 'string' && (typeof _options === 'undefined' ? 'undefined' : _typeof(_options)) === 'object') { return { name: _name, options: _options }; } } return null; } function hasRollupVersionOfPreset(preset, resolve) { try { // this will throw if it can't resolve it resolve('babel-preset-' + preset + '-rollup'); return true; } catch (err) { return false; } } exports['default'] = babelrc; exports.configWithoutModules = configWithoutModules;
/* Use strict */ // CONSTRUCTORS // Here is where you'll create your constructors for you player and monster. // e.g. function Monster(){}; // e.g. function Player(){}; function Player(options){ this.name = options.name; this.health = options.health; this.attack = function(monsta){ return monsta.health = monsta.health - (Math.floor(Math.random() * 10)); }; this.select = function(dino,image, backgroundimage){ $('#character').css('background-image','url('+ image +')'); $('header').css('display', 'none'); $('#after-char-select').css('display','initial'); $('#char-name').html(dino.name); $('#background').css('background-image','url('+ backgroundimage +')'); }; this.startBattle = function(dino,monster){ dino.attack(monster); $('#monster-health').html(monster.health); setInterval(function(){ monster.fight(dino); },100); $('#dino-health').html(dino.health); if(monster.health < 0){ $('#battle').css('display','none'); $('#victoryPage').css('display','initial'); $('#score').html(dino.health); } if(dino.health < 0){ $('#battle').css('display','none'); $('#lostPage').css('display','intial'); } }; }; function Monster(options){ this.health = options.health; this.name = options.name; this.fight = function(player){ return player.health = player.health - (Math.floor(Math.random() * 8)); }; }; // GLOBAL VARIABLES // You'll also want to create variables for the specific players and monsters. // e.g. var purplePeopleEater = new Monster(); // e.g. var tinaFey = new Player(); // e.g. var attackMode = function(target){ Some code that produces an attack - pew, pew! }; // var dino1 = new Player({ health: 100, name: "cartoon Rex" }); var dino2 = new Player({ health: 100, name: "T-rex" }); var dino3 = new Player({ health: 100, name: "Brontasaurus" }); var monster1 = new Monster({ name: "Ugly", health: 100 }); var monster2 = new Monster({ name: "Even Uglier", health: 200 }); // ACTIONS // This is where jQuery will come into play and where you'll set a lot of your // interactions for players and monsters. (e.g. player selection, attack interactions) // e.g. $('.purple-people-eater').click(function () { Some code that attacks the monster! }; //jQuery Variables $header = $('header'); $ACS = $('#after-char-select'); image1 = "images/images.duckduckgo.gif" image2 = "images/images.duckduckgo.jpg" image3 = "images/images.duckduckgo-1.jpg" backgroundImage1 = "images/dino-background-1.jpg" backgroundImage2 = "images/dino-background-2.jpg" backgroundImage3 = "images/dino-background-3.jpg" // After selecting character message $('#after-char-select').click(function(){ $('#after-char-select').css('display','none'); $('#battle').css('display','initial'); }); // Adding health remaining to battle scene $('#dino-health').html(dino1.health); $('#dino-health').html(dino2.health); $('#dino-health').html(dino3.health); //Fighting function for dino1 $('#fightFunction').click(function(){ dino1.attack(monster1); $('#monster-health').html(monster1.health); setInterval(function(){ monster1.fight(dino1); },100); $('#dino-health').html(dino1.health); if(monster1.health < 0){ $('#battle').css('display','none'); $('#victoryPage').css('display','initial'); $('#score').html(dino1.health); } if(dino3.health < 0){ $('#battle').css('display','none'); $('#lostPage').css('display','intial'); } }); // Fighting function for dino2 $('#fightFunction').click(function(){ dino2.attack(monster1); $('#monster-health').html(monster1.health); setInterval(function(){ monster1.fight(dino2); },100); $('#dino-health').html(dino2.health); if(monster1.health < 0){ $('#battle').css('display','none'); $('#victoryPage').css('display','initial'); $('#score').html(dino2.health); } if(dino3.health < 0){ $('#battle').css('display','none'); $('#lostPage').css('display','intial'); } }); //Fighting function for dino3 $('#fightFunction').click(function(){ dino3.attack(monster1); $('#monster-health').html(monster1.health); setInterval(function(){ monster1.fight(dino3); },100); $('#dino-health').html(dino3.health); if(monster1.health < 0){ $('#battle').css('display','none'); $('#victoryPage').css('display','initial'); $('#score').html(dino3.health); } if(dino3.health < 0){ $('#battle').css('display','none'); $('#lostPage').css('display','initial'); } }); $('#newCharSelect').click(function(){ open('http://localhost:9000') }); $('#img1').click(function(){ dino1.select(dino1,image1,backgroundImage1); }); $('#img2').click(function(){ dino2.select(dino2,image2,backgroundImage2); }); $('#img3').click(function(){ dino3.select(dino3,image3,backgroundImage3); });
/* WHILE STATEMENTS */ var cnt = 0; var goal = 10; function setup() { createCanvas(800,600); while (cnt <= goal) { cnt++; console.log(cnt); } } function draw() { }
const fs = require( "fs" ); const glob = require( "tiny-glob/sync" ); // This is a meta test to validate structural expectations of our // tests, such as checking for fixture files that aren't used or // missing from one of the test targets. QUnit.module( "structure", () => { QUnit.module( "test/main/*.js", () => { const files = fs.readdirSync( __dirname + "/../main/" ) .map( file => `main/${file}` ); QUnit.test( "files", assert => { assert.true( files.length > 5, "found files" ); assert.deepEqual( files.filter( file => file.endsWith( ".js" ) ), files, "js files" ); } ); QUnit.test( "test/index.html", assert => { const contents = fs.readFileSync( __dirname + "/../index.html", "utf8" ); files.forEach( file => { assert.true( contents.includes( file ), file ); } ); } ); QUnit.test( "Gruntfile#test-on-node", assert => { const raw = fs.readFileSync( __dirname + "/../../Gruntfile.js", "utf8" ); const contents = raw.match( /test-on-node.*?\{.*?\}/s )[ 0 ]; files.forEach( file => { assert.true( contents.includes( file ), file ); } ); } ); QUnit.test( "test/mozjs", assert => { const contents = fs.readFileSync( __dirname + "/../mozjs.js", "utf8" ); files.forEach( file => { assert.true( contents.includes( file ), file ); } ); } ); QUnit.test( "test/webWorker-worker.js", assert => { const contents = fs.readFileSync( __dirname + "/../webWorker-worker.js", "utf8" ); files.forEach( file => { assert.true( contents.includes( file ), file ); } ); } ); } ); QUnit.module( "test/**.html", () => { // Get a list of the HTML files, including in subdirectories (e.g. "test/reporter-html/"). const files = glob( "**/*.html", { cwd: __dirname + "/../", filesOnly: true } ) // Normalize Windows-style line endings as yielded by glob. // The expected HTML paths use Unix-style line ending, as per HTTP. .map( file => file.replace( /\\/g, "/" ) ) // Ignore file names containing "--", which are subresources (e.g. iframes). // Ignore integration/grunt-contrib-qunit, which is managed separately. .filter( file => !file.includes( "--" ) && !file.includes( "integration/" ) ) .map( file => `test/${file}` ); QUnit.test( "files", assert => { assert.true( files.length > 5, "found files" ); } ); QUnit.test( "Gruntfile", assert => { const raw = fs.readFileSync( __dirname + "/../../Gruntfile.js", "utf8" ); const contents = raw.match( /@HTML_FILES.*?\[.*?\]/s )[ 0 ]; files.forEach( file => { assert.true( contents.includes( file ), file ); } ); } ); } ); } );
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:user/packages', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { var controller = this.subject(); assert.ok(controller); });
/** usage: $.tips({ content: '', class: 'tip-holder', maxNum: 3 }) */ $.tips = function(options) { var defaults = { selector: '#tipHolder', maxNum: 3, autoClose: false, showTime: 5 }; var opts=$.extend({}, defaults, options); var o = $.meta ? $.extend({}, opts, $(this).data()) : opts; if (!$(o.selector).length) { if (o.selector.indexOf('#') != -1) { $('<div id="'+o.selector.slice(1)+'"></div>').appendTo('body'); } else if (o.selector.indexOf('.') != -1) { $('<div class="'+o.selector.slice(1)+'"></div>').appendTo('body'); } else { $('<'+o.selector+'></'+o.selector+'>').appendTo('body'); } } var $tipHolder = $(o.selector); if (o.data && o.data.data.length) { var data = o.data; if ($tipHolder.is(':visible')) { var $divs = createTips(data.data[0]); $tipHolder.prepend($divs.hide()); if ($tipHolder.find('.dialog').length > o.maxNum) { $tipHolder.find('.dialog:nth-child(n+'+(o.maxNum+1)+')').slideUp(function(){$(this).remove();}); } $divs.slideDown(); if (o.autoClose) { setTimeout(function() {$divs.slideUp(function(){$divs.remove();})}, (o.showTime ? (o.showTime * 1000) : 5000)); } } else { var divs = ''; for (var i = 0; i < data.data.length; i ++) { if (i < o.maxNum) { $tipHolder.append(createTips(data.data[i])).slideDown(); } else { break; } } if (o.autoClose) { setTimeout(function() {$divs.slideUp(function(){$divs.remove();})}, (o.showTime ? (o.showTime * 1000) : 5000)); } } } function createTips(item) { var $close = $('<span />', { 'class': 'close' }).text('X'); if ($.isFunction(o.close)) { $close.on('click', function() { var $this = $(this); o.close.call($this); }); } var $dialog = $('<div />', { 'class': 'dialog' }); var temp = ''; for (var i in item) { temp += '<p data-' + i + '="' + item[i] + '">' + item[i] + '</p>'; } $dialog.append($close).append(temp); return $dialog; } };
// Public domain // http://unlicense.org/ Script.requireExtension("Console"); var x = {a: 100, b: 101, c: 102, d: 103}; var kx = []; var vx = []; var n = 0; for(var m in x) { kx[n] = m; vx[n] = x[m]; ++n; }; if( (kx[0] == "a" && vx[0] == 100) && (kx[1] == "b" && vx[1] == 101) && (kx[2] == "c" && vx[2] == 102) && (kx[3] == "d" && vx[3] == 103) ) { Console.writeLn("-> test 0019 ok"); } else { Console.writeLn("-> test 0019 fail"); };
/** * Created by leoriccao on 2015/9/1. */ LBF.define('qidian.comp.emoji',function (require, exports, module) { var jEmoji = require('qidian.comp.emoji.emoji'); function emoji(){ this.parse=function(text){ return jEmoji.unifiedToHTML(text); } } module.exports=new emoji(); });
Object.defineProperty(exports, "__esModule", { value: true }); var reg_1 = require("./reg"); var _ = new reg_1.default(); var storage; if ((typeof Storage) !== 'undefined') { storage = window.localStorage; } var Store = (function () { function Store() { } Store.prototype.getCookie = function (name) { var cname = name + "="; var cookieVal = ''; if (document.cookie) { var ca = document.cookie.split(';'); for (var _i = 0, ca_1 = ca; _i < ca_1.length; _i++) { var key = ca_1[_i]; var c = _.trim(key); if (c.indexOf(cname) === 0) { cookieVal = c.substring(cname.length, c.length); } } } return cookieVal; }; Store.prototype.setCookie = function (name, value, time) { var d = new Date(); var expires; d.setTime(d.getTime() + (time * 1000)); expires = "expires=" + d.toUTCString(); document.cookie = name + "=" + value + ";" + expires; }; Store.prototype.clearCookie = function (name) { this.setCookie(name, '', -1); }; Store.prototype.getStoreItem = function (name) { if (!_.isNull(storage)) { return storage.getItem(name); } }; Store.prototype.setStoreItem = function (name, val) { if (!_.isNull(storage)) { return storage.setItem(name, val); } }; Store.prototype.setStoreObj = function (obj) { if (_.isObject(obj)) { for (var v in obj) { this.setStoreItem(v, obj[v]); } } }; Store.prototype.getStoreObj = function () { var len = storage.length; var obj = {}; for (var i = 0; i < len; i++) { var key = storage.key(i); var val = this.getStoreItem(key); obj[key] = val; } return obj; }; Store.prototype.removeStoreItem = function (name) { storage.removeItem(name); return this.getStoreItem(name) === null ? true : false; }; Store.prototype.clearStore = function () { storage.clear(); }; return Store; }()); exports.default = Store;
import _ from 'lodash'; import ui from 'src/util/ui'; import chemspider from './chemspider'; import chemexper from './chemexper'; import epfl from './epfl'; const defaultOptions = { chemexper: true, chemspider: true, epfl: false }; module.exports = { chemspider: chemspider, chemexper: chemexper, epfl: epfl, choose(term, options) { options = Object.assign({}, defaultOptions, options); const sources = []; if (options.epfl) { sources.push({ promise: epfl.search(term) }); } if (options.chemspider) { sources.push({ promise: chemspider.search(term) }); } if (options.chemexper) sources.push({ promise: chemexper.search(term) }); if (options.roc) { const roc = options.roc; const rocPromise = roc .view('entryByKindAndId', { startkey: ['sample', [term]], endkey: ['sample', [`${term}\ufff0`, {}]] }) .then((data) => { data.forEach((d) => { let names = []; // we start with the title if (d.$content.general && d.$content.general.title) { names.push(d.$content.general.title); } // then the names if (d.$content.general && d.$content.general.name > 0) { names.push(...d.$content.general.name.map((d) => d.value)); } names.push(d.$id.join(' ')); if (d.$content.general && d.$content.general.description) { names.push(d.$content.general.description); } d.id = d._id; d.source = 'sample'; d.names = _.uniq(names); }); return data; }); sources.push({ promise: rocPromise }); } return ui .choose(sources, { autoSelect: options.autoSelect, asynchronous: true, noConfirmation: true, returnRow: true, dialog: { width: 1000, height: 800 }, columns: [ { id: 'names', name: 'names', jpath: [], rendererOptions: { forceType: 'object', twig: ` <div style="height: 100%; line-height: initial;"> <table style="width: 100%;"> {% for n in names %} <tr><td>{{ n }}</td></tr> {% endfor %} </table> </div> ` } }, { id: 'cas', name: 'cas', jpath: ['$content', 'identifier'], rendererOptions: { forceType: 'object', twig: listTemplate('cas', '.value') }, maxWidth: 100 }, { id: 'molfile', name: 'molfile', jpath: ['$content', 'general', 'molfile'], rendererOptions: { forceType: 'mol2d' }, maxWidth: 250 }, { id: 'source', name: 'source', field: 'source', maxWidth: 70 } ], idField: 'id', slick: { rowHeight: 150 } }) .catch(function (e) { console.error(e); // eslint-disable-line no-console ui.showNotification('search failed', 'error'); }); } }; function listTemplate(val, prop) { return ` <div style="height: 100%; line-height: initial; vertical-align: middle"> <table style="width: 100%; text-align: center;"> {% for n in ${val} %} <tr><td>{{ n${prop} }}</td></tr> {% endfor %} </table> </div> `; }
var App, container; var compile = Ember.Handlebars.compile; module("Application Lifecycle - Component Registration", { setup: function() { Ember.TEMPLATES["components/expand-it"] = compile("<p>hello {{yield}}</p>"); Ember.TEMPLATES.application = compile("Hello world {{#expand-it}}world{{/expand-it}}"); }, teardown: function() { Ember.run(function() { App.destroy(); App = null; Ember.TEMPLATES = {}; }); } }); function boot(callback) { Ember.run(function() { App = Ember.Application.create({ name: 'App', rootElement: '#qunit-fixture' }); App.deferReadiness(); App.Router = Ember.Router.extend({ location: 'none' }); container = App.__container__; if (callback) { callback(); } }); var router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); Ember.run(function() { router.handleURL('/'); }); } if (!Ember.FEATURES.isEnabled('container-renderables')) { test("A helper is registered for templates under the components/ directory", function() { boot(); ok(Ember.Handlebars.helpers['expand-it'], "The helper is registered"); }); } test("The helper becomes the body of the component", function() { boot(); equal(Ember.$('div.ember-view > div.ember-view', '#qunit-fixture').text(), "hello world", "The component is composed correctly"); }); test("If a component is registered, it is used", function() { boot(function() { container.register('component:expand-it', Ember.Component.extend({ classNames: 'testing123' })); }); equal(Ember.$('div.testing123', '#qunit-fixture').text(), "hello world", "The component is composed correctly"); }); if (Ember.FEATURES.isEnabled('container-renderables')) { test("Late-registered components can be rendered with custom `template` property", function() { Ember.TEMPLATES.application = compile("<div id='wrapper'>there goes {{my-hero}}</div>"); boot(function() { container.register('component:my-hero', Ember.Component.extend({ classNames: 'testing123', template: function() { return "watch him as he GOES"; } })); }); equal(Ember.$('#wrapper').text(), "there goes watch him as he GOES", "The component is composed correctly"); ok(!Ember.Handlebars.helpers['my-hero'], "Component wasn't saved to global Handlebars.helpers hash"); }); test("Late-registered components can be rendered with template registered on the container", function() { Ember.TEMPLATES.application = compile("<div id='wrapper'>hello world {{sally-rutherford}} {{#sally-rutherford}}!!!{{/sally-rutherford}}</div>"); boot(function() { container.register('template:components/sally-rutherford', compile("funkytowny{{yield}}")); container.register('component:sally-rutherford', Ember.Component); }); equal(Ember.$('#wrapper').text(), "hello world funkytowny funkytowny!!!", "The component is composed correctly"); ok(!Ember.Handlebars.helpers['sally-rutherford'], "Component wasn't saved to global Handlebars.helpers hash"); }); test("Late-registered components can be rendered with ONLY the template registered on the container", function() { Ember.TEMPLATES.application = compile("<div id='wrapper'>hello world {{borf-snorlax}} {{#borf-snorlax}}!!!{{/borf-snorlax}}</div>"); boot(function() { container.register('template:components/borf-snorlax', compile("goodfreakingTIMES{{yield}}")); }); equal(Ember.$('#wrapper').text(), "hello world goodfreakingTIMES goodfreakingTIMES!!!", "The component is composed correctly"); ok(!Ember.Handlebars.helpers['borf-snorlax'], "Component wasn't saved to global Handlebars.helpers hash"); }); test("Component-like invocations are treated as bound paths if neither template nor component are registered on the container", function() { Ember.TEMPLATES.application = compile("<div id='wrapper'>{{user-name}} hello {{api-key}} world</div>"); boot(function() { container.register('controller:application', Ember.Controller.extend({ 'user-name': 'machty' })); }); equal(Ember.$('#wrapper').text(), "machty hello world", "The component is composed correctly"); }); test("Component lookups should take place on components' subcontainers", function() { expect(1); Ember.TEMPLATES.application = compile("<div id='wrapper'>{{#sally-rutherford}}{{mach-ty}}{{/sally-rutherford}}</div>"); boot(function() { container.register('component:sally-rutherford', Ember.Component.extend({ init: function() { this._super(); this.container = new Ember.Container(this.container); this.container.register('component:mach-ty', Ember.Component.extend({ didInsertElement: function() { ok(true, "mach-ty was rendered"); } })); } })); }); }); }
define(["ko"], function(ko){ function KarmaViewModel(){ var self = this; self._ = { shown: false, disposed: false }; self.shown = function(){ if(!self._.shown){ self._.shown = true; } }; self.hidden = function(){ if(self._.shown){ self._.shown = false; } }; self.dispose = function(){ if(!self._.disposed){ self._.disposed = true; } }; } return { get: function(){ return new KarmaViewModel(); }, type: function(){ return KarmaViewModel; } } });
;(function(){ var setVisibleStep,getCompIdByName,tmplid,approveid = location.hash.substr(1); var stepData = {},sendids = [],step; jsonReq.post('/open/approve','show',{id:approveid},function(data){ var strUsers = []; stepData = data.result; step = stepData.status; $('#approve_name p span').html(stepData.name); $(stepData.users).each(function(){ strUsers.push('<em>'+this.name+'</em>') sendids.push(this.id); }) $('#next-user span').html(strUsers.join(',')) if(stepData.end){ $('#btn-send,#btn-back,#btn-complete,#senderEl').remove(); } if(stepData.flow.terminal == 1){ $('#btn-complete').show(); } if(!stepData.hasNext){ $('#btn-send').remove(); } jsonReq.post('/open/approve','get',[stepData.tmpl_id],function(d){ initTemplate(d.result); }) }) function formatComps(){ var coms = stepData.components,arr = [],o; for(var i=0;i<coms.length;i++){ o = {}; o[coms[i].id] = coms[i].value; arr.push(o) } return arr; } function transObject(arr){ var b = {},c = []; $(arr).each(function(){ $.extend(b,this); }) for(var o in b){ var s = {}; s[o] = b[o] c.push(s) } return c; } $('#btn-send').click(function(){ var coms = getCompIdByName(step-1); jsonReq.post('/open/approve','next',{ approveid:approveid, components : transObject(formatComps().concat(coms)), sender : sendids.join(',') },function(d){ if(d.result){ location.href = '/approve/deal' } }) return false; }) $('#btn-back').click(function(){ var coms = getCompIdByName(step-1); jsonReq.post('/open/approve','back',{ approveid:approveid, components : formatComps().concat(coms), sender : sendids.join(',') },function(d){ if(d.result){ location.href = '/approve/deal' } }) return false; }) $('#btn-complete').click(function(){ var coms = getCompIdByName(step-1); jsonReq.post('/open/approve','complete',{ approveid:approveid, components : formatComps().concat(coms) },function(d){ if(d.result){ location.href = '/approve/deal' } }) return false; }) function initTemplate(data){ $('#table').html(data.content).find('table').addClass('table table-bordered responsive dataTable'); var date = new Date(), dateStr = date.getFullYear()+"-"+(date.getMonth()+1)+'-'+date.getDate()+' 00:00:00'; var tmpl = '{{each list}}'+ '<div class="control-group">'+ ' <label class="control-label">第{{$index+1}}步</label>'+ ' <div class="controls">'+ ' <p><span class="input-xlarge uneditable-input">{{$value.name}}</span></p>'+ ' <p><span class="input-xlarge uneditable-input">{{$value.desc}}</span></p>'+ ' </div>'+ '</div>'+ '{{/each}}'; var render = template.compile(tmpl); var tpl = render({list:data.flows}); $('#approve-steps-list').html(tpl); function fStepDataComs(arr){ var obj = {},narr = []; for(var i=0;i<arr.length;i++){ obj[arr[i].id] = arr[i].value; } for(var o in obj){ var to = {}; to[o] = obj[o]; narr.push(to) } return narr; } getCompIdByName = function(step){ var arr = []; $(data.components).each(function(){ if(this.flowsets[step].editable){ var o = {}; o[this.id] = $('#table [name="'+this.name+'"]').val(); arr.push(o) } }) return arr; } function setComById(){ var stepComs = stepData.components,stepCom; var arr = []; for(var i=0;i<stepComs.length;i++){ stepCom = stepComs[i]; for(var j=0;j<data.components.length;j++){ if(stepCom.id == data.components[j].id){ var el = $('#table').find('[name="'+data.components[j].name+'"]'); if(el.attr('data-form') == "datepicker"){ el.attr('data-date',stepCom.value).val(stepCom.value); }else{ el.val(stepCom.value) } } } } } setComById() setVisibleStep = function(step){ var arr = [],index = Number(step)-1; if(stepData.end) return ''; $(data.components).each(function(){ if(this.flowsets[index] && this.flowsets[index].editable){ arr.push('[name="'+this.name+'"]'); } }) return arr.join(','); } var namefilters = setVisibleStep(stepData.status); $(namefilters).each(function(){ if($(this).attr('data-form') == "datepicker"){ if($(this).val() == "年-月-日 时:分:秒"){ $(this).val(dateStr) } $(this).datepicker(); }else if($(this).attr('data-form') == "select2"){ $(this).removeAttr('disabled').removeAttr('readonly'); $(this).css('width',220).select2(); }else{ $(this).removeAttr('disabled').removeAttr('readonly'); } }) } })()
import expect from 'expect'; import headerReducer from '../reducer'; import { fromJS } from 'immutable'; describe('headerReducer', () => { it('returns the initial state', () => { expect(headerReducer(undefined, {})).toEqual(fromJS({})); }); });
var Generator = require('./../../node-forge/src/Generator'); var _ = require("underscore") var americano = require('./../americano'); /** * A generator */ module.exports = Generator.extend({ // set the generator name key: 'model', project_dir: americano.generatorpath, /** * What to do on setup (will be reversed for teardown) * @param {String} name the name of the object being generated * @param {Object} options a list of options being passed to the generator */ create: function (name, options) { datatypes = {} _.each(options, function (item) { var ary = item.split(':'); datatypes[ary[0]] = ary[1]; }); this.template('model.coffee.tmpl', this.project_dir + '/models/' + name + 'Model.coffee', {name: name + "Model", data: datatypes}); } });
{"response":{"bookname":"1 Thessalonians","number_of_chapters":"5","chapters":[{"chapter":"1","link":"./?book=1-Thessalonians&chapter=1"},{"chapter":"2","link":"./?book=1-Thessalonians&chapter=2"},{"chapter":"3","link":"./?book=1-Thessalonians&chapter=3"},{"chapter":"4","link":"./?book=1-Thessalonians&chapter=4"},{"chapter":"5","link":"./?book=1-Thessalonians&chapter=5"}]}}
"use strict"; var _ = require('underscore'); var util = require('substance-util'); var errors = util.errors; var Schema = require('./schema'); var Property = require('./property'); var Index = require('./graph_index'); var GraphError = errors.define("GraphError"); // Data types registry // ------------------- // Available data types for graph properties. var VALUE_TYPES = [ 'object', 'array', 'string', 'number', 'boolean', 'date' ]; // Check if composite type is in types registry. // The actual type of a composite type is the first entry // I.e., ["array", "string"] is an array in first place. var isValueType = function (type) { if (_.isArray(type)) { type = type[0]; } return VALUE_TYPES.indexOf(type) >= 0; }; // Graph // ===== // A `Graph` can be used for representing arbitrary complex object // graphs. Relations between objects are expressed through links that // point to referred objects. Graphs can be traversed in various ways. // See the testsuite for usage. // // Need to be documented: // @options (mode,seed,chronicle,store,load,graph) var Graph = function(schema, options) { options = options || {}; // Initialization this.schema = new Schema(schema); // Check if provided seed conforms to the given schema // Only when schema has an id and seed is provided if (this.schema.id && options.seed && options.seed.schema) { if (!_.isEqual(options.seed.schema, [this.schema.id, this.schema.version])) { throw new GraphError([ "Graph does not conform to schema. Expected: ", this.schema.id+"@"+this.schema.version, " Actual: ", options.seed.schema[0]+"@"+options.seed.schema[1] ].join('')); } } this.nodes = {}; this.indexes = {}; this.__seed__ = options.seed; this.init(); }; Graph.Prototype = function() { // Graph manipulation API // ====================== // Add a new node // -------------- // Adds a new node to the graph // Only properties that are specified in the schema are taken: // var node = { // id: "apple", // type: "fruit", // name: "My Apple", // color: "red", // val: { size: "big" } // }; // Create new node: // Data.Graph.create(node); // Note: graph create operation should reject creation of duplicate nodes. _.extend(this, util.Events); this.create = function(node) { this.nodes[node.id] = node; this._updateIndexes({ type: 'create', path: [node.id], val: node }); }; // Remove a node // ------------- // Removes a node with given id and key (optional): // Data.Graph.delete(this.graph.get('apple')); this.delete = function(id) { var oldVal = this.nodes[id]; delete this.nodes[id]; this._updateIndexes({ type: 'delete', path: [id], val: oldVal }); }; // Set the property // ---------------- // // Sets the property to a given value: // Data.Graph.set(["fruit_2", "val", "size"], "too small"); // Let's see what happened with node: // var blueberry = this.graph.get("fruit_2"); // console.log(blueberry.val.size); // = > 'too small' this.set = function(path, newValue) { var prop = this.resolve(path); if (!prop) { throw new GraphError("Could not resolve property with path "+JSON.stringify(path)); } var oldVal = prop.get(); prop.set(newValue); this._updateIndexes({ type: 'set', path: path, val: newValue, original: oldVal }); }; // Get the node [property] // ----------------------- // // Gets specified graph node using id: // var apple = this.graph.get("apple"); // console.log(apple); // => // { // id: "apple", // type: "fruit", // name: "My Apple", // color: "red", // val: { size: "big" } // } // or get node's property: // var apple = this.graph.get(["apple","color"]); // console.log(apple); // => 'red' this.get = function(path) { if (!_.isArray(path) && !_.isString(path)) { throw new GraphError("Invalid argument path. Must be String or Array"); } if (arguments.length > 1) path = _.toArray(arguments); if (_.isString(path)) return this.nodes[path]; var prop = this.resolve(path); return prop.get(); }; // Query graph data // ---------------- // // Perform smart querying on graph // graph.create({ // id: "apple-tree", // type: "tree", // name: "Apple tree" // }); // var apple = this.graph.get("apple"); // apple.set({["apple","tree"], "apple-tree"}); // let's perform query: // var result = graph.query(["apple", "tree"]); // console.log(result); // => [{id: "apple-tree", type: "tree", name: "Apple tree"}] this.query = function(path) { var prop = this.resolve(path); var type = prop.type; var baseType = prop.baseType; var val = prop.get(); // resolve referenced nodes in array types if (baseType === "array") { return this._queryArray.call(this, val, type); } else if (!isValueType(baseType)) { return this.get(val); } else { return val; } }; // Serialize current state // ----------------------- // // Convert current graph state to JSON object this.toJSON = function() { return { id: this.id, schema: [this.schema.id, this.schema.version], nodes: util.deepclone(this.nodes) }; }; // Check node existing // ------------------- // // Checks if a node with given id exists // this.graph.contains("apple"); // => true // this.graph.contains("orange"); // => false this.contains = function(id) { return (!!this.nodes[id]); }; // Resolve a property // ------------------ // Resolves a property with a given path this.resolve = function(path) { return new Property(this, path); }; // Reset to initial state // ---------------------- // Resets the graph to its initial state. // Note: This clears all nodes and calls `init()` which may seed the graph. this.reset = function() { this.init(); this.trigger("graph:reset"); }; // Graph initialization. this.init = function() { this.__is_initializing__ = true; if (this.__seed__) { this.nodes = util.clone(this.__seed__.nodes); } else { this.nodes = {}; } _.each(this.indexes, function(index) { index.reset(); }); delete this.__is_initializing__; }; this.addIndex = function(name, options) { if (this.indexes[name]) { throw new GraphError("Index with name " + name + "already exists."); } var index = new Index(this, options); this.indexes[name] = index; return index; }; this.removeIndex = function(name) { delete this.indexes[name]; }; this._updateIndexes = function(op) { _.each(this.indexes, function(index) { if (!op) { index.rebuild(); } else { index.onGraphChange(op); } }, this); }; this._queryArray = function(arr, type) { if (!_.isArray(type)) { throw new GraphError("Illegal argument: array types must be specified as ['array'(, 'array')*, <type>]"); } var result, idx; if (type[1] === "array") { result = []; for (idx = 0; idx < arr.length; idx++) { result.push(this._queryArray(arr[idx], type.slice(1))); } } else if (!isValueType(type[1])) { result = []; for (idx = 0; idx < arr.length; idx++) { result.push(this.get(arr[idx])); } } else { result = arr; } return result; }; }; // Index Modes // ---------- Graph.STRICT_INDEXING = 1 << 1; Graph.DEFAULT_MODE = Graph.STRICT_INDEXING; Graph.prototype = new Graph.Prototype(); Graph.Schema = Schema; Graph.Property = Property; Graph.Index = Index; // Exports // ======== module.exports = Graph;
var baseCastPath = require('./_baseCastPath'), has = require('./has'), isKey = require('./_isKey'), last = require('./last'), parent = require('./_parent'); /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = isKey(path, object) ? [path + ''] : baseCastPath(path); object = parent(object, path); var key = last(path); return (object != null && has(object, key)) ? delete object[key] : true; } module.exports = baseUnset;
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2015-03-09 using // generator-karma 0.9.0 module.exports = function (config) { "use strict"; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: "../", // testing framework to use (jasmine/mocha/qunit/...) frameworks: ["jasmine"], preprocessors: { 'app/partials/*.html': ["ng-html2js"] }, ngHtml2JsPreprocessor: { stripPrefix: "app/" }, // list of files / patterns to load in the browser files: [ "bower_components/jquery/dist/jquery.js", "bower_components/angular/angular.js", "bower_components/angular-mocks/angular-mocks.js", "bower_components/angular-animate/angular-animate.js", "bower_components/angular-cookies/angular-cookies.js", "bower_components/angular-resource/angular-resource.js", "bower_components/angular-route/angular-route.js", "bower_components/angular-sanitize/angular-sanitize.js", "bower_components/angular-touch/angular-touch.js", "bower_components/angular-marked/angular-marked.js", "bower_components/angular-utils-disqus/dirDisqus.js", "app/scripts/**/*.js", "app/partials/*.html", "test/mock/**/*.js", "test/spec/**/*.js" ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ "PhantomJS" ], // Which plugins to enable plugins: [ "karma-chrome-launcher", "karma-phantomjs-launcher", "karma-jasmine", 'karma-ng-html2js-preprocessor' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt"s server to run the tests // proxies: { // "/": "http://localhost:9000/" // }, // URL root prevent conflicts with the site root // urlRoot: "_karma_" }); };
/** * Use jsdom and jquery */ var scrapinode = require('./../'); scrapinode.use(/http:\/\/society6.com/,'title',function(window){ var $ = window.$; var title = $('h1[itemprop="name"]').text(); return title; }); var options = { url : 'http://society6.com/product/Sounds-Good-Dude_T-shirt', engine : 'jsdom' }; scrapinode.createScraper(options,function(err,scraper){ if(err) return console.error(err); var title = scraper.get('title'); console.log(title); // "Sound Good dude" });
/* * grunt-sourcemap-localize * https://github.com/abovethewater/grunt-sourcemap-localize * * Copyright (c) 2013 Joe Mathews * Licensed under the MIT license. * http://abovethewater.mit-license.org/ */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', ], options: { jshintrc: '.jshintrc', }, }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); // By default, lint and run all tests. grunt.registerTask('default', ['jshint']); };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92c0-1.61-1.31-2.92-2.92-2.92zM18 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM6 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm12 7.02c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /> , 'ShareOutlined');
let request = require('supertest'); let expect = require('chai').expect; let config = require('../../lib/config'); let _ = require('lodash'); let getSession = require('../helpers/get-session'); let HowhapList = require('howhap-list'); describe('POST /auth/register', function() { describe('responseFormat json', function() { it('should throw an error if the user is already registered', function(done) { request(app) .post('/auth/register') .send('firstName=Aaron') .send('lastName=Larner') .send('email=test@test.com') .send('password=password') .expect('Content-Type', /json/) .expect(function(res) { expect( res.body, 'EMAIL_EXISTS error should be returned' ).to.deep.equal({ default: _.assign({params:{}}, config.errors.auth.EMAIL_EXISTS) }); }) .expect(409, done); }); it('should throw an error if no email is supplied', function(done) { request(app) .post('/auth/register') .send('password=password') .expect('Content-Type', /json/) .expect(function(res) { expect( res.body, 'MISSING_EMAIL error should be returned' ).to.deep.equal({ email: _.assign({params:{}}, config.errors.auth.MISSING_EMAIL) }); }) .expect(400, done); }); it('should throw an error if no password is supplied', function(done) { request(app) .post('/auth/register') .send('email=foo@test.com') .expect('Content-Type', /json/) .expect(function(res) { expect( res.body, 'MISSING_PASSWORD error should be returned' ).to.deep.equal({ password: _.assign({params:{}}, config.errors.auth.MISSING_PASSWORD) }); }) .expect(400, done); }); it('should throw an error if no email and no password are supplied', function(done) { request(app) .post('/auth/register') .expect('Content-Type', /json/) .expect(function(res) { expect( res.body, 'MISSING_EMAIL and MISSING_PASSWORD error should be returned' ).to.deep.equal({ email: _.assign({params:{}}, config.errors.auth.MISSING_EMAIL), password: _.assign({params:{}}, config.errors.auth.MISSING_PASSWORD) }); }) .expect(400, done); }); it('should throw an error if a bad field is supplied', function(done) { request(app) .post('/auth/register') .expect('Content-Type', /json/) .send('email=foo@test.com') .send('password=password') .send('username=bananas') .expect(function(res) { expect(res.body.default).not.to.be.undefined; expect(res.body.default.message).to.equal('An unknown error occurred: {{message}}'); }) .expect(500, done); }); it('should not log the user in if registration fails', function(done) { let cookie = null; request(app) .post('/auth/register') .expect('Content-Type', /json/) .send('email=foo@test.com') .send('password=password') .send('username=bananas') .expect(function(res) { expect(res.body.default).not.to.be.undefined; expect(res.body.default.message).to.equal('An unknown error occurred: {{message}}'); }) .expect(500) .end(function (err, res) { cookie = res.headers['set-cookie'].pop().split(';')[0]; let req = request(app).get('/dashboard?responseFormat=json'); req.cookies = cookie; req.expect('Content-Type', /json/) .expect(function(res) { expect(res.body).to.deep.equal({ default: { message: 'You must be logged in to perform that action.', params: {}, status: 403 } }); }) .expect(403, done); }); }); it('should create a user if all necessary information is provided', function(done) { request(app) .post('/auth/register') .send('email=foo@test.com') .send('password=password') .expect('Content-Type', /json/) .expect(function(res) { expect(res.body.email).to.equal('foo@test.com'); }) .expect(200, done); }); it('should log the user in after registration', function(done) { let cookie = null; request(app) .post('/auth/register') .send('email=foo@test.com') .send('password=password') .expect('Content-Type', /json/) .expect(function(res) { expect(res.body.email).to.equal('foo@test.com'); }) .expect(200) .end(function (err, res) { getSession(res).then(session => { expect(session.passport).to.be.ok; expect(session.passport.user).to.be.ok; cookie = res.headers['set-cookie'].pop().split(';')[0]; let req = request(app).get('/dashboard'); req.cookies = cookie; req.expect(200, done); }) .catch(err => console.log(err)); }); }); }); describe('responseFormat html', function() { it('should throw an error if the user is already registered', function(done) { request(app) .post('/auth/register?responseFormat=html') .send('firstName=Aaron') .send('lastName=Larner') .send('email=test@test.com') .send('password=password') .expect(302) .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); expect(list.toObject()).to.deep.equal({ default: _.assign({params:{}}, config.errors.auth.EMAIL_EXISTS) }); done(); }) .catch(err => console.log(err)); }); }); it('should throw an error if no email is supplied', function(done) { request(app) .post('/auth/register?responseFormat=html') .send('password=password') .expect(302) .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); expect(list.toObject()).to.deep.equal({ email: _.assign({params:{}}, config.errors.auth.MISSING_EMAIL) }); done(); }) .catch(err => console.log(err)); }); }); it('should throw an error if no password is supplied', function(done) { request(app) .post('/auth/register?responseFormat=html') .send('email=foo@test.com') .expect(302) .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); expect(list.toObject()).to.deep.equal({ password: _.assign({params:{}}, config.errors.auth.MISSING_PASSWORD) }); done(); }) .catch(err => console.log(err)); }); }); it('should throw an error if no email and no password are supplied', function(done) { request(app) .post('/auth/register?responseFormat=html') .expect(302) .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); expect(list.toObject()).to.deep.equal({ email: _.assign({params:{}}, config.errors.auth.MISSING_EMAIL), password: _.assign({params:{}}, config.errors.auth.MISSING_PASSWORD) }); done(); }) .catch(err => console.log(err)); }); }); it('should throw an error if a bad field is supplied', function(done) { request(app) .post('/auth/register?responseFormat=html') .expect(302) .send('email=foo@test.com') .send('password=password') .send('username=bananas') .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); let obj = list.toObject(); expect(obj.default).not.to.be.undefined; expect(obj.default.message).to.equal('An unknown error occurred: {{message}}'); done(); }) .catch(err => console.log(err)); }); }); it('should not log the user in if registration fails', function(done) { let cookie = null; request(app) .post('/auth/register?responseFormat=html') .expect(302) .send('email=foo@test.com') .send('password=password') .send('username=bananas') .end(function(err, res) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); let obj = list.toObject(); expect(obj.default).not.to.be.undefined; expect(obj.default.message).to.equal('An unknown error occurred: {{message}}'); cookie = res.headers['set-cookie'][0].split(';')[0]; let req = request(app).get('/dashboard?responseFormat=html'); req.cookies = cookie; req.expect(302) .end(function(err, r) { getSession(res).then(session => { let list = new HowhapList(session._howhap.errors); expect(list.toObject()).to.deep.equal({ default: { message: 'You must be logged in to perform that action.', params: {}, status: 403 } }); done(); }) .catch(err => console.log(err)); }); }) .catch(err => console.log(err)); }); }); it('should create a user if all necessary information is provided', function(done) { request(app) .post('/auth/register?responseFormat=html') .send('email=foo@test.com') .send('password=password') .expect('Location', '/dashboard') .expect(302, done); }); it('should log the user in after registration', function(done) { let cookie = null; request(app) .post('/auth/register?responseFormat=html') .send('email=foo@test.com') .send('password=password') .expect(302) .end(function (err, res) { getSession(res).then(session => { expect(session.passport).to.be.ok; expect(session.passport.user).to.be.ok; cookie = res.headers['set-cookie'].pop().split(';')[0]; let req = request(app).get('/dashboard'); req.cookies = cookie; req.expect(200, done); }) .catch(err => console.log(err)); }); }); }); });
/* * * Author reducer * */ import { fromJS } from 'immutable'; import { AUTHOR_PROFILE_LOADED, AUTHOR_PROFILE_LOADING_ERROR, } from './constants'; const initialState = fromJS({ author: { fetching: true, error: false, data: {}, }, }); function authorReducer(state = initialState, action) { switch (action.type) { case AUTHOR_PROFILE_LOADED: return state .setIn(['author', 'fetching'], false) .setIn(['author', 'data'], fromJS(action.profile)); case AUTHOR_PROFILE_LOADING_ERROR: return state .setIn(['author', 'fetching'], false) .setIn(['author', 'error'], true); default: return state; } } export default authorReducer;
var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(106, 218, 228, 0.8)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(52, 152, 219, 0.8)", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("canvas1").getContext("2d")).Bar(barChartData,{ scaleShowLabels : false, pointLabelFontSize : 24 });
(function( document, stik ){ stik.createBehavior = function behavior( spec ){ if ( !spec.name ) { throw "Stik: Behavior name is missing"; } if ( spec.name.indexOf(" ") !== -1 ) { throw "Stik: '" + spec.name + "' is not a valid Behavior name. Please replace empty spaces with dashes ('-')"; } if ( !spec.executionUnit ) { throw "Stik: Behavior needs a function to use as its execution unit"; } var behaviorKey = "data-behaviors"; spec.bind = function bind( modules ){ var templates = spec.findTemplates(), i = templates.length; while ( i-- ) { bindWithTemplate( templates[ i ] ).context.load( spec.executionUnit, modules ); markAsApplyed( templates[ i ] ); } return templates.length > 0; }; function bindWithTemplate( template ){ return { context: stik.context({ behavior: spec.behavior, template: template }), executionUnit: spec.executionUnit }; } spec.bindWithTemplate = bindWithTemplate; function findTemplates(){ var selector = "[class*=" + spec.name + "]" + ":not([data-behaviors*=" + spec.name + "])"; return document.querySelectorAll( selector ); } spec.findTemplates = findTemplates; function resolveDependencies( modules ){ var injector = stik.injector({ executionUnit: spec.executionUnit, modules: modules }); return injector.resolveDependencies(); } function markAsApplyed( template ){ var behaviors = template.getAttribute( behaviorKey ); behaviors = ( ( behaviors || "" ) + " " + spec.name ).trim(); template.setAttribute( behaviorKey, behaviors ) & removeBehaviorClass( template ); } function removeBehaviorClass( template ){ var regex = new RegExp( "(^|\\s)?" + spec.name + "(\\s|$)", "g" ); template.className = template.className.replace( regex, " " ).trim(); } return spec; }; })( window.document, window.stik );
/** * Created by Kevin Boutin on 08/23/15. */ angular.module('crudApp.services', []).factory('Item', function ($resource) { return $resource('http://crudapp.weprovideit.com/api/items/:id', { id: '@id' }, { 'get': { method: 'GET' }, 'query': { method: 'GET', isArray: true }, 'update': { method: 'POST' }, 'remove': { method: 'DELETE' }, 'delete': { method: 'DELETE' } }); }).service('popupService', function ($window) { this.showPopup = function (message) { return $window.confirm(message); }; });
var gulp = require('gulp') gulp.task('default', [ 'css', 'app' ])
import Ember from 'ember-metal/core'; // A import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import run from "ember-metal/run_loop"; import Registry from 'container/registry'; import Namespace from "ember-runtime/system/namespace"; import { classify } from "ember-runtime/system/string"; import Controller from "ember-runtime/controllers/controller"; import ObjectController from "ember-runtime/controllers/object_controller"; import ArrayController from "ember-runtime/controllers/array_controller"; import controllerFor from "ember-routing/system/controller_for"; import generateController from "ember-routing/system/generate_controller"; import { generateControllerFactory } from "ember-routing/system/generate_controller"; var buildContainer = function(namespace) { var registry = new Registry(); var container = registry.container(); registry.set = set; registry.resolver = resolverFor(namespace); registry.optionsForType('view', { singleton: false }); registry.register('application:main', namespace, { instantiate: false }); registry.register('controller:basic', Controller, { instantiate: false }); registry.register('controller:object', ObjectController, { instantiate: false }); registry.register('controller:array', ArrayController, { instantiate: false }); return container; }; function resolverFor(namespace) { return function(fullName) { var nameParts = fullName.split(":"); var type = nameParts[0]; var name = nameParts[1]; if (name === 'basic') { name = ''; } var className = classify(name) + classify(type); var factory = get(namespace, className); if (factory) { return factory; } }; } var container, appController, namespace; QUnit.module("Ember.controllerFor", { setup: function() { namespace = Namespace.create(); container = buildContainer(namespace); container._registry.register('controller:app', Controller.extend()); appController = container.lookup('controller:app'); }, teardown: function() { run(function () { container.destroy(); namespace.destroy(); }); } }); QUnit.test("controllerFor should lookup for registered controllers", function() { var controller = controllerFor(container, 'app'); equal(appController, controller, 'should find app controller'); }); QUnit.module("Ember.generateController", { setup: function() { namespace = Namespace.create(); container = buildContainer(namespace); }, teardown: function() { run(function () { container.destroy(); namespace.destroy(); }); } }); QUnit.test("generateController and generateControllerFactory are properties on the root namespace", function() { equal(Ember.generateController, generateController, 'should export generateController'); equal(Ember.generateControllerFactory, generateControllerFactory, 'should export generateControllerFactory'); }); QUnit.test("generateController should create Ember.Controller", function() { var controller = generateController(container, 'home'); ok(controller instanceof Controller, 'should create controller'); }); QUnit.test("generateController should create Ember.ObjectController [DEPRECATED]", function() { var context = {}; var controller = generateController(container, 'home', context); ok(controller instanceof ObjectController, 'should create controller'); }); QUnit.test("generateController should create Ember.ArrayController", function() { var context = Ember.A(); var controller = generateController(container, 'home', context); ok(controller instanceof ArrayController, 'should create controller'); }); QUnit.test("generateController should create App.Controller if provided", function() { var controller; namespace.Controller = Controller.extend(); controller = generateController(container, 'home'); ok(controller instanceof namespace.Controller, 'should create controller'); }); QUnit.test("generateController should create App.ObjectController if provided", function() { var context = {}; var controller; namespace.ObjectController = ObjectController.extend(); controller = generateController(container, 'home', context); ok(controller instanceof namespace.ObjectController, 'should create controller'); }); QUnit.test("generateController should create App.ArrayController if provided", function() { var context = Ember.A(); var controller; namespace.ArrayController = ArrayController.extend(); controller = generateController(container, 'home', context); ok(controller instanceof namespace.ArrayController, 'should create controller'); });
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var APP_OPTIONS = {}; var app_deploy_target = process.env['APP_DEPLOY_TARGET']; APP_OPTIONS.fingerprint = { "prepend": process.env['APP_DEPLOY_FINGERPRINT_PREPEND'], "extensions": ['js', 'css', 'png', 'jpg', 'gif', 'map', 'svg'] } APP_OPTIONS.sassOptions = { "includePaths": [ "node_modules/totem-assets/styles", "node_modules/thinkspace-assets/styles", "bower_components/foundation-sites/scss" ], "imagePath": "/assets/images" } var app = new EmberApp(defaults, APP_OPTIONS); var trees = []; // **Imports** // compile runtime templates app.import('bower_components/ember/ember-template-compiler.js'); // foundation.min app.import('bower_components/foundation-sites/dist/foundation.min.js'); // pick a date app.import('bower_components/pickadate/lib/picker.js'); app.import('bower_components/pickadate/lib/picker.time.js'); app.import('bower_components/pickadate/lib/picker.date.js'); // rangeslider css app.import('bower_components/rangeslider.js/dist/rangeslider.css'); // rangeslider js app.import('bower_components/rangeslider.js/dist/rangeslider.js'); // **Trees** var pick_files = require('broccoli-funnel'); // thinkspace-assets images trees.push(pick_files('node_modules/thinkspace-assets/images', {"srcDir":"/","include":["**/*.*"],"destDir":"assets/images"})); return app.toTree(trees); };
require('proof')(2, require('cadence')(prove)) function prove (async, okay) { var Procession = require('..') var Reader = require('../reader') var Writer = require('../writer') var stream = require('stream') var through = new stream.PassThrough var reader = new Reader(new Procession, through) var writer = new Writer(new Procession, through) writer.outbox.push({ key: 1 }) writer.outbox.push(null) var inbox = reader.inbox.shifter() reader.read(function (error) { if (error) throw error }) writer.write(function (error) { if (error) throw error }) async(function () { inbox.dequeue(async()) }, function (envelope) { okay(envelope, { key: 1 }, 'serialized') inbox.dequeue(async()) }, function (envelope) { okay(envelope, null, 'eoq') reader.raise() writer.raise() }) }
define("model/project", ["require", "exports", "module", "configs/settings", "lang/index", "utils/log", "service/userProfile"], function(e, t) { var i = e("configs/settings"), n = e("lang/index"), s = e("utils/log"), a = e("service/userProfile"); t.Model = Backbone.Model.extend({ defaults: { id: "", name: "", listType: "", sortType: "", taskType: "" }, messages: function() { this.on("change", this.markDirty), this.on("sync", this.unmarkDirty) }, initialize: function() { this.messages() }, markDirty: function() { this.isDirty = !0 }, unmarkDirty: function() { this.isDirty = !1 }, url: function() { return i.API_HOST + "/project" + (this.isNew() ? "" : "/" + this.id) }, validate: function(e) { return _.isEmpty(e.name) ? n.get("empty_project_name") : void 0 }, saveSortType: function(e) { var t = this; setTimeout(function() { t.id === a.get("inboxId") ? t.set("sortType", e) : t.get("sortType") !== e && t.save({ sortType: e }) }, i.responsiveTime) }, changeGroupId: function(e) { this.get("groupId") != e ? (this.set("groupId", e), this.save()) : this.trigger("change:groupId") }, save: function(e, t) { t || (t = {}), t.error = function() { s.log("project save error") }, Backbone.Model.prototype.save.call(this, e, t) }, isShared: function() { return this.get("userCount") > 1 ? !0 : !1 } }) })
{ ("use strict"); var HTMLElement = scope.wrappers.HTMLElement; var mixin = scope.mixin; var registerWrapper = scope.registerWrapper; var OriginalHTMLContentElement = window.HTMLContentElement; function HTMLContentElement(node) { HTMLElement.call(this, node); } HTMLContentElement.prototype = Object.create(HTMLElement.prototype); mixin(HTMLContentElement.prototype, { constructor: HTMLContentElement, get select() { return this.getAttribute("select"); }, set select(value) { this.setAttribute("select", value); }, setAttribute: function(n, v) { HTMLElement.prototype.setAttribute.call(this, n, v); if (String(n).toLowerCase() === "select") this.invalidateShadowRenderer(true); } }); if (OriginalHTMLContentElement) registerWrapper(OriginalHTMLContentElement, HTMLContentElement); scope.wrappers.HTMLContentElement = HTMLContentElement; }
module.exports = { "env": { "es6": true, "node": true, "mocha": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "space-before-function-paren": ["error", { "anonymous": "always", "named": "never", "asyncArrow": "ignore" }], "no-unused-vars": [ "warn" ], "no-console": [ "off" ], "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "never" ] } };
// @flow import React from 'react' import styled from 'styled-components' import { myTheme } from '../../styles' import assets from './assets' const { color, breakpoint, borderRadii } = myTheme // Profile Photo // ---------------------------------------- const StyledProfilePhoto = styled.img` width: 100%; object-fit: cover; margin: 0; line-height: 0; padding: 0; ` const DifussedBlur = styled.div` display: none; @media screen and (min-width: ${breakpoint.small}) { bottom: -2%; display: block; filter: blur(30px) saturate(150%); height: 80%; left: 10%; right: 10%; opacity: 0.75; position: absolute; z-index: -1; } ` const GradientOverlay = styled.div` background-image: linear-gradient( -225deg, ${color.lightCyan} 0%, ${color.strongPurple} 100% ); bottom: 0; left: 0; mix-blend-mode: lighten; opacity: 0.6; position: absolute; right: 0; top: 0; border-top-left-radius: ${borderRadii.one}; border-bottom-left-radius: ${borderRadii.one}; @media screen and (min-width: ${breakpoint.small}) { border-radius: ${borderRadii.two}; } ` const ProfilePhotoContainer = styled.div` line-height: 0; ` const ProfilePhotoFrame = styled.div` border-top-left-radius: ${borderRadii.two}; border-bottom-left-radius: ${borderRadii.two}; overflow: hidden; @media screen and (min-width: ${breakpoint.small}) { border-radius: ${borderRadii.two}; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.05), 0 1rem 1rem rgba(0, 0, 0, 0.2); } ` const ProfilePhoto = () => ( <ProfilePhotoContainer className="relative"> <ProfilePhotoFrame> <StyledProfilePhoto src={assets.profilePhoto.default} srcSet={assets.profilePhoto.set} alt={ 'Matt Mischuk working on his laptop. Behind him in the ' + 'background is Maple Leaf Square.' } /> <GradientOverlay /> </ProfilePhotoFrame> <DifussedBlur> <StyledProfilePhoto src={assets.profilePhoto.default} alt="" /> <GradientOverlay /> </DifussedBlur> </ProfilePhotoContainer> ) export default ProfilePhoto
var expect = require("chai").expect, triggerDeps = require('../src/trigger'); describe("Trigger", function () { it("should run all systems with given event", function () { var called = false, trigger = triggerDeps({ frame: [function () { called = true; }] }); trigger("frame"); expect(called).to.equal(true); }); it("should forward event argument to systems", function () { var expected = "hello", actual, trigger = triggerDeps({ frame: [function (arg) { actual = arg; }] }); trigger("frame", expected); expect(actual).to.equal(expected); }); it("should forward ALL event arguments to systems", function () { var expected = ["hello", "world"], actual, trigger = triggerDeps({ frame: [function () { actual = Array.prototype.slice.call(arguments); }] }); trigger.apply(null, ["frame"].concat(expected)); expect(actual).to.deep.equal(expected); }); });
(function($) { "use strict"; $.extend({ isiPhone : /iphone/img.test(navigator.userAgent), isiPad : /ipad/img.test(navigator.userAgent), isiPod : /ipod/img.test(navigator.userAgent), isiOS : /ip(hone|od|ad)/img.test(navigator.userAgent), isAndroid : (/android/img.test(navigator.userAgent) && !/trident/img.test(navigator.userAgent)), isWebOS : /webos/img.test(navigator.userAgent), isBlackberry : /blackberry/img.test(navigator.userAgent), isTouchEnabled : ('createTouch' in document), isOnline : navigator.onLine, isStandalone : navigator.standalone, isiOS6 : navigator.userAgent.match(/OS 6/i), isiOS7 : navigator.userAgent.match(/OS 7/i), isWin : /trident/img.test(navigator.userAgent), isWinPhone : (/trident/img.test(navigator.userAgent) && /mobile/img.test(navigator.userAgent)), isIE10 : navigator.userAgent.match(/msie 10/i), isIE11 : (navigator.userAgent.match(/windows nt/i) && navigator.userAgent.match(/trident/i)), isIEEdge : (navigator.userAgent.match(/windows nt/i) && navigator.userAgent.match(/edge/i)), isWebkit : navigator.userAgent.match(/webkit/), isMobile : /mobile/img.test(navigator.userAgent), isDesktop : !(/mobile/img.test(navigator.userAgent)), isSafari : (!/Chrome/img.test(navigator.userAgent) && /Safari/img.test(navigator.userAgent) && !/android/img.test(navigator.userAgent)), isChrome : /Chrome/img.test(navigator.userAgent), isNativeAndroid : (/android/i.test(navigator.userAgent) && /webkit/i.test(navigator.userAgent) && !/chrome/i.test(navigator.userAgent)), isWideScreen : window.innerWidth >= 960 && (window.orientation === 90 || window.orentation === -90), isWideScreenPortrait : window.innerWidth >= 960 && (window.orientation !== 90 || window.orientation !== -90) }); })(window.$);
(function($) { window.getWeather = function(latitude, longitude, callback) { var getAddressFromLocation = function(lat, lng, cb) { $.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&sensor=true&language=ko', function(response) { if (response.status === 'OK') { var address = response.results[0].formatted_address; cb(address.split(' ').slice(1, 4)); } else cb([]); }); }; var getXYFromAddress = function(address, cb) { var mdl, leaf, url = 'http://www.kma.go.kr/DFSROOT/POINT/DATA/'; if (address.length < 3) { cb({x : 59, y : 127}); return; } $.get(url + 'top.json.txt', function(response) { for (var i = 0; i < response.length; i++) { if (response[i].value == address[0]) { mdl = parseInt(response[i].code, 10); break; } } $.get(url + 'mdl.' + mdl + '.json.txt', function(response) { for (var i = 0; i < response.length; i++) { if (response[i].value == address[1]) { leaf = parseInt(response[i].code, 10); break; } } $.get(url + 'leaf.' + leaf + '.json.txt', function(response) { for (var i = 0; i < response.length; i++) { if (response[i].value == address[2]) { cb({ x : parseInt(response[i].x, 10), y : parseInt(response[i].y, 10) }); break; } } }, 'json'); }, 'json'); }, 'json'); }; var getWeatherFromXY = function (coord, cb) { $.get('http://www.kma.go.kr/wid/queryDFS.jsp?gridx=' + coord.x + '&gridy=' + coord.y, function(response) { var $response = $(response); var $data = $response.find('data'); var time_str = $response.find('tm').text().match(/^(\d{4})(\d{2})(\d{2})(\d{2})\d{2}$/); var time_start = new Date(time_str[1], time_str[2] - 1, time_str[3], time_str[4], 0, 0); var return_str = []; $data.each(function() { var $this = $(this); var c = new Date(time_start); c.setHours(parseInt($this.find('hour').text(), 10)); c.setDate(c.getDate() + parseInt($this.find('day').text(), 10)); return_str.push({ date : (c.getMonth() + 1) + '월 ' + c.getDate() + '일 ' + c.getHours() + '시', status : $this.find('wfKor').text(), pop : $this.find('pop').text() }); }); cb(return_str); }, 'xml'); }; getAddressFromLocation(latitude, longitude, function(address) { $('#nasel-zone').html('<div>' + address.join(' ') + '<div>'); getXYFromAddress(address, function(coord) { getWeatherFromXY(coord, function(forecast) { callback(forecast); }); }); }); }; $(function() { wpid = navigator.geolocation.getCurrentPosition(function(position) { getWeather(position.coords.latitude, position.coords.longitude, function(forecast) { window.weather = forecast; var index = 0, $nasel = $('#nasel-zone'); setInterval(function() { var $old = $nasel.children(); $old.slideUp(1000, function() { $(this).remove(); }); var $new = $('<div style="display:none"></div>').text( forecast[index].date + ': ' + forecast[index].status + '(강수확률 ' + forecast[index].pop + '%)' ); $new.appendTo($nasel).slideDown(1000); index = ((index + 1) % forecast.length); }, 4000); }); }, function() { alert('GPS 정보를 받지 못해 날씨 정보를 가져올 수 없습니다.'); }, { enableHighAccuracy : true, maximumAge : 30000, timeout : 27000 }); }); })(jQuery);
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/m/ToolbarLayoutData'],function(T){"use strict";var O=T.extend("sap.m.OverflowToolbarLayoutData",{metadata:{properties:{moveToOverflow:{type:"boolean",defaultValue:true},stayInOverflow:{type:"boolean",defaultValue:false}}}});return O;},true);
import React, {Component} from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { staleDucks, staleUser } from 'helpers/utils' import * as usersActionCreators from 'redux/modules/users' import * as usersDucksActionCreators from 'redux/modules/usersDucks' import { User } from 'components'; class UserContainer extends Component { componentDidMount() { const uid = this.props.match.params.uid; if (this.props.noUser === true || staleUser(this.props.lastUpdated)) { this.props.fetchAndHandleUser(uid) } if (this.props.noUser === true || staleDucks(this.props.lastUpdated)) { this.props.fetchAndHandleUsersDucks(uid) } } render() { return ( <User noUser={this.props.noUser} isFetching={this.props.isFetching} name={this.props.name} error={this.props.error} duckIds={this.props.duckIds}/> ) } } UserContainer.propTypes = { name: PropTypes.string.isRequired, noUser: PropTypes.bool.isRequired, isFetching: PropTypes.bool.isRequired, error: PropTypes.string.isRequired, lastUpdated: PropTypes.number.isRequired, duckIds: PropTypes.array.isRequired, match: PropTypes.shape({ params: PropTypes.shape({ uid: PropTypes.string.isRequired }) }), fetchAndHandleUsersDucks: PropTypes.func.isRequired, fetchAndHandleUser: PropTypes.func.isRequired } function mapStateToProps({users, usersDucks}, props) { const specificUsersDucks = usersDucks[props.match.params.uid]; const user = users[props.match.params.uid]; const noUser = typeof user === 'undefined'; const name = noUser ? '' : user.info.name; return { noUser, name, isFetching: users.isFetching || usersDucks.isFetching, error: users.error || usersDucks.error, lastUpdated: specificUsersDucks ? specificUsersDucks.lastUpdated : 0, duckIds: specificUsersDucks ? specificUsersDucks.duckIds : [], } } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...usersActionCreators, ...usersDucksActionCreators }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(UserContainer);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Table = require('./Table'); Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _interopRequireDefault(_Table).default; } }); var _TableBody = require('./TableBody'); Object.defineProperty(exports, 'TableBody', { enumerable: true, get: function get() { return _interopRequireDefault(_TableBody).default; } }); var _TableCell = require('./TableCell'); Object.defineProperty(exports, 'TableCell', { enumerable: true, get: function get() { return _interopRequireDefault(_TableCell).default; } }); var _TableFooter = require('./TableFooter'); Object.defineProperty(exports, 'TableFooter', { enumerable: true, get: function get() { return _interopRequireDefault(_TableFooter).default; } }); var _TableHead = require('./TableHead'); Object.defineProperty(exports, 'TableHead', { enumerable: true, get: function get() { return _interopRequireDefault(_TableHead).default; } }); var _TablePagination = require('./TablePagination'); Object.defineProperty(exports, 'TablePagination', { enumerable: true, get: function get() { return _interopRequireDefault(_TablePagination).default; } }); var _TableRow = require('./TableRow'); Object.defineProperty(exports, 'TableRow', { enumerable: true, get: function get() { return _interopRequireDefault(_TableRow).default; } }); var _TableSortLabel = require('./TableSortLabel'); Object.defineProperty(exports, 'TableSortLabel', { enumerable: true, get: function get() { return _interopRequireDefault(_TableSortLabel).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 2.4.1 (function() { //Language: Danish //Translators: LarsBuur var da; da = { add: "tilføj", and: "og", back: "tilbage", changePassword: "Skift kodeord", choosePassword: "Vælg kodeord", clickAgree: "Ved at klikke på tilmeld accepterer du vores", configure: "Konfigurer", createAccount: "Opret konto", currentPassword: "Nuværende kodeord", dontHaveAnAccount: "Har du ikke en konto?", email: "E-mail", emailAddress: "E-mail adresse", emailResetLink: "Nulstil E-mail Link", forgotPassword: "Glemt kodeord?", ifYouAlreadyHaveAnAccount: "Hvis jeg allerede har en konto", newPassword: "Nyt kodeord", newPasswordAgain: "Nyt kodeord (igen)", optional: "Frivilligt", OR: "eller", password: "Kodeord", passwordAgain: "Kodeord (igen)", privacyPolicy: "Privatlivspolitik", remove: "fjern", resetYourPassword: "Nulstil dit kodeord", setPassword: "Sæt kodeord", sign: "Log", signIn: "Log ind", signin: "Log ind", signOut: "Log ud", signUp: "Tilmeld", signupCode: "Tilmeldingskode", signUpWithYourEmailAddress: "Tilmeld med din e-mail adresse", terms: "Betingelser for brug", updateYourPassword: "Skift dit kodeord", username: "Brugernavn", usernameOrEmail: "Brugernavn eller e-mail", with: "med", info: { emailSent: "E-mail sendt", emailVerified: "Email verificeret", passwordChanged: "Password ændret", passwordReset: "Password reset" }, error: { emailRequired: "E-mail er påkrævet.", minChar: "Kodeordet skal være mindst 7 tegn.", pwdsDontMatch: "De to kodeord er ikke ens.", pwOneDigit: "Kodeord kræver mindste et tal.", pwOneLetter: "Kodeord kræver mindst et bogstav.", signInRequired: "Du skal være logget ind for at kunne gøre det.", signupCodeIncorrect: "Tilmeldingskode er forkert.", signupCodeRequired: "Tilmeldingskode er påkrævet.", usernameIsEmail: "Brugernavn kan ikke være en e-mail adresse.", usernameRequired: "Brugernavn skal udfyldes.", accounts: { //---- accounts-base //"@" + domain + " email required" //"A login handler should return a result or undefined" "Email already exists.": "E-mail findes allerede.", "Email doesn't match the criteria.": "E-mail modsvarer ikke kriteriet.", "Invalid login token": "Invalid log ind token", "Login forbidden": "Log ind forbudt", //"Service " + options.service + " already configured" "Service unknown": "Service ukendt", "Unrecognized options for login request": "Ukendte options for login forsøg", "User validation failed": "Bruger validering fejlede", "Username already exists.": "Brugernavn findes allerede.", "You are not logged in.": "Du er ikke logget ind.", "You've been logged out by the server. Please log in again.": "Du er blevet logget af serveren. Log ind igen.", "Your session has expired. Please log in again.": "Din session er udløbet. Log ind igen.", //---- accounts-oauth "No matching login attempt found": "Der fandtes ingen login forsøg", //---- accounts-password-client "Password is old. Please reset your password.": "Kodeordet er for gammelt. Du skal resette det.", //---- accounts-password "Incorrect password": "Forkert kodeord", "Invalid email": "Invalid e-mail", "Must be logged in": "Du skal være logget ind", "Need to set a username or email": "Du skal angive enten brugernavn eller e-mail", "old password format": "gammelt kodeord format", "Password may not be empty": "Kodeord skal være udfyldt", "Signups forbidden": "Tilmeldinger forbudt", "Token expired": "Token udløbet", "Token has invalid email address": "Token har en invalid e-mail adresse", "User has no password set": "Bruger har ikke angivet noget kodeord", "User not found": "Bruger ej fundet", "Verify email link expired": "Verify email link expired", "Verify email link is for unknown address": "Verificer e-mail link for ukendt adresse", //---- match "Match failed": "Match fejlede", //---- Misc... "Unknown error": "Ukendt fejl" } } }; if (typeof T9n !== "undefined" && T9n !== null) { T9n.map("da", da); } if (typeof module !== "undefined" && module !== null) { module.exports = da; } }).call(this);
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { registerLanguage } from '../_.contribution.js'; registerLanguage({ id: 'dockerfile', extensions: ['.dockerfile'], filenames: ['Dockerfile'], aliases: ['Dockerfile'], loader: function () { return import('./dockerfile.js'); } });
import styled from 'styled-components'; export default styled.div` position: absolute; overflow: hidden; height: 100%; width: 100%; `;
export const ic_tour_twotone = {"viewBox":"0 0 24 24","children":[{"name":"g","attribs":{},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]}]},{"name":"g","attribs":{},"children":[{"name":"g","attribs":{},"children":[{"name":"polygon","attribs":{"opacity":".3","points":"7,12 7,6 18.05,6 16.85,9 18.05,12"},"children":[{"name":"polygon","attribs":{"opacity":".3","points":"7,12 7,6 18.05,6 16.85,9 18.05,12"},"children":[]}]},{"name":"g","attribs":{},"children":[{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M21,4h-8h-1H7V2H5v2v10v8h2v-8h4h1h9l-2-5L21,4z M7,12V6h11.05l-1.2,3l1.2,3H7z M14,9c0,1.1-0.9,2-2,2s-2-0.9-2-2 s0.9-2,2-2S14,7.9,14,9z"},"children":[{"name":"path","attribs":{"d":"M21,4h-8h-1H7V2H5v2v10v8h2v-8h4h1h9l-2-5L21,4z M7,12V6h11.05l-1.2,3l1.2,3H7z M14,9c0,1.1-0.9,2-2,2s-2-0.9-2-2 s0.9-2,2-2S14,7.9,14,9z"},"children":[]}]}]}]}]}]}]}]};
/** * Breaks Gulp tasks into different files. */ 'use strict'; var requireDir = require( 'require-dir' ); requireDir( './gulp/tasks', { recurse : true } );
!function(Framework, exports) { 'use strict'; var Scene = Framework.Scene, Location = Framework.Location, Game = Framework.Game; var score = 5, index = 0, called = false, scenes = [], locations = []; function decrement() { score--; next(Location.get(this.attributes.location)); } function noop() { next(Location.get(this.attributes.location)); } function next(location) { index++; update(location); } function restart(location) { index = 0; score = 5; update(Location.get(this.attributes.location)); } function update(location) { Game.Scenes.important.push(scenes[index]); Game.Location.set(location); } function scene(name, options) { scenes.push(Scene.define(name, options)); } function template(name, data) { var prop, regex, text = $('#ab-' + name).text(); if(data) { for(prop in data) { if(data.hasOwnProperty(prop)) { regex = '{{\\s*' + prop + '\\s*}}'; text = text.replace(new RegExp(regex), data[prop]); } } } return text; } scene('intro', { text: function() { return template('intro'); }, attributes: { location: 'SOMA' }, options: { 'drive east': noop } }); scene('arrival', { text: function() { return template('arrival'); }, attributes: { location: '20 Rausch' }, options: { 'open car door': noop, 'sit inside': decrement } }); scene('call', { text: function() { return template('call') }, attributes: { location: '20 Rausch' }, options: { 'call passenger': function() { score--; index += 2; called = true; update(Location.get(this.attributes.location)); }, 'wait': noop } }); scene('call2', { text: function() { return template('call2') }, attributes: { location: '20 Rausch' }, options: { 'call passenger': function() { called = true; decrement(); }, 'wait': function() { index += 2; update(Location.get(this.attributes.location)); } } }); scene('phone', { text: function() { return template('phone'); }, attributes: { location: '20 Rausch' }, options: { 'wait': noop } }) scene('appearance', { text: function() { return template('appearance', { statement: called ? 'Sorry to keep you waiting' : 'Hey' }); }, attributes: { location: 'Folsom' }, options: { 'drive south': noop } }); scene('talking', { text: function() { return template('talking'); }, attributes: { location: 'Harrison' }, options: { 'meet his gaze': noop, 'avoid his gaze': decrement } }); scene('destination', { text: function() { return template('destination'); }, attributes: { location: 'Brannan' }, options: { 'pull away from the curb': noop, } }); scene('end', { text: function() { return template('end', { score: score }); }, attributes: { location: 'SOMA' }, options: { 'replay ↩': restart } }); update(Location.get(scenes[0].attributes.location)); Game.start(); }(Adventure.Framework, Adventure.Game);
/** * Created by tom on 5/6/14. */ (function ($, google) { var resizeFont = function () { var fontSize = $('#help').height() * 0.67; // 10% of container height if(fontSize > 20) { fontSize = 20; } $('#help-p').css('font-size', fontSize); }; $(window).resize(resizeFont); // Give me all of the executable code. $(document).ready(function () { resizeFont(); // What url do I get the weather data from? var weatherUrl = 'service/weather.php'; // Where is the center of the map? var lat = 41.8764219; var lng = -87.6281078; var GooglMapDefaultLatLng = new google.maps.LatLng(lat, lng); var GoogleMap = new google.maps.Map(document.getElementById('map'), { disableDefaultUI: true, center: GooglMapDefaultLatLng, styles: [ { featureType: "administrative", stylers: [{ saturation: -87 }] }, { featureType: "landscape", stylers: [{ saturation: -87 }] }, { featureType: "poi", stylers: [{ saturation: -87 }] }, { featureType: "road", stylers: [{ saturation: -87 }] }, { featureType: "water", stylers: [{ saturation: -87 }] }, { featureType: "road.arterial", elementType: "geometry", stylers: [{ lightness: 85 }] }, { featureType: "water", stylers: [{ lightness: -20 }] }, { featureType: "transit.station.rail", stylers: [{ saturation: 85 }] }], zoom: 12 } ); var DefaultCenters = new Centers(); DefaultCenters.makeMarkers(GoogleMap); DefaultCenters.makeInfoWindows(); DefaultCenters.addClickListeners(GoogleMap); var DefaultNWS = new NWS(lat, lng, weatherUrl); DefaultNWS.getWeather(DefaultCenters); var FMe = new FindMe(); if (FMe.geolocate) { var FMeDiv = document.createElement('div'); FMe.setFindMeControl(FMeDiv, GoogleMap, FMe); FMeDiv.index = 1; GoogleMap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(FMeDiv); } else { alert('We\'re sorry. It seems we cannot attempt to use your device to geolocate.'); } }); })(jQuery, google);
/** * Grunt JSCS plugin * https://github.com/jscs-dev/grunt-jscs */ module.exports = { options: { config: '.jscsrc', fix: false }, frontend: [ '<%= srcPath %>**/*.js' ], grunt: [ '<%= gruntPath %>**/*.js', 'Gruntfile.js' ], karma: [ 'karma.conf.js' ], ci: { options: { fix: false, force: true, reporter: 'checkstyle', reporterOutput: '<%= testResultPath %>jscs-lint-report.checkstyle.xml' }, files: { src: [ '<%= srcPath %>**/*.js', '<%= gruntPath %>**/*.js', 'Gruntfile.js', 'karma-conf.js' ] } } };
$(document).ready(function () { $('#submit-button').parent().hide(); var wait; $('#id_search_string').keyup( function(){ clearTimeout(wait); wait = setTimeout("getPosts()", 1000); } ); }); function getPosts(){ $.ajax({ beforeSend: function(){ $('#id_search_string').after('<span id="ajax-spinner-container">&nbsp;<img id="ajax-spinner" src="/media/images/ajax-spinner.gif" height="16" width="16" alt="ajax request in progress"></span>'); }, cache: false, dataType: 'json', data: 'search_string='+$('#id_search_string').val(), type: 'GET', url: '/posts/search/', success: function(posts){ $('#search-results').html('<p>Found '+posts.length+' post(s) with <em>'+$('#id_search_string').val()+'</em></p><ul class="results"></ul>'); $.each(posts, function(i, post){ $('ul.results').append('<li><a href="/posts/'+post.fields.slug+'">'+post.fields.title+'</a>, '+prettyDate(post.fields.published_on)+'</li>'); }); $('span#ajax-spinner-container').remove(); } }); }
var burntToast = new BurntToast(); var toastBtn1 = document.querySelector('#make_toast'); var toastBtn2 = document.querySelector('#make_toast_2'); var toastAction = document.querySelector('#make_toast_action'); function doUndo() { burntToast.makeToast('Undo action success!'); } toastBtn1.addEventListener('click', function() { burntToast.makeToast('Toasted!', { duration: 2000 }); }); toastBtn2.addEventListener('click', function() { burntToast.makeToast('Don\'t Burn the Toast!', { duration: 2000, location: { left: true } }); }); toastAction.addEventListener('click', function() { burntToast.makeToast('Toast with Action!', { duration: 4000, action: { string: 'Undo', callback: doUndo } }); });
Number.prototype.formatMoney = function(c, d, t){ var n = this; var c = isNaN(c = Math.abs(c)) ? 2 : c; var d = d == undefined ? "," : d; var t = t == undefined ? "." : t; var s = n < 0 ? "-" : ""; var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + ""; var j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; var x = (2000).formatMoney(/*'casas decimais', 'separador virgula', 'separador ponto'*/); console.log(x); // R$: 2.000,00 =D
'use strict'; var theModule = angular.module('gservDocsApp', [ 'ngResource','ngRoute','ngLocale', 'ui.bootstrap' ]); theModule.config(function ($routeProvider) { $routeProvider .when('/general', { templateUrl: 'views/general.html', controller: "GServGeneralDocsCtrl" }).when('/framework', { templateUrl: 'views/framework.html', controller: "GServFrameworkDocsCtrl" }).when('/standalone', { templateUrl: 'views/standalone.html', controller: "GServStandaloneDocsCtrl" }).when('/examples/basicauth', { templateUrl: 'views/examples/basicAuth.html', controller: "ExampleCtrl" }).when('/examples/cors', { templateUrl: 'views/examples/cors.html', controller: "ExampleCtrl" }) .otherwise({ redirectTo: '/general' }); });
/*globals casper, __utils__, url */ CasperTest.begin("Settings screen is correct", 18, function suite(test) { casper.thenOpen(url + "ghost/settings/", function testTitleAndUrl() { test.assertTitle("Ghost Admin", "Ghost admin has no title"); test.assertUrlMatch(/ghost\/settings\/general\/$/, "Ghost doesn't require login this time"); }); casper.then(function testViews() { test.assertExists(".wrapper", "Settings main view is present"); test.assertExists(".settings-sidebar", "Settings sidebar view is present"); test.assertExists(".settings-menu", "Settings menu is present"); test.assertExists(".settings-menu .general", "General tab is present"); test.assertExists(".settings-menu .users", "Users tab is present"); test.assertExists(".settings-menu .apps", "Apps is present"); test.assertExists(".wrapper", "Settings main view is present"); test.assertExists(".settings-content", "Settings content view is present"); test.assertEval(function testGeneralIsActive() { return document.querySelector('.settings-menu .general').classList.contains('active'); }, "general tab is marked active"); test.assertEval(function testContentIsGeneral() { return document.querySelector('.settings-content').id === 'general'; }, "loaded content is general screen"); }); // test the user tab casper.thenClick('.settings-menu .users'); casper.waitForSelector('#user', function then() { test.assertEval(function testGeneralIsNotActive() { return !document.querySelector('.settings-menu .general').classList.contains('active'); }, "general tab is not marked active"); test.assertEval(function testUserIsActive() { return document.querySelector('.settings-menu .users').classList.contains('active'); }, "user tab is marked active"); test.assertEval(function testContentIsUser() { return document.querySelector('.settings-content').id === 'user'; }, "loaded content is user screen"); }, function onTimeOut() { test.fail('User screen failed to load'); }); function handleUserRequest(requestData, request) { // make sure we only get requests from the user pane if (requestData.url.indexOf('settings/') !== -1) { test.fail("Saving the user pane triggered another settings pane to save"); } } function handleSettingsRequest(requestData, request) { // make sure we only get requests from the user pane if (requestData.url.indexOf('users/') !== -1) { test.fail("Saving a settings pane triggered the user pane to save"); } } casper.then(function listenForRequests() { casper.on('resource.requested', handleUserRequest); }); casper.thenClick('#user .button-save'); casper.waitFor(function successNotification() { return this.evaluate(function () { return document.querySelectorAll('.js-bb-notification section').length > 0; }); }, function doneWaiting() { }, function waitTimeout() { test.fail("Saving the user pane did not result in a notification"); }); casper.then(function checkUserWasSaved() { casper.removeListener('resource.requested', handleUserRequest); }); casper.waitForSelector('.notification-success', function onSuccess() { test.assert(true, 'Got success notification'); }, function onTimeout() { test.assert(false, 'No success notification :('); }); casper.thenClick('#main-menu .settings a').then(function testOpeningSettingsTwice() { casper.on('resource.requested', handleSettingsRequest); test.assertEval(function testUserIsActive() { return document.querySelector('.settings-menu .general').classList.contains('active'); }, "general tab is marked active"); }); casper.thenClick('#general .button-save').waitFor(function successNotification() { return this.evaluate(function () { return document.querySelectorAll('.js-bb-notification section').length > 0; }); }, function doneWaiting() { }, function waitTimeout() { test.fail("Saving the general pane did not result in a notification"); }); casper.then(function checkSettingsWereSaved() { casper.removeListener('resource.requested', handleSettingsRequest); }); casper.waitForSelector('.notification-success', function onSuccess() { test.assert(true, 'Got success notification'); }, function onTimeout() { test.assert(false, 'No success notification :('); }); CasperTest.beforeDone(function () { casper.removeListener('resource.requested', handleUserRequest); casper.removeListener('resource.requested', handleSettingsRequest); }); }); CasperTest.begin("User settings screen validates email", 6, function suite(test) { var email, brokenEmail; casper.thenOpen(url + "ghost/settings/user/", function testTitleAndUrl() { test.assertTitle("Ghost Admin", "Ghost admin has no title"); test.assertUrlMatch(/ghost\/settings\/user\/$/, "Ghost doesn't require login this time"); }); casper.then(function setEmailToInvalid() { email = casper.getElementInfo('#user-email').attributes.value; brokenEmail = email.replace('.', '-'); casper.fillSelectors('.user-profile', { '#user-email': brokenEmail }, false); }); casper.thenClick('#user .button-save'); casper.waitForResource('/users/'); casper.waitForSelector('.notification-error', function onSuccess() { test.assert(true, 'Got error notification'); test.assertSelectorDoesntHaveText('.notification-error', '[object Object]'); }, function onTimeout() { test.assert(false, 'No error notification :('); }); casper.then(function resetEmailToValid() { casper.fillSelectors('.user-profile', { '#user-email': email }, false); }); casper.thenClick('#user .button-save'); casper.waitForResource(/users/); casper.waitForSelector('.notification-success', function onSuccess() { test.assert(true, 'Got success notification'); test.assertSelectorDoesntHaveText('.notification-success', '[object Object]'); }, function onTimeout() { test.assert(false, 'No success notification :('); }); }); CasperTest.begin("User settings screen shows remaining characters for Bio properly", 4, function suite(test) { function getRemainingBioCharacterCount() { return casper.getHTML('.word-count'); } casper.thenOpen(url + "ghost/settings/user/", function testTitleAndUrl() { test.assertTitle("Ghost Admin", "Ghost admin has no title"); test.assertUrlMatch(/ghost\/settings\/user\/$/, "Ghost doesn't require login this time"); }); casper.then(function checkCharacterCount() { test.assert(getRemainingBioCharacterCount() === '200', 'Bio remaining characters is 200'); }); casper.then(function setBioToValid() { casper.fillSelectors('.user-profile', { '#user-bio': 'asdf\n' // 5 characters }, false); }); casper.then(function checkCharacterCount() { test.assert(getRemainingBioCharacterCount() === '195', 'Bio remaining characters is 195'); }); });
import Packet from './Packet'; export default class PacketTOT extends Packet { utc = 0; descriptorLength = 0; descriptors = []; constructor(data) { super(data); } };
var webpack = require('webpack'); var path = require('path'); var config = require('./webpack.config'); config.output = { filename: '[name].bundle.js', publicPath: '/', path: path.resolve(__dirname, 'client') }; config.plugins = config.plugins.concat([ new webpack.DefinePlugin({ 'api': '"http://api.local.bha.com/api"' }), // Adds webpack HMR support. It act's like livereload, // reloading page after webpack rebuilt modules. // It also updates stylesheets and inline assets without page reloading. new webpack.HotModuleReplacementPlugin() ]); module.exports = config;
function solveTask(number) { for (var i = 1; i <= number; i++) { if (i % 3 === 0 && i % 7 === 0) { console.log(i); } } } solveTask(5); solveTask(999); solveTask(28713);
'use strict'; module.exports = function redirector(/* options */) { var Poison = require('poison'); var log = require('unilog'); var Util = require('util'); Poison.getModulesByName('debug').forEach(redirect); Poison.addHook('debug', function(moduleName, mod) { redirect(mod); }); function redirect(debugModule) { var debug = debugModule.exports; if (typeof debug !== 'function') { return; } var newDebug = function unilogNexus_debug(groupId) { var groupedLog = log.withGroupId(String(groupId).replace(/:/g, '.')); var debugInstance = function unilogNexus_debugInstance() { groupedLog.putEvent({ callee: unilogNexus_debugInstance, level: 'debug', message: Util.format.apply(Util, arguments), }); }; debugInstance.raw = debug(groupId); return debugInstance; }; newDebug.raw = debug; debugModule.exports = newDebug; } };
this.NesDb = this.NesDb || {}; NesDb[ '1F6072AE901F3D3530ADCD3C136178E3C7354990' ] = { "$": { "name": "Star Wars: The Empire Strikes Back", "class": "Licensed", "catalog": "NES-EK-NOE", "publisher": "JVC", "developer": "LucasFilm Games", "portdeveloper": "Sculptured Software", "region": "Germany", "players": "1", "date": "1992-07-18" }, "cartridge": [ { "$": { "system": "NES-PAL-B", "crc": "54E43C57", "sha1": "1F6072AE901F3D3530ADCD3C136178E3C7354990", "dump": "ok", "dumper": "Kinopio", "datedumped": "2007-11-06" }, "board": [ { "$": { "type": "NES-TLROM", "pcb": "NES-TLROM-03", "mapper": "4" }, "prg": [ { "$": { "name": "PAL-EK-0 PRG", "size": "256k", "crc": "69CB509C", "sha1": "738524397555DD8187B5E1F6E6F2B475C28A8291" } } ], "chr": [ { "$": { "name": "PAL-EK-0 CHR", "size": "256k", "crc": "3BDAA968", "sha1": "4A4E21186986931BEE6DD129EA282B9B99247556" } } ], "chip": [ { "$": { "type": "MMC3B" } } ], "cic": [ { "$": { "type": "3195A" } } ] } ] } ], "gameGenieCodes": [ { "name": "Start with 14 continues", "codes": [ [ "TENLGIYE" ] ] }, { "name": "Don't take damage from most enemies", "codes": [ [ "GZVZTNOO" ] ] }, { "name": "9 harpoons--scene 2", "codes": [ [ "PESZYPIE" ] ] }, { "name": "1 harpoons--scene 2", "codes": [ [ "PESZYPIA" ] ] }, { "name": "Infinite harpoons--scene 2", "codes": [ [ "GZVZVKVK" ] ] }, { "name": "Infinite energy for ship--scene 2", "codes": [ [ "GXSLIISA" ] ] }, { "name": "Always have Lightsaber", "codes": [ [ "AEXOETYL" ] ] }, { "name": "Start on scene 2", "codes": [ [ "PAEGXLAA" ] ] }, { "name": "Start on scene 3", "codes": [ [ "ZAEGXLAA" ] ] }, { "name": "Start on scene 4", "codes": [ [ "LAEGXLAA" ] ] }, { "name": "Start on scene 5", "codes": [ [ "GAEGXLAA" ] ] }, { "name": "Start on scene 6", "codes": [ [ "IAEGXLAA" ] ] }, { "name": "Start on scene 7", "codes": [ [ "TAEGXLAA" ] ] } ] };
var webpack = require("webpack"); var path = require("path"); var node_modules_dir = path.join(__dirname, "node_modules"); var config = { cache: true, context: __dirname, entry: { app: [ "webpack/hot/dev-server", "./index.js" ] }, output: { path: path.join(__dirname, "./build"), filename: "bundle.js", }, devtool: "source-map", module: { noParse: [], loaders: [{ test: /\.jsx/, loader: "jsx-loader?harmony" }, { test: /\.js$/, loader: "jsx-loader?harmony" }, { test: /\.scss$/, loaders: ["style-loader", "css-loader", "autoprefixer-loader?browsers=last 2 version", "sass-loader?sync" ] }, { test: /\.css$/, loaders: ["style-loader", "css-loader?sourceMap", "autoprefixer-loader?browser=last 2 version", ] }, { test: /\.(jpg|png|svg|gif|eot|ttf|woff)$/, loader: "url-loader", query: { name: "[path][name].[ext]", context: "src", limit: "8192" } }, ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), ], resolve: { // add aliases for commonly used modules alias: { }, //this teaches webpack extensions so you can require("file") rather than require(file.ext). extensions: ["", ".js", ".jsx", ".css", ".scss", ".jpg", ".png", ".svg", ".gif", "html"], modulesDirectories: ["components", "base", "core", "node_modules"] }, }; module.exports = config;
import React from 'react'; const Header = () => { return ( <nav className="nav navbar-default"> <div className="navbar-header"> <a className="navbar-brand">ShortenMyLink</a> </div> </nav> ); }; export default Header;
/** * Adapted from Kes Thomas' JavaScript Perlin noise code at * http://asserttrue.blogspot.ca/2011/12/perlin-noise-in-javascript_31.html **/ // This is a port of Ken Perlin's Java code. The // original Java code is at http://cs.nyu.edu/%7Eperlin/noise/. // Note that in this version, a number from 0 to 1 is returned. (function(){ var permutation = [ 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ]; function scalenum(n) { return (1 + n)/2; } function grad(hash, x, y, z) { var h = hash & 15, // convert lo 4 bits of hash code u = h < 8 ? x : y, // into 12 gradient directions v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } // linear interpolation between a and b by amount t (0, 1) function lerp(t, a, b) { return a + t * (b - a); } var noise = function(scale) { // build the perm array var p = new Array(512) for (var i=0; i < 256 ; i++) { p[256+i] = p[i] = permutation[i]; } return function(x, y, z) { if(!z) z = 0; x *= scale; y *= scale; z *= scale; // find unit cube that contains this point var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; // find relative x, y, z of point in cube x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); // compute the face curves for each of X, Y, Z var u = fade(x), v = fade(y), w = fade(z); // hash coordinates of the 8 cube corners var A = p[X ]+Y, AA = p[A ]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B ]+Z, BB = p[B+1]+Z; var lo = lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))); var hi = lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 ))); // add blended results from 8 corners of cube return scalenum(lerp(w, lo, hi)); } }; window.perlin = { noise: noise }; })();